/** * Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。 * 支持两种安全模式: * open 所有工具都交给模型 * restricted 只有白名单里的工具可用(连执行都会再拦一道) */ import { providerInfo } from './config.mjs'; import { streamChat } from './providers.mjs'; import { discoverPythonTools, runPythonTool, toOpenAITool } from './python-tools.mjs'; import { callMcpTool, isMcpTool, mcpToolDefs } from './mcp.mjs'; /** 汇总当前可用的全部工具 */ export async function listAllTools(settings) { const out = { python: [], mcp: [], errors: [], pythonInfo: null }; if (settings.tools?.python !== false) { const res = await discoverPythonTools(); out.python = res.tools; out.errors = res.errors; out.pythonInfo = res.python; } if (settings.tools?.mcp !== false) { out.mcp = mcpToolDefs(); } return out; } /** 只读工具的名字特征,用来给"限制模式"生成一份保守的默认白名单 */ const READONLY_NAME = /^(read|list|get|search|open|find|fetch|show|describe|query|inspect|calc|now|web_fetch)/i; export function suggestAllowlist(toolNames) { return toolNames.filter((name) => READONLY_NAME.test(name.split('__').pop() || name)); } /** 按安全模式过滤工具 */ export function applySecurity(defs, settings) { const mode = settings.security?.mode || 'open'; if (mode !== 'restricted') return defs; const allow = new Set(settings.security?.allow || []); return defs.filter((def) => allow.has(def.function.name)); } export async function buildToolDefs(settings) { const all = await listAllTools(settings); const defs = [...all.python.map(toOpenAITool), ...all.mcp]; return applySecurity(defs, settings); } /** 执行任意工具(Python 或 MCP),返回可序列化结果 */ export async function executeTool(name, args, settings) { // 限制模式下即使模型硬编出工具名也不能执行 if ((settings?.security?.mode || 'open') === 'restricted') { const allow = settings.security?.allow || []; if (!allow.includes(name)) { return { ok: false, error: `限制模式:工具 ${name} 未授权` }; } } if (isMcpTool(name)) { const res = await callMcpTool(name, args); const parts = []; for (const item of res.content || []) { if (item.type === 'text') parts.push(item.text); else parts.push(`[${item.type}]`); } return { ok: !res.isError, result: parts.join('\n') || '(空结果)' }; } return runPythonTool(name, args); } function truncate(text, max = 6000) { const s = typeof text === 'string' ? text : JSON.stringify(text); return s.length > max ? `${s.slice(0, max)}\n…(已截断)` : s; } /** * 跑一轮完整对话。 * @param {object} opts * @param {object} opts.settings 当前设置 * @param {Array} opts.messages [{role, content}] 历史(不含 system) * @param {object} [opts.agent] 当前智能体(systemPrompt 覆盖全局的) * @param {(event:object)=>void} opts.emit 事件回调 * @param {AbortSignal} [opts.signal] */ export async function runAgent({ settings, messages, agent, emit, signal }) { // ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的, // 留空才继承全局 const provider = providerInfo(settings, agent); const providerKey = provider.provider || settings.provider; const toolDefs = await buildToolDefs(settings); const maxRounds = Math.max(1, Math.min(12, Number(settings.maxRounds) || 6)); const mode = settings.security?.mode || 'open'; const systemPrompt = (agent?.systemPrompt || '').trim() || settings.systemPrompt; const thinkingLevel = settings.thinkingLevel || 'auto'; emit({ type: 'start', provider: providerKey, model: provider.model, tools: toolDefs.length, mode, thinkingLevel, agent: agent ? { id: agent.id, name: agent.name } : null, }); const convo = []; if (systemPrompt?.trim()) { convo.push({ role: 'system', content: systemPrompt }); } convo.push(...messages); let answer = ''; let reasoningAll = ''; let toolCallCount = 0; let usage = null; for (let round = 0; round < maxRounds; round += 1) { let roundText = ''; let toolCalls = []; for await (const ev of streamChat({ // provider 是"提供商名字"(ark/openai),已按"智能体 > 全局"解析过 provider: providerKey, baseUrl: provider.baseUrl, apiKey: settings.apiKey, model: provider.model, messages: convo, tools: toolDefs.length ? toolDefs : undefined, temperature: settings.temperature, thinkingLevel, signal, })) { if (ev.type === 'text') { roundText += ev.text; // 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文, // 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。 answer += ev.text; emit({ type: 'delta', text: ev.text, round }); } else if (ev.type === 'reasoning') { reasoningAll += ev.text; emit({ type: 'reasoning', text: ev.text, round }); } else if (ev.type === 'tool_calls') { toolCalls = ev.toolCalls; } else if (ev.type === 'usage') { usage = ev.usage; } } if (!toolCalls.length) { emit({ type: 'done', content: answer, reasoning: reasoningAll, rounds: round + 1, toolCalls: toolCallCount, usage, }); return { content: answer, reasoning: reasoningAll, rounds: round + 1, toolCalls: toolCallCount, usage }; } convo.push({ role: 'assistant', content: roundText || '', tool_calls: toolCalls.map((tc) => ({ id: tc.id, type: 'function', function: { name: tc.name, arguments: tc.argsRaw || JSON.stringify(tc.args || {}) }, })), }); for (const tc of toolCalls) { toolCallCount += 1; emit({ type: 'tool_call', id: tc.id, name: tc.name, args: tc.args }); let result; try { result = await executeTool(tc.name, tc.args, settings); } catch (err) { result = { ok: false, error: err?.message || String(err) }; } const payload = result.ok ? truncate(result.result ?? '(无输出)') : `调用失败:${result.error || '未知错误'}`; emit({ type: 'tool_result', id: tc.id, name: tc.name, ok: Boolean(result.ok), result: payload }); convo.push({ role: 'tool', tool_call_id: tc.id, content: payload }); } } emit({ type: 'done', content: answer, reasoning: reasoningAll, rounds: maxRounds, toolCalls: toolCallCount, usage, truncated: true, }); return { content: answer, reasoning: reasoningAll, rounds: maxRounds, toolCalls: toolCallCount, usage }; }