用户要求:"弹出的网页可再点进去。支持js"。
## JS 开了
`javaScriptEnabled = true`。模型可以在 show_ui 的 HTML 里写 <script>:
canvas 画图、动态生成界面、算完再渲染。实测柱状图正常。
回传用户选择两条路都留着:
· `<button data-doubao-result="值">` —— App 侧字符串替换成 doubao://pick,
由 shouldOverrideUrlLoading 拦。**不依赖 JS**,页面脚本出错也能用
· `Doubao.pick("值")` / `Doubao.close()` —— 给会写 JS 的模型用
## 链接能点进去
http/https 在 WebView 里直接打开(以前 return true 吃掉了),
顶部自动出现「←」返回键;系统返回键也先回退网页、退不了才关界面。
## 安全:JS 开着但 App 接口不漏
开 JS 之后最大的风险是 `addJavascriptInterface` 那个桥 —— 它对**之后加载的
每一个页面**都可见。AI 页面里点个链接落到外部站点,那个站点的脚本就能调我们的桥。
按页面收口:
· 桥只挂在 AI 那一页(初始 load 前挂,保证内联脚本能用)
· 一导航出去立刻摘 —— **实测外部页面里 typeof Doubao === 'undefined'**
· 返回 AI 页时自动恢复(否则"点进去再返回,按钮全失灵")
· 桥只暴露 pick / close 两个方法
· allowFileAccess / allowContentAccess / 混合内容 依然全关
## 这段时序改了三版(每版失败都很隐蔽,记下来)
第一版:load 前挂,导航时摘。
→ 外部页面在 onPageStarted 摘桥**之前**有"已开始加载、桥还在"的窗口。
第二版:只在 onPageFinished 里判 url 才挂。
→ 实测 `Uncaught ReferenceError: Doubao is not defined`。
**onPageFinished 的回调比页面内联 <script> 执行还晚**,
脚本跑的时候桥还没挂上。
第三版(现在):load 前挂 + `payloadLoaded` 标志挡窗口期 +
返回时用**页面里的标记变量**判"是不是我们的页"再重挂。
(用 url 判会漏:从外部页 goBack 回来时 url 不是 about:blank,
表现是"返回后按钮全失灵")
## 验证
新增 `scripts/verify-ai-webview.py`(17 项)钉住上面这些:
JS 开着、危险开关关着、初始 add 在 load 之前、onPageFinished 里有重挂、
重挂走探针而不是 url、**探针返回值按字符串处理**(evaluateJavascript 的回调
就是字符串,按 Boolean 判条件永远不成立 —— 我也踩了)、
http(s) 放行、BackHandler、桥只暴露两个方法。
★ 写这个验证脚本时它自己也错了一次:去注释的正则把字符串里的 `"http://"`
从中间截断,于是"http 有没有放行"永远判不合格。**验证脚本自己有 bug 比没有
验证脚本更坏**(它会让人去改本来对的代码),所以只去块注释、不去行注释。
真机实测(Android 14 x86_64):
初始页 → typeof Doubao = object | pick 可用: true
JS 按钮回传 → 日志 "界面里点了:优先级=中"
点链接 → example.com 在界面里打开,顶部出现返回键
导航后外部页 → typeof Doubao = undefined(桥确实摘了)
返回后再点按钮 → 回传仍然工作(桥恢复了)
228 lines
9.9 KiB
Python
228 lines
9.9 KiB
Python
"""
|
||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||
|
||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||
open 所有工具都交给模型
|
||
restricted 只有白名单里的工具可用(连执行都会再拦一道,见 tools_runtime.execute_tool)
|
||
|
||
同步实现(生成器 + 普通函数),因为上游是 stdlib urllib 的阻塞式读取;
|
||
在 HTTP 服务里每个请求占一个线程,ThreadingHTTPServer 正好够用。
|
||
"""
|
||
|
||
import json
|
||
from typing import Callable, Optional
|
||
|
||
import store
|
||
import tools_runtime
|
||
from providers import stream_chat
|
||
|
||
MAX_TOOL_RESULT_CHARS = 6000
|
||
|
||
|
||
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||
if isinstance(text, str):
|
||
out = text
|
||
else:
|
||
try:
|
||
out = json.dumps(text, ensure_ascii=False)
|
||
except (TypeError, ValueError):
|
||
out = str(text)
|
||
return f'{out[:max_len]}\n…(已截断)' if len(out) > max_len else out
|
||
|
||
|
||
def _max_rounds(settings: dict) -> int:
|
||
raw = settings.get('maxRounds')
|
||
try:
|
||
value = int(float(raw))
|
||
except (TypeError, ValueError):
|
||
value = 6
|
||
if not value: # 0 / 空 都按默认 6 处理(对应 JS 的 `Number(x) || 6`)
|
||
value = 6
|
||
return max(1, min(12, value))
|
||
|
||
|
||
# 界面能力的用法说明。**只在开关打开时**追加到系统提示词(见 run_agent)。
|
||
#
|
||
# ★ 为什么需要这段:`show_ui` / `ask_user` 这类工具的 description 里已经写了
|
||
# 怎么用,但模型**不会主动想到去用** —— 它默认走"用文字回答"这条路。
|
||
# 加一段"什么时候该用",它才会在合适的时候弹界面/弹窗,而不是把一张宽表
|
||
# 硬塞进 markdown。
|
||
#
|
||
# ★ 也不能写得太热情:这三个工具会打断用户,滥用比不用更烦。
|
||
# 所以措辞是"确实用文字说不清时才用"。
|
||
UI_TOOLS_HINT = '\n'.join([
|
||
'界面能力(用户已打开):',
|
||
'8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:',
|
||
' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。',
|
||
' 界面**支持 JavaScript**(canvas 画图、动态渲染都行);要回传用户的选择可以写',
|
||
' `<button data-doubao-result="值">`,或者用 JS 调 `Doubao.pick("值")`。',
|
||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
|
||
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
|
||
' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。',
|
||
])
|
||
|
||
|
||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||
should_stop: Optional[Callable[[], bool]] = None,
|
||
conversation_id: str = '') -> dict:
|
||
"""
|
||
跑一轮完整对话。
|
||
|
||
settings 当前设置
|
||
messages [{role, content}] 历史(不含 system)
|
||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||
emit 事件回调,直接往 SSE 里写
|
||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
|
||
"""
|
||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||
provider = store.provider_info(settings, agent)
|
||
provider_key = provider.get('provider') or settings.get('provider')
|
||
tool_defs = tools_runtime.build_tool_defs(settings)
|
||
max_rounds = _max_rounds(settings)
|
||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||
# ★★ 界面能力的用法**只在开关打开时才追加**。
|
||
#
|
||
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
|
||
# 会存进用户的 settings.json;而开关可能是关的 —— 关着的时候提示词里
|
||
# 还在教模型"你可以用 show_ui",它就会去调,然后收到"工具已关闭"。
|
||
# 按开关动态追加,两边永远一致。
|
||
#
|
||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||
if tools_runtime.ui_tools_enabled(settings):
|
||
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
|
||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||
|
||
emit({
|
||
'type': 'start',
|
||
'provider': provider_key,
|
||
'model': provider.get('model'),
|
||
'tools': len(tool_defs),
|
||
'mode': mode,
|
||
'thinkingLevel': thinking_level,
|
||
'agent': {'id': agent.get('id'), 'name': agent.get('name')} if agent else None,
|
||
})
|
||
|
||
convo = []
|
||
if system_prompt.strip():
|
||
convo.append({'role': 'system', 'content': system_prompt})
|
||
convo.extend(messages)
|
||
|
||
answer = ''
|
||
reasoning_all = ''
|
||
tool_call_count = 0
|
||
usage = None
|
||
|
||
for round_index in range(max_rounds):
|
||
round_text = ''
|
||
tool_calls = []
|
||
|
||
for event in stream_chat(
|
||
# provider 是"提供商名字"(ark/openai),已经按"智能体 > 全局"解析过了
|
||
provider=provider_key,
|
||
base_url=provider.get('baseUrl'),
|
||
api_key=settings.get('apiKey') or '',
|
||
model=provider.get('model'),
|
||
messages=convo,
|
||
tools=tool_defs if tool_defs else None,
|
||
temperature=settings.get('temperature'),
|
||
thinking_level=thinking_level,
|
||
should_stop=should_stop,
|
||
):
|
||
kind = event.get('type')
|
||
if kind == 'text':
|
||
round_text += event['text']
|
||
# 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文,
|
||
# 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。
|
||
answer += event['text']
|
||
emit({'type': 'delta', 'text': event['text'], 'round': round_index})
|
||
elif kind == 'reasoning':
|
||
reasoning_all += event['text']
|
||
emit({'type': 'reasoning', 'text': event['text'], 'round': round_index})
|
||
elif kind == 'tool_calls':
|
||
tool_calls = event.get('toolCalls') or []
|
||
elif kind == 'usage':
|
||
usage = event.get('usage')
|
||
|
||
if not tool_calls:
|
||
emit({
|
||
'type': 'done',
|
||
'content': answer,
|
||
'reasoning': reasoning_all,
|
||
'rounds': round_index + 1,
|
||
'toolCalls': tool_call_count,
|
||
'usage': usage,
|
||
})
|
||
return {
|
||
'content': answer, 'reasoning': reasoning_all,
|
||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||
}
|
||
|
||
convo.append({
|
||
'role': 'assistant',
|
||
'content': round_text or '',
|
||
'tool_calls': [
|
||
{
|
||
'id': tc.get('id'),
|
||
'type': 'function',
|
||
'function': {
|
||
'name': tc.get('name'),
|
||
# 参数原样回传:模型可能给出坏 JSON,服务端往往还能自己纠正
|
||
'arguments': tc.get('argsRaw') or json.dumps(tc.get('args') or {}, ensure_ascii=False),
|
||
},
|
||
}
|
||
for tc in tool_calls
|
||
],
|
||
})
|
||
|
||
for tc in tool_calls:
|
||
tool_call_count += 1
|
||
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
||
# ★ 界面工具(show_ui / ask_user / end_conversation)要拿到"当前是哪次对话",
|
||
# 而工具签名只有 run(args)。所以在这里把上下文放进 thread-local,
|
||
# 执行完立刻清掉 —— HTTP 是每请求一线程,thread-local 天然隔离。
|
||
tools_runtime.push_context(
|
||
conversationId=conversation_id,
|
||
agentId=(agent or {}).get('id') or '',
|
||
toolName=tc.get('name') or '',
|
||
)
|
||
try:
|
||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||
finally:
|
||
tools_runtime.clear_context()
|
||
if result.get('ok'):
|
||
raw = result.get('result')
|
||
payload = truncate('(无输出)' if raw is None else raw)
|
||
else:
|
||
payload = f"调用失败:{result.get('error') or '未知错误'}"
|
||
emit({
|
||
'type': 'tool_result',
|
||
'id': tc.get('id'),
|
||
'name': tc.get('name'),
|
||
'ok': bool(result.get('ok')),
|
||
'result': payload,
|
||
})
|
||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||
|
||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||
emit({
|
||
'type': 'done',
|
||
'content': answer,
|
||
'reasoning': reasoning_all,
|
||
'rounds': max_rounds,
|
||
'toolCalls': tool_call_count,
|
||
'usage': usage,
|
||
'truncated': True,
|
||
})
|
||
return {
|
||
'content': answer, 'reasoning': reasoning_all,
|
||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||
}
|