豆包复刻:原生安卓(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:
160
tools/_mcp_python_example.py
Normal file
160
tools/_mcp_python_example.py
Normal file
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
示例:用 Python 写的 MCP 服务(同时支持两种跑法)。
|
||||
|
||||
1) 桌面/服务器 —— stdio 模式:内核把它当子进程起,走标准输入输出收发 JSON-RPC
|
||||
|
||||
{
|
||||
"name": "py-demo",
|
||||
"transport": "stdio",
|
||||
"command": "python",
|
||||
"args": ["C:\\\\path\\\\to\\\\tools\\\\mcp_python_example.py"]
|
||||
}
|
||||
|
||||
2) 安卓端 —— inproc 模式:手机上没有独立 python 可执行文件,起不了子进程。
|
||||
内核(Chaquopy 内嵌的 CPython)会直接 import 这个文件,调用下面的 handle()。
|
||||
|
||||
{ "name": "py-demo", "transport": "inproc", "path": "/sdcard/.../mcp_python_example.py" }
|
||||
|
||||
所以这个文件里:协议实现完全一样,只是入口不同 —— `handle()` 给 inproc 用,
|
||||
`main()` 给 stdio 用。你自己写 MCP 工具时照抄这个骨架即可。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
PROTOCOL_VERSION = "2024-11-05"
|
||||
SERVER_INFO = {"name": "py-demo", "version": "0.1.0"}
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"name": "word_count",
|
||||
"description": "统计一段文本的字数、词数和行数",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"text": {"type": "string", "description": "要统计的文本"}},
|
||||
"required": ["text"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "http_get",
|
||||
"description": "用 Python 抓一个 URL 并返回前 2000 个字符(演示网络能力)",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"url": {"type": "string", "description": "http/https 地址"}},
|
||||
"required": ["url"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "host_info",
|
||||
"description": "返回运行这个 MCP 服务的机器/手机信息",
|
||||
"inputSchema": {"type": "object", "properties": {}},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def call_tool(name, args):
|
||||
"""真正干活的地方。返回字符串就是工具结果。"""
|
||||
if name == "word_count":
|
||||
text = str(args.get("text", ""))
|
||||
return json.dumps(
|
||||
{
|
||||
"chars": len(text),
|
||||
"chars_no_space": len(text.replace(" ", "").replace("\n", "")),
|
||||
"words": len(text.split()),
|
||||
"lines": len(text.splitlines()) or 1,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
if name == "http_get":
|
||||
url = str(args.get("url", ""))
|
||||
if not url.startswith(("http://", "https://")):
|
||||
raise ValueError("url 必须是 http/https")
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "py-demo-mcp/0.1"})
|
||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||
body = resp.read(200_000).decode("utf-8", errors="replace")
|
||||
return body[:2000]
|
||||
|
||||
if name == "host_info":
|
||||
return json.dumps(
|
||||
{
|
||||
"python": sys.version.split()[0],
|
||||
"os": f"{platform.system()} {platform.release()}",
|
||||
"machine": platform.machine(),
|
||||
"cwd": os.getcwd(),
|
||||
"android": "ANDROID_ROOT" in os.environ or "ANDROID_DATA" in os.environ,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
raise ValueError(f"未知工具:{name}")
|
||||
|
||||
|
||||
def handle(request: dict) -> dict:
|
||||
"""
|
||||
处理一条 JSON-RPC 请求,返回响应 dict(通知类请求返回 None)。
|
||||
安卓 inproc 模式直接调它;stdio 模式的 main() 也是调它。
|
||||
"""
|
||||
method = request.get("method")
|
||||
req_id = request.get("id")
|
||||
params = request.get("params") or {}
|
||||
|
||||
# 通知没有 id,不需要回
|
||||
if req_id is None and method and method.startswith("notifications/"):
|
||||
return None
|
||||
|
||||
def ok(result):
|
||||
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
||||
|
||||
def err(code, message):
|
||||
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
|
||||
|
||||
if method == "initialize":
|
||||
return ok(
|
||||
{
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": SERVER_INFO,
|
||||
}
|
||||
)
|
||||
|
||||
if method == "ping":
|
||||
return ok({})
|
||||
|
||||
if method == "tools/list":
|
||||
return ok({"tools": TOOLS})
|
||||
|
||||
if method == "tools/call":
|
||||
name = params.get("name")
|
||||
args = params.get("arguments") or {}
|
||||
try:
|
||||
text = call_tool(name, args)
|
||||
return ok({"content": [{"type": "text", "text": text}], "isError": False})
|
||||
except Exception as exc: # noqa: BLE001 - 错误要回给模型看
|
||||
return ok({"content": [{"type": "text", "text": f"{type(exc).__name__}: {exc}"}], "isError": True})
|
||||
|
||||
return err(-32601, f"不支持的方法:{method}")
|
||||
|
||||
|
||||
def main():
|
||||
"""stdio 模式:一行一条 JSON-RPC。"""
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
request = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
response = handle(request)
|
||||
if response is not None:
|
||||
sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
55
tools/_protocol.py
Normal file
55
tools/_protocol.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
Python 工具协议(所有 tools/*.py 共用)。
|
||||
|
||||
一个工具文件长这样:
|
||||
|
||||
from _protocol import serve
|
||||
|
||||
TOOL = {
|
||||
"name": "calc",
|
||||
"description": "计算数学表达式",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"expression": {"type": "string", "description": "表达式"}},
|
||||
"required": ["expression"],
|
||||
},
|
||||
}
|
||||
|
||||
def run(args):
|
||||
return {"answer": eval_safely(args["expression"])}
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
|
||||
协议约定:
|
||||
* `python tool.py --spec` 输出 TOOL 的 JSON(内核用它做工具发现)
|
||||
* `python tool.py --input args.json` 从文件读参数,往 stdout 打一行 {"ok":true,"result":...}
|
||||
* 参数走文件而不是管道,是为了在限制命名管道的沙箱里也能跑
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
|
||||
|
||||
def serve(tool: dict, run):
|
||||
if "--spec" in sys.argv:
|
||||
json.dump(tool, sys.stdout, ensure_ascii=False)
|
||||
sys.stdout.write("\n")
|
||||
return
|
||||
|
||||
argv = sys.argv
|
||||
if "--input" in argv:
|
||||
with open(argv[argv.index("--input") + 1], encoding="utf-8") as fh:
|
||||
payload = json.load(fh)
|
||||
else:
|
||||
raw = sys.stdin.read().strip()
|
||||
payload = json.loads(raw) if raw else {}
|
||||
|
||||
try:
|
||||
result = run(payload or {})
|
||||
json.dump({"ok": True, "result": result}, sys.stdout, ensure_ascii=False, default=str)
|
||||
sys.stdout.write("\n")
|
||||
except Exception as exc: # noqa: BLE001 - 工具错误要原样回传给模型
|
||||
json.dump({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, sys.stdout, ensure_ascii=False)
|
||||
sys.stdout.write("\n")
|
||||
sys.exit(1)
|
||||
95
tools/calc.py
Normal file
95
tools/calc.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""计算器工具:用 AST 白名单求值,不执行任意代码。"""
|
||||
|
||||
import ast
|
||||
import math
|
||||
import operator
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "calc",
|
||||
"description": "计算数学表达式,支持 + - * / // % ** 与 sqrt/log/sin/cos/exp 等函数。需要口算或精确数值时使用。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"expression": {
|
||||
"type": "string",
|
||||
"description": "要计算的表达式,例如 '(1+2)*3' 或 'sqrt(16)+log(100,10)'",
|
||||
}
|
||||
},
|
||||
"required": ["expression"],
|
||||
},
|
||||
}
|
||||
|
||||
BIN_OPS = {
|
||||
ast.Add: operator.add,
|
||||
ast.Sub: operator.sub,
|
||||
ast.Mult: operator.mul,
|
||||
ast.Div: operator.truediv,
|
||||
ast.FloorDiv: operator.floordiv,
|
||||
ast.Mod: operator.mod,
|
||||
ast.Pow: operator.pow,
|
||||
}
|
||||
UNARY_OPS = {ast.UAdd: operator.pos, ast.USub: operator.neg}
|
||||
|
||||
FUNCS = {
|
||||
"sqrt": math.sqrt,
|
||||
"abs": abs,
|
||||
"round": round,
|
||||
"log": math.log,
|
||||
"log10": math.log10,
|
||||
"log2": math.log2,
|
||||
"exp": math.exp,
|
||||
"sin": math.sin,
|
||||
"cos": math.cos,
|
||||
"tan": math.tan,
|
||||
"floor": math.floor,
|
||||
"ceil": math.ceil,
|
||||
"pow": pow,
|
||||
"min": min,
|
||||
"max": max,
|
||||
"sum": sum,
|
||||
}
|
||||
|
||||
CONSTS = {"pi": math.pi, "e": math.e, "tau": math.tau}
|
||||
|
||||
|
||||
def evaluate(node):
|
||||
if isinstance(node, ast.Expression):
|
||||
return evaluate(node.body)
|
||||
if isinstance(node, ast.Constant):
|
||||
if isinstance(node.value, (int, float)):
|
||||
return node.value
|
||||
raise ValueError("只支持数字常量")
|
||||
if isinstance(node, ast.BinOp) and type(node.op) in BIN_OPS:
|
||||
return BIN_OPS[type(node.op)](evaluate(node.left), evaluate(node.right))
|
||||
if isinstance(node, ast.UnaryOp) and type(node.op) in UNARY_OPS:
|
||||
return UNARY_OPS[type(node.op)](evaluate(node.operand))
|
||||
if isinstance(node, ast.Name):
|
||||
if node.id in CONSTS:
|
||||
return CONSTS[node.id]
|
||||
raise ValueError(f"未知标识符 {node.id}")
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
|
||||
if node.func.id not in FUNCS:
|
||||
raise ValueError(f"不支持的函数 {node.func.id}")
|
||||
return FUNCS[node.func.id](*[evaluate(a) for a in node.args])
|
||||
if isinstance(node, (ast.List, ast.Tuple)):
|
||||
return [evaluate(e) for e in node.elts]
|
||||
raise ValueError("表达式包含不允许的语法")
|
||||
|
||||
|
||||
def run(args):
|
||||
expression = str(args.get("expression", "")).strip()
|
||||
if not expression:
|
||||
raise ValueError("expression 不能为空")
|
||||
if len(expression) > 500:
|
||||
raise ValueError("表达式过长")
|
||||
value = evaluate(ast.parse(expression, mode="eval"))
|
||||
return {"expression": expression, "value": value}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
55
tools/mcp.servers.example.json
Normal file
55
tools/mcp.servers.example.json
Normal file
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"_说明": [
|
||||
"MCP 服务配置示例。复制到你的配置文件里改就行:",
|
||||
" 桌面版(exe):%APPDATA%\\Doubao\\data\\mcp.servers.json(应用内「技能·连接器 → 编辑配置」可直接改)",
|
||||
" 源码版:tools/mcp.servers.json",
|
||||
"字段:name(唯一) / enabled / transport(stdio|http|sse)",
|
||||
" stdio: command + args + env",
|
||||
" http : url + headers(Streamable HTTP,推荐)",
|
||||
" sse : url + headers(官方已标记 deprecated,仅兼容老服务)",
|
||||
"路径支持 ${DOUBAO_DATA} ${APPDATA} ${USERPROFILE} 等占位符。",
|
||||
"Windows 下 command 写 npx/npm/node/pnpm/yarn 会自动包一层 cmd /c。",
|
||||
"改完点「保存并重连」即可生效,不用重启。"
|
||||
],
|
||||
"servers": [
|
||||
{
|
||||
"name": "filesystem",
|
||||
"enabled": false,
|
||||
"transport": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "${USERPROFILE}\\Documents"],
|
||||
"env": {}
|
||||
},
|
||||
{
|
||||
"name": "memory",
|
||||
"enabled": false,
|
||||
"transport": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-memory"],
|
||||
"env": {}
|
||||
},
|
||||
{
|
||||
"name": "everything",
|
||||
"enabled": false,
|
||||
"transport": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-everything"],
|
||||
"env": {}
|
||||
},
|
||||
{
|
||||
"name": "my-remote-server",
|
||||
"enabled": false,
|
||||
"transport": "http",
|
||||
"url": "https://your-host.example.com/mcp",
|
||||
"headers": { "Authorization": "Bearer 你的token" }
|
||||
},
|
||||
{
|
||||
"name": "my-python-server",
|
||||
"enabled": false,
|
||||
"transport": "stdio",
|
||||
"command": "python",
|
||||
"args": ["-m", "my_mcp_server"],
|
||||
"env": { "MY_TOKEN": "xxx" }
|
||||
}
|
||||
]
|
||||
}
|
||||
90
tools/notes.py
Normal file
90
tools/notes.py
Normal file
@@ -0,0 +1,90 @@
|
||||
"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
NOTES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes")
|
||||
|
||||
TOOL = {
|
||||
"name": "notes",
|
||||
"description": "本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条,action=search 关键词搜索。适合记录用户偏好、待办、结论。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["save", "list", "read", "search"], "description": "要做的操作"},
|
||||
"title": {"type": "string", "description": "save 时的标题"},
|
||||
"content": {"type": "string", "description": "save 时的正文"},
|
||||
"query": {"type": "string", "description": "search 时的关键词"},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def ensure_dir():
|
||||
os.makedirs(NOTES_DIR, exist_ok=True)
|
||||
|
||||
|
||||
def slug(title):
|
||||
safe = re.sub(r'[\\/:*?"<>|\s]+', "-", title.strip())[:40]
|
||||
return safe or "note"
|
||||
|
||||
|
||||
def run(args):
|
||||
ensure_dir()
|
||||
action = str(args.get("action", "list")).lower()
|
||||
|
||||
if action == "save":
|
||||
title = str(args.get("title", "")).strip() or "未命名"
|
||||
content = str(args.get("content", ""))
|
||||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
path = os.path.join(NOTES_DIR, f"{stamp}-{slug(title)}.md")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(f"# {title}\n\n{content}\n")
|
||||
return {"saved": os.path.basename(path), "title": title, "chars": len(content)}
|
||||
|
||||
if action == "list":
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
items = []
|
||||
for name in files[:50]:
|
||||
full = os.path.join(NOTES_DIR, name)
|
||||
with open(full, encoding="utf-8") as fh:
|
||||
first = fh.readline().strip().lstrip("# ")
|
||||
items.append({"file": name, "title": first, "bytes": os.path.getsize(full)})
|
||||
return {"count": len(files), "notes": items}
|
||||
|
||||
if action == "read":
|
||||
name = str(args.get("title") or args.get("query") or "").strip()
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
hit = next((f for f in files if name and name in f), None)
|
||||
if not hit:
|
||||
return {"ok": False, "error": f"没找到匹配 {name} 的笔记"}
|
||||
with open(os.path.join(NOTES_DIR, hit), encoding="utf-8") as fh:
|
||||
return {"file": hit, "content": fh.read()[:4000]}
|
||||
|
||||
if action == "search":
|
||||
query = str(args.get("query", "")).strip()
|
||||
if not query:
|
||||
raise ValueError("search 需要 query")
|
||||
hits = []
|
||||
for name in sorted(os.listdir(NOTES_DIR), reverse=True):
|
||||
with open(os.path.join(NOTES_DIR, name), encoding="utf-8") as fh:
|
||||
text = fh.read()
|
||||
if query in text:
|
||||
idx = text.index(query)
|
||||
hits.append({"file": name, "excerpt": text[max(0, idx - 60): idx + 120]})
|
||||
if len(hits) >= 20:
|
||||
break
|
||||
return {"query": query, "hits": hits}
|
||||
|
||||
raise ValueError(f"不支持的 action: {action}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
47
tools/now.py
Normal file
47
tools/now.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""时间工具:当前时间、日期推算、星期几。"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "now",
|
||||
"description": "获取当前日期时间(可指定时区/偏移天数)。问\u201c今天几号\u201d\u201c三天后是星期几\u201d这类问题时使用。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tz_offset": {
|
||||
"type": "number",
|
||||
"description": "相对 UTC 的时区偏移小时数,中国是 8,默认 8",
|
||||
},
|
||||
"offset_days": {
|
||||
"type": "number",
|
||||
"description": "偏移天数,可为负,默认 0",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
WEEKDAYS = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
|
||||
|
||||
|
||||
def run(args):
|
||||
offset = float(args.get("tz_offset", 8) or 0)
|
||||
days = int(args.get("offset_days", 0) or 0)
|
||||
tz = timezone(timedelta(hours=offset))
|
||||
moment = datetime.now(tz) + timedelta(days=days)
|
||||
return {
|
||||
"iso": moment.isoformat(timespec="seconds"),
|
||||
"date": moment.strftime("%Y-%m-%d"),
|
||||
"time": moment.strftime("%H:%M:%S"),
|
||||
"weekday": WEEKDAYS[moment.weekday()],
|
||||
"timezone": f"UTC{offset:+g}",
|
||||
"timestamp": int(moment.timestamp()),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
119
tools/python_run.py
Normal file
119
tools/python_run.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Python 运行工具:直接执行一段 Python 代码或一个 .py 文件,拿回输出。
|
||||
|
||||
- 子进程运行,崩溃不影响内核
|
||||
- 需要联网时可以直接 import requests / httpx / urllib(装了就有)
|
||||
- `libs` 动作可以列出当前环境装了哪些常用库
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "python_run",
|
||||
"description": (
|
||||
"运行一段 Python 代码或指定 .py 文件,返回标准输出/错误。"
|
||||
"适合做计算、数据处理、调用网络接口(requests/httpx/urllib 可用)。"
|
||||
"action=libs 可以查看当前环境装了哪些库。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["run", "libs"],
|
||||
"description": "run=执行代码/文件(默认);libs=列出可用库",
|
||||
},
|
||||
"code": {"type": "string", "description": "要执行的 Python 代码(action=run 时二选一)"},
|
||||
"file": {"type": "string", "description": "要执行的 .py 文件路径(action=run 时二选一)"},
|
||||
"stdin": {"type": "string", "description": "传给脚本的标准输入,可留空"},
|
||||
"timeout": {"type": "number", "description": "超时秒数,默认 60,最大 600"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
WATCHED = [
|
||||
"requests", "httpx", "aiohttp", "urllib3", "bs4", "lxml", "pandas", "numpy",
|
||||
"PIL", "openpyxl", "docx", "pptx", "yaml", "dotenv", "mcp", "flask", "fastapi",
|
||||
]
|
||||
|
||||
|
||||
def python_bin():
|
||||
"""优先用当前解释器;安卓上没有独立解释器时返回 None(由内核在进程内执行)"""
|
||||
if sys.executable and os.path.basename(sys.executable).lower().startswith("python"):
|
||||
return sys.executable
|
||||
for name in ("python3", "python"):
|
||||
for folder in os.environ.get("PATH", "").split(os.pathsep):
|
||||
candidate = os.path.join(folder, name)
|
||||
if os.path.isfile(candidate):
|
||||
return candidate
|
||||
return sys.executable or "python"
|
||||
|
||||
|
||||
def run(args):
|
||||
action = str(args.get("action") or "run").lower()
|
||||
|
||||
if action == "libs":
|
||||
available = []
|
||||
missing = []
|
||||
for name in WATCHED:
|
||||
(available if importlib.util.find_spec(name) else missing).append(name)
|
||||
return {
|
||||
"python": sys.version.split()[0],
|
||||
"executable": sys.executable,
|
||||
"available": available,
|
||||
"missing": missing,
|
||||
"hint": "缺库时可以用 shell 工具执行 pip install <包名>" if missing else "常用库齐全",
|
||||
}
|
||||
|
||||
code = args.get("code")
|
||||
file_path = args.get("file")
|
||||
if not code and not file_path:
|
||||
raise ValueError("code 和 file 至少要给一个")
|
||||
|
||||
timeout = max(1, min(600, int(args.get("timeout", 60) or 60)))
|
||||
stdin_text = args.get("stdin") or ""
|
||||
|
||||
cleanup = None
|
||||
if file_path:
|
||||
target = str(file_path)
|
||||
if not os.path.isfile(target):
|
||||
raise ValueError(f"文件不存在:{target}")
|
||||
else:
|
||||
fd, target = tempfile.mkstemp(suffix=".py", prefix="doubao_run_")
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
fh.write(str(code))
|
||||
cleanup = target
|
||||
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[python_bin(), target],
|
||||
input=stdin_text,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
text=True,
|
||||
errors="replace",
|
||||
cwd=os.path.dirname(os.path.abspath(target)),
|
||||
)
|
||||
return {
|
||||
"exit_code": proc.returncode,
|
||||
"stdout": (proc.stdout or "")[-12000:],
|
||||
"stderr": (proc.stderr or "")[-6000:],
|
||||
}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"error": f"执行超时({timeout}s)", "timeout": True}
|
||||
finally:
|
||||
if cleanup:
|
||||
try:
|
||||
os.unlink(cleanup)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
104
tools/shell.py
Normal file
104
tools/shell.py
Normal file
@@ -0,0 +1,104 @@
|
||||
"""终端工具:在系统 shell 里执行命令,拿回 stdout/stderr。
|
||||
|
||||
- Windows 走 cmd /c,Linux/macOS/Android 走 /bin/sh -c
|
||||
- 有超时和一份最小黑名单(防止一条命令把机器搞没)
|
||||
- 想放开限制:把环境变量 DOUBAO_SHELL_UNSAFE=1 打开(或在设置里关掉限制模式)
|
||||
"""
|
||||
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "shell",
|
||||
"description": (
|
||||
"在用户电脑/手机的终端里执行一条 shell 命令,返回退出码、标准输出和标准错误。"
|
||||
"适合查看文件、跑脚本、装依赖、查系统信息。危险命令会被拦截。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {"type": "string", "description": "要执行的命令,例如 ls -la 或 python --version"},
|
||||
"cwd": {"type": "string", "description": "工作目录,可留空"},
|
||||
"timeout": {"type": "number", "description": "超时秒数,默认 30,最大 300"},
|
||||
},
|
||||
"required": ["command"],
|
||||
},
|
||||
}
|
||||
|
||||
# 明显会搞坏机器的模式(可用 DOUBAO_SHELL_UNSAFE=1 关闭)
|
||||
BLOCKED = [
|
||||
"rm -rf /",
|
||||
"rm -rf /*",
|
||||
"mkfs",
|
||||
"dd if=/dev/zero",
|
||||
":(){:|:&};:",
|
||||
"shutdown",
|
||||
"reboot",
|
||||
"format c:",
|
||||
"del /f /s /q c:\\",
|
||||
"rmdir /s /q c:\\",
|
||||
]
|
||||
|
||||
|
||||
def run(args):
|
||||
command = str(args.get("command", "")).strip()
|
||||
if not command:
|
||||
raise ValueError("command 不能为空")
|
||||
if len(command) > 4000:
|
||||
raise ValueError("命令过长")
|
||||
|
||||
unsafe = os.environ.get("DOUBAO_SHELL_UNSAFE") == "1"
|
||||
if not unsafe:
|
||||
lowered = command.lower()
|
||||
for bad in BLOCKED:
|
||||
if bad in lowered:
|
||||
raise ValueError(f"命令命中黑名单({bad}),已拒绝执行。确实需要请设置 DOUBAO_SHELL_UNSAFE=1")
|
||||
|
||||
timeout = max(1, min(300, int(args.get("timeout", 30) or 30)))
|
||||
cwd = args.get("cwd") or None
|
||||
if cwd and not os.path.isdir(cwd):
|
||||
raise ValueError(f"工作目录不存在:{cwd}")
|
||||
|
||||
system = platform.system().lower()
|
||||
if system == "windows":
|
||||
# ★ Windows 的 cmd 默认用 GBK 输出,直接按 UTF-8 解会变乱码、按 GBK 解又和后端不一致。
|
||||
# 这里强制切到 65001(UTF-8) 再执行,后面统一按 UTF-8 解码。
|
||||
argv = ["cmd", "/c", f"chcp 65001 >nul && {command}"]
|
||||
encoding = "utf-8"
|
||||
via = "cmd"
|
||||
else:
|
||||
argv = ["/bin/sh", "-c", command]
|
||||
encoding = "utf-8"
|
||||
via = "sh"
|
||||
if os.path.exists("/system/bin/sh") or "ANDROID_ROOT" in os.environ:
|
||||
via = "toybox"
|
||||
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
argv,
|
||||
cwd=cwd,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
text=True,
|
||||
encoding=encoding,
|
||||
errors="replace",
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"error": f"命令超时({timeout}s)", "timeout": True}
|
||||
|
||||
return {
|
||||
"exit_code": proc.returncode,
|
||||
"stdout": (proc.stdout or "")[-8000:],
|
||||
"stderr": (proc.stderr or "")[-4000:],
|
||||
"platform": f"{platform.system()} {platform.release()}",
|
||||
"via": via,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
112
tools/weather.py
Normal file
112
tools/weather.py
Normal file
@@ -0,0 +1,112 @@
|
||||
"""天气工具:用 open-meteo 免费接口(无需 API Key)。"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "get_weather",
|
||||
"description": "查询指定城市的当前天气与未来三天预报(open-meteo,无需密钥)。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "城市名,例如 宁波、北京、Tokyo"},
|
||||
"days": {"type": "number", "description": "预报天数 1-7,默认 3"},
|
||||
},
|
||||
"required": ["city"],
|
||||
},
|
||||
}
|
||||
|
||||
GEO_URL = "https://geocoding-api.open-meteo.com/v1/search"
|
||||
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
|
||||
|
||||
WEATHER_CODE = {
|
||||
0: "晴",
|
||||
1: "多云转晴",
|
||||
2: "多云",
|
||||
3: "阴",
|
||||
45: "雾",
|
||||
48: "冻雾",
|
||||
51: "小毛毛雨",
|
||||
53: "毛毛雨",
|
||||
55: "大毛毛雨",
|
||||
61: "小雨",
|
||||
63: "中雨",
|
||||
65: "大雨",
|
||||
71: "小雪",
|
||||
73: "中雪",
|
||||
75: "大雪",
|
||||
80: "阵雨",
|
||||
81: "强阵雨",
|
||||
82: "暴雨",
|
||||
95: "雷阵雨",
|
||||
96: "雷阵雨伴冰雹",
|
||||
99: "强雷暴伴冰雹",
|
||||
}
|
||||
|
||||
|
||||
def http_json(url, params, timeout=15):
|
||||
full = f"{url}?{urllib.parse.urlencode(params)}"
|
||||
req = urllib.request.Request(full, headers={"User-Agent": "doubao-kernel/0.1"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
|
||||
def run(args):
|
||||
city = str(args.get("city", "")).strip()
|
||||
if not city:
|
||||
raise ValueError("city 不能为空")
|
||||
days = max(1, min(7, int(args.get("days", 3) or 3)))
|
||||
|
||||
geo = http_json(GEO_URL, {"name": city, "count": 1, "language": "zh", "format": "json"})
|
||||
results = geo.get("results") or []
|
||||
if not results:
|
||||
return {"ok": False, "error": f"找不到城市 {city}"}
|
||||
place = results[0]
|
||||
|
||||
forecast = http_json(
|
||||
FORECAST_URL,
|
||||
{
|
||||
"latitude": place["latitude"],
|
||||
"longitude": place["longitude"],
|
||||
"current": "temperature_2m,relative_humidity_2m,wind_speed_10m,weather_code",
|
||||
"daily": "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max",
|
||||
"timezone": "auto",
|
||||
"forecast_days": days,
|
||||
},
|
||||
)
|
||||
|
||||
current = forecast.get("current", {})
|
||||
daily = forecast.get("daily", {})
|
||||
return {
|
||||
"city": place.get("name"),
|
||||
"admin": place.get("admin1"),
|
||||
"country": place.get("country"),
|
||||
"current": {
|
||||
"temperature": current.get("temperature_2m"),
|
||||
"humidity": current.get("relative_humidity_2m"),
|
||||
"wind": current.get("wind_speed_10m"),
|
||||
"weather": WEATHER_CODE.get(current.get("weather_code"), current.get("weather_code")),
|
||||
"time": current.get("time"),
|
||||
},
|
||||
"forecast": [
|
||||
{
|
||||
"date": daily.get("time", [])[i],
|
||||
"weather": WEATHER_CODE.get(daily.get("weather_code", [])[i], daily.get("weather_code", [])[i]),
|
||||
"high": daily.get("temperature_2m_max", [])[i],
|
||||
"low": daily.get("temperature_2m_min", [])[i],
|
||||
"rain_probability": daily.get("precipitation_probability_max", [])[i],
|
||||
}
|
||||
for i in range(len(daily.get("time", [])))
|
||||
],
|
||||
"source": "open-meteo.com",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
74
tools/web_fetch.py
Normal file
74
tools/web_fetch.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""网页抓取工具:拉取 URL 正文并转成纯文本(不依赖第三方库)。"""
|
||||
|
||||
import html
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "web_fetch",
|
||||
"description": "抓取一个网页或接口返回的文本内容(自动去 HTML 标签)。需要看某个链接里的内容时使用。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"url": {"type": "string", "description": "要抓取的 http/https 地址"},
|
||||
"max_chars": {"type": "number", "description": "最多返回多少字符,默认 4000,上限 20000"},
|
||||
},
|
||||
"required": ["url"],
|
||||
},
|
||||
}
|
||||
|
||||
SCRIPT_RE = re.compile(r"<(script|style|noscript)[^>]*>.*?</\1>", re.S | re.I)
|
||||
TAG_RE = re.compile(r"<[^>]+>")
|
||||
SPACE_RE = re.compile(r"[ \t\r\f\v]+")
|
||||
BLANK_RE = re.compile(r"\n{3,}")
|
||||
|
||||
|
||||
def strip_html(raw):
|
||||
text = SCRIPT_RE.sub(" ", raw)
|
||||
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.I)
|
||||
text = re.sub(r"</(p|div|li|h[1-6]|tr)>", "\n", text, flags=re.I)
|
||||
text = TAG_RE.sub(" ", text)
|
||||
text = html.unescape(text)
|
||||
text = SPACE_RE.sub(" ", text)
|
||||
text = "\n".join(line.strip() for line in text.split("\n"))
|
||||
return BLANK_RE.sub("\n\n", text).strip()
|
||||
|
||||
|
||||
def run(args):
|
||||
url = str(args.get("url", "")).strip()
|
||||
if not url.startswith(("http://", "https://")):
|
||||
raise ValueError("url 必须是 http/https 开头")
|
||||
limit = max(200, min(20000, int(args.get("max_chars", 4000) or 4000)))
|
||||
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"User-Agent": "Mozilla/5.0 (compatible; doubao-kernel/0.1)",
|
||||
"Accept": "text/html,application/json;q=0.9,*/*;q=0.8",
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=25) as resp:
|
||||
charset = resp.headers.get_content_charset() or "utf-8"
|
||||
raw = resp.read(2_000_000).decode(charset, errors="replace")
|
||||
content_type = resp.headers.get("Content-Type", "")
|
||||
|
||||
if "json" in content_type.lower():
|
||||
body = raw[:limit]
|
||||
else:
|
||||
body = strip_html(raw)[:limit]
|
||||
|
||||
return {
|
||||
"url": url,
|
||||
"content_type": content_type,
|
||||
"truncated": len(body) >= limit,
|
||||
"content": body,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
Reference in New Issue
Block a user