豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows
一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、 不需要另外装 Termux。 安卓端 - 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的 - 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹 - 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端; pty 不可用的 ROM 上自动降级成命令控制台 - APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上 - 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板 - 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎 AI 能力 - 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义 - 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发), 认不出来的一律不发,避免给不支持的厂商发字段直接 400 - MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式 跨端 - 安卓走原生 Compose,Web / Windows 走 Lynx - Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本 自检脚本(都不需要真 Key) - verify-phone.mjs 设备端 24 项验收 - verify-speech.mjs 语音链路 31 项,两份内核各跑一遍 - parity-thinking.mjs 思考强度映射对拍 - probe-settings-wipe.mjs 设置防清空攻击测试 - mock-llm.mjs 假的 OpenAI + 火山语音服务 许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron) 的授权见 LICENSE。
This commit is contained in:
194
server/src/agent.mjs
Normal file
194
server/src/agent.mjs
Normal file
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* 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 }) {
|
||||
const provider = providerInfo(settings);
|
||||
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: settings.provider,
|
||||
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),
|
||||
// 和上面那个 providerInfo 出来的对象不是一回事,别搞混
|
||||
provider: settings.provider,
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user