vantuz 3.4.2 → 3.5.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.
Files changed (70) hide show
  1. package/LICENSE +45 -45
  2. package/admin-keygen.js +51 -0
  3. package/cli.js +685 -585
  4. package/config.js +733 -733
  5. package/core/agent-loop.js +190 -190
  6. package/core/ai-provider.js +298 -261
  7. package/core/automation.js +523 -523
  8. package/core/brand-analyst.js +101 -0
  9. package/core/channels.js +167 -167
  10. package/core/dashboard.js +230 -230
  11. package/core/database.js +135 -37
  12. package/core/eia-monitor.js +3 -1
  13. package/core/engine.js +648 -636
  14. package/core/gateway.js +447 -447
  15. package/core/learning.js +214 -214
  16. package/core/license.js +113 -0
  17. package/core/marketplace-adapter.js +168 -168
  18. package/core/memory.js +190 -190
  19. package/core/migrations/001-initial-schema.sql +1 -1
  20. package/core/queue.js +120 -120
  21. package/core/self-healer.js +314 -314
  22. package/core/unified-product.js +214 -214
  23. package/core/vision-service.js +113 -113
  24. package/index.js +217 -174
  25. package/modules/crm/sentiment-crm.js +231 -231
  26. package/modules/healer/listing-healer.js +201 -201
  27. package/modules/oracle/predictor.js +214 -214
  28. package/modules/researcher/agent.js +169 -169
  29. package/modules/team/agents/base.js +92 -92
  30. package/modules/team/agents/dev.js +33 -33
  31. package/modules/team/agents/josh.js +40 -40
  32. package/modules/team/agents/marketing.js +33 -33
  33. package/modules/team/agents/milo.js +36 -36
  34. package/modules/team/index.js +78 -78
  35. package/modules/team/shared-memory.js +87 -87
  36. package/modules/war-room/competitor-tracker.js +250 -250
  37. package/modules/war-room/pricing-engine.js +308 -308
  38. package/nodes/warehouse.js +238 -238
  39. package/onboard.js +1 -1
  40. package/package.json +7 -5
  41. package/platforms/pttavm.js +14 -14
  42. package/plugins/vantuz/index.js +528 -528
  43. package/plugins/vantuz/memory/hippocampus.js +465 -465
  44. package/plugins/vantuz/package.json +20 -20
  45. package/plugins/vantuz/platforms/_template.js +118 -118
  46. package/plugins/vantuz/platforms/amazon.js +236 -236
  47. package/plugins/vantuz/platforms/ciceksepeti.js +166 -166
  48. package/plugins/vantuz/platforms/hepsiburada.js +180 -180
  49. package/plugins/vantuz/platforms/index.js +165 -165
  50. package/plugins/vantuz/platforms/n11.js +229 -229
  51. package/plugins/vantuz/platforms/pazarama.js +154 -154
  52. package/plugins/vantuz/platforms/pttavm.js +127 -127
  53. package/plugins/vantuz/platforms/trendyol.js +326 -326
  54. package/plugins/vantuz/services/alerts.js +253 -253
  55. package/plugins/vantuz/services/license.js +34 -34
  56. package/plugins/vantuz/services/scheduler.js +232 -232
  57. package/plugins/vantuz/tools/analytics.js +152 -152
  58. package/plugins/vantuz/tools/crossborder.js +187 -187
  59. package/plugins/vantuz/tools/nl-parser.js +211 -211
  60. package/plugins/vantuz/tools/product.js +110 -110
  61. package/plugins/vantuz/tools/quick-report.js +175 -175
  62. package/plugins/vantuz/tools/repricer.js +314 -314
  63. package/plugins/vantuz/tools/sentiment.js +115 -115
  64. package/plugins/vantuz/tools/vision.js +257 -257
  65. package/private.pem +28 -0
  66. package/public.pem +9 -0
  67. package/server/app.js +260 -260
  68. package/server/public/index.html +514 -514
  69. package/start.bat +33 -33
  70. package/vantuz.sqlite +0 -0
@@ -1,261 +1,298 @@
1
- /**
2
- * 🤖 AI Provider Integration v3.1
3
- * Gerçek AI API çağrıları + Context desteği
4
- */
5
-
6
- import axios from 'axios';
7
- import fs from 'fs';
8
- import path from 'path';
9
- import os from 'os';
10
-
11
- const LOG_FILE = path.join(os.homedir(), '.vantuz', 'vantuz.log');
12
-
13
- export const PROVIDER_CONFIG = {
14
- gemini: {
15
- url: (apiKey) => `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`,
16
- body: (systemPrompt, message) => ({
17
- contents: [{ parts: [{ text: `${systemPrompt}\n\nKullanıcı: ${message}` }] }]
18
- }),
19
- headers: { 'Content-Type': 'application/json' },
20
- parseResponse: (data) => data?.candidates?.[0]?.content?.parts?.[0]?.text,
21
- errorMsg: 'Gemini yanıt vermedi',
22
- config_label: 'Google Gemini',
23
- config_description: 'Önerilen/Ücretsiz',
24
- config_icon: '🔷',
25
- envKey: 'GEMINI_API_KEY'
26
- },
27
- groq: {
28
- url: 'https://api.groq.com/openai/v1/chat/completions',
29
- body: (systemPrompt, message) => ({
30
- model: 'llama-3.3-70b-versatile',
31
- messages: [
32
- { role: 'system', content: systemPrompt },
33
- { role: 'user', content: message }
34
- ],
35
- max_tokens: 1000,
36
- temperature: 0.7
37
- }),
38
- headers: (apiKey) => ({ 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }),
39
- parseResponse: (data) => data?.choices?.[0]?.message?.content,
40
- errorMsg: 'Groq yanıt vermedi',
41
- config_label: 'Groq',
42
- config_description: 'Hızlı/Ücretsiz',
43
- config_icon: '⚡',
44
- envKey: 'GROQ_API_KEY'
45
- },
46
- openai: {
47
- url: 'https://api.openai.com/v1/chat/completions',
48
- body: (systemPrompt, message) => ({
49
- model: 'gpt-4o-mini',
50
- messages: [
51
- { role: 'system', content: systemPrompt },
52
- { role: 'user', content: message }
53
- ],
54
- max_tokens: 1000
55
- }),
56
- headers: (apiKey) => ({ 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }),
57
- parseResponse: (data) => data?.choices?.[0]?.message?.content,
58
- errorMsg: 'OpenAI yanıt vermedi',
59
- config_label: 'OpenAI GPT-4o',
60
- config_description: 'Premium',
61
- config_icon: '🟢',
62
- envKey: 'OPENAI_API_KEY'
63
- },
64
- anthropic: {
65
- url: 'https://api.anthropic.com/v1/messages',
66
- body: (systemPrompt, message) => ({
67
- model: 'claude-3-haiku-20240307',
68
- max_tokens: 1000,
69
- messages: [
70
- { role: 'user', content: message }
71
- ],
72
- system: systemPrompt
73
- }),
74
- headers: (apiKey) => ({ 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'Content-Type': 'application/json' }),
75
- parseResponse: (data) => data?.content?.[0]?.text,
76
- errorMsg: 'Anthropic yanıt vermedi',
77
- config_label: 'Anthropic Claude 3.5',
78
- config_description: 'Advanced',
79
- config_icon: '🟣',
80
- envKey: 'ANTHROPIC_API_KEY'
81
- },
82
- deepseek: {
83
- url: 'https://api.deepseek.com/v1/chat/completions',
84
- body: (systemPrompt, message) => ({
85
- model: 'deepseek-chat',
86
- messages: [
87
- { role: 'system', content: systemPrompt },
88
- { role: 'user', content: message }
89
- ],
90
- max_tokens: 1000
91
- }),
92
- headers: (apiKey) => ({ 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }),
93
- parseResponse: (data) => data?.choices?.[0]?.message?.content,
94
- errorMsg: 'DeepSeek yanıt vermedi',
95
- config_label: 'DeepSeek V3',
96
- config_description: 'Fast',
97
- config_icon: '🔵',
98
- envKey: 'DEEPSEEK_API_KEY'
99
- }
100
- };
101
-
102
- // ═══════════════════════════════════════════════════════════════════════════
103
- // LOGGING
104
- // ═══════════════════════════════════════════════════════════════════════════
105
-
106
- export function log(level, message, data = null) {
107
- const timestamp = new Date().toISOString();
108
- const logLine = `[${timestamp}] [${level}] ${message}${data ? ' | ' + JSON.stringify(data) : ''}\n`;
109
-
110
- try {
111
- fs.appendFileSync(LOG_FILE, logLine);
112
- } catch (e) { }
113
- }
114
-
115
- export function getLogs(lines = 50) {
116
- try {
117
- if (!fs.existsSync(LOG_FILE)) {
118
- return 'Log dosyası bulunamadı.';
119
- }
120
- const content = fs.readFileSync(LOG_FILE, 'utf-8');
121
- const allLines = content.split('\n').filter(l => l.trim());
122
- return allLines.slice(-lines).join('\n');
123
- } catch (e) {
124
- return `Log okuma hatası: ${e.message}`;
125
- }
126
- }
127
-
128
- export function clearLogs() {
129
- try {
130
- fs.writeFileSync(LOG_FILE, '');
131
- return true;
132
- } catch (e) {
133
- return false;
134
- }
135
- }
136
-
137
- // ═══════════════════════════════════════════════════════════════════════════
138
- // WORKSPACE IDENTITY LOADER
139
- // ═══════════════════════════════════════════════════════════════════════════
140
-
141
- const WORKSPACE_DIR = path.join(process.cwd(), 'workspace');
142
-
143
- /**
144
- * Loads workspace identity files (BRAND.md, SOUL.md, AGENTS.md)
145
- * These files define the AI's personality, brand rules, and capabilities.
146
- */
147
- function loadWorkspaceIdentity() {
148
- const files = ['BRAND.md', 'SOUL.md', 'AGENTS.md'];
149
- let identity = '';
150
-
151
- for (const file of files) {
152
- const filePath = path.join(WORKSPACE_DIR, file);
153
- try {
154
- if (fs.existsSync(filePath)) {
155
- const content = fs.readFileSync(filePath, 'utf-8').trim();
156
- if (content) {
157
- identity += `\n\n--- ${file} ---\n${content}`;
158
- log('INFO', `Workspace identity loaded: ${file}`, { chars: content.length });
159
- }
160
- }
161
- } catch (e) {
162
- log('WARN', `Workspace file read error: ${file}`, { error: e.message });
163
- }
164
- }
165
-
166
- return identity;
167
- }
168
-
169
- // ═══════════════════════════════════════════════════════════════════════════
170
- // SYSTEM PROMPT
171
- // ═══════════════════════════════════════════════════════════════════════════
172
-
173
- const VANTUZ_SYSTEM_PROMPT = `Sen Vantuz AI, e-ticaret operasyonlarını yöneten yapay zeka asistanısın.
174
-
175
- ## Kimliğin
176
- - İsim: Vantuz AI
177
- - Uzmanlık: E-ticaret yönetimi, pazaryeri entegrasyonları, fiyatlandırma stratejileri
178
- - Dil: Türkçe
179
- - Kişilik: Profesyonel, çözüm odaklı, verimli
180
-
181
- ## Desteklenen Pazaryerleri
182
- 1. 🟠 Trendyol - Tam entegrasyon
183
- 2. 🟣 Hepsiburada - Tam entegrasyon
184
- 3. 🔵 N11 - Tam entegrasyon
185
- 4. 🟡 Amazon - FBA destekli
186
- 5. 🌸 Çiçeksepeti - Entegre
187
- 6. 📮 PTTavm - Entegre
188
- 7. 🛒 Pazarama - Entegre
189
-
190
- ## Yeteneklerin
191
- - Stok kontrolü ve güncelleme
192
- - Fiyat analizi ve güncelleme
193
- - Sipariş yönetimi (Listeleme, Durum sorgulama)
194
- - Rakip analizi
195
- - Satış raporları
196
- - Zamanlanmış görevler (Cron Jobs) oluşturma/yönetme
197
-
198
- ## Önemli Kurallar
199
- 1. **ASLA VE ASLA** elindeki "MEVCUT SİSTEM DURUMU" verisinde olmayan bir sayıyı uydurma.
200
- 2. Eğer mesajda "cron" veya "zamanla" geçiyorsa, cron formatında zamanlanmış görev oluşturmayı teklif et.
201
- 3. Sipariş veya ürün listeleme gibi OKUMA (Read) işlemleri için ASLA onay isteme. Doğrudan listele.
202
- 4. Sadece Fiyat/Stok güncelleme veya Silme gibi YAZMA (Write) işlemleri için risk uyarısı ver.
203
- 5. Kullanıcı "Risk Kabul Edildi" modundaysa (RISK_ACCEPTED=true), onay istemeden işlemi yap.
204
- 6. Kar marjının altına fiyat düşürme önerme.
205
-
206
- ## Yanıt Formatı
207
- - Kısa ve öz ol
208
- - Emoji kullan ama abartma
209
- - Sayısal verileri tablo formatında göster
210
- - Hata durumunda çözüm öner ve hata kodunu analiz et`;
211
-
212
- // ═══════════════════════════════════════════════════════════════════════════
213
- // AI CHAT
214
- // ═══════════════════════════════════════════════════════════════════════════
215
-
216
- async function _makeApiRequest(providerName, providerConfig, message, apiKey, systemPrompt) {
217
- if (!apiKey) throw new Error(`${providerName.toUpperCase()}_API_KEY ayarlanmamış`);
218
-
219
- const url = typeof providerConfig.url === 'function' ? providerConfig.url(apiKey) : providerConfig.url;
220
- const headers = typeof providerConfig.headers === 'function' ? providerConfig.headers(apiKey) : providerConfig.headers;
221
- const body = providerConfig.body(systemPrompt, message);
222
-
223
- const response = await axios.post(url, body, {
224
- headers,
225
- timeout: 30000
226
- });
227
-
228
- const text = providerConfig.parseResponse(response.data);
229
- if (!text) throw new Error(providerConfig.errorMsg);
230
-
231
- log('INFO', `${providerName} yanıtı alındı`, { chars: text.length });
232
- return text;
233
- }
234
-
235
- export async function chat(message, config, env) {
236
- const provider = config.aiProvider || 'gemini';
237
- const providerConfig = PROVIDER_CONFIG[provider];
238
-
239
- // Context bilgisi ekle
240
- const contextInfo = config.systemContext || '';
241
- const workspaceIdentity = loadWorkspaceIdentity();
242
- const fullSystemPrompt = VANTUZ_SYSTEM_PROMPT + contextInfo + (workspaceIdentity ? `\n\n## MARKA KİMLİĞİ VE STRATEJİ\nAşağıdaki kurallara MUTLAKA uy:${workspaceIdentity}` : '');
243
-
244
- log('INFO', `AI isteği: ${provider}`, { message: message.slice(0, 100) });
245
-
246
- if (!providerConfig) {
247
- return 'Desteklenmeyen AI sağlayıcı: ' + provider;
248
- }
249
-
250
- try {
251
- const apiKey = env[`${provider.toUpperCase()}_API_KEY`];
252
- return await _makeApiRequest(provider, providerConfig, message, apiKey, fullSystemPrompt);
253
- } catch (error) {
254
- log('ERROR', `AI hatası: ${error.message}`, { provider });
255
- return `AI hatası: ${error.message}. /logs komutu ile detay görün.`;
256
- }
257
- }
258
-
259
-
260
-
261
- export default { chat, log, getLogs, clearLogs };
1
+ /**
2
+ * 🤖 AI Provider Integration v3.1
3
+ * Gerçek AI API çağrıları + Context desteği
4
+ */
5
+
6
+ import axios from 'axios';
7
+ import fs from 'fs';
8
+ import path from 'path';
9
+ import os from 'os';
10
+
11
+ const LOG_FILE = path.join(os.homedir(), '.vantuz', 'vantuz.log');
12
+
13
+ export const PROVIDER_CONFIG = {
14
+ gemini: {
15
+ url: (apiKey) => `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`,
16
+ body: (systemPrompt, message) => ({
17
+ contents: [{ parts: [{ text: `${systemPrompt}\n\nKullanıcı: ${message}` }] }]
18
+ }),
19
+ headers: { 'Content-Type': 'application/json' },
20
+ parseResponse: (data) => data?.candidates?.[0]?.content?.parts?.[0]?.text,
21
+ errorMsg: 'Gemini yanıt vermedi',
22
+ config_label: 'Google Gemini',
23
+ config_description: 'Önerilen/Ücretsiz',
24
+ config_icon: '🔷',
25
+ envKey: 'GEMINI_API_KEY'
26
+ },
27
+ groq: {
28
+ url: 'https://api.groq.com/openai/v1/chat/completions',
29
+ body: (systemPrompt, message) => ({
30
+ model: 'llama-3.3-70b-versatile',
31
+ messages: [
32
+ { role: 'system', content: systemPrompt },
33
+ { role: 'user', content: message }
34
+ ],
35
+ max_tokens: 1000,
36
+ temperature: 0.7
37
+ }),
38
+ headers: (apiKey) => ({ 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }),
39
+ parseResponse: (data) => data?.choices?.[0]?.message?.content,
40
+ errorMsg: 'Groq yanıt vermedi',
41
+ config_label: 'Groq',
42
+ config_description: 'Hızlı/Ücretsiz',
43
+ config_icon: '⚡',
44
+ envKey: 'GROQ_API_KEY'
45
+ },
46
+ openai: {
47
+ url: 'https://api.openai.com/v1/chat/completions',
48
+ body: (systemPrompt, message) => ({
49
+ model: 'gpt-4o-mini',
50
+ messages: [
51
+ { role: 'system', content: systemPrompt },
52
+ { role: 'user', content: message }
53
+ ],
54
+ max_tokens: 1000
55
+ }),
56
+ headers: (apiKey) => ({ 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }),
57
+ parseResponse: (data) => data?.choices?.[0]?.message?.content,
58
+ errorMsg: 'OpenAI yanıt vermedi',
59
+ config_label: 'OpenAI GPT-4o',
60
+ config_description: 'Premium',
61
+ config_icon: '🟢',
62
+ envKey: 'OPENAI_API_KEY'
63
+ },
64
+ anthropic: {
65
+ url: 'https://api.anthropic.com/v1/messages',
66
+ body: (systemPrompt, message) => ({
67
+ model: 'claude-3-haiku-20240307',
68
+ max_tokens: 1000,
69
+ messages: [
70
+ { role: 'user', content: message }
71
+ ],
72
+ system: systemPrompt
73
+ }),
74
+ headers: (apiKey) => ({ 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'Content-Type': 'application/json' }),
75
+ parseResponse: (data) => data?.content?.[0]?.text,
76
+ errorMsg: 'Anthropic yanıt vermedi',
77
+ config_label: 'Anthropic Claude 3.5',
78
+ config_description: 'Advanced',
79
+ config_icon: '🟣',
80
+ envKey: 'ANTHROPIC_API_KEY'
81
+ },
82
+ deepseek: {
83
+ url: 'https://api.deepseek.com/v1/chat/completions',
84
+ body: (systemPrompt, message) => ({
85
+ model: 'deepseek-chat',
86
+ messages: [
87
+ { role: 'system', content: systemPrompt },
88
+ { role: 'user', content: message }
89
+ ],
90
+ max_tokens: 1000
91
+ }),
92
+ headers: (apiKey) => ({ 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }),
93
+ parseResponse: (data) => data?.choices?.[0]?.message?.content,
94
+ errorMsg: 'DeepSeek yanıt vermedi',
95
+ config_label: 'DeepSeek V3',
96
+ config_description: 'Fast',
97
+ config_icon: '🔵',
98
+ envKey: 'DEEPSEEK_API_KEY'
99
+ },
100
+ gemini_cli: {
101
+ url: 'local',
102
+ config_label: 'Gemini CLI',
103
+ config_description: 'Yerel CLI',
104
+ config_icon: '💻',
105
+ envKey: 'GEMINI_CLI_KEY' // Not really used, but keeps structure consistent
106
+ }
107
+ };
108
+
109
+ // ═══════════════════════════════════════════════════════════════════════════
110
+ // LOGGING
111
+ // ═══════════════════════════════════════════════════════════════════════════
112
+
113
+ export function log(level, message, data = null) {
114
+ const timestamp = new Date().toISOString();
115
+ const logLine = `[${timestamp}] [${level}] ${message}${data ? ' | ' + JSON.stringify(data) : ''}\n`;
116
+
117
+ try {
118
+ fs.appendFileSync(LOG_FILE, logLine);
119
+ } catch (e) { }
120
+ }
121
+
122
+ export function getLogs(lines = 50) {
123
+ try {
124
+ if (!fs.existsSync(LOG_FILE)) {
125
+ return 'Log dosyası bulunamadı.';
126
+ }
127
+ const content = fs.readFileSync(LOG_FILE, 'utf-8');
128
+ const allLines = content.split('\n').filter(l => l.trim());
129
+ return allLines.slice(-lines).join('\n');
130
+ } catch (e) {
131
+ return `Log okuma hatası: ${e.message}`;
132
+ }
133
+ }
134
+
135
+ export function clearLogs() {
136
+ try {
137
+ fs.writeFileSync(LOG_FILE, '');
138
+ return true;
139
+ } catch (e) {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ // ═══════════════════════════════════════════════════════════════════════════
145
+ // WORKSPACE IDENTITY LOADER
146
+ // ═══════════════════════════════════════════════════════════════════════════
147
+
148
+ const WORKSPACE_DIR = path.join(process.cwd(), 'workspace');
149
+
150
+ /**
151
+ * Loads workspace identity files (BRAND.md, SOUL.md, AGENTS.md)
152
+ * These files define the AI's personality, brand rules, and capabilities.
153
+ */
154
+ function loadWorkspaceIdentity() {
155
+ const files = ['BRAND.md', 'SOUL.md', 'AGENTS.md'];
156
+ let identity = '';
157
+
158
+ for (const file of files) {
159
+ const filePath = path.join(WORKSPACE_DIR, file);
160
+ try {
161
+ if (fs.existsSync(filePath)) {
162
+ const content = fs.readFileSync(filePath, 'utf-8').trim();
163
+ if (content) {
164
+ identity += `\n\n--- ${file} ---\n${content}`;
165
+ log('INFO', `Workspace identity loaded: ${file}`, { chars: content.length });
166
+ }
167
+ }
168
+ } catch (e) {
169
+ log('WARN', `Workspace file read error: ${file}`, { error: e.message });
170
+ }
171
+ }
172
+
173
+ return identity;
174
+ }
175
+
176
+ // ═══════════════════════════════════════════════════════════════════════════
177
+ // SYSTEM PROMPT
178
+ // ═══════════════════════════════════════════════════════════════════════════
179
+
180
+ const VANTUZ_SYSTEM_PROMPT = `Sen Vantuz AI, e-ticaret operasyonlarını yöneten yapay zeka asistanısın.
181
+
182
+ ## Kimliğin
183
+ - İsim: Vantuz AI
184
+ - Uzmanlık: E-ticaret yönetimi, pazaryeri entegrasyonları, fiyatlandırma stratejileri
185
+ - Dil: Türkçe
186
+ - Kişilik: Profesyonel, çözüm odaklı, verimli
187
+
188
+ ## Desteklenen Pazaryerleri
189
+ 1. 🟠 Trendyol - Tam entegrasyon
190
+ 2. 🟣 Hepsiburada - Tam entegrasyon
191
+ 3. 🔵 N11 - Tam entegrasyon
192
+ 4. 🟡 Amazon - FBA destekli
193
+ 5. 🌸 Çiçeksepeti - Entegre
194
+ 6. 📮 PTTavm - Entegre
195
+ 7. 🛒 Pazarama - Entegre
196
+
197
+ ## Yeteneklerin
198
+ - Stok kontrolü ve güncelleme
199
+ - Fiyat analizi ve güncelleme
200
+ - Sipariş yönetimi (Listeleme, Durum sorgulama)
201
+ - Rakip analizi
202
+ - Satış raporları
203
+ - Zamanlanmış görevler (Cron Jobs) oluşturma/yönetme
204
+
205
+ ## Önemli Kurallar
206
+ 1. **ASLA VE ASLA** elindeki "MEVCUT SİSTEM DURUMU" verisinde olmayan bir sayıyı uydurma.
207
+ 2. Eğer mesajda "cron" veya "zamanla" geçiyorsa, cron formatında zamanlanmış görev oluşturmayı teklif et.
208
+ 3. Sipariş veya ürün listeleme gibi OKUMA (Read) işlemleri için ASLA onay isteme. Doğrudan listele.
209
+ 4. Sadece Fiyat/Stok güncelleme veya Silme gibi YAZMA (Write) işlemleri için risk uyarısı ver.
210
+ 5. Kullanıcı "Risk Kabul Edildi" modundaysa (RISK_ACCEPTED=true), onay istemeden işlemi yap.
211
+ 6. Kar marjının altına fiyat düşürme önerme.
212
+
213
+ ## Yanıt Formatı
214
+ - Kısa ve öz ol
215
+ - Emoji kullan ama abartma
216
+ - Sayısal verileri tablo formatında göster
217
+ - Hata durumunda çözüm öner ve hata kodunu analiz et`;
218
+
219
+ // ═══════════════════════════════════════════════════════════════════════════
220
+ // AI CHAT
221
+ // ═══════════════════════════════════════════════════════════════════════════
222
+
223
+ async function _makeApiRequest(providerName, providerConfig, message, apiKey, systemPrompt) {
224
+ if (!apiKey) throw new Error(`${providerName.toUpperCase()}_API_KEY ayarlanmamış`);
225
+
226
+ const url = typeof providerConfig.url === 'function' ? providerConfig.url(apiKey) : providerConfig.url;
227
+ const headers = typeof providerConfig.headers === 'function' ? providerConfig.headers(apiKey) : providerConfig.headers;
228
+ const body = providerConfig.body(systemPrompt, message);
229
+
230
+ const response = await axios.post(url, body, {
231
+ headers,
232
+ timeout: 30000
233
+ });
234
+
235
+ const text = providerConfig.parseResponse(response.data);
236
+ if (!text) throw new Error(providerConfig.errorMsg);
237
+
238
+ log('INFO', `${providerName} yanıtı alındı`, { chars: text.length });
239
+ return text;
240
+ }
241
+
242
+ export async function chat(message, config, env) {
243
+ const provider = config.aiProvider || 'gemini';
244
+ const providerConfig = PROVIDER_CONFIG[provider];
245
+
246
+ // Context bilgisi ekle
247
+ const contextInfo = config.systemContext || '';
248
+ const workspaceIdentity = loadWorkspaceIdentity();
249
+ const fullSystemPrompt = VANTUZ_SYSTEM_PROMPT + contextInfo + (workspaceIdentity ? `\n\n## MARKA KİMLİĞİ VE STRATEJİ\nAşağıdaki kurallara MUTLAKA uy:${workspaceIdentity}` : '');
250
+
251
+ log('INFO', `AI isteği: ${provider}`, { message: message.slice(0, 100) });
252
+
253
+ if (!providerConfig) {
254
+ return 'Desteklenmeyen AI sağlayıcı: ' + provider;
255
+ }
256
+
257
+ try {
258
+ if (provider === 'gemini_cli') {
259
+ const { exec } = await import('child_process');
260
+ const { promisify } = await import('util');
261
+ const execAsync = promisify(exec);
262
+
263
+ // Construct command with context
264
+ // Note: gemini cli might not support system prompts directly in args easily,
265
+ // so we'll prepend it to the message or use a temp file if needed.
266
+ // For simplicity, we'll try direct argument.
267
+ const prompt = `System: ${fullSystemPrompt}\n\nUser: ${message}`;
268
+ // Escaping might be tricky, let's keep it simple for now or write to file
269
+ const tmpFile = path.join(os.tmpdir(), `vantuz_prompt_${Date.now()}.txt`);
270
+ fs.writeFileSync(tmpFile, prompt);
271
+
272
+ // Assuming 'gemini' command takes a file or prompt.
273
+ // If it takes prompt as arg: gemini "prompt"
274
+ // If it supports file input: gemini < file
275
+ // Let's try piping: cat file | gemini
276
+
277
+ // Note: The user mentioned "gemini --help" hung, so we must be careful.
278
+ // But they specifically requested gemini_cli support.
279
+
280
+ const { stdout, stderr } = await execAsync(`cat "${tmpFile}" | gemini`, { timeout: 30000 });
281
+
282
+ fs.unlinkSync(tmpFile);
283
+
284
+ if (stderr && !stdout) throw new Error(stderr);
285
+ return stdout.trim();
286
+ }
287
+
288
+ const apiKey = env[`${provider.toUpperCase()}_API_KEY`];
289
+ return await _makeApiRequest(provider, providerConfig, message, apiKey, fullSystemPrompt);
290
+ } catch (error) {
291
+ log('ERROR', `AI hatası: ${error.message}`, { provider });
292
+ return `AI hatası: ${error.message}. /logs komutu ile detay görün.`;
293
+ }
294
+ }
295
+
296
+
297
+
298
+ export default { chat, log, getLogs, clearLogs };