'use strict'; // ML AI Code (the `mlai` CLI, npm package mlai-code) as a third chat engine. // Headless runs: `mlai -p --output-format stream-json`, the prompt on stdin. // translator() turns its events into the Gemini-style events chat.js already // handles, so both engines share one code path. const fs = require('fs'); const path = require('path'); const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; // Ids `mlai -m` accepts (its own error message lists them). const MODELS = [ { value: '', displayName: 'Varsayılan (Opus 5.5R)', description: 'Zor kodlama işleri için en güçlüsü; Infinite planda sınırsız' }, { value: 'pixis', displayName: 'Pixis', description: 'Hızlı, kodlamaya ayarlı' }, { value: 'pixis-sol', displayName: 'GPT 6.1R Sol', description: 'Çok hızlı, çok büyük bağlam' }, { value: 'ml-ai-forge', displayName: 'ML.ai Forge', description: 'ML.ai\'ın kendi modeli (yalnız metin)' }, { value: 'mlai-coder', displayName: 'ML AI Coder', description: 'Kodlama modeli' }, { value: 'gpt-6-astra', displayName: 'GPT 6 Astra', description: 'Plan kredisi harcar' }, { value: 'grok-4.7', displayName: 'Grok 4.7', description: 'Plan kredisi harcar' }, { value: 'glm-5.3', displayName: 'GLM 5.3', description: 'Plan kredisi harcar' }, { value: 'claude-sonnet-5.5', displayName: 'Claude Sonnet 5.5', description: 'Plan kredisi harcar' }, { value: 'claude-fable-5.2', displayName: 'Claude Fable 5.2', description: 'Plan kredisi harcar' }, ]; // The Storage Bucket drops execute permissions: after a restart the native // binary inside the npm package is no longer executable (spawn EACCES). // Looks for it next to the launcher's package and restores the bit. function ensureExecutable(launcher) { try { let real = fs.realpathSync(launcher); // The launcher may be a small shell shim: "exec node /path/to/mlai-code/bin/mlai.js". if (!/\.js$/.test(real)) { const head = fs.readFileSync(real, 'utf8').slice(0, 2000); const m = /"(\/[^"\n]+\.js)"/.exec(head); if (m && fs.existsSync(m[1])) real = fs.realpathSync(m[1]); } let dir = path.dirname(real); for (let i = 0; i < 4; i += 1, dir = path.dirname(dir)) { const mods = path.join(dir, 'node_modules'); if (!fs.existsSync(mods)) continue; for (const name of fs.readdirSync(mods)) { if (!/^mlai-code-/.test(name)) continue; const native = path.join(mods, name, 'bin', 'mlai'); try { if (fs.existsSync(native)) fs.accessSync(native, fs.constants.X_OK); } catch { fs.chmodSync(native, 0o755); } } return; } } catch { // best effort } } // The launcher unpacks a second native program (mlai-engine) into // ~/.mlai/app//engine; it loses the execute bit the same way. function ensureEngineExecutable() { try { const home = process.env.HOME || require('os').homedir(); const appDir = path.join(home, '.mlai', 'app'); for (const ver of fs.readdirSync(appDir)) { const engine = path.join(appDir, ver, 'engine'); let names; try { names = fs.readdirSync(engine); } catch { continue; } for (const name of names) { if (name !== 'mlai-engine' && !/\.(sh)$/.test(name)) continue; const f = path.join(engine, name); try { fs.accessSync(f, fs.constants.X_OK); } catch { try { fs.chmodSync(f, 0o755); } catch { /* best effort */ } } } } } catch { // best effort } } function findBin(envPath) { for (const dir of String(envPath || process.env.PATH || '').split(path.delimiter)) { if (!dir) continue; const full = path.join(dir, 'mlai'); try { fs.accessSync(full, fs.constants.X_OK); ensureExecutable(full); ensureEngineExecutable(); return full; } catch { // sonraki } } return null; } function signedIn(home) { try { return fs.statSync(path.join(home, '.mlai', 'auth.json')).size > 4; } catch { return false; } } // Working rules for every ML AI run (engine and ask_mlai), sent through the system prompt. const WORK_RULES = [ 'WORKING RULES (always follow):', '- Git: NEVER run git commit, push, tag, merge, rebase, reset, stash or anything else that changes git history or a remote unless the user (or the task text) explicitly asks for it. Leave your changes uncommitted and say so at the end.', '- No destructive or outward actions without explicit permission: deleting many files, rm -rf, overwriting work you did not create, deploying, publishing or sending anything to an external service.', '- Do not repeat yourself: never run the same command or make the same edit again without a change that could alter the result. If an approach failed twice, do not try small variations of it; step back, form a different, simpler hypothesis, or stop and report what you learned and what you need.', '- Start simple: test the most likely, cheapest explanation first. Search (grep) instead of reading huge or minified files line by line.', '- Tests and builds are slow here: run them together and only when a change needs it, not after every small edit.', '- Verify before you say done: at the end run the relevant tests or build once. Never claim success with failing tests or unchecked steps; list what is verified and what is not, honestly.', ].join('\n'); // Headless guided mode cannot ask: auto mode needs an OS sandbox the // container lacks, so it runs with --no-sandbox (the container is the sandbox). function buildArgs({ resumeId, model, permissionMode, systemPrompt }) { const args = ['-p', '--output-format', 'stream-json']; if (permissionMode === 'plan') args.push('--mode', 'plan'); else args.push('--mode', 'auto', '--no-sandbox'); if (model && MODEL_RE.test(model)) args.push('-m', model); if (resumeId) args.push('-r', resumeId); // The instructions go through the system prompt: inside the task text they made ML AI treat the turn as "no changes". args.push('--append-system-prompt', `${WORK_RULES}${systemPrompt ? `\n\n${String(systemPrompt).slice(0, 100000)}` : ''}`); return args; } function parseLine(line) { const s = line.trim(); if (!s.startsWith('{')) return null; try { const ev = JSON.parse(s); return ev && typeof ev.type === 'string' ? ev : null; } catch { return null; } } // mlai events -> Gemini-style events (init, message, text_break, tool_use, // tool_result, usage, error, result). function translator() { let n = 0; let lastTool = null; let answered = false; const toolResult = (output, failed) => { if (!lastTool) return []; const id = lastTool; lastTool = null; return [{ type: 'tool_result', tool_id: id, status: failed ? 'error' : 'success', output: String(output || ''), error: failed ? { message: String(output || 'Hata') } : undefined }]; }; return (ev) => { switch (ev.type) { case 'session': return [{ type: 'init', session_id: String(ev.id || ''), model: String(ev.model || '') }]; case 'thought': { // The engine's own short reasoning note (e.g. how it read the request). const text = String(ev.content || ev.text || '').trim(); return text ? [{ type: 'thinking', text }] : []; } case 'assistant': if (typeof ev.content !== 'string' || !ev.content.trim()) return []; return [{ type: 'message', role: 'assistant', content: ev.content }, { type: 'text_break' }]; case 'tool': { n += 1; lastTool = `ml${n}`; const params = {}; if (ev.target) params.target = String(ev.target); const name = String(ev.name || 'tool'); return [{ type: 'tool_use', tool_name: AGENTWEB_TOOL_RE.test(name) ? `mcp__agentweb__${name}` : name, tool_id: lastTool, parameters: params }]; } case 'command': { n += 1; lastTool = `ml${n}`; return [{ type: 'tool_use', tool_name: 'run_command', tool_id: lastTool, parameters: { command: String(ev.command || '') } }]; } case 'output': return toolResult(ev.output, typeof ev.returncode === 'number' && ev.returncode !== 0); case 'answer': if (typeof ev.content !== 'string' || !ev.content.trim()) return []; answered = true; return [{ type: 'message', role: 'assistant', content: ev.content }]; case 'error': return [{ type: 'error', severity: 'error', message: String(ev.error || ev.message || ev.content || 'Hata') }]; case 'result': { const out = []; const u = ev.usage || {}; const cached = Number(u.cachedTokens) || 0; const calls = Math.max(1, Number(u.calls) || 1); // promptTokens adds up every model call of the turn: the context size is about one call's share. out.push({ type: 'usage', input: Math.max(0, (Number(u.promptTokens) || 0) - cached), cacheRead: cached, output: Number(u.completionTokens) || 0, context: Math.round((Number(u.promptTokens) || 0) / calls) }); if (!answered && typeof ev.text === 'string' && ev.text.trim()) out.push({ type: 'message', role: 'assistant', content: ev.text }); const ok = ev.subtype === 'success' || ev.state === 'completed'; out.push({ type: 'result', status: ok ? 'success' : 'error', error: ok ? undefined : { message: String(ev.error || ev.state || 'error') }, session_id: ev.sessionId || undefined, credits: ev.credits }); return out; } default: return []; } }; } // ML AI names MCP tools without the server prefix; Agent Web's own tools get it back so the chat shows download cards etc. const AGENTWEB_TOOL_RE = /^(share_file|note_file|log_change|ask_gemini|ask_mlai|gemini_image|gemini_quota|pixel_[a-z_]+)$/; function friendlyError(message) { const m = String(message || ''); if (/not signed in|sign in|login|unauthor|401|auth/i.test(m)) return `ML AI Code'a giriş yapılmamış: Terminal sekmesinde \`mlai login\` çalıştırıp hesabı onayla. Ayrıntı: ${m.slice(0, 300)}`; if (/credit|quota|limit|402|429/i.test(m)) return `ML AI Code kredisi ya da kotası doldu. Başka bir model seç ya da daha sonra dene. Ayrıntı: ${m.slice(0, 300)}`; if (/No model/i.test(m)) return `Bu ML AI modeli yok; model menüsünden başka bir model seç. Ayrıntı: ${m.slice(0, 300)}`; return `ML AI hatası: ${m.slice(0, 1500)}`; } function isMissingSession(text) { return /session.{0,30}(not found|no such|unknown|missing)|No session|cannot (find|resume)/i.test(String(text || '')); } module.exports = { WORK_RULES, ensureExecutable, ensureEngineExecutable, MODEL_RE, MODELS, findBin, signedIn, buildArgs, parseLine, translator, friendlyError, isMissingSession };