Compare commits
114 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 57a9ff4ea1 | |||
| ab063d0674 | |||
| 3d5c02e7a9 | |||
| 4ed6c6a4ee | |||
| f665b83b34 | |||
| 1c07e37932 | |||
| daccc3fd10 | |||
| e62dd7b87b | |||
| 8ccf009958 | |||
| ff1c2e3400 | |||
| bea9debe15 | |||
| 8ac14bdaa2 | |||
| f84c68762b | |||
| 5878ec7a7f | |||
| 77b4f3d74f | |||
| fbfd50eb56 | |||
| 5a7ed44226 | |||
| 0b80ca4830 | |||
| c1da6486a4 | |||
| f877bd6ee8 | |||
| c9e0d689c0 | |||
| cceffd77ec | |||
| 2142e119c6 | |||
| 4ad2ea8e90 | |||
| bbc32dcb46 | |||
| 778c19b088 | |||
| 7e7aea0f48 | |||
| 4effa968ac | |||
| 76d6445ed6 | |||
| b55ce63c6e | |||
| 28a2ede206 | |||
| 1a9229aa75 | |||
| e11e178810 | |||
| 6bcb5d72f8 | |||
| b693f22f61 | |||
| 6e5ea9d3b6 | |||
| 08eecb9e0a | |||
| 182c0005a4 | |||
| 9ff60e684b | |||
| f8ab075f5e | |||
| 56b15f1d19 | |||
| d3a327da26 | |||
| 4b94e3eef3 | |||
| d557dbd2e3 | |||
| a6840f383e | |||
| 9024810558 | |||
| ef42aa70ca | |||
| a87eca329a | |||
| fd72ad06a1 | |||
| 2a25cf623f | |||
| c7fed95650 | |||
| d82c3d3176 | |||
| 4850ea12af | |||
| 2c259d4270 | |||
| 39813985b5 | |||
|
|
f330af963a | ||
|
|
74c87686ef | ||
|
|
5e95e17c3e | ||
|
|
b1dd740b0d | ||
|
|
103c939051 | ||
|
|
885a1f0123 | ||
|
|
ba429e67cd | ||
|
|
5f138be5fa | ||
|
|
f7454c0b60 | ||
|
|
0ad999b6e6 | ||
|
|
e18970c85f | ||
|
|
0fe43d67df | ||
|
|
f789803eae | ||
|
|
52680b9eb7 | ||
|
|
6197b726a5 | ||
|
|
cead531983 | ||
|
|
2601e9ae43 | ||
|
|
8123fff9ca | ||
|
|
c25e94583a | ||
|
|
ecb6e6f924 | ||
|
|
028d67c3ec | ||
| 982c64939b | |||
| b39c23b4dd | |||
| 82fbbe8887 | |||
| 9dc26ed427 | |||
| 85238013a1 | |||
| 97793231c1 | |||
| 59e12a7261 | |||
| dd7bce574e | |||
| 71703c173c | |||
| ed97ec6c63 | |||
| 0f618ba2b0 | |||
| 04f00d1114 | |||
| 754ff80b2b | |||
| 19fe7a6af6 | |||
| 659a212465 | |||
| 626ac89ac8 | |||
| df909f3dd6 | |||
| 5c157c3044 | |||
| 7705a3eb7e | |||
| 52feef35cd | |||
| d88a7aa8aa | |||
| fb105377a9 | |||
| a536b7ba27 | |||
| 519250b109 | |||
| cfdf10a035 | |||
| 7f3dbb4002 | |||
| bec25b71ac | |||
| 19a03724bb | |||
| 5ed71f4f1b | |||
| 3266afd1a4 | |||
| bc6a172888 | |||
| 4883cedfeb | |||
| c8c3dfd59c | |||
| affc407f5e | |||
| 29f29a4524 | |||
| 2a459dd5a4 | |||
| a661102bf1 | |||
| d46008cb11 |
14
AGENTS.md
14
AGENTS.md
@@ -123,6 +123,20 @@ if (editCode.isNotEmpty()) { ... } // 代码编辑
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **会议节点的定义都在 `android/nodekit/`**(独立模块)。
|
||||
节点类型、引脚、算子、配色、几何、形状**只有那一份** ——
|
||||
`MeetingsScreen.kt` 里**不要再写 `when (node.type)` 的长表**(默认标题、颜色、
|
||||
引脚、配置面板标题都从库查)。
|
||||
加一种节点看 [docs/节点库.md](docs/节点库.md) 的清单,改完跑
|
||||
`python scripts/verify-nodekit.py`(它会拿库和 Python 引擎逐项对拍)。
|
||||
- **加一种类型 / 一种能力时,先列一遍所有要同步的地方**。
|
||||
已经反复出现"加了 list 类型,但某些表没跟上":
|
||||
`NODE_DATA_IN` / `NODE_DATA_OUT` / 界面 `inputPins` / `outputPins` /
|
||||
`Ops.ALL` / 变量类型选择器 / 列表渲染。
|
||||
做法:加之前先 grep 一遍所有 `str.*bool.*num` 的地方,逐处过。
|
||||
- **对称的节点要一起改**。读变量和写变量是一对 ——
|
||||
改了读变量的出口类型,**必须同时**改写变量的入口类型。
|
||||
只改一半,用户会说"你不会举一反三的吗"。
|
||||
- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到"
|
||||
这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、
|
||||
预览文字、配置面板、选择器。
|
||||
|
||||
128
README.md
128
README.md
@@ -1,4 +1,4 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
@@ -322,6 +322,126 @@ mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
### 3.12 会议模式的节点(独立库 `:nodekit`)
|
||||
|
||||
会议编辑器是「节点 + 连线」编排多个智能体。**节点是什么形式** —— 有哪些节点、
|
||||
每个节点什么引脚、什么颜色、什么形状、卡片多高、连线从哪儿出去 ——
|
||||
这些定义全在**独立模块 [`android/nodekit/`](android/nodekit/)** 里,只有一份。
|
||||
|
||||
界面上最能看出差别的是**形状**(形状即语法,和积木编辑器同一套思路):
|
||||
|
||||
| 形状 | 含义 |
|
||||
|---|---|
|
||||
| 帽形 | 起点(开始事件) |
|
||||
| 菱形 | 一进两出(判断 / 分支) |
|
||||
| 六边形 | 会绕回来(while 循环) |
|
||||
| 胶囊 | 不执行,只提供值(读变量 / 值 / 运算 / 转换) |
|
||||
| 上边切角 | 到这里结束(最终输出) |
|
||||
| 圆角矩形 | 普通动作 |
|
||||
|
||||
「加节点」面板里每个类型前面有形状缩略图,节点卡片标题栏左边也有一个小徽标。
|
||||
|
||||
定义是**跨语言**的(界面 Kotlin、执行 Python),靠
|
||||
`python scripts/verify-nodekit.py` 逐项对拍守着 —— 节点类型、引脚类型、
|
||||
23 个算子、判断条件、转换类型、引脚方向。
|
||||
|
||||
完整说明看 **[docs/节点库.md](docs/节点库.md)**(含"怎么加一种节点"的清单)。
|
||||
|
||||
### 3.13 超时(全部可调)
|
||||
|
||||
设置页最下面那张卡片 →「超时」,**18 项全都能调**:
|
||||
|
||||

|
||||
|
||||
每一项都带一句说明(写在界面上,不用翻文档),`-` / `+` 按钮加输入框,
|
||||
右上角「恢复默认」。
|
||||
|
||||
| 分组 | 有哪些 |
|
||||
|---|---|
|
||||
| 对话 | 等模型回复、连接空闲上限、心跳间隔、本地接口请求 |
|
||||
| 工具 | 工具执行、shell 命令、跑 Python 代码、Termux 命令、会议节点、自定义节点 |
|
||||
| 界面 | AI 提问等多久、AI 界面等多久、选文件等多久 |
|
||||
| 语音 | 语音合成、语音识别 |
|
||||
| MCP | 单次请求、连接、调用工具 |
|
||||
|
||||
以前这 15 个超时**散在 10 个文件里当模块级常量**,谁也不知道一共有几个 ——
|
||||
"哪些能调、哪些不能调"这个问题根本回答不了。现在收在
|
||||
[`android/kernel/timeouts.py`](android/kernel/timeouts.py) 一份里:
|
||||
|
||||
- 界面上有哪几项、叫什么、默认多少、能填多大、说明写什么 —— **全是内核给的**
|
||||
(`GET /api/timeouts`),加一项只改那个文件,界面自动多出一行
|
||||
- 改完**立刻生效**,不用重启(各处都是现读)
|
||||
- 取值一律夹在每项的 `[min, max]` 里,填 "60秒"、空串、负数、999999 都不会出问题
|
||||
- 「改回默认」= 从配置里**删掉**这一项(不是存一个相同的值),
|
||||
这样以后调默认值时没动过的用户会跟着新默认走
|
||||
- Node 端(Web / exe)有一份对称的 [`server/src/timeouts.mjs`](server/src/timeouts.mjs),
|
||||
`python scripts/verify-timeouts.py` 会把两边**逐项对拍**
|
||||
|
||||
三个"等用户"的项(AI 提问 / AI 界面 / 工具执行)默认是 **0 = 不限时** ——
|
||||
它们的时长取决于你什么时候点,给上限等于"你想久了 AI 就自己编"。
|
||||
|
||||
> 想让 AI 别等太久?把「AI 提问等多久」填个有限值就行。但**不建议**:
|
||||
> 你去忙一会儿回来,AI 已经按自己猜的答案往下跑了,而它并不知道自己在猜。
|
||||
|
||||
---
|
||||
|
||||
### 3.14 智能体系统(记忆 / 情绪 / Token / 世界观 / 技能 / 多模型)
|
||||
|
||||
按《智能体系统需求文档 v1.1》实现。**详细文档在
|
||||
[`docs/智能体系统.md`](docs/智能体系统.md)**(需求项 → 文件对照、数据分界、踩过的坑、
|
||||
接口一览),这里只说结论。
|
||||
|
||||

|
||||
|
||||
**选择界面**:左列表 + 右侧四层叠加(背景图 / 主体边框 / 角色图 / 介绍边框),
|
||||
切换按 0.3s 出 → 0.5s 间隔 → 0.4s 换框 → 0.3s 入的四阶段走(连点立即打断、
|
||||
从眼前画面接着走)。圆形「更多」按钮进用量页。缺哪张图就走内置默认,
|
||||
**最差也是「默认人物 + 默认背景 + 方框边框」**,不会有空白展示区。
|
||||
|
||||

|
||||
|
||||
**六个能力**(都能在界面上单独关掉或不管它):
|
||||
|
||||
| | 一句话 |
|
||||
|---|---|
|
||||
| Token | 按智能体独立统计、**按模型分桶**、输入输出分开;能设上限,用满时发起前拦住并附一句告别 |
|
||||
| 记忆 | 无上限、AI 自己记,**用户能改能删**(兜底);「必须保留」的 AI 改不动 |
|
||||
| 情绪 | 每个智能体一个当前情绪,写进提示词;**绑同一世界观也不共享**(需求明确要求) |
|
||||
| 世界观 | 独立资源。绑了它的智能体**共用一份记忆**,但**只能改自己写的**那几条 |
|
||||
| 技能 | 纯文本手册,按绑定顺序注入;内置那份默认就生效 |
|
||||
| 多模型 | 全局模型列表 + UUID 引用。引用了就**整组覆盖**(地址/Key/模型一起换) |
|
||||
|
||||
**两处需要解释的设计**:
|
||||
|
||||
1. **数据分界**:记忆/情绪/Token/Skill 绑定进 SQLite(条目无上限、每轮全量读、
|
||||
要检索、要按行改删),其余仍是 JSON(量级小、要人肉可读)。
|
||||
判据写在 `android/kernel/agentdb.py` 文件头,加新数据时先按那张表判一次。
|
||||
|
||||
2. **幻觉调用检测**:模型很容易在"该记东西"的时候只在正文里说一句"我记住了"
|
||||
—— 用户当场看不出来,下次发现它完全不记得,信任就没了。所以由程序比对
|
||||
「说了什么」和「做了什么」,对不上就在那条回复下面挂一条警示。
|
||||
判宽比判窄更糟(误伤几次之后用户就不看那个警示了),所以只收明确句式。
|
||||
|
||||
**验证**(都不需要装机、不需要网络):
|
||||
|
||||
```bash
|
||||
python scripts/probe-agent-system.py # 12 节 70+ 项:UUID、记忆、限权、注入顺序、
|
||||
# 20 多个接口、包的边界、多模型解析
|
||||
python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calling 的降级
|
||||
```
|
||||
|
||||
> ⚠️ **改完内核记得跑一次 `py_compile`**:Gradle 不编译 Python
|
||||
> (Chaquopy 只是把 `.py` 打进 APK),语法错误要等手机上启动内核才炸,
|
||||
> 而那时整个 App 不可用。`scripts/build-apk.mjs` 里加了这道闸,
|
||||
> 但它拦的是"打包",不是"你刚改的那一行"。
|
||||
|
||||
**全部界面和入口在哪**:[`docs/界面总览.md`](docs/界面总览.md) ——
|
||||
把 App 里所有界面画成树(含"每个界面从哪进"),而且
|
||||
`python scripts/audit-ui-tree.py` 会拿它**和源码对拍**:
|
||||
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
|
||||
|
||||
**还没做的**:Node 端(Web / exe)的智能体系统仍是旧的那套 ——
|
||||
按仓库约定"引擎改了另一端必须跟上",这是欠账。
|
||||
|
||||
|
||||
---
|
||||
@@ -593,6 +713,12 @@ node scripts/device-state.mjs <serial> # 看设备内核当前设
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-timeouts.py # 超时清单:边界 + 没有硬编码 + Node 端对拍
|
||||
python scripts/verify-seed-tools.py # 内置工具的播种/覆盖规则
|
||||
python scripts/verify-ui-tools.py # interface 工具的参数与提示词
|
||||
python scripts/verify-extract-urls.py # 「打开网页」的链接抽取
|
||||
python scripts/verify-ai-webview.py # AI 界面里的 JS 桥
|
||||
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||
|
||||
# mock(不消耗额度)
|
||||
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 201
|
||||
versionName = "2.0.1"
|
||||
versionCode = 278
|
||||
versionName = "2.0.78"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -39,14 +39,77 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lint 不挡 release 构建。
|
||||
*
|
||||
* ★ 唯一让它报错的是 `targetSdk = 28` 那条:
|
||||
*
|
||||
* Error: Google Play requires that apps target API level 33 or higher.
|
||||
* [ExpiredTargetSdkVersion]
|
||||
*
|
||||
* 而 **28 是必须的**,不能改 —— Android 10 起 targetSdk>=29 的应用
|
||||
* 不允许执行自己数据目录里的二进制(W^X 限制),而 bash / python /
|
||||
* dpkg 全在 /data/data/<包名>/files/usr 里。Termux 自己也是锁 28
|
||||
* 才活下来的。这条 lint 检查针对的是"上架 Google Play",而我们
|
||||
* 这个 App 本来就上不了架(自签证书 + 这个 targetSdk)。
|
||||
*
|
||||
* ★ 设 `abortOnError = false` 而不是 `checkReleaseBuilds = false`:
|
||||
* lint **照常跑**、报告照常生成,只是不因为这一条把构建打断。
|
||||
* 别的真问题仍然看得到。
|
||||
*/
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名。
|
||||
*
|
||||
* ★ 用的是**原来那个 debug 证书**(fingerprint 83:28:15:D6…),
|
||||
* 只是把它**拷进了仓库**,并且**显式开了 v1/v2/v3**。
|
||||
*
|
||||
* 为什么这么做(踩过两次,记下来):
|
||||
*
|
||||
* 1. **不能随便换证书**。Android 不允许同包名不同签名覆盖安装 ——
|
||||
* 换了之后用户必须**先卸载**(数据全丢)。
|
||||
* 我第一次"修签名问题"时顺手换了一把新证书,结果老用户装不上,
|
||||
* 报"已安装了签名冲突的应用"。**修 A 问题不能引入 B 问题。**
|
||||
*
|
||||
* 2. **缺 v1(JAR)签名会让很多安装器拒绝**。Android 7+ 自己装没问题,
|
||||
* 但从远程传过去再装(MT 管理器 / UU远程 之类)会报
|
||||
* "解析失败:安装包没有签名文件"。所以 v1/v2/v3 全开。
|
||||
*
|
||||
* 3. **debug 证书默认在 ~/.android/ 里,换台机器就变**。
|
||||
* 拷进仓库(连密码一起)之后,**哪台机器构建出来的指纹都一样**,
|
||||
* 能互相覆盖安装。
|
||||
*
|
||||
* ★ 密码是 debug 证书的标准密码,**它不是秘密**。
|
||||
* 自签证书只保证"指纹稳定、能覆盖安装",不证明"是谁发的"。
|
||||
*/
|
||||
signingConfigs {
|
||||
create("doubao") {
|
||||
storeFile = file("../doubao-release.jks")
|
||||
storePassword = "android"
|
||||
keyAlias = "androiddebugkey"
|
||||
keyPassword = "android"
|
||||
enableV1Signing = true
|
||||
enableV2Signing = true
|
||||
enableV3Signing = true
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
signingConfig = signingConfigs.getByName("doubao")
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
}
|
||||
debug {
|
||||
// debug 包也用同一把 —— 本地调试的包和发出去的包能互相覆盖安装
|
||||
signingConfig = signingConfigs.getByName("doubao")
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
@@ -118,6 +181,10 @@ chaquopy {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// 会议节点定义库:节点类型 / 引脚 / 算子 / 几何 / 形状的唯一一份定义
|
||||
// (以前散在 MeetingsScreen.kt 里,同一样东西写 6 遍 —— 见 docs/节点库.md)
|
||||
implementation(project(":nodekit"))
|
||||
|
||||
// 原生 UI 用 Compose
|
||||
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||
implementation("androidx.compose.ui:ui")
|
||||
|
||||
@@ -17,7 +17,17 @@
|
||||
<!-- 通话时想在被叫/接听场景抢音频焦点用得上;多数机型不加也行 -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
|
||||
<!-- Android 11+ 用于判断 Termux 是否安装 -->
|
||||
<!-- ★★ 发通知(用户要求"还可以发送通知")。
|
||||
Android 13(API 33) 起这是**运行时权限**,新装的 App **默认是拒绝的** ——
|
||||
不申请的话 `NotificationManager.notify()` 不报错但通知**不显示**。
|
||||
实测踩到:渠道建出来了(importance=3),但 App 级 `importance=NONE`,
|
||||
通知栏里什么都没有,而调用方还以为成功了。
|
||||
声明了不算完,还得在运行时 requestPermissions —— 见 MainActivity。 -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- 通知带声音/震动需要它(Android 13+ 才有这个权限名) -->
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
|
||||
<!-- Android 11+ 包可见性:不声明的话查不到别的 App,也就「打开手机 app」不了 -->
|
||||
<queries>
|
||||
<package android:name="com.termux" />
|
||||
<!-- 系统语音识别服务:不声明的话 Android 11+ 查不到可用引擎 -->
|
||||
@@ -28,6 +38,13 @@
|
||||
<intent>
|
||||
<action android:name="android.intent.action.TTS_SERVICE" />
|
||||
</intent>
|
||||
<!-- ★「打开手机 app」需要的:列出所有能启动的 App。
|
||||
Android 11 起不声明这条 queries,queryIntentActivities 只会返回空列表,
|
||||
表现是"已安装的 App 一个都找不到"。 -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<!-- 加速度计/陀螺仪等传感器不需要权限 -->
|
||||
@@ -55,5 +72,19 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- ★★ 读手机通知(用户要求的工具)。
|
||||
Android **没有**"读取通知"的运行时权限 —— 唯一合法的路是让用户
|
||||
手动去「设置 → 通知 → 通知使用权」勾上本 App,系统才会把通知流过来。
|
||||
不声明这个 Service,权限开了也收不到任何东西。 -->
|
||||
<service
|
||||
android:name=".DoubaoNotificationListener"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
261
android/app/src/main/java/com/doubao/lynxclone/AppShortcuts.kt
Normal file
261
android/app/src/main/java/com/doubao/lynxclone/AppShortcuts.kt
Normal file
@@ -0,0 +1,261 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.Intent
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★★ 「预设快捷入口」—— 一句话直达某个 App 的某个页面。
|
||||
*
|
||||
* 用户要求:"打开应用工具支持打开活动,并预设几个比如微信对话,支付宝菜鸟"
|
||||
*
|
||||
* ## 为什么每个预设是一**串**候选而不是一个
|
||||
*
|
||||
* 深链 scheme 和 Activity 名字**都会随 App 版本变**。
|
||||
* 只赌一个的话,用户那边 App 一升级这个功能就静默失效了 ——
|
||||
* 而且报的还是"打不开",查起来很费劲。
|
||||
*
|
||||
* 所以每个预设给一组候选,**按顺序试,第一个成的算**:
|
||||
* 1. 深链(最稳,scheme 通常不变)
|
||||
* 2. 指定 Activity(有的页面有独立 Activity)
|
||||
* 3. 退回主界面(保证"至少把 App 打开了",不会让用户觉得功能坏了)
|
||||
*
|
||||
* ★ 每个候选都标了 `kind`,返回里如实说**是哪一个成的** ——
|
||||
* 万一以后要调,一眼看得出走到哪一层了。
|
||||
*
|
||||
* ## ★ 诚实说明:这些 scheme 没法离线验证
|
||||
*
|
||||
* 我没法在没有真机 App 的情况下确认 `weixin://` 一定进"聊天列表"、
|
||||
* `alipays://platformapi/startapp?appId=200011235` 一定开菜鸟。
|
||||
* 这些值来自公开的深链惯例,**大多数情况可用,但 App 大版本更新后可能失效**。
|
||||
*
|
||||
* 所以设计上:
|
||||
* · 全部走"多候选 + 退回主界面",失效也不会让功能变成"点了没反应"
|
||||
* · 返回里带 `how`(哪一条成的)和 `tried`(试过哪些),方便排查
|
||||
* · 用户可以在 `tools/apps.py` 的说明里看到怎么改用自己手机上的值
|
||||
*/
|
||||
object AppShortcuts {
|
||||
|
||||
private const val WECHAT = "com.tencent.mm"
|
||||
private const val ALIPAY = "com.eg.android.AlipayGphone"
|
||||
private const val TAOBAO = "com.taobao.taobao"
|
||||
private const val QQ = "com.tencent.mobileqq"
|
||||
private const val DOUYIN = "com.ss.android.ugc.aweme"
|
||||
|
||||
/**
|
||||
* 一个候选:怎么打开。
|
||||
*
|
||||
* ★ 可见性跟着用的地方走:`run()` 的参数/返回类型里出现了它,
|
||||
* 所以它至少要**一样宽**。Kotlin 不允许 public 函数暴露 private/internal 类型
|
||||
* (报 "Function 'public' exposes its 'private-in-class' return type")。
|
||||
* 这个坑连着踩了两次(先 private 后 internal),索性都用默认的 public。
|
||||
*/
|
||||
data class Shot(
|
||||
val kind: String, // uri / activity / main
|
||||
val pkg: String,
|
||||
val uri: String = "",
|
||||
val cls: String = "",
|
||||
val note: String = "",
|
||||
)
|
||||
|
||||
/** 一个预设:名字 + 关键词 + 一串候选 */
|
||||
data class Preset(
|
||||
val id: String,
|
||||
val label: String,
|
||||
val keywords: List<String>,
|
||||
val shots: List<Shot>,
|
||||
)
|
||||
|
||||
private fun p(id: String, label: String, kw: List<String>, vararg shots: Shot) =
|
||||
Preset(id, label, kw, shots.toList())
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
// 预设表
|
||||
//
|
||||
// ★ 加新预设只要往这个列表里塞一条 —— 工具说明、列表接口都是从这里生成的,
|
||||
// 不存在"两边不一致"的问题(这个仓库里抄两份的坑踩过好几次)。
|
||||
// ------------------------------------------------------------------ //
|
||||
|
||||
private val PRESETS: List<Preset> = listOf(
|
||||
// ---------------- 微信 ----------------
|
||||
p(
|
||||
"wechat", "微信(主界面)", listOf("微信", "wechat", "weixin"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "微信主 scheme"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-chat", "微信 · 聊天列表", listOf("微信聊天", "微信对话", "聊天列表", "wechat chat"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/chat", note = "聊天列表"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-scan", "微信 · 扫一扫", listOf("微信扫一扫", "扫码", "扫一扫", "wechat scan"),
|
||||
Shot("uri", WECHAT, uri = "weixin://scanqrcode", note = "扫一扫"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-moments", "微信 · 朋友圈", listOf("朋友圈", "moments", "wechat moments"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/moments", note = "朋友圈"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-pay", "微信 · 收付款", listOf("微信支付", "微信收付款", "付款码", "wechat pay"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/offline", note = "收付款(付款码)"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
|
||||
// ---------------- 支付宝 ----------------
|
||||
p(
|
||||
"alipay", "支付宝(主界面)", listOf("支付宝", "alipay", "zhifubao"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "支付宝主 scheme"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-scan", "支付宝 · 扫一扫", listOf("支付宝扫一扫", "支付宝扫码", "alipay scan"),
|
||||
// 200011235 是支付宝"扫一扫"的公开 appId;后面那个通用端口是备选
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=200011235", note = "扫一扫"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?saId=10000007", note = "通用启动端口"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-pay", "支付宝 · 付款码", listOf("支付宝付款", "支付宝收付款", "付款码", "alipay pay"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=20000056", note = "付款码"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-cainiao", "支付宝 · 菜鸟裹裹", listOf("菜鸟", "菜鸟裹裹", "快递", "cainiao"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=200011235&url=%2Fwww%2Fcainiao.html", note = "菜鸟"),
|
||||
// 菜鸟也有独立 App,装了就直接开它
|
||||
Shot("uri", "com.cainiao.wireless", uri = "cainiao://", note = "菜鸟独立 App"),
|
||||
Shot("main", "com.cainiao.wireless", note = "菜鸟独立 App 主界面"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-card", "支付宝 · 卡包", listOf("卡包", "支付宝卡包", "alipay card"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=20000021", note = "卡包"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
|
||||
// ---------------- 别的常用的 ----------------
|
||||
p(
|
||||
"taobao", "淘宝", listOf("淘宝", "taobao"),
|
||||
Shot("uri", TAOBAO, uri = "taobao://", note = "淘宝主 scheme"),
|
||||
Shot("main", TAOBAO),
|
||||
),
|
||||
p(
|
||||
"qq", "QQ", listOf("qq", "腾讯qq"),
|
||||
Shot("uri", QQ, uri = "mqq://", note = "QQ 主 scheme"),
|
||||
Shot("main", QQ),
|
||||
),
|
||||
p(
|
||||
"douyin", "抖音", listOf("抖音", "douyin", "tiktok"),
|
||||
Shot("uri", DOUYIN, uri = "snssdk1128://", note = "抖音主 scheme"),
|
||||
Shot("main", DOUYIN),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* 全部预设。
|
||||
*
|
||||
* ★ Context 当**参数**传,不存一个可空的全局变量 ——
|
||||
* 第一版用 `@Volatile var appCtx`,于是编译期类型是 `Context?`,
|
||||
* 每次用都要解包,还容易忘了先赋值(那样"装了没有"永远返回 false)。
|
||||
* 传参是编译期就能保证的。
|
||||
*/
|
||||
fun all(ctx: android.content.Context): List<Map<String, Any>> = PRESETS.map { p ->
|
||||
mapOf(
|
||||
"id" to p.id,
|
||||
"label" to p.label,
|
||||
"keywords" to p.keywords,
|
||||
// 只看第一个候选那个 App 装了没有 —— 后面的候选可能包含没装的备选
|
||||
"installed" to PhoneOps.isInstalled(ctx, p.shots.first().pkg),
|
||||
"app" to p.shots.first().pkg,
|
||||
)
|
||||
}
|
||||
|
||||
fun ids(): List<String> = PRESETS.map { it.id }
|
||||
|
||||
/** 按 id 或关键词找一个预设 */
|
||||
fun find(query: String): Preset? {
|
||||
val q = query.trim().lowercase()
|
||||
if (q.isEmpty()) return null
|
||||
PRESETS.firstOrNull { it.id.equals(q, ignoreCase = true) }?.let { return it }
|
||||
PRESETS.firstOrNull { it.label.lowercase() == q }?.let { return it }
|
||||
PRESETS.firstOrNull { it.keywords.any { k -> k.lowercase() == q } }?.let { return it }
|
||||
// 先匹配 label 里的,再匹配关键词 —— 避免"微信"先命中"微信扫一扫"那种歧义
|
||||
PRESETS.firstOrNull { it.label.lowercase().contains(q) }?.let { return it }
|
||||
return PRESETS.firstOrNull { p ->
|
||||
p.keywords.any { k -> k.lowercase().contains(q) || q.contains(k.lowercase()) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一个预设:按候选顺序试,第一个成的算。
|
||||
*
|
||||
* ★ 全失败时返回**试过哪些 + 各自为什么失败** ——
|
||||
* 只回一句"打不开"的话,用户和模型都不知道下一步该干嘛。
|
||||
*/
|
||||
fun run(ctx: android.content.Context, preset: Preset): JSONObject {
|
||||
val tried = JSONArray()
|
||||
for (shot in preset.shots) {
|
||||
if (!PhoneOps.isInstalled(ctx, shot.pkg)) {
|
||||
tried.put(JSONObject().put("kind", shot.kind).put("pkg", shot.pkg)
|
||||
.put("error", "没装这个 App"))
|
||||
continue
|
||||
}
|
||||
val err: String? = when (shot.kind) {
|
||||
"uri" -> PhoneOps.launchUri(ctx, shot.uri)
|
||||
"activity" -> PhoneOps.launchActivity(ctx, shot.pkg, shot.cls)
|
||||
else -> if (PhoneOps.launchApp(ctx, shot.pkg, mainActivityOf(ctx, shot.pkg))) {
|
||||
null
|
||||
} else {
|
||||
"启动主界面失败"
|
||||
}
|
||||
}
|
||||
if (err == null) {
|
||||
return JSONObject()
|
||||
.put("ok", true)
|
||||
.put("shortcut", preset.id)
|
||||
.put("label", preset.label)
|
||||
.put("how", shot.kind)
|
||||
.put("detail", shot.note)
|
||||
.put("tried", tried)
|
||||
}
|
||||
tried.put(JSONObject().put("kind", shot.kind)
|
||||
.put("detail", shot.note)
|
||||
.put("error", err))
|
||||
}
|
||||
return JSONObject()
|
||||
.put("error", "「${preset.label}」的所有打开方式都没成功")
|
||||
.put("tried", tried)
|
||||
.put(
|
||||
"hint",
|
||||
"多半是这个 App 没装,或者它的版本改了深链。可以先用 action=open 打开 App 主界面," +
|
||||
"或者在 tools/apps.py 里把这个预设的链接改成你手机上的实际值。",
|
||||
)
|
||||
}
|
||||
|
||||
/** 拿一个包的 launcher activity */
|
||||
fun mainActivityOf(ctx: android.content.Context, pkg: String): String {
|
||||
val i = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(android.content.Intent.CATEGORY_LAUNCHER)
|
||||
.setPackage(pkg)
|
||||
val list = if (android.os.Build.VERSION.SDK_INT >= 33) {
|
||||
ctx.packageManager.queryIntentActivities(
|
||||
i, android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ctx.packageManager.queryIntentActivities(i, 0)
|
||||
}
|
||||
return list.firstOrNull()?.activityInfo?.name.orEmpty()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.app.Notification
|
||||
import android.os.Bundle
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* ★★ 读手机通知 —— 用户要求"加个读取手机通知的工具"。
|
||||
*
|
||||
* ## 为什么必须是个 Service
|
||||
*
|
||||
* Android **没有**"读取通知"的运行时权限。唯一合法的路是让用户手动去
|
||||
* 「设置 → 通知 → 通知使用权」里把这个 App 勾上,系统才会把通知流给我们。
|
||||
* 这个 Service 就是那个接收端 —— 不声明它,权限开了也收不到任何东西。
|
||||
*
|
||||
* ## 不落盘,只在内存里留最近的
|
||||
*
|
||||
* 通知是**高度隐私**的内容(验证码、私信、银行短信都在里面)。
|
||||
* 写进磁盘意味着卸载前一直躺在那儿,也可能被别的工具读到。
|
||||
* 只留内存,进程一死就没了 —— 用户要"读最近的通知"这个需求完全够用,
|
||||
* 而隐私面小得多。
|
||||
*
|
||||
* ★ 上限 [MAX_KEEP] 条:用户一天能收几百条通知,不限量会把内存吃满。
|
||||
*/
|
||||
class DoubaoNotificationListener : NotificationListenerService() {
|
||||
|
||||
override fun onListenerConnected() {
|
||||
super.onListenerConnected()
|
||||
connected = true
|
||||
instance = this
|
||||
// ★ 连上的瞬间就把当前挂着的通知同步进来 —— 不然用户装完 App 立刻问
|
||||
// "我最近收到什么通知了",答案是空的(那些通知在他装 App 之前就收到了)
|
||||
syncActive()
|
||||
Log.i(TAG, "通知使用权已连接,当前挂着 ${items.size} 条")
|
||||
}
|
||||
|
||||
override fun onListenerDisconnected() {
|
||||
super.onListenerDisconnected()
|
||||
connected = false
|
||||
if (instance === this) instance = null
|
||||
Log.i(TAG, "通知使用权已断开")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
if (instance === this) instance = null
|
||||
}
|
||||
|
||||
override fun onNotificationPosted(sbn: StatusBarNotification?) {
|
||||
val n = sbn ?: return
|
||||
try {
|
||||
// ★ 跳过我们自己的通知(不然"AI 读通知"会把 App 自己的提示也读进去)
|
||||
if (n.packageName == packageName) return
|
||||
record(n, removed = false)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "记通知失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification?) {
|
||||
val n = sbn ?: return
|
||||
// ★ 只标成"已消失",**不删掉** —— 用户问"刚才那条验证码呢"的时候,
|
||||
// 通知早就被划掉了,删了就直接查不到了。
|
||||
try {
|
||||
val key = n.key ?: return
|
||||
items[key]?.let { it.removed = true; it.atRemoved = System.currentTimeMillis() }
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记一条通知。
|
||||
*
|
||||
* ★ 可见性要 **internal**(不能 private):`companion object` 里的
|
||||
* `syncActive()` 要调它,而 Kotlin 的 private 成员**只对同一个类体可见**,
|
||||
* 伴生对象不算 —— 写成 private 会报"cannot access"。
|
||||
*/
|
||||
internal fun record(n: StatusBarNotification, removed: Boolean) {
|
||||
val extras: Bundle = n.notification?.extras ?: Bundle()
|
||||
val title = extras.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
|
||||
val text = extras.getCharSequence(Notification.EXTRA_TEXT)?.toString().orEmpty()
|
||||
val big = extras.getCharSequence(Notification.EXTRA_BIG_TEXT)?.toString().orEmpty()
|
||||
val sub = extras.getCharSequence(Notification.EXTRA_SUB_TEXT)?.toString().orEmpty()
|
||||
|
||||
val item = Item(
|
||||
key = n.key ?: "${n.packageName}:${n.postTime}",
|
||||
pkg = n.packageName.orEmpty(),
|
||||
app = appLabel(n.packageName.orEmpty()),
|
||||
title = title,
|
||||
text = if (big.isNotBlank()) big else text,
|
||||
subText = sub,
|
||||
at = if (n.postTime > 0) n.postTime else System.currentTimeMillis(),
|
||||
removed = removed,
|
||||
atRemoved = 0L,
|
||||
)
|
||||
// ★ 标题和正文都空的就**不进列表**。
|
||||
//
|
||||
// 这类通知真实存在:媒体控制、正在进行的下载、某些 App 的纯图标通知 ——
|
||||
// 它们的文字要么在 RemoteViews 里(`extras` 取不到),要么压根没有。
|
||||
// 留着的话用户/模型会看到一条"什么都没有"的条目,纯噪音。
|
||||
// (实测:`cmd notification post` 发的测试通知就有一条是这样的。)
|
||||
if (item.title.isBlank() && item.text.isBlank()) return
|
||||
|
||||
items[item.key] = item
|
||||
|
||||
// 超上限就丢最旧的。用 postTime 排(key 是字符串,排不了时间序)
|
||||
if (items.size > MAX_KEEP) {
|
||||
items.values.sortedBy { it.at }.take(items.size - MAX_KEEP).forEach { items.remove(it.key) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun appLabel(pkg: String): String = try {
|
||||
val pm = packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString()
|
||||
} catch (_: Throwable) {
|
||||
pkg
|
||||
}
|
||||
|
||||
data class Item(
|
||||
val key: String,
|
||||
val pkg: String,
|
||||
val app: String,
|
||||
val title: String,
|
||||
val text: String,
|
||||
val subText: String,
|
||||
val at: Long,
|
||||
var removed: Boolean,
|
||||
var atRemoved: Long,
|
||||
)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DoubaoNotif"
|
||||
private const val MAX_KEEP = 200
|
||||
|
||||
/** 最近的通知(内存里,进程死了就没了 —— 见类注释里的隐私考虑) */
|
||||
private val items = ConcurrentHashMap<String, Item>()
|
||||
|
||||
/**
|
||||
* 当前活着的 service 实例。
|
||||
*
|
||||
* ★ 必须有它:`getActiveNotifications()` 是 **service 自己**的方法,
|
||||
* 不是静态的。没有实例就调不到,也就拿不到"系统里现在挂着哪些通知"。
|
||||
*/
|
||||
@Volatile
|
||||
private var instance: DoubaoNotificationListener? = null
|
||||
|
||||
/** 通知使用权连上了没有 */
|
||||
@Volatile
|
||||
var connected: Boolean = false
|
||||
|
||||
/**
|
||||
* ★★★ 把系统里**当前还挂着的**通知同步进来。
|
||||
*
|
||||
* ## 为什么必须有这个(用户报"还是没有读到"的根因)
|
||||
*
|
||||
* 第一版只在 `onNotificationPosted` 里记 —— 也就是说**只有本进程活着的
|
||||
* 那段时间收到的通知才算数**。而进程一重启(用户升级 App、或者系统杀后台)
|
||||
* 内存就清空了,那之前收到的通知**全都看不到**。
|
||||
*
|
||||
* 用户的期望是"读我手机上现在的通知" —— 那本来就该包含
|
||||
* **在他打开 App 之前就收到的那些**。
|
||||
*
|
||||
* `NotificationListenerService.getActiveNotifications()` 正好干这个:
|
||||
* 系统把当前通知栏上挂着的全给它。所以每次读之前先同步一遍。
|
||||
*
|
||||
* ★ 拿不到实例(service 没起来)时不报错,就用手上已有的 ——
|
||||
* 至少比什么都不给强。
|
||||
*/
|
||||
fun syncActive() {
|
||||
val svc = instance ?: return
|
||||
try {
|
||||
for (sbn in svc.activeNotifications ?: emptyArray()) {
|
||||
if (sbn.packageName == svc.packageName) continue
|
||||
svc.record(sbn, removed = false)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "同步当前通知失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取最近的通知。
|
||||
*
|
||||
* @param limit 最多几条
|
||||
* @param onlyAlive 只要"还在通知栏上"的(默认 false = 包括已经被划掉的)
|
||||
* @param query 关键词过滤(标题/正文/App 名里含它)
|
||||
*/
|
||||
fun recent(limit: Int = 20, onlyAlive: Boolean = false, query: String = ""): JSONArray {
|
||||
// ★ 先跟系统对一次账,把"我们没见过的、但此刻挂着的"补进来
|
||||
syncActive()
|
||||
|
||||
var list = items.values.toList()
|
||||
if (onlyAlive) list = list.filter { !it.removed }
|
||||
if (query.isNotBlank()) {
|
||||
val q = query.lowercase()
|
||||
list = list.filter {
|
||||
it.title.lowercase().contains(q) ||
|
||||
it.text.lowercase().contains(q) ||
|
||||
it.app.lowercase().contains(q) ||
|
||||
it.pkg.lowercase().contains(q)
|
||||
}
|
||||
}
|
||||
val arr = JSONArray()
|
||||
list.sortedByDescending { it.at }.take(limit.coerceIn(1, MAX_KEEP)).forEach { it ->
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("app", it.app)
|
||||
.put("package", it.pkg)
|
||||
.put("title", it.title)
|
||||
.put("text", it.text)
|
||||
.put("subText", it.subText)
|
||||
.put("at", it.at)
|
||||
.put("removed", it.removed),
|
||||
)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
fun count(): Int = items.size
|
||||
|
||||
fun clear() = items.clear()
|
||||
}
|
||||
}
|
||||
33
android/app/src/main/java/com/doubao/lynxclone/KernelHost.kt
Normal file
33
android/app/src/main/java/com/doubao/lynxclone/KernelHost.kt
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
|
||||
/**
|
||||
* 内核监听的端口。
|
||||
*
|
||||
* ## 为什么要有这个单例
|
||||
*
|
||||
* 端口原来是 `MainActivity` 里一个局部变量(`client.baseUrl` 也在那儿设)。
|
||||
* 但 `NativeBridge` 也需要打内核的接口 —— `end_conversation` 要
|
||||
* `PATCH /api/conversations/<id>` 把"这次对话已结束"落盘,而
|
||||
* `NativeBridge` 在**内核的工作线程**上被调,拿不到 Activity 的局部变量,
|
||||
* 也不该去依赖 UI 层的 `KernelClient`。
|
||||
*
|
||||
* 所以放一个进程级的单例:`MainActivity` 启动内核后写一次,别处只读。
|
||||
*/
|
||||
object KernelHost {
|
||||
|
||||
/** 内核端口;0 表示还没起来 */
|
||||
@Volatile
|
||||
var port: Int = 0
|
||||
|
||||
/** 内核起来之后由 MainActivity 调 */
|
||||
fun set(p: Int) {
|
||||
port = p
|
||||
}
|
||||
|
||||
fun baseUrl(): String = if (port > 0) "http://127.0.0.1:$port" else ""
|
||||
}
|
||||
|
||||
/** 全项目统一的 JSON 请求体类型(别在各处手写字符串,写错一个字符就是 415) */
|
||||
val JSON_MEDIA_TYPE = "application/json; charset=utf-8".toMediaType()
|
||||
@@ -35,10 +35,32 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
private val client = KernelClient()
|
||||
|
||||
companion object {
|
||||
/** 发通知权限的请求码(只要不和别的撞就行) */
|
||||
private const val REQ_NOTIF = 0x4D32
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
// ★★ 申请「发通知」权限(用户要求"还可以发送通知")。
|
||||
//
|
||||
// Android 13(API 33) 起这是**运行时权限**,新装的 App **默认拒绝** ——
|
||||
// 不申请的话 `NotificationManager.notify()` 不报错、但通知**根本不显示**。
|
||||
// 实测踩到:渠道建出来了(importance=3),App 级却是 `importance=NONE`,
|
||||
// 通知栏里什么都没有,而工具还返回"发送成功"。
|
||||
//
|
||||
// ★ 只在 33+ 申请:低版本没这个权限,申请了系统会直接忽略(但会打日志)。
|
||||
// ★ 用户拒绝也不影响别的功能 —— 只是发通知会失败,而且工具会如实报错。
|
||||
if (android.os.Build.VERSION.SDK_INT >= 33) {
|
||||
val need = checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
if (need) {
|
||||
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), REQ_NOTIF)
|
||||
}
|
||||
}
|
||||
|
||||
var kernelUrl by mutableStateOf("")
|
||||
var status by mutableStateOf("正在启动本地内核…")
|
||||
var termuxReady by mutableStateOf(false)
|
||||
@@ -70,6 +92,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
if (port != null && port > 0) {
|
||||
client.baseUrl = "http://127.0.0.1:$port"
|
||||
// ★ 端口也放进 KernelHost —— NativeBridge 里的 end_conversation
|
||||
// 要 PATCH 内核接口把"对话已结束"落盘,而它在内核工作线程上跑,
|
||||
// 拿不到这里的局部变量、也不该依赖 UI 层的 client。
|
||||
KernelHost.set(port)
|
||||
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
||||
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
||||
withContext(Dispatchers.IO) {
|
||||
|
||||
@@ -20,7 +20,11 @@ import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.data.AppTimeouts
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -36,9 +40,17 @@ import java.util.concurrent.TimeUnit
|
||||
*/
|
||||
class NativeBridge(private val activity: Activity) {
|
||||
|
||||
/**
|
||||
* 一次最多列多少个 App。
|
||||
*
|
||||
* ★ 必须有上限:手机上有 100~300 个 App,全塞给模型光这一条就几千 token,
|
||||
* 而且它多半只需要"找那一个"。要全量就用 query 过滤。
|
||||
*/
|
||||
private val APP_LIST_MAX = 120
|
||||
|
||||
// ------------------------------------------------------------------ 设备能力
|
||||
|
||||
/** 统一入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
/** 统一的入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
@Suppress("unused")
|
||||
fun device(payloadJson: String): String {
|
||||
val req = try {
|
||||
@@ -67,6 +79,84 @@ class NativeBridge(private val activity: Activity) {
|
||||
req.optString("cwd"),
|
||||
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||
)
|
||||
// ---- 界面能力(AI 主动弹界面 / 弹窗 / 结束对话)----
|
||||
//
|
||||
// ★ 这三个 action 只在「技能」页打开了 uiTools 之后才会被内核调用
|
||||
// (tools_runtime 有两道拦截)。但这里**不再判一次开关** ——
|
||||
// 判两遍会让"开关忘了传下来"变成难查的静默失败;权限的事在内核那侧管。
|
||||
"ui_screen" -> uiScreen(req)
|
||||
// 再打开一个存下来的界面(用户要求"AI 写的界面可以再点开")
|
||||
"ui_screen_reopen" -> uiScreenReopen(req)
|
||||
"ui_screen_list" -> uiScreenList(req)
|
||||
"ui_screen_delete" -> uiScreenDelete(req)
|
||||
"ui_dialog" -> uiDialog(req)
|
||||
"end_conversation" -> endConversation(req)
|
||||
// AI 主动往会话里发一条消息(tools/send_message.py)
|
||||
"session_message" -> sessionMessage(req)
|
||||
// AI 写的界面里用户选了什么 → 排队送回模型(见 pushUiResult)
|
||||
"ui_result" -> pushUiResult(req)
|
||||
// ---- 操作手机:通知 / 打开 App / 音量 ----
|
||||
"notifications" -> notifications(req)
|
||||
"notification_access" -> JSONObject()
|
||||
.put("granted", PhoneOps.hasNotificationAccess(activity))
|
||||
.put("kept", DoubaoNotificationListener.count())
|
||||
"notification_settings" -> {
|
||||
// 带用户去开「通知使用权」—— Android 没有这个权限的运行时申请弹窗,
|
||||
// 只能跳到设置页让他自己勾
|
||||
activity.startActivity(PhoneOps.notificationAccessIntent())
|
||||
JSONObject().put("ok", true).put("opened", "通知使用权设置页")
|
||||
}
|
||||
"notification_clear" -> {
|
||||
DoubaoNotificationListener.clear()
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
// ★ AI 主动发一条通知(用户要求"还可以发送通知")
|
||||
"notification_post" -> {
|
||||
val title = req.optString("title")
|
||||
val text = req.optString("text")
|
||||
if (title.isBlank() && text.isBlank()) {
|
||||
JSONObject().put("error", "title 和 text 至少要给一个")
|
||||
} else {
|
||||
PhoneOps.postNotification(
|
||||
activity, title, text, req.optBoolean("autoCancel", true),
|
||||
)
|
||||
}
|
||||
}
|
||||
"apps" -> appsList(req)
|
||||
"app_launch" -> appLaunch(req)
|
||||
// ★ 预设快捷入口(用户要求"预设几个比如微信对话,支付宝菜鸟")
|
||||
"app_shortcuts" -> {
|
||||
val arr = JSONArray()
|
||||
AppShortcuts.all(activity).forEach { m ->
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("id", m["id"])
|
||||
.put("label", m["label"])
|
||||
.put("app", m["app"])
|
||||
.put("installed", m["installed"])
|
||||
.put("keywords", JSONArray(m["keywords"] as List<*>)),
|
||||
)
|
||||
}
|
||||
JSONObject().put("shortcuts", arr)
|
||||
}
|
||||
"app_shortcut_open" -> {
|
||||
val key = req.optString("shortcut").ifBlank { req.optString("name") }
|
||||
val hit = AppShortcuts.find(key)
|
||||
if (hit == null) {
|
||||
JSONObject()
|
||||
.put("error", "没有叫「$key」的预设快捷入口")
|
||||
.put("hint", "可以用的有:" + AppShortcuts.ids().joinToString("、"))
|
||||
} else {
|
||||
AppShortcuts.run(activity, hit)
|
||||
}
|
||||
}
|
||||
"volume" -> JSONObject().put("state", PhoneOps.volumeState(activity))
|
||||
"volume_set" -> PhoneOps.setVolume(
|
||||
activity,
|
||||
req.optString("stream", "music"),
|
||||
req.optString("mode", "set"),
|
||||
req.optInt("value", 0),
|
||||
)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
@@ -74,6 +164,437 @@ class NativeBridge(private val activity: Activity) {
|
||||
}.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 主动往**当前会话**里发一条消息(`tools/send_message.py`)。
|
||||
*
|
||||
* 走内核的 `/api/session-message` —— 那边负责落进会话历史、
|
||||
* 以及**两道防死循环的闸**(嵌套深度、每会话条数)。
|
||||
*
|
||||
* ★ 为什么闸不在 Kotlin 这层做:内核才有会话上下文和那两处的计数。
|
||||
* 这层只转发,判断留给一处,避免两个地方规则不一致。
|
||||
*/
|
||||
private fun sessionMessage(req: JSONObject): JSONObject {
|
||||
val conv = req.optString("conversationId").trim()
|
||||
val text = req.optString("text").trim()
|
||||
if (conv.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
if (text.isEmpty()) return JSONObject().put("error", "text 是空的")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("conversationId", conv)
|
||||
.put("text", text)
|
||||
.put("role", req.optString("role", "user"))
|
||||
.put("reply", req.optBoolean("reply", false))
|
||||
.put("depth", req.optInt("depth", 1))
|
||||
val resp = kernelPost("/api/session-message", body) ?: return JSONObject()
|
||||
.put("error", "内核没响应,消息没发出去")
|
||||
// 内核把"闸门拒绝"也放在 error 字段里(HTTP 200 + error)——
|
||||
// 所以这里原样透传,别把它当成成功。
|
||||
resp
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ **AI 自己写的界面里,用户选了什么 —— 送回模型的那条路。**
|
||||
*
|
||||
* AI 在 `show_ui` 的 HTML 里写 `Doubao.sendToAi('值')`,那个值会打到这里,
|
||||
* 然后 POST 到内核的 `/api/ui-result` 排队。
|
||||
* 下一轮对话开始时,`agent_loop` 会把队里的东西作为上下文交给模型 ——
|
||||
* 于是模型**真的知道**用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 为什么经内核排队、而不是让 Kotlin 直接起一轮对话:
|
||||
* 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型既慢又费 token,
|
||||
* 而且用户还没说完。排队 → 下一次说话时一起带上,语义上也更对:
|
||||
* **界面上的选择是提问的一部分,不是提问本身**。
|
||||
*
|
||||
* ★ 失败不抛异常,只回 ok:false:这是"用户点了一下按钮",
|
||||
* 内核没起来不该让 App 崩(用户会看到提示,也能再点一次)。
|
||||
*/
|
||||
private fun pushUiResult(req: JSONObject): JSONObject {
|
||||
val value = req.optString("value").trim()
|
||||
val convId = req.optString("conversationId").trim()
|
||||
if (value.isEmpty()) return JSONObject().put("error", "value 是空的")
|
||||
if (convId.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
return try {
|
||||
val body = JSONObject().put("conversationId", convId).put("value", value)
|
||||
val resp = kernelPost("/api/ui-result", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,这次选择没能送出去")
|
||||
} else {
|
||||
JSONObject().put("ok", true).put("queued", resp.optInt("queued"))
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
||||
*
|
||||
* [wait] 由工具参数决定:
|
||||
* · false(默认)——**不阻塞**,弹出来就返回,用户看完自己关
|
||||
* · true ——**等用户操作**:点了回传按钮或关掉界面才返回,
|
||||
* 用户点的值原样带回给模型
|
||||
*
|
||||
* ★ 等待模式下要**先备好闩再弹** —— 顺序反了的话,
|
||||
* 用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
* `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。
|
||||
* 这类"用户比代码快"的竞态在真机上很容易出现。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**(用户要求"AI 询问界面不要限时")。
|
||||
* 想限时得模型显式传 timeout。
|
||||
*/
|
||||
private fun uiScreen(req: JSONObject): JSONObject {
|
||||
val html = req.optString("html")
|
||||
if (html.isBlank()) return JSONObject().put("error", "html 是空的")
|
||||
val wait = req.optBoolean("wait", false)
|
||||
val title = req.optString("title")
|
||||
val fullHtml = req.optBoolean("full_html", false)
|
||||
val convId = req.optString("conversationId")
|
||||
|
||||
// ★★ 先存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
// 用户的原话:"AI 写的界面可以再点开"。
|
||||
// 以前界面只活在内存里,一关(或退出 App)就没了;想再看只能让 AI
|
||||
// 重新生成,而重新生成的内容不一定一样(模型有随机性)——
|
||||
// 用户会觉得"我明明看过的东西怎么变了"。
|
||||
//
|
||||
// 存失败不影响弹出(用户至少还能看这一眼),所以不抛异常。
|
||||
val saved = runCatching {
|
||||
AiSurface.saveScreen(activity, html, title, fullHtml, convId)
|
||||
}.getOrNull()
|
||||
val screenId = saved?.optString("id").orEmpty()
|
||||
|
||||
if (wait) AiSurface.armScreenLatch()
|
||||
return AiSurface.showScreen(
|
||||
html = html,
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = convId,
|
||||
wait = wait,
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
screenId = screenId,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 再打开一个存下来的界面。
|
||||
*
|
||||
* ★ 和 [uiScreen] 的区别:那个是"AI 刚写了一个新界面",
|
||||
* 这个是"用户想再看一遍**以前那个**"。后者不需要模型参与 ——
|
||||
* 内容就在磁盘上,读出来直接显示。
|
||||
*/
|
||||
private fun uiScreenReopen(req: JSONObject): JSONObject {
|
||||
val id = req.optString("screenId")
|
||||
if (id.isBlank()) return JSONObject().put("error", "缺少 screenId")
|
||||
val html = AiSurface.readScreen(activity, id)
|
||||
?: return JSONObject().put("error", "这个界面已经不在了(可能被清理或删除)")
|
||||
|
||||
// 从索引里把标题 / fullHtml 取回来,不然重开之后标题会变成"AI 界面"
|
||||
var title = ""
|
||||
var fullHtml = false
|
||||
val arr = AiSurface.loadScreenIndex(activity)
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") == id) {
|
||||
title = it.optString("title")
|
||||
fullHtml = it.optBoolean("fullHtml")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
AiSurface.showScreen(
|
||||
html = html,
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = req.optString("conversationId"),
|
||||
wait = false,
|
||||
screenId = id,
|
||||
)
|
||||
return JSONObject().put("ok", true).put("screenId", id)
|
||||
}
|
||||
|
||||
/** 列出存下来的界面(消息操作栏的「界面」按钮用它) */
|
||||
private fun uiScreenList(req: JSONObject): JSONObject {
|
||||
val conv = req.optString("conversationId")
|
||||
val arr = AiSurface.loadScreenIndex(activity)
|
||||
val out = JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (conv.isNotBlank() && it.optString("conversationId") != conv) continue
|
||||
out.put(it)
|
||||
}
|
||||
return JSONObject().put("screens", out)
|
||||
}
|
||||
|
||||
private fun uiScreenDelete(req: JSONObject): JSONObject {
|
||||
val id = req.optString("screenId")
|
||||
if (id.isBlank()) return JSONObject().put("error", "缺少 screenId")
|
||||
AiSurface.deleteScreen(activity, id)
|
||||
return JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。
|
||||
*
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点 ——
|
||||
* 和 [pickFile] 同一套路。**绝不能**在主线程调它。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**。用户的原话是"AI 询问界面不要限时":
|
||||
* 他在思考的时候弹窗到点自己消失、模型还收到 timeout 当成"用户不理我",
|
||||
* 这一轮就答非所问了。
|
||||
*/
|
||||
private fun uiDialog(req: JSONObject): JSONObject {
|
||||
val question = req.optString("question")
|
||||
if (question.isBlank()) return JSONObject().put("error", "question 是空的")
|
||||
|
||||
val options = mutableListOf<AiSurface.Option>()
|
||||
val arr = req.optJSONArray("options") ?: JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.optJSONObject(i) ?: continue
|
||||
val label = o.optString("label").ifBlank { o.optString("value") }
|
||||
if (label.isBlank()) continue
|
||||
options.add(
|
||||
AiSurface.Option(
|
||||
label = label,
|
||||
value = o.optString("value").ifBlank { label },
|
||||
description = o.optString("description"),
|
||||
),
|
||||
)
|
||||
}
|
||||
if (options.isEmpty()) return JSONObject().put("error", "至少要有一个选项")
|
||||
|
||||
return AiSurface.ask(
|
||||
question = question,
|
||||
options = options,
|
||||
multiple = req.optBoolean("multiple", false),
|
||||
allowCancel = req.optBoolean("allowCancel", true),
|
||||
conversationId = req.optString("conversationId"),
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 永久结束当前对话(tools/end_conversation.py)。
|
||||
*
|
||||
* ★ 必须**落盘**(PATCH /api/conversations/<id>),不能只改界面状态 ——
|
||||
* 界面状态一刷新就没了,用户重进会看到一个能继续输入的框,
|
||||
* 而模型以为自己已经结束了。两边状态不一致是这类功能最容易出的问题。
|
||||
*/
|
||||
private fun endConversation(req: JSONObject): JSONObject {
|
||||
val convId = req.optString("conversationId").ifBlank {
|
||||
return JSONObject().put("error", "没有 conversationId,无法结束对话")
|
||||
}
|
||||
val reason = req.optString("reason")
|
||||
val summary = req.optString("summary")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("ended", true)
|
||||
.put("endedAt", System.currentTimeMillis())
|
||||
.put("endedReason", reason)
|
||||
if (summary.isNotBlank()) body.put("endedSummary", summary)
|
||||
// 走内核自己的 HTTP 接口 —— 这是唯一一条"由 Kotlin 写内核数据"的既有通道
|
||||
val resp = kernelPatch("/api/conversations/$convId", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,对话状态没写进去")
|
||||
} else {
|
||||
AiSurface.markEnded(convId)
|
||||
JSONObject().put("ok", true).put("conversationId", convId)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH 一下内核的接口。
|
||||
*
|
||||
* ★ 这里**不能用 KernelClient** —— 那是 ViewModel 层的东西,NativeBridge
|
||||
* 拿不到(而且它跑在内核工作线程上,不该依赖 UI 层的对象)。
|
||||
* 直接用 OkHttp 打本机端口,和内核在同一个进程里,开销可以忽略。
|
||||
*
|
||||
* 端口从 [KernelHost.port] 取(内核起来之后写进去的)。
|
||||
*/
|
||||
private fun kernelPatch(path: String, body: JSONObject): String? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.patch(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
client.newCall(req).execute().use { resp ->
|
||||
return if (resp.isSuccessful) resp.body?.string() else null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST 一下内核的接口,返回解析好的 JSON;失败返回 null。
|
||||
*
|
||||
* ★ 和 [kernelPatch] 共用同一套"直接打本机端口"的做法 ——
|
||||
* 不用 `KernelClient`(那是 ViewModel 层的东西,NativeBridge 拿不到,
|
||||
* 而且这里是内核工作线程,不该依赖 UI 层对象)。
|
||||
*/
|
||||
private fun kernelPost(path: String, body: JSONObject): JSONObject? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.post(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
return client.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val text = resp.body?.string() ?: return null
|
||||
runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列 App。
|
||||
*
|
||||
* ★ 没传 query 就返回全部(截前 [APP_LIST_MAX] 个)——
|
||||
* 模型可以先看一眼有哪些 App,再决定开哪个。
|
||||
*/
|
||||
private fun appsList(req: JSONObject): JSONObject {
|
||||
val query = req.optString("query").trim()
|
||||
val all = PhoneOps.installedApps(activity)
|
||||
val out = JSONArray()
|
||||
if (query.isBlank()) {
|
||||
all.take(APP_LIST_MAX).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("apps", out)
|
||||
}
|
||||
val q = query.lowercase()
|
||||
all.filter {
|
||||
it.first.lowercase().contains(q) || it.second.lowercase().contains(q)
|
||||
}.take(30).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("matched", out.length()).put("apps", out)
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个 App。
|
||||
*
|
||||
* ★ 找不到时**明确报错并给出相近的名字** —— 让模型能自己改一个再来,
|
||||
* 而不是回一个干巴巴的"失败"(那样它只会反复重试同一个错名字)。
|
||||
*/
|
||||
private fun appLaunch(req: JSONObject): JSONObject {
|
||||
// 已经知道包名和 Activity(从上一步 app_list 拿到的)就直接开,省一次全表扫描
|
||||
val pkg = req.optString("package").trim()
|
||||
val cls = req.optString("activity").trim()
|
||||
if (pkg.isNotEmpty()) {
|
||||
// ★ 只给包名不给 activity 是**最常见的用法**(比如"打开微信"),
|
||||
// 这时候自己去查它的 launcher activity —— 让模型去记
|
||||
// `com.tencent.mm.ui.LauncherUI` 这种名字既没必要也容易记错。
|
||||
val realCls = cls.ifEmpty { AppShortcuts.mainActivityOf(activity, pkg) }
|
||||
if (realCls.isEmpty()) {
|
||||
return JSONObject()
|
||||
.put("error", "找不到 $pkg 的启动入口(可能没装,或者它没有可启动的界面)")
|
||||
}
|
||||
// ★ 有 activity 时先试"直接拉起那个 Activity"(能直达指定页面),
|
||||
// 失败再退回标准 launcher 方式 —— App 内部 Activity 常常没导出,
|
||||
// 直接拉会被系统拒。
|
||||
if (cls.isNotEmpty()) {
|
||||
val directErr = PhoneOps.launchActivity(activity, pkg, cls)
|
||||
if (directErr == null) {
|
||||
return JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", cls).put("how", "direct")
|
||||
}
|
||||
// 直拉失败就退回标准方式;两者都失败才报错
|
||||
if (PhoneOps.launchApp(activity, pkg, realCls)) {
|
||||
return JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", realCls).put("how", "launcher")
|
||||
.put("note", "没法直达指定页面($directErr),已经打开 App 主界面")
|
||||
}
|
||||
// ★ 两边都失败:错误里**两个原因都要说**。
|
||||
// 只说直拉那个的话会误导 —— 用户/模型以为是"activity 名字写错了",
|
||||
// 其实退回主界面也失败了(那才是更严重的问题)。
|
||||
return JSONObject().put(
|
||||
"error",
|
||||
"启动 $pkg 失败:直达指定页面不行($directErr)," +
|
||||
"退回主界面也不行($realCls 打不开)。这个 App 可能被停用了。",
|
||||
)
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, pkg, realCls)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", realCls).put("how", "launcher")
|
||||
} else {
|
||||
JSONObject().put("error", "启动 $pkg 失败(系统拒绝了,可能被停用)")
|
||||
}
|
||||
}
|
||||
|
||||
val name = req.optString("name").trim()
|
||||
if (name.isEmpty()) {
|
||||
return JSONObject().put("error", "至少要给 name(App 名字)或 package+activity")
|
||||
}
|
||||
val hit = PhoneOps.findApp(activity, name)
|
||||
?: run {
|
||||
// 给几个名字相近的当提示
|
||||
val q = name.lowercase()
|
||||
val near = PhoneOps.installedApps(activity)
|
||||
.filter { it.first.lowercase().contains(q.take(2)) }
|
||||
.take(5)
|
||||
.map { it.first }
|
||||
return JSONObject()
|
||||
.put("error", "没找到叫「$name」的 App")
|
||||
.put("hint", if (near.isEmpty()) {
|
||||
// ★ 这里写的 action 名必须和 tools/apps.py 里 enum 的一致。
|
||||
// 第一版写的 `app_list` —— 那个名字不存在,模型照着调会失败。
|
||||
"可以用 action=list 看看装了哪些 App"
|
||||
} else {
|
||||
"名字相近的有:" + near.joinToString("、") + "。换个名字再试"
|
||||
})
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, hit.second, hit.third)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true)
|
||||
.put("label", hit.first)
|
||||
.put("package", hit.second)
|
||||
} else {
|
||||
JSONObject().put("error", "找到「${hit.first}」但启动失败(系统拒绝了)")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读通知。
|
||||
*
|
||||
* ★ 权限没开时**返回明确错误**,不是空列表。
|
||||
* 返回空列表的话模型会说"最近没有通知" —— 那是**错的**
|
||||
* (明明有几条,只是我们读不到),用户会被误导。
|
||||
*/
|
||||
private fun notifications(req: JSONObject): JSONObject {
|
||||
if (!PhoneOps.hasNotificationAccess(activity)) {
|
||||
return JSONObject()
|
||||
.put("error", "没有「通知使用权」,读不到任何通知")
|
||||
.put("granted", false)
|
||||
.put(
|
||||
"hint",
|
||||
"这个权限安卓不给运行时申请,必须用户手动开:" +
|
||||
"设置 → 通知 → 通知使用权(或「通知读取权限」)→ 找到本 App 打开。" +
|
||||
"调用 action=notification_settings 可以直接跳到那个设置页。",
|
||||
)
|
||||
}
|
||||
val arr = DoubaoNotificationListener.recent(
|
||||
limit = req.optInt("limit", 20),
|
||||
onlyAlive = req.optBoolean("onlyAlive", false),
|
||||
query = req.optString("query"),
|
||||
)
|
||||
return JSONObject()
|
||||
.put("granted", true)
|
||||
.put("count", arr.length())
|
||||
.put("notifications", arr)
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
@@ -317,7 +838,10 @@ class NativeBridge(private val activity: Activity) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(PICK_TIMEOUT_S, TimeUnit.SECONDS)
|
||||
latch.await(
|
||||
AppTimeouts.seconds("filePicker", PICK_TIMEOUT_S.toDouble()).toLong(),
|
||||
TimeUnit.SECONDS,
|
||||
)
|
||||
pickLatch = null
|
||||
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||
}
|
||||
@@ -360,8 +884,25 @@ class NativeBridge(private val activity: Activity) {
|
||||
|
||||
companion object {
|
||||
const val REQ_PICK = 0x4D31
|
||||
|
||||
/**
|
||||
* AI 让你挑文件时等多久的**兜底值**。
|
||||
*
|
||||
* ★ 真实值从设置读(设置 → 超时 → 选文件等多久)——
|
||||
* 去相册里翻一张老照片可能不止两分钟。这里是拿不到设置时的兜底。
|
||||
*/
|
||||
private const val PICK_TIMEOUT_S = 120L
|
||||
|
||||
/**
|
||||
* 打本机内核端口([kernelPost] / [kernelPatch])的读超时。
|
||||
*
|
||||
* ★ 也做成可调的(设置 → 超时 → 本地接口请求):这些请求里有几个
|
||||
* 体积不小(读一条很长的会话、传附件),老设备上 10 秒不一定够。
|
||||
* 每次现读而不是建 client 时读一次 —— 改完立刻生效。
|
||||
*/
|
||||
private val LOCAL_READ_S: Long
|
||||
get() = AppTimeouts.seconds("kernelLocal", 10.0).toLong().coerceAtLeast(3L)
|
||||
|
||||
/** 内核起来后把 bridge 注册给 Python */
|
||||
fun register(bridge: NativeBridge) {
|
||||
val entry = Python.getInstance().getModule("doubao_entry")
|
||||
|
||||
367
android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
367
android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
@@ -0,0 +1,367 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★ 三个"操作手机"的能力:读通知 / 打开 App / 调音量。
|
||||
*
|
||||
* 抽成一个文件是因为它们同类(都是"AI 要动手机"),
|
||||
* 而且都要处理"权限没给"这一种失败 —— 收在一起比较好统一口径。
|
||||
*
|
||||
* ## 一律"如实报错",不假装成功
|
||||
*
|
||||
* 通知使用权没开、找不到那个 App、音量被系统锁住 —— 这些都会**明确返回错误**,
|
||||
* 而不是返回一个空列表或者一个看起来成功的值。
|
||||
* 模型拿到"权限没开"才会去告诉用户怎么开;拿到空列表它只会说
|
||||
* "最近没有通知",那是**错的**(明明有几条,只是我们读不到)。
|
||||
*/
|
||||
object PhoneOps {
|
||||
|
||||
private const val TAG = "DoubaoPhone"
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、通知 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/** 通知使用权开了没有 */
|
||||
fun hasNotificationAccess(ctx: Context): Boolean {
|
||||
val flat = Settings.Secure.getString(ctx.contentResolver, "enabled_notification_listeners")
|
||||
?: return false
|
||||
if (flat.isBlank()) return false
|
||||
val me = ComponentName(ctx, DoubaoNotificationListener::class.java)
|
||||
// enabled_notification_listeners 是 `pkg/cls:pkg/cls` 的形式,
|
||||
// 而且**不同 ROM 的大小写和简写不一样**,所以比对时统一转小写再找
|
||||
return flat.lowercase().split(':').any { entry ->
|
||||
val e = entry.trim()
|
||||
e == me.flattenToString().lowercase() ||
|
||||
e == me.flattenToShortString().lowercase() ||
|
||||
e.startsWith(me.packageName.lowercase() + "/")
|
||||
}
|
||||
}
|
||||
|
||||
/** 通知使用权的设置页(带用户去开) */
|
||||
fun notificationAccessIntent(): Intent =
|
||||
Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 四、发通知 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 通知渠道 id。
|
||||
*
|
||||
* ★ Android 8+ 必须挂在渠道上,否则通知**直接被丢掉**(连报错都没有)。
|
||||
* 渠道的重要性用 DEFAULT:太低会被折叠成静音,用户根本注意不到;
|
||||
* 太高(HIGH)会弹横幅 —— 对"AI 提醒你一件事"这种场景
|
||||
* 弹横幅太打扰了,DEFAULT 正合适(有声音 + 进通知栏,不弹横幅)。
|
||||
*/
|
||||
private const val CHANNEL_ID = "doubao_ai"
|
||||
private const val CHANNEL_NAME = "AI 提醒"
|
||||
|
||||
private fun ensureChannel(ctx: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
if (nm.getNotificationChannel(CHANNEL_ID) != null) return
|
||||
val ch = android.app.NotificationChannel(
|
||||
CHANNEL_ID, CHANNEL_NAME, android.app.NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "豆包主动发出来的提醒"
|
||||
enableVibration(true)
|
||||
}
|
||||
nm.createNotificationChannel(ch)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 发一条通知 —— 用户要求"还可以发送通知"。
|
||||
*
|
||||
* 用途:AI 说到点提醒你什么、长任务跑完了通知一声。
|
||||
*
|
||||
* ★ 点通知要能回到 App:用 `PendingIntent` 打开 MainActivity。
|
||||
* 不给 PendingIntent 的话点了没反应 —— 用户会觉得"这通知是死的"。
|
||||
*
|
||||
* ★ 用 `System.currentTimeMillis()` 当通知 id:每条独立存在,不会互相覆盖。
|
||||
* 固定 id 的话后一条会把前一条顶掉("我刚收到的提醒怎么没了")。
|
||||
*/
|
||||
fun postNotification(ctx: Context, title: String, text: String, autoCancel: Boolean): JSONObject {
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
ensureChannel(ctx)
|
||||
|
||||
val t = title.trim().ifBlank { "豆包" }
|
||||
val body = text.trim()
|
||||
|
||||
// 点通知打开 App
|
||||
val open = Intent(ctx, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
var flags = android.app.PendingIntent.FLAG_UPDATE_CURRENT
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags = flags or android.app.PendingIntent.FLAG_IMMUTABLE
|
||||
}
|
||||
val pi = android.app.PendingIntent.getActivity(ctx, 0, open, flags)
|
||||
|
||||
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
android.app.Notification.Builder(ctx, CHANNEL_ID)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
android.app.Notification.Builder(ctx)
|
||||
}
|
||||
builder
|
||||
.setSmallIcon(ctx.applicationInfo.icon) // ★ 不给 smallIcon 通知**不会显示**
|
||||
.setContentTitle(t)
|
||||
.setContentText(body)
|
||||
.setAutoCancel(autoCancel)
|
||||
.setContentIntent(pi)
|
||||
// 正文长的话展开显示(否则通知栏只显示一行,被截断)
|
||||
if (body.length > 40) {
|
||||
builder.setStyle(android.app.Notification.BigTextStyle().bigText(body))
|
||||
}
|
||||
|
||||
val id = (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
|
||||
return try {
|
||||
nm.notify(id, builder.build())
|
||||
JSONObject().put("ok", true).put("id", id)
|
||||
.put("title", t)
|
||||
.put("chars", body.length)
|
||||
} catch (t2: Throwable) {
|
||||
Log.w(TAG, "发通知失败:${t2.message}")
|
||||
JSONObject().put("error", "发通知失败:${t2.javaClass.simpleName}: ${t2.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、打开 App */
|
||||
/* ==================================================================== */
|
||||
|
||||
/** 能启动的 App 列表(系统 + 用户装的) */
|
||||
fun installedApps(ctx: Context): List<Triple<String, String, String>> {
|
||||
val pm = ctx.packageManager
|
||||
val main = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
// ★ Android 11+ 必须先在 Manifest 的 <queries> 里声明 LAUNCHER intent,
|
||||
// 否则这里返回空列表(看着像"这台手机没有 App",很误导)
|
||||
val list = if (Build.VERSION.SDK_INT >= 33) {
|
||||
pm.queryIntentActivities(
|
||||
main,
|
||||
android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
pm.queryIntentActivities(main, 0)
|
||||
}
|
||||
return list.mapNotNull { ri ->
|
||||
val pkg = ri.activityInfo?.packageName ?: return@mapNotNull null
|
||||
val cls = ri.activityInfo?.name ?: return@mapNotNull null
|
||||
val label = ri.loadLabel(pm).toString()
|
||||
Triple(label, pkg, cls)
|
||||
}.sortedBy { it.first }
|
||||
}
|
||||
|
||||
/** 模糊匹配一个 App;找不到返回 null */
|
||||
fun findApp(ctx: Context, query: String): Triple<String, String, String>? {
|
||||
val q = query.trim().lowercase()
|
||||
if (q.isEmpty()) return null
|
||||
val all = installedApps(ctx)
|
||||
// 优先级:包名完全相同 > 名字完全相同 > 名字以它开头 > 包含 > 包名包含
|
||||
return all.firstOrNull { it.second.lowercase() == q }
|
||||
?: all.firstOrNull { it.first.lowercase() == q }
|
||||
?: all.firstOrNull { it.first.lowercase().startsWith(q) }
|
||||
?: all.firstOrNull { it.first.lowercase().contains(q) }
|
||||
?: all.firstOrNull { it.second.lowercase().contains(q) }
|
||||
}
|
||||
|
||||
/** 启动一个 App */
|
||||
fun launchApp(ctx: Context, pkg: String, cls: String): Boolean = try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(ComponentName(pkg, cls))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED),
|
||||
)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "启动 $pkg/$cls 失败:${t.message}")
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接拉起某个 Activity(不一定是 launcher 那个)。
|
||||
*
|
||||
* 用途:微信的某些页面有独立 Activity,用它能直达。
|
||||
*
|
||||
* ★ 会被系统拦的情况很多:Activity 没导出(`android:exported=false`)、
|
||||
* 被 App 的权限保护、或者版本更新后改了名字。
|
||||
* 所以**返回具体原因**,不要只回一个 false —— 模型据此决定要不要退回主界面。
|
||||
*/
|
||||
fun launchActivity(ctx: Context, pkg: String, cls: String): String? = try {
|
||||
ctx.startActivity(
|
||||
Intent().setComponent(ComponentName(pkg, cls))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
null
|
||||
} catch (t: Throwable) {
|
||||
"${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
|
||||
/**
|
||||
* 用自定义 scheme 打开(深链)。
|
||||
*
|
||||
* ★ 这是"预设快捷入口"的主力:像 `weixin://`、`alipays://` 这种,
|
||||
* 比猜 Activity 名字稳得多 —— Activity 名字随版本变,scheme 通常不变。
|
||||
*
|
||||
* ★ 必须查 `resolveActivity`:没装那个 App、或者它不认这个 scheme 时,
|
||||
* `startActivity` 会抛 `ActivityNotFoundException`。
|
||||
* 先查一遍能给出**更准确的错误**("没装"vs"不认这个链接")。
|
||||
*/
|
||||
fun launchUri(ctx: Context, uri: String): String? {
|
||||
val parsed = try {
|
||||
android.net.Uri.parse(uri)
|
||||
} catch (t: Throwable) {
|
||||
return "链接解析失败:${t.message}"
|
||||
}
|
||||
val intent = Intent(Intent.ACTION_VIEW, parsed).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val hit = if (Build.VERSION.SDK_INT >= 33) {
|
||||
ctx.packageManager.resolveActivity(
|
||||
intent, android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ctx.packageManager.resolveActivity(intent, 0)
|
||||
}
|
||||
if (hit == null) {
|
||||
return "没有 App 能处理这个链接(对应 App 没装,或者版本不认这个 scheme)"
|
||||
}
|
||||
return try {
|
||||
ctx.startActivity(intent)
|
||||
null
|
||||
} catch (t: Throwable) {
|
||||
"${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
}
|
||||
|
||||
/** 某个包装了没有 */
|
||||
fun isInstalled(ctx: Context, pkg: String): Boolean = try {
|
||||
ctx.packageManager.getApplicationInfo(pkg, 0)
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、音量 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 音量流。
|
||||
*
|
||||
* ★ 用**字符串名**而不是整数常量:模型要写 `music` / `ring` 这种可读的名字,
|
||||
* 让它记 `STREAM_MUSIC = 3` 既没必要也容易错。
|
||||
*/
|
||||
private fun streamOf(name: String): Int = when (name.trim().lowercase()) {
|
||||
"ring", "ringtone", "铃声" -> AudioManager.STREAM_RING
|
||||
"alarm", "闹钟" -> AudioManager.STREAM_ALARM
|
||||
"call", "voice_call", "通话" -> AudioManager.STREAM_VOICE_CALL
|
||||
"system", "系统" -> AudioManager.STREAM_SYSTEM
|
||||
"notification", "通知" -> AudioManager.STREAM_NOTIFICATION
|
||||
else -> AudioManager.STREAM_MUSIC // 默认媒体音量(最常用)
|
||||
}
|
||||
|
||||
private fun streamName(stream: Int): String = when (stream) {
|
||||
AudioManager.STREAM_RING -> "ring"
|
||||
AudioManager.STREAM_ALARM -> "alarm"
|
||||
AudioManager.STREAM_VOICE_CALL -> "call"
|
||||
AudioManager.STREAM_SYSTEM -> "system"
|
||||
AudioManager.STREAM_NOTIFICATION -> "notification"
|
||||
else -> "music"
|
||||
}
|
||||
|
||||
/**
|
||||
* 读所有音量流的当前值。
|
||||
*
|
||||
* ★ 同时给**原始值**和**百分比**:模型想"调到一半"用百分比直观,
|
||||
* 想"加一格"用原始值准。两个都给,它自己挑。
|
||||
*/
|
||||
fun volumeState(ctx: Context): JSONObject {
|
||||
val am = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val arr = JSONArray()
|
||||
val streams = listOf(
|
||||
AudioManager.STREAM_MUSIC, AudioManager.STREAM_RING, AudioManager.STREAM_ALARM,
|
||||
AudioManager.STREAM_VOICE_CALL, AudioManager.STREAM_SYSTEM,
|
||||
AudioManager.STREAM_NOTIFICATION,
|
||||
)
|
||||
for (s in streams) {
|
||||
val cur = am.getStreamVolume(s)
|
||||
val max = am.getStreamMaxVolume(s).coerceAtLeast(1)
|
||||
val pct = Math.round(cur * 100f / max)
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("stream", streamName(s))
|
||||
.put("current", cur)
|
||||
.put("max", max)
|
||||
.put("percent", pct)
|
||||
.put("muted", cur == 0),
|
||||
)
|
||||
}
|
||||
return JSONObject().put("streams", arr)
|
||||
}
|
||||
|
||||
/**
|
||||
* 调音量。
|
||||
*
|
||||
* @param mode set=设成具体值 / up=加 / down=减 / mute=静音 / unmute=取消静音
|
||||
* @param value set 时的值,或 up/down 的步数(默认 1)
|
||||
*/
|
||||
fun setVolume(ctx: Context, streamArg: String, mode: String, value: Int): JSONObject {
|
||||
val am = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val stream = streamOf(streamArg)
|
||||
val max = am.getStreamMaxVolume(stream).coerceAtLeast(1)
|
||||
val before = am.getStreamVolume(stream)
|
||||
|
||||
val target: Int = when (mode.trim().lowercase()) {
|
||||
"mute" -> 0
|
||||
"unmute" -> {
|
||||
// 取消静音:恢复到"上次非零"不好拿,用 max 的一半,至少能听见
|
||||
if (before > 0) before else (max / 2).coerceAtLeast(1)
|
||||
}
|
||||
"up" -> (before + value.coerceAtLeast(1)).coerceAtMost(max)
|
||||
"down" -> (before - value.coerceAtLeast(1)).coerceAtLeast(0)
|
||||
else -> value.coerceIn(0, max)
|
||||
}
|
||||
|
||||
// ★ DND(勿扰)开着时系统会**拒绝**改铃声/通知音量 —— 静默失败。
|
||||
// 所以改完必须**回读**确认,不能假定成功。
|
||||
var err = ""
|
||||
try {
|
||||
am.setStreamVolume(stream, target, 0)
|
||||
} catch (t: Throwable) {
|
||||
err = "${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
val after = am.getStreamVolume(stream)
|
||||
|
||||
val ok = if (err.isEmpty()) after == target else false
|
||||
val out = JSONObject()
|
||||
.put("stream", streamName(stream))
|
||||
.put("before", before)
|
||||
.put("requested", target)
|
||||
.put("current", after)
|
||||
.put("max", max)
|
||||
.put("percent", Math.round(after * 100f / max))
|
||||
.put("ok", ok)
|
||||
if (err.isNotEmpty()) out.put("error", err)
|
||||
if (!ok && err.isEmpty()) {
|
||||
// 回读和请求不一致 = 系统拦了(多半是勿扰模式)
|
||||
out.put(
|
||||
"error",
|
||||
"系统没有接受这次调整(可能开了勿扰模式,或该音量流被系统锁定)。" +
|
||||
"当前值仍是 $after。",
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,16 @@ class SpeechController(
|
||||
private val context: Context,
|
||||
private val client: KernelClient,
|
||||
private val scope: CoroutineScope,
|
||||
/**
|
||||
* 当前说话的是哪个智能体 —— 朗读时把它带给内核,用**它自己的音色**。
|
||||
*
|
||||
* ★★ 这个参数是补上来的:以前 `client.speak(text)` 只传正文,
|
||||
* 内核拿不到 agentId 就一律用全局音色,于是**智能体编辑页里选的声音
|
||||
* 配了也没用**(用户报的"智能体语音咋没生效")。
|
||||
* 做成 lambda 而不是字符串,是因为它会随用户切换智能体而变,
|
||||
* 而这个 controller 是在进聊天页时 remember 一次的。
|
||||
*/
|
||||
private val agentId: () -> String = { "" },
|
||||
) {
|
||||
private val speaker = Speaker(context)
|
||||
private val recorder = Recorder(context)
|
||||
@@ -61,8 +71,18 @@ class SpeechController(
|
||||
|
||||
/* ------------------------------ 朗读 ------------------------------ */
|
||||
|
||||
/** 念第 index 条消息 */
|
||||
fun speak(text: String, index: Int) {
|
||||
/**
|
||||
* 念第 [index] 条消息。
|
||||
*
|
||||
* [who] = **说这句话的智能体**(群聊里每条消息的发言者都不一样)。
|
||||
* 传空串就退回 [agentId] 那个"当前智能体"。
|
||||
*
|
||||
* ★★ 这个参数是补上来的:以前只会拿"当前对话的主人"去要音色,
|
||||
* 于是群聊里小黑和寐眠各配了不同音色,读出来却始终是同一个声音
|
||||
* (用户报的"群聊的时候不同智能体的语音不会切换")。
|
||||
* 内核其实**一直在消息里存 agentId**,只是客户端没读。
|
||||
*/
|
||||
fun speak(text: String, index: Int, who: String = "") {
|
||||
if (text.isBlank()) return
|
||||
// 正在念同一条 → 再点一次就是停
|
||||
if (speakingIndex == index && speaker.isPlaying) {
|
||||
@@ -76,6 +96,7 @@ class SpeechController(
|
||||
cancelRecording()
|
||||
|
||||
speakingIndex = index
|
||||
val voice = who.ifBlank { agentId() }
|
||||
scope.launch {
|
||||
// ★ 首选流式:内核边合成边下发 PCM,这边边收边喂 AudioTrack,
|
||||
// 首句大约 1 秒就能出声(整段合成再播要等 3 秒以上)。
|
||||
@@ -89,7 +110,7 @@ class SpeechController(
|
||||
// 用户看到的就是"一读语音就闪退"。
|
||||
val played = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
client.streamTts(text).use { r ->
|
||||
client.streamTts(text, voice).use { r ->
|
||||
val mime = r.body?.contentType().toString()
|
||||
val source = r.body?.source()
|
||||
source != null && speaker.playStream(mime, source)
|
||||
@@ -107,7 +128,7 @@ class SpeechController(
|
||||
}
|
||||
|
||||
try {
|
||||
val result = client.speak(text)
|
||||
val result = client.speak(text, voice)
|
||||
if (!result.optBoolean("ok")) {
|
||||
// 云端失败就退回系统 TTS —— 用户点了朗读却一点动静都没有是最差的体验
|
||||
val reason = result.optString("error").ifBlank { "云端合成失败" }
|
||||
@@ -157,8 +178,8 @@ class SpeechController(
|
||||
*/
|
||||
private var lastAutoReadKey: String? = null
|
||||
|
||||
/** 自动朗读:新回复刚落地时调它 */
|
||||
fun maybeAutoRead(text: String, index: Int) {
|
||||
/** 自动朗读:新回复刚落地时调它。[who] 同 [speak] —— 群聊里要按发言者挑音色 */
|
||||
fun maybeAutoRead(text: String, index: Int, who: String = "") {
|
||||
if (!autoRead || text.isBlank()) return
|
||||
if (recording) return
|
||||
|
||||
@@ -168,7 +189,7 @@ class SpeechController(
|
||||
if (speakingIndex == index && speaker.isPlaying) return
|
||||
|
||||
lastAutoReadKey = key
|
||||
speak(text, index)
|
||||
speak(text, index, who)
|
||||
}
|
||||
|
||||
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
/**
|
||||
* ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。
|
||||
*
|
||||
* ## 为什么要一个单例控制器
|
||||
*
|
||||
* 内核(Python,跑在 HTTP 工作线程上)通过 `NativeBridge.device()` 说
|
||||
* "给我弹个界面",而界面是 Compose 画的、归 `AppViewModel` 管。
|
||||
* 这两边**没有互相引用**:
|
||||
*
|
||||
* · `NativeBridge` 在 `MainActivity` 里 new 出来(见 MainActivity:76)
|
||||
* · `AppViewModel` 在 Compose 树里由 `rememberAppViewModel` 造
|
||||
*
|
||||
* 所以中间放一个单例:NativeBridge 往里写,ViewModel 订阅。
|
||||
* 这也让"内核线程"和"UI 状态"的边界很清楚 —— 内核永远不直接碰 Compose。
|
||||
*
|
||||
* ## 线程模型(这是最容易出错的地方)
|
||||
*
|
||||
* `device()` 是在**内核的 HTTP 工作线程**上被调的,而:
|
||||
* · 写状态:用 `@Volatile` + 监听器回调,ViewModel 在自己的协程里切主线程更新 Compose
|
||||
* · 等用户选择:用 [CountDownLatch] 阻塞**那个工作线程**(不能阻塞 UI 线程)
|
||||
*
|
||||
* 跟 `NativeBridge.pickFile()` 是同一套路子(它已经验证过可行)。
|
||||
*/
|
||||
object AiSurface {
|
||||
|
||||
private const val TAG = "DoubaoAiSurface"
|
||||
|
||||
/** 一次 AI 界面的标识。每次弹出都换一个,用来让 Compose 重建 WebView。 */
|
||||
private val seq = AtomicLong(0)
|
||||
|
||||
/** 正在显示的 HTML 界面;null 表示没有 */
|
||||
@Volatile
|
||||
var screen: Screen? = null
|
||||
private set
|
||||
|
||||
/** 正在等的选择弹窗;null 表示没有 */
|
||||
@Volatile
|
||||
var dialog: Dialog? = null
|
||||
private set
|
||||
|
||||
/** 当前对话被 AI 结束过 —— 界面据此禁用输入框 */
|
||||
@Volatile
|
||||
var endedConversationId: String = ""
|
||||
private set
|
||||
|
||||
data class Screen(
|
||||
val id: Long,
|
||||
val html: String,
|
||||
val title: String,
|
||||
val fullHtml: Boolean,
|
||||
val conversationId: String,
|
||||
/** true = 这一屏在等用户操作(用户点了回传按钮后自动收掉) */
|
||||
val waiting: Boolean = false,
|
||||
/** 磁盘上那一份的 id(空 = 没存)。再打开时靠它去读。 */
|
||||
val screenId: String = "",
|
||||
)
|
||||
|
||||
data class Option(val label: String, val value: String, val description: String)
|
||||
|
||||
data class Dialog(
|
||||
val id: Long,
|
||||
val question: String,
|
||||
val options: List<Option>,
|
||||
val multiple: Boolean,
|
||||
val allowCancel: Boolean,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
/** ViewModel 订阅这个来把状态同步进 Compose。参数是"发生了什么"。 */
|
||||
@Volatile
|
||||
private var listener: ((String) -> Unit)? = null
|
||||
|
||||
fun subscribe(fn: ((String) -> Unit)?) {
|
||||
listener = fn
|
||||
}
|
||||
|
||||
private fun notify(kind: String) {
|
||||
try {
|
||||
listener?.invoke(kind)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "通知界面失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 界面
|
||||
|
||||
/**
|
||||
* 把界面存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
*
|
||||
* ## 为什么需要(用户的原话:"AI 写的界面可以再点开")
|
||||
*
|
||||
* 界面以前只活在内存里:用户一关(或者退出 App),那份 HTML 就没了。
|
||||
* 过一会儿想"刚才那个图表再看一眼"就再也找不回来,只能让 AI 重新生成 ——
|
||||
* 而重新生成的内容**和上次不一定一样**(模型有随机性),
|
||||
* 用户看到的是"我明明看过的东西怎么变了"。
|
||||
*
|
||||
* ## 为什么不放内核(Python)那边
|
||||
*
|
||||
* 内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的
|
||||
* `device()` 参数。要走内核就得 Kotlin 再 POST 一次上去,多一次往返、
|
||||
* 还多一个失败点。而 App 私有目录本来就是 Kotlin 最顺手的地方。
|
||||
*
|
||||
* 存法:
|
||||
* `<app files>/ai-screens/<id>.html` 正文
|
||||
* `<app files>/ai-screens/index.json` 索引(列表只读这个)
|
||||
*/
|
||||
private val screensLock = Any()
|
||||
|
||||
fun screenDir(ctx: android.content.Context): java.io.File =
|
||||
java.io.File(ctx.filesDir, "ai-screens").apply { mkdirs() }
|
||||
|
||||
fun screenIndexFile(ctx: android.content.Context): java.io.File =
|
||||
java.io.File(screenDir(ctx), "index.json")
|
||||
|
||||
fun loadScreenIndex(ctx: android.content.Context): JSONArray = synchronized(screensLock) {
|
||||
try {
|
||||
val text = screenIndexFile(ctx).readText()
|
||||
JSONArray(text)
|
||||
} catch (_: Throwable) {
|
||||
JSONArray()
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveScreenIndex(ctx: android.content.Context, arr: JSONArray) {
|
||||
try {
|
||||
screenIndexFile(ctx).writeText(arr.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "写界面索引失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 存下一个界面,返回它的索引项(含 id)。
|
||||
*
|
||||
* ★ 每个会话只留最近 [KEEP_PER_CONV] 个:用户跟 AI 聊久了会弹出几十个界面,
|
||||
* 列表没法看、磁盘也白占。超出时把**最旧的正文删掉**(索引项也去掉),
|
||||
* 保留最近这些。
|
||||
*/
|
||||
fun saveScreen(
|
||||
ctx: android.content.Context,
|
||||
html: String,
|
||||
title: String,
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
): JSONObject? {
|
||||
val id = "s_" + java.util.UUID.randomUUID().toString().replace("-", "").take(12)
|
||||
return try {
|
||||
java.io.File(screenDir(ctx), "$id.html").writeText(html)
|
||||
val item = JSONObject()
|
||||
.put("id", id)
|
||||
.put("title", title.ifBlank { "AI 界面" })
|
||||
.put("fullHtml", fullHtml)
|
||||
.put("bytes", html.length)
|
||||
.put("conversationId", conversationId)
|
||||
.put("preview", previewOf(html))
|
||||
.put("at", System.currentTimeMillis())
|
||||
synchronized(screensLock) {
|
||||
val arr = loadScreenIndex(ctx)
|
||||
val next = JSONArray().put(item)
|
||||
var kept = 0
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("conversationId") != conversationId) {
|
||||
next.put(it); continue
|
||||
}
|
||||
if (kept < KEEP_PER_CONV) {
|
||||
next.put(it); kept++
|
||||
} else {
|
||||
runCatching { java.io.File(screenDir(ctx), "${it.optString("id")}.html").delete() }
|
||||
}
|
||||
}
|
||||
saveScreenIndex(ctx, next)
|
||||
}
|
||||
item
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "存界面失败:${t.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** 读一个界面的正文 */
|
||||
fun readScreen(ctx: android.content.Context, id: String): String? {
|
||||
if (id.isBlank() || id.contains('/') || id.contains("..")) return null
|
||||
return try {
|
||||
java.io.File(screenDir(ctx), "$id.html").readText()
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteScreen(ctx: android.content.Context, id: String) {
|
||||
synchronized(screensLock) {
|
||||
runCatching { java.io.File(screenDir(ctx), "$id.html").delete() }
|
||||
val arr = loadScreenIndex(ctx)
|
||||
val next = JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") != id) next.put(it)
|
||||
}
|
||||
saveScreenIndex(ctx, next)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 HTML 里抠一小段纯文字做预览(列表里靠它认出是哪个界面) */
|
||||
private fun previewOf(html: String): String =
|
||||
html.replace(Regex("(?is)<(script|style)[^>]*>.*?</\\1>"), " ")
|
||||
.replace(Regex("<[^>]+>"), " ")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
.take(120)
|
||||
|
||||
private const val KEEP_PER_CONV = 30
|
||||
|
||||
/**
|
||||
* 弹一个 HTML 界面。
|
||||
*
|
||||
* [wait] = false(默认):**不阻塞** —— 弹出来就返回。
|
||||
* [wait] = true:**等用户交互**(点回传按钮 / 关掉界面),最多等 [timeoutMs]。
|
||||
*
|
||||
* ★ 为什么要两种:
|
||||
* 展示性的界面(图表、报告)不该把对话卡住 —— 用户可能盯着看很久。
|
||||
* 但"让用户在几个选项里挑一个"必须拿到答案才能继续,那就是阻塞语义。
|
||||
* 以前只有前者,于是 AI 想"问一个带图的选择题"就没辙了。
|
||||
*
|
||||
* ★ 阻塞是怎么实现的:和 [ask](ask_user 弹窗)、`NativeBridge.pickFile`
|
||||
* 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**,
|
||||
* 不碰 UI 线程。
|
||||
*
|
||||
* ★★ [timeoutMs] <= 0 表示**不限时**(等用户到天荒地老),这是默认。
|
||||
* 以前默认 120 秒,用户明确要求"AI 询问界面不要限时"——
|
||||
* 他可能看着界面想很久,120 秒到点界面自己收掉,体验很差。
|
||||
* 现在想限时得由模型显式传 timeout。
|
||||
*/
|
||||
fun showScreen(
|
||||
html: String,
|
||||
title: String,
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
wait: Boolean = false,
|
||||
timeoutMs: Long = 0L,
|
||||
screenId: String = "",
|
||||
): JSONObject {
|
||||
val s = Screen(
|
||||
seq.incrementAndGet(), html, title, fullHtml, conversationId,
|
||||
waiting = wait, screenId = screenId,
|
||||
)
|
||||
screen = s
|
||||
screenClosed = false
|
||||
screenAnswer = null
|
||||
notify("screen")
|
||||
Log.i(
|
||||
TAG,
|
||||
"AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}," +
|
||||
if (wait) "等用户操作(${waitLabel(timeoutMs)})" else "不等待",
|
||||
)
|
||||
|
||||
if (!wait) {
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
// ★ 带上 id —— 它一路回到模型的工具返回值、再进 ToolTrace,
|
||||
// 消息操作栏据此显示「界面」按钮(用户要求"可以再点开")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
// ---- 等待模式 ----
|
||||
val latch = screenLatch
|
||||
val answered = latch?.let { awaitUser(it, timeoutMs) } ?: false
|
||||
val answer = screenAnswer
|
||||
val closed = screenClosed
|
||||
screenLatch = null
|
||||
|
||||
// 等到答案(或超时)之后把界面收掉 —— 否则用户看到一个已经"用完了"
|
||||
// 的界面还开着,会以为还能再点。
|
||||
if (answered) {
|
||||
screen = null
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
.put("waited", true)
|
||||
.put("timeout", !answered)
|
||||
.put("closed", closed)
|
||||
// 用户点的值。超时/直接关掉时是空串。
|
||||
.put("value", answer ?: "")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
/** 等用户交互用的闩。非等待模式下是 null。 */
|
||||
@Volatile
|
||||
private var screenLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var screenAnswer: String? = null
|
||||
|
||||
@Volatile
|
||||
private var screenClosed: Boolean = false
|
||||
|
||||
/**
|
||||
* 用户在界面上点了回传按钮(`Doubao.sendToAi` / `data-doubao-result`)。
|
||||
*
|
||||
* ★ 等待模式下这一下就是"用户答完了"的信号:记下值、放行。
|
||||
* 界面侧收到后会把自己收掉。
|
||||
*/
|
||||
fun screenResult(value: String) {
|
||||
Log.i(TAG, "界面里点了:$value")
|
||||
lastScreenResult = value
|
||||
screenAnswer = value
|
||||
screenClosed = false
|
||||
screenLatch?.countDown()
|
||||
notify("screenResult")
|
||||
}
|
||||
|
||||
@Volatile
|
||||
var lastScreenResult: String = ""
|
||||
private set
|
||||
|
||||
/** 用户把界面关掉了 */
|
||||
fun closeScreen() {
|
||||
screen = null
|
||||
// 等待模式下"关掉"也是一个答案(用户不想选)—— 放行,值是空串
|
||||
screenClosed = true
|
||||
screenLatch?.countDown()
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
/** 进等待模式前由 NativeBridge 调一次,准备闩 */
|
||||
fun armScreenLatch() {
|
||||
screenLatch = CountDownLatch(1)
|
||||
screenAnswer = null
|
||||
screenClosed = false
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 弹窗
|
||||
|
||||
/**
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完。
|
||||
*
|
||||
* ★★ [timeoutMs] <= 0 = **不限时**(默认)。这是用户明确要求的:
|
||||
* "AI 询问界面不要限时" —— 他可能对着选项想很久,或者在忙别的事,
|
||||
* 120 秒到点弹窗自己消失、模型收到 `timeout=true` 以为他不想理,
|
||||
* 然后自说自话往下走 —— 整轮就废了。
|
||||
*
|
||||
* ★ 放行的方式(用户总得有一个出口,不然内核线程永远挂着):
|
||||
* · 点任意一个选项 → [answerDialog] → countDown
|
||||
* · 点「取消」(`allowCancel` 默认 true)→ 同上,`cancelled=true`
|
||||
* · 关掉 App → 进程结束,线程一起没了
|
||||
* 所以只要界面上留着取消按钮,无限等就不会变成死锁。
|
||||
*
|
||||
* ★ 这个函数只会在内核线程上被调,**绝不能在主线程调** ——
|
||||
* 它会 await。MainActivity 那边是通过 device() 进来的,天然是工作线程。
|
||||
*/
|
||||
fun ask(
|
||||
question: String,
|
||||
options: List<Option>,
|
||||
multiple: Boolean,
|
||||
allowCancel: Boolean,
|
||||
conversationId: String,
|
||||
timeoutMs: Long,
|
||||
): JSONObject {
|
||||
val d = Dialog(seq.incrementAndGet(), question, options, multiple, allowCancel, conversationId)
|
||||
val latch = CountDownLatch(1)
|
||||
answerLatch = latch
|
||||
answer = null
|
||||
dialog = d
|
||||
notify("dialog")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,${waitLabel(timeoutMs)})")
|
||||
|
||||
val answered = awaitUser(latch, timeoutMs)
|
||||
val a = answer
|
||||
answerLatch = null
|
||||
answer = null
|
||||
dialog = null
|
||||
notify("dialog")
|
||||
|
||||
if (!answered || a == null) {
|
||||
Log.i(TAG, "用户没在时限内回答")
|
||||
return JSONObject()
|
||||
.put("timeout", true)
|
||||
.put("multiple", multiple)
|
||||
.put("choice", "")
|
||||
.put("values", JSONArray())
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
/**
|
||||
* 等用户动作。
|
||||
*
|
||||
* [timeoutMs] <= 0 → **无限等**(`await()` 不带超时);否则最多等那么久。
|
||||
* 返回 true 表示等到了。
|
||||
*
|
||||
* ★ 只有这一个地方做等待,[ask] 和 [showScreen] 都走它 ——
|
||||
* 两处各写一遍的话,"不限时"这种改动迟早只改到一处。
|
||||
*/
|
||||
private fun awaitUser(latch: CountDownLatch, timeoutMs: Long): Boolean =
|
||||
if (timeoutMs <= 0L) {
|
||||
latch.await()
|
||||
true
|
||||
} else {
|
||||
latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
/** 日志里怎么描述等待时长 */
|
||||
private fun waitLabel(timeoutMs: Long): String =
|
||||
if (timeoutMs <= 0L) "不限时,等用户回答" else "最多等 ${timeoutMs / 1000}s"
|
||||
|
||||
@Volatile
|
||||
private var answerLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var answer: JSONObject? = null
|
||||
|
||||
/** 用户选了。界面调这个。 */
|
||||
fun answerDialog(values: List<String>, cancelled: Boolean) {
|
||||
val arr = JSONArray()
|
||||
values.forEach { arr.put(it) }
|
||||
answer = JSONObject()
|
||||
.put("timeout", false)
|
||||
.put("cancelled", cancelled)
|
||||
.put("multiple", dialog?.multiple ?: false)
|
||||
.put("choice", values.firstOrNull() ?: "")
|
||||
.put("values", arr)
|
||||
answerLatch?.countDown()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 结束对话
|
||||
|
||||
fun markEnded(conversationId: String) {
|
||||
endedConversationId = conversationId
|
||||
notify("ended")
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,295 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Termux 的软件源(apt 源)管理。
|
||||
*
|
||||
* ★ 为什么要单独做这个:Termux 官方源(packages.termux.dev)在国内**基本连不上**,
|
||||
* 表现是 `pkg install` 卡在 "Reading package lists..." 或者直接超时 ——
|
||||
* 用户会以为"内置的 Termux 坏了",其实是源的问题。
|
||||
*
|
||||
* 国内几个镜像都是完整同步的,换一下就好。做成界面而不是让用户手敲 sed:
|
||||
* 换源这件事**每次重装都要做**,而且 apt 的源格式写错一点就整个不能用。
|
||||
*/
|
||||
object TermuxMirror {
|
||||
|
||||
/**
|
||||
* 一个源。
|
||||
*
|
||||
* @param id 稳定标识(存进偏好,别用下标 —— 以后插入新源会串位)
|
||||
* @param name 显示名
|
||||
* @param host 给 termux-main 用的仓库根地址(不带 /apt/ 之后的部分)
|
||||
* @param note 副标题:速度/稳定性之类的实话
|
||||
*/
|
||||
data class Mirror(val id: String, val name: String, val host: String, val note: String)
|
||||
|
||||
/**
|
||||
* 源列表。
|
||||
*
|
||||
* ★ 顺序是有讲究的:**默认放第一个**。
|
||||
* 镜像偶尔会挂(同步中断、证书过期),所以官方源要留着能切回去。
|
||||
*/
|
||||
val MIRRORS = listOf(
|
||||
Mirror(
|
||||
"tuna", "清华 TUNA", "http://mirrors.tuna.tsinghua.edu.cn/termux",
|
||||
"国内最快最稳的一个,推荐",
|
||||
),
|
||||
Mirror(
|
||||
"ustc", "中科大 USTC", "http://mirrors.ustc.edu.cn/termux",
|
||||
"同样完整同步,教育网更快",
|
||||
),
|
||||
Mirror(
|
||||
"aliyun", "阿里云", "http://mirrors.aliyun.com/termux",
|
||||
"公网覆盖好,偶尔缺 science 仓库",
|
||||
),
|
||||
Mirror(
|
||||
"bfsu", "北外 BFSU", "http://mirrors.bfsu.edu.cn/termux",
|
||||
"清华的备份站",
|
||||
),
|
||||
Mirror(
|
||||
"official", "官方源", "http://packages.termux.dev/apt",
|
||||
"国内经常连不上,镜像挂了才用它",
|
||||
),
|
||||
)
|
||||
|
||||
/** Termux 的仓库分几个「频道」,各自一条 sources.list 行 */
|
||||
private data class Channel(val name: String, val path: String, val components: String)
|
||||
|
||||
private val CHANNELS = listOf(
|
||||
Channel("termux-main", "apt/termux-main", "stable main"),
|
||||
Channel("termux-root", "apt/termux-root", "root stable"),
|
||||
Channel("termux-x11", "apt/termux-x11", "x11 main"),
|
||||
)
|
||||
|
||||
private fun aptDir(context: Context) = File(TermuxInstaller.prefix(context), "etc/apt")
|
||||
fun sourcesFile(context: Context) = File(aptDir(context), "sources.list")
|
||||
|
||||
/** 当前用的是哪个源(认不出来就返回 null) */
|
||||
fun current(context: Context): Mirror? {
|
||||
val file = sourcesFile(context)
|
||||
if (!file.exists()) return null
|
||||
val text = try {
|
||||
file.readText()
|
||||
} catch (_: Throwable) {
|
||||
return null
|
||||
}
|
||||
return MIRRORS.firstOrNull { text.contains(it.host) }
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 让 **`pkg`** 也认这个源。
|
||||
*
|
||||
* 踩过的坑:一开始只写了 `etc/apt/sources.list`,结果 `pkg update` 说
|
||||
* "No mirror or mirror group selected",然后**把全世界几十个镜像测了一遍**,
|
||||
* 最后挑了中国连不上的俄罗斯源 —— 用户看到一屏 `bad` 加一句
|
||||
* `E: Unable to determine a suitable packaging system type`。
|
||||
*
|
||||
* 原因:**`pkg` 不看 `sources.list`**,它自己有一套(见 `bin/pkg`):
|
||||
*
|
||||
* if [ -d .../etc/termux/chosen_mirrors ] → 镜像组(取目录下所有文件)
|
||||
* elif [ -f .../etc/termux/chosen_mirrors ] → 单个镜像(**文件本身**就是路径)
|
||||
* elif [ -L ... ] → 断链,退回测全部
|
||||
* else → 没选,测全部
|
||||
*
|
||||
* bootstrap 已经带了 `etc/termux/mirrors/<地区>/<主机名>` 这些源文件,
|
||||
* 内容是 `WEIGHT= / MAIN= / ROOT= / X11=` 的 shell 片段。
|
||||
* `termux-change-repo` 的做法就是**建个符号链接**指过去。这里照做。
|
||||
*/
|
||||
private fun selectForPkg(context: Context, mirror: Mirror): String {
|
||||
val termuxDir = File(TermuxInstaller.prefix(context), "etc/termux")
|
||||
val mirrorsDir = File(termuxDir, "mirrors")
|
||||
val chosen = File(termuxDir, "chosen_mirrors")
|
||||
if (!mirrorsDir.isDirectory) return "没有 mirrors 目录,跳过"
|
||||
|
||||
val hostOnly = mirror.host
|
||||
.removePrefix("https://").removePrefix("http://")
|
||||
.substringBefore('/')
|
||||
|
||||
val target = mirrorsDir.walkTopDown()
|
||||
.filter { it.isFile && it.name == hostOnly }
|
||||
.firstOrNull()
|
||||
?: return "mirrors/ 里没有 $hostOnly"
|
||||
|
||||
try {
|
||||
chosen.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
return try {
|
||||
java.nio.file.Files.createSymbolicLink(chosen.toPath(), target.toPath())
|
||||
"链接到 ${target.name}"
|
||||
} catch (t: Throwable) {
|
||||
// 有些文件系统不给建链接 → 退回复制(pkg 读的是文件内容,效果一样)
|
||||
try {
|
||||
target.copyTo(chosen, overwrite = true)
|
||||
"复制 ${target.name}(建链接失败:${t.javaClass.simpleName})"
|
||||
} catch (t2: Throwable) {
|
||||
"失败:${t2.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 换源。
|
||||
*
|
||||
* ★ 有个坑:Termux 官方的 sources.list **里面是带注释和 deb-src 的**,
|
||||
* 直接整份覆盖会丢掉用户自己加的东西。所以这里只**替换行**:
|
||||
* 凡是以 `deb ` 开头、且指向 termux 仓库的行,按频道重写;
|
||||
* 其余(注释、第三方源)原样留着。
|
||||
*
|
||||
* @return 写进去的行数
|
||||
*/
|
||||
fun set(context: Context, mirror: Mirror): Int {
|
||||
val dir = aptDir(context)
|
||||
dir.mkdirs()
|
||||
val file = sourcesFile(context)
|
||||
|
||||
val existing = if (file.exists()) {
|
||||
try {
|
||||
file.readLines()
|
||||
} catch (_: Throwable) {
|
||||
emptyList()
|
||||
}
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
// 保留非 termux 的行(注释、用户自己加的源)
|
||||
val kept = existing.filter { line ->
|
||||
val t = line.trim()
|
||||
!t.startsWith("deb ") || !t.contains("termux")
|
||||
}
|
||||
|
||||
// ★ 只写**原本就有**的频道:termux-root / termux-x11 这两个仓库
|
||||
// 国内镜像不一定同步了,凭空写进去会让 apt update 整条报错
|
||||
// (一个源 404,apt 就整个失败,用户看到的是"换源之后更坏了")。
|
||||
// main 永远要(没有它 pkg 什么都装不了)。
|
||||
val original = existing.joinToString("\n")
|
||||
val wanted = CHANNELS.filter {
|
||||
it.name == "termux-main" || original.contains(it.name)
|
||||
}
|
||||
|
||||
val header = listOf(
|
||||
"# 由豆包 App 生成 —— 当前源:${mirror.name}",
|
||||
"# 换源:内置终端右上角「源」按钮;也可以手动改这个文件",
|
||||
)
|
||||
val lines = wanted.map { "deb ${mirror.host}/${it.path} ${it.components}" }
|
||||
|
||||
file.writeText(
|
||||
(header + kept.filter { it.isNotBlank() } + lines).joinToString("\n") + "\n",
|
||||
)
|
||||
|
||||
// ★★ 光写 sources.list **不够** —— `pkg` 不看这个文件!
|
||||
// 它有自己的 chosen_mirrors(见 selectForPkg 的注释)。
|
||||
// 不写的话 `pkg update` 会把全世界几十个镜像挨个测一遍,
|
||||
// 最后挑中一个国内连不上的(实测挑中了俄罗斯的 mephi),
|
||||
// 用户看到一屏 `bad` 和 `E: Unable to determine a suitable packaging system type`。
|
||||
val pkgNote = try {
|
||||
selectForPkg(context, mirror)
|
||||
} catch (t: Throwable) {
|
||||
"失败:${t.message}"
|
||||
}
|
||||
android.util.Log.i(
|
||||
"DoubaoTermux",
|
||||
"换源 ${mirror.name}:sources.list ${lines.size} 条;pkg $pkgNote",
|
||||
)
|
||||
return lines.size
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 当前源要是**用不了**,自动换一个能用的。
|
||||
*
|
||||
* ## 为什么需要
|
||||
*
|
||||
* 用户实测撞到的(原话):
|
||||
*
|
||||
* E: Failed to fetch .../binary-x86_64/Packages.bz2
|
||||
* File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
* E: Some index files failed to download. They have been ignored,
|
||||
* or old ones used instead.
|
||||
*
|
||||
* 这是**镜像正在同步**时的典型症状:`InRelease` 已经是新的了,
|
||||
* 但 `Packages.bz2` 还是旧的,apt 一对哈希就拒绝。用户侧完全没辙 ——
|
||||
* 「源」按钮他按了也没用(换到的还是同一个坏源,或者他根本不知道该换)。
|
||||
*
|
||||
* 而我们**默认给的就是清华**([MIRRORS] 第一个)。镜像偶尔同步是常态,
|
||||
* 所以这不是"清华不好",是"任何单一默认值都会偶尔把用户卡死"。
|
||||
*
|
||||
* ## 做法
|
||||
*
|
||||
* 真跑一次 `apt-get update` 当探测 —— **不自己写校验逻辑**:
|
||||
*
|
||||
* · apt 的校验比我们严(哈希、时间戳、架构都对),复用它最准
|
||||
* · 反正换源之后本来就要 update,探测这一步不白花
|
||||
* · 自己写"拉 InRelease 看看"那种轻量探针**测不出这个 bug** ——
|
||||
* InRelease 恰恰是好的那一半
|
||||
*
|
||||
* 当前源能用就**什么都不做**(不打扰用户的选择)。
|
||||
* 用不了才按 [MIRRORS] 顺序往下试,换成功就记住(写 sources.list + pkg 那套)。
|
||||
*
|
||||
* @param onSwitched 换成功时回调(给界面提示用),参数是新的源
|
||||
* @return 最终可用的源;全都不可用时返回 null
|
||||
*/
|
||||
fun autoPickIfBroken(context: Context, onSwitched: ((Mirror) -> Unit)? = null): Mirror? {
|
||||
val current = current(context) ?: MIRRORS.first()
|
||||
|
||||
if (probe(context, current)) return current
|
||||
|
||||
android.util.Log.i("DoubaoTermux", "源 ${current.name} 探测失败,开始找能用的")
|
||||
for (candidate in MIRRORS) {
|
||||
if (candidate.id == current.id) continue
|
||||
if (!probe(context, candidate)) continue
|
||||
val n = set(context, candidate)
|
||||
android.util.Log.i("DoubaoTermux", "已自动切到 ${candidate.name}($n 条)")
|
||||
onSwitched?.invoke(candidate)
|
||||
return candidate
|
||||
}
|
||||
android.util.Log.w("DoubaoTermux", "所有源都探测失败,保持 ${current.name}")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测一个源能不能用:**临时**写进 sources.list 跑一次 `apt-get update`,
|
||||
* 不管成败都把原来的 sources.list 还原回去。
|
||||
*
|
||||
* ★ 必须还原:探测失败时若留着半个写入状态,用户会看到"源莫名其妙变了"。
|
||||
*/
|
||||
private fun probe(context: Context, mirror: Mirror): Boolean {
|
||||
val file = sourcesFile(context)
|
||||
val backup = try {
|
||||
if (file.exists()) file.readText() else null
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
return try {
|
||||
set(context, mirror)
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val pb = ProcessBuilder("$prefix/bin/apt-get", "update")
|
||||
.directory(TermuxInstaller.home(context))
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
// 输出必须读掉,否则管道写满会把子进程卡死(apt 输出很多)
|
||||
val sink = Thread { proc.inputStream.readBytes(); proc.errorStream.readBytes() }
|
||||
sink.isDaemon = true
|
||||
sink.start()
|
||||
val ok = proc.waitFor(PROBE_TIMEOUT_S, java.util.concurrent.TimeUnit.SECONDS) &&
|
||||
proc.exitValue() == 0
|
||||
if (!ok) proc.destroyForcibly()
|
||||
ok
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.i("DoubaoTermux", "探测 ${mirror.name} 抛异常:${t.message}")
|
||||
false
|
||||
} finally {
|
||||
try {
|
||||
if (backup != null) file.writeText(backup) else file.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测超时。apt 卡住时不能把用户等死 */
|
||||
private const val PROBE_TIMEOUT_S = 45L
|
||||
}
|
||||
@@ -39,10 +39,21 @@ object TermuxShell {
|
||||
return try {
|
||||
// 用 -c 而不是 -lc:登录式会去 source 编译期写死的 /etc/profile(那是别的包的路径),
|
||||
// 每次都在 stderr 里冒一条 Permission denied。rc 该设的东西我们在环境变量里都设好了。
|
||||
val proc = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
//
|
||||
// ★★★ 用 `childEnvMap()` 而不是 `environment()`:ProcessBuilder 起的是
|
||||
// 子进程,**默认继承整个 App 进程的环境**,而里面带着 Chaquopy 注入的
|
||||
// `PYTHONPATH`(指向 3.13 编的 .imy)。不清掉的话 Termux 的 python 3.14
|
||||
// 一起来就读到 3.13 的 encodings/__init__.pyc,魔数不符直接核心崩溃:
|
||||
// Fatal Python error: Failed to import encodings module
|
||||
// 详见 TermuxInstaller.childEnv 的注释。
|
||||
//
|
||||
// ★ `environment().putAll(...)` 这种写法是**追加**,删不掉已有的键 ——
|
||||
// 所以必须显式摘掉那几个变量(childEnvMap 做了这件事)。
|
||||
val pb = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
.directory(workdir)
|
||||
.apply { environment().putAll(TermuxInstaller.environment(context)) }
|
||||
.start()
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
|
||||
// 读流要放到线程里,否则大输出会把管道塞满导致死锁
|
||||
val outBuf = StringBuilder()
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 真·终端会话:用 Termux 自己的 pty(libtermux.so 的 JNI)+ 它的终端模拟器。
|
||||
@@ -23,62 +24,209 @@ class TermuxTerminal(private val context: Context) {
|
||||
var session: TerminalSession? = null
|
||||
private set
|
||||
|
||||
/** 这次是用哪种起法建起来的(写进日志,排查时一眼能看到是哪一步坏的) */
|
||||
@Volatile
|
||||
var startedWith: String = ""
|
||||
private set
|
||||
|
||||
/**
|
||||
* 开一个登录 shell。Termux 的标准做法就是跑 `$PREFIX/bin/login`,
|
||||
* 它会按 /etc/profile 把 PATH、PS1、动态库路径都准备好。
|
||||
* ★★★ 必须把 `TerminalView` 接进来,否则**屏幕永远不刷新**。
|
||||
*
|
||||
* Termux 的分工是:会话把输出解析进 emulator 的屏幕缓冲,
|
||||
* 然后通过 `TerminalSessionClient.onTextChanged()` 通知"该重画了",
|
||||
* 由 `TerminalView.onScreenUpdated()` 真正去 invalidate。
|
||||
*
|
||||
* 我这里的 `onTextChanged` 之前是**空的** —— 于是:pty 通了、bash 活着、
|
||||
* 输出也解析进缓冲了,**但屏幕一动不动**,看起来像"什么都没发生"。
|
||||
* (这个坑和 pty 那个是两回事,修好 argv 之后才暴露出来。)
|
||||
*/
|
||||
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||
@Volatile
|
||||
var view: TerminalView? = null
|
||||
|
||||
|
||||
/** 用完了没有(决定要不要切成命令控制台) */
|
||||
val candidatesExhausted: Boolean get() = candidateIndex >= candidateCount
|
||||
|
||||
private var candidateIndex = 0
|
||||
private var candidateCount = 0
|
||||
|
||||
/**
|
||||
* ★ 诊断用:`cat` 无参数时**一直读 stdin**,不会自己退出。
|
||||
*
|
||||
* 三种环境各试一次,就能定位到底哪一段环境变量把子进程搞坏了:
|
||||
* A. 干净环境(只留 PATH=/system/bin)—— 系统二进制,测 pty 本身
|
||||
* B. 干净环境 + 我们自己的 bash —— 测 bash 在干净环境下活不活
|
||||
* C. 完整环境(现在的默认)
|
||||
*
|
||||
* 怀疑点:`LD_LIBRARY_PATH=$prefix/lib` 会**屏蔽系统库**,
|
||||
* 系统二进制(toybox 之类)因此加载失败 → exec 返回 127。
|
||||
* 定位完这几条诊断候选都删掉。
|
||||
*/
|
||||
private fun cleanEnv(): List<String> = listOf(
|
||||
"PATH=/system/bin:/system/xbin",
|
||||
"HOME=/data",
|
||||
"TERM=xterm-256color",
|
||||
"LANG=en_US.UTF-8",
|
||||
)
|
||||
|
||||
private fun candidateList(): List<Triple<String, Array<String>, Boolean>> {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val rc = TermuxInstaller.interactiveShellArgs(context)
|
||||
return listOf(
|
||||
// ⓪-A 干净环境跑 cat:能挂住 → pty 没问题
|
||||
// ⓪-B 干净环境跑我们的 bash
|
||||
Triple("$prefix/bin/bash", rc, false),
|
||||
// ★★ 决定性实验(定位完删):让**子进程自己**把关键信息
|
||||
// **重定向到文件**(这样绕开 pty,不依赖输出通道通不通)。
|
||||
//
|
||||
// 要看的是 fd 0/1/2 到底指向什么:
|
||||
// · 指向 /dev/pts/N → 从端接上了,EIO 另有原因
|
||||
// · 指向别的东西/没有 → 从端根本没接上(那就是根因)
|
||||
// `tty` 和 `stty` 顺带验证"是不是一个真正的终端"。
|
||||
// ★ 用 **/system/bin/sh**(toybox 的 sh)而不是我们 prefix 里的:
|
||||
// 它不依赖 Termux 的库,变量最少,能干净地回答"子进程的 fd 是什么"。
|
||||
// 输出写**绝对路径**,别用 $PREFIX(那种环境里不一定会展开)。
|
||||
Triple(
|
||||
"/system/bin/sh",
|
||||
arrayOf(
|
||||
"-c",
|
||||
"{ echo '=== fds ==='; ls -l /proc/self/fd; " +
|
||||
"echo '=== tty ==='; tty; echo tty_exit=$?; " +
|
||||
"echo '=== stty ==='; stty -a 2>&1 | head -2; " +
|
||||
"echo '=== tty_nr ==='; awk '{print $7}' /proc/self/stat; " +
|
||||
"} > /data/user/0/com.doubao.lynxclone/files/childinfo.txt 2>&1; sleep 20",
|
||||
),
|
||||
true,
|
||||
),
|
||||
// ① 直接 bash + 我们自己的 rc(正常路径)
|
||||
Triple("$prefix/bin/bash", rc, true),
|
||||
// ② ★ **不带 LD_PRELOAD** 起。
|
||||
//
|
||||
// `libtermux-exec.so` 是拦 execve/open 的 .so,让二进制里写死的
|
||||
// `/data/data/com.termux/...` 在运行时被改写到我们的 prefix。
|
||||
// 但它**在 pty 里可能把 stdin 搞坏** —— 实测现象是:
|
||||
// bash 的 rc 正常跑完(那行 echo 打出来了),然后读 stdin 直接 EOF
|
||||
// 就退出(退出码 0),终端上只剩 [Process completed]。
|
||||
// 去掉它 bash 只认编译期路径(读不到 /etc/profile),
|
||||
// 但**至少能交互** —— 哪个能用用哪个。
|
||||
Triple("$prefix/bin/bash", rc, false),
|
||||
// ③ Termux 的登录入口(有些机型上它才行;实测退出码 126)
|
||||
Triple("$prefix/bin/login", arrayOf("$prefix/bin/login", "-shell", "$prefix/bin/bash"), true),
|
||||
// ④ 最朴素的兜底:不带 preload。★ 第一个元素仍是程序名(见 interactiveShellArgs)
|
||||
Triple("$prefix/bin/bash", arrayOf("$prefix/bin/bash", "-i"), false),
|
||||
)
|
||||
}
|
||||
|
||||
private fun tryCreate(
|
||||
onTitle: (String) -> Unit,
|
||||
onExit: () -> Unit,
|
||||
): TerminalSession? {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val home = TermuxInstaller.home(context).absolutePath
|
||||
val env = TermuxInstaller.environment(context).map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
val baseEnv = TermuxInstaller.childEnv(context)
|
||||
|
||||
val client = object : TerminalSessionClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||
TermuxInstaller.trace(context, "终端会话结束,退出码=${finishedSession.exitStatus}")
|
||||
onExit()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||
}
|
||||
val list = candidateList()
|
||||
candidateCount = list.size
|
||||
if (candidateIndex >= list.size) {
|
||||
TermuxInstaller.trace(context, "所有起法都试过了")
|
||||
return null
|
||||
}
|
||||
val (shell, args, usePreload) = list[candidateIndex]
|
||||
if (!File(shell).exists()) {
|
||||
TermuxInstaller.trace(context, "$shell 不在,跳过")
|
||||
return tryNextCandidate(onTitle, onExit)
|
||||
}
|
||||
// 前两条候选(诊断用)走**干净环境**:只留 PATH/HOME/TERM/LANG。
|
||||
// 目的就是把"环境变量把子进程搞坏"这个可能性单独拎出来验。
|
||||
val env = when {
|
||||
candidateIndex < 0 -> cleanEnv()
|
||||
usePreload -> baseEnv
|
||||
else -> baseEnv.filterNot { s: String -> s.startsWith("LD_PRELOAD=") }
|
||||
}
|
||||
startedWith = "$shell ${args.joinToString(" ")}" + if (usePreload) "" else "(不带 preload)"
|
||||
return try {
|
||||
val created = TerminalSession(shell, home, args, env.toTypedArray(), 2000, client(onTitle, onExit))
|
||||
TermuxInstaller.trace(context, "终端会话已建:$startedWith")
|
||||
session = created
|
||||
created
|
||||
} catch (t: Throwable) {
|
||||
TermuxInstaller.trace(context, "起 $shell 抛异常:${t.javaClass.simpleName}: ${t.message}")
|
||||
tryNextCandidate(onTitle, onExit)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||
}
|
||||
/**
|
||||
* ★ 秒退之后换下一种起法。
|
||||
*
|
||||
* 关键点:**"起法失败"不是靠异常发现的** ——
|
||||
* bash 起得来(构造函数不抛)、rc 也跑了,然后读 stdin 拿到 EOF 就退出。
|
||||
* 从代码角度看一切正常,只有"退出得太快"这个**事件**能说明它坏了。
|
||||
* 所以回退必须由秒退来驱动(TerminalScreen 在秒退回调里调这个)。
|
||||
*
|
||||
* @return 还有下一种就返回新会话;都用完了返回 null
|
||||
*/
|
||||
fun tryNextCandidate(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession? {
|
||||
candidateIndex += 1
|
||||
TermuxInstaller.trace(context, "换下一种起法(第 ${candidateIndex + 1} 种)")
|
||||
return tryCreate(onTitle, onExit)
|
||||
}
|
||||
|
||||
override fun onBell(session: TerminalSession) {}
|
||||
override fun onColorsChanged(session: TerminalSession) {}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||
/** 光标样式:0=块 1=竖线 2=下划线,用 Termux 的默认值 */
|
||||
override fun getTerminalCursorStyle(): Int = 1
|
||||
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
/**
|
||||
* 开一个登录 shell。
|
||||
*
|
||||
* ★ 会**依次试几种起法**,哪个活下来用哪个。
|
||||
* 为什么要试:pty 的从端没接上时 shell 的 stdin 立刻 EOF,
|
||||
* bash 读不到东西**直接退出(退出码 0)** —— 现象是"终端一闪就没了",
|
||||
* 而且**看不出是哪一步坏的**。分步试 + 每步落盘就能定位。
|
||||
*/
|
||||
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||
candidateIndex = 0
|
||||
return tryCreate(onTitle, onExit)
|
||||
?: throw IllegalStateException("$prefixPath 下没有能用的 shell")
|
||||
}
|
||||
|
||||
private val prefixPath: String get() = TermuxInstaller.prefix(context).absolutePath
|
||||
|
||||
private fun client(onTitle: (String) -> Unit, onExit: () -> Unit) = object : TerminalSessionClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {
|
||||
// ★ 这一行就是"屏幕刷新"的开关,别删(见 view 字段的注释)
|
||||
val v = view ?: return
|
||||
v.post { v.onScreenUpdated() }
|
||||
}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||
TermuxInstaller.trace(
|
||||
context,
|
||||
"终端会话结束,退出码=${finishedSession.exitStatus} 用的=$startedWith",
|
||||
)
|
||||
onExit()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||
}
|
||||
|
||||
val created = TerminalSession(
|
||||
"$prefix/bin/bash",
|
||||
home,
|
||||
// 用我们自己的 rc:Termux 的 bash 带的是编译期路径 /data/data/com.termux/...,
|
||||
// 直接当登录 shell 跑会去读别的包的 profile,报权限拒绝
|
||||
TermuxInstaller.interactiveShellArgs(context),
|
||||
env,
|
||||
2000,
|
||||
client,
|
||||
)
|
||||
session = created
|
||||
return created
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||
}
|
||||
|
||||
override fun onBell(session: TerminalSession) {}
|
||||
override fun onColorsChanged(session: TerminalSession) {}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||
/** 光标样式:0=块 1=竖线 2=下划线 */
|
||||
override fun getTerminalCursorStyle(): Int = 1
|
||||
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
/** 给 TerminalView 用的客户端:把按键/手势接上,其余保持默认行为 */
|
||||
|
||||
@@ -0,0 +1,608 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.R
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.PRESETS
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.foundation.Image
|
||||
|
||||
/*
|
||||
* 智能体的完整编辑界面(需求 2.5 / 3.1 / 3.3 / 3.5 / 3.6 / 3.7)。
|
||||
*
|
||||
* ## ★ 为什么是全屏,而不是沿用那个弹窗
|
||||
*
|
||||
* 字段从 8 个涨到了二十多个(外观四件套、模型引用、世界观、限额、技能……)。
|
||||
* AGENTS.md 里那张表写得很清楚:「**列表 / 多组配置 / 任何要滚动的 → 独立全屏界面**」,
|
||||
* 而"节点配置 NodeConfigDialog → 全屏(字段很多)"到现在还挂在待办清单上 ——
|
||||
* 这次不再欠新账。
|
||||
*
|
||||
* ## 三处会让人困惑的地方,界面上直接说清
|
||||
*
|
||||
* ① **介绍(description)和一句话介绍(tagline)不是一回事**:
|
||||
* 前者只在选择界面的介绍框里显示,后者是列表里的摘要。
|
||||
* ② **绑了世界观 = 记忆变成共享的**(需求 3.6)—— 不写清楚,
|
||||
* 用户会以为"我给 A 记的东西怎么 B 也知道"。
|
||||
* ③ **限额 0 就是无限制**,不是"限额为 0"。
|
||||
*/
|
||||
|
||||
/** 除立绘以外的三件套(立绘是**五档**的,单独处理) */
|
||||
private val ASSET_SLOTS = listOf(
|
||||
Triple("back", "背景图", "铺在展示区最底层;缺了用内置默认背景"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区;缺了用简单方框"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本;缺了跟主体边框一个样式"),
|
||||
)
|
||||
|
||||
/** 立绘五档各档的说明 —— 每档都要写清"缺了会退回哪张",不然用户不知道该传几张 */
|
||||
private fun portraitHint(preset: String): String = when (preset) {
|
||||
"喜" -> "高兴时用这张;缺了用「平常」那张"
|
||||
"怒" -> "发怒时用这张;缺了用「平常」那张"
|
||||
"哀" -> "悲伤时用这张;缺了用「平常」那张"
|
||||
"死亡" -> "死亡时用这张(那时不能对话);缺了用「平常」那张"
|
||||
else -> "其他档都缺时兜底用这张;连它也没有就用内置默认人物"
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AgentEditScreen(
|
||||
vm: AppViewModel,
|
||||
initial: Agent?,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
val isNew = initial == null
|
||||
var draft by remember { mutableStateOf(initial ?: Agent(avatar = "custom")) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var promptDraft by remember { mutableStateOf(draft.systemPrompt) }
|
||||
var limitDraft by remember { mutableStateOf(
|
||||
if (draft.tokenLimit > 0) draft.tokenLimit.toInt().toString() else ""
|
||||
) }
|
||||
val ctx = LocalContext.current
|
||||
|
||||
// 选一张外观图 → 读字节 → base64 → 立刻上传
|
||||
// ★ 不等"保存":图片可能好几 MB,混在保存里用户会以为卡死了
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
|
||||
// 读图 / 压缩 / 上传全在 ViewModel 的 IO 线程里 ——
|
||||
// launcher 回调是**主线程**,解码一张 30MB 的手机照片放这儿会卡死界面
|
||||
vm.uploadAgentAssetFrom(ctx.applicationContext, draft.id, slot, uri)
|
||||
}
|
||||
|
||||
// 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。
|
||||
// ★ 包里**只有**名字/介绍/提示词/外观四件套 —— 模型引用、世界观绑定、限额
|
||||
// 一律不进包(需求 2.5 的"包的边界约定"),更不会有 API Key。
|
||||
var pendingZip by remember { mutableStateOf<String?>(null) }
|
||||
val saveZip = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.CreateDocument("application/zip"),
|
||||
) { uri ->
|
||||
val data = pendingZip
|
||||
pendingZip = null
|
||||
if (uri != null && data != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openOutputStream(uri)
|
||||
?.use { it.write(Base64.decode(data, Base64.DEFAULT)) }
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = if (isNew) "新建智能体" else "编辑智能体",
|
||||
subtitle = if (isNew) "保存后可以加外观图片" else draft.name,
|
||||
onBack = onDone,
|
||||
actions = {
|
||||
TopAction("保存", enabled = !saving) {
|
||||
saving = true
|
||||
vm.saveAgentFull(
|
||||
draft.copy(systemPrompt = promptDraft, tokenLimit = limitDraft.toDoubleOrNull() ?: 0.0),
|
||||
isNew,
|
||||
) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
) {
|
||||
// 编辑中的智能体可能是**别处刚改过**的(比如刚上传完图片)——
|
||||
// vm.agents 里的那份才是最新的,这里同步一下,否则预览是旧的
|
||||
val fresh = vm.agents.firstOrNull { it.id == draft.id }
|
||||
if (!isNew && fresh != null && fresh.image != draft.image) {
|
||||
draft = draft.copy(image = fresh.image)
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
|
||||
/* ---------------- 基本信息 ---------------- */
|
||||
SectionLabel("基本信息")
|
||||
Card {
|
||||
LabeledField("名字", draft.name, "比如:玄辰") { draft = draft.copy(name = it) }
|
||||
Spacer(Modifier.height(10.dp))
|
||||
LabeledField("一句话介绍", draft.greeting, "列表里的摘要,比如:仙门大师兄") {
|
||||
draft = draft.copy(greeting = it)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("显示在智能体列表里。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
LabeledField("介绍文案", draft.description, "选择界面右边那个介绍框里显示的话") {
|
||||
draft = draft.copy(description = it)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("★ 和上面那条不一样:这条只在选择智能体时的介绍框里显示。留空就只显示名字。")
|
||||
}
|
||||
|
||||
/* ---------------- 外观 ---------------- */
|
||||
SectionLabel("外观")
|
||||
Card {
|
||||
if (isNew) {
|
||||
// ★ 图片要落到"这个智能体的资源目录"里,所以必须先在库里有一条记录
|
||||
Text(
|
||||
"先点右上角「保存」把智能体建出来,再回来加外观图片。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
// ---- 立绘:五档(v1.2 需求 2.5 / 2.6)----
|
||||
//
|
||||
// ★ 槽位名带档位(`front:喜`),内核按这个落到不同文件 ——
|
||||
// 五档存成一张的话会互相覆盖。
|
||||
Text("角色立绘(按情绪换)", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Hint(
|
||||
"情绪的五档各自一张图,缺哪档就退回「平常」那张。" +
|
||||
"现在显示的是「${draft.image.portrait.ifBlank { "内置默认人物" }}」那张。",
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
for (preset in PRESETS) {
|
||||
AssetRow(
|
||||
title = preset,
|
||||
desc = portraitHint(preset),
|
||||
path = draft.image.slot(preset),
|
||||
onPick = {
|
||||
pendingSlot = "front:$preset"
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
|
||||
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
|
||||
showDefaultPerson = true,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// ---- 其余三件套 ----
|
||||
Text("其他三件套", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
for ((key, title, desc) in ASSET_SLOTS) {
|
||||
AssetRow(
|
||||
title = title,
|
||||
desc = desc,
|
||||
path = draft.image.pathOf(key),
|
||||
onPick = { pendingSlot = key; pickImage.launch(arrayOf("image/*")) },
|
||||
onClear = { vm.uploadAgentAsset(draft.id, key, "", "") },
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Hint("支持 PNG / JPG / GIF(动图会动)。SVG 也能显示。缺哪张就用内置默认。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 人设 ---------------- */
|
||||
SectionLabel("人设(系统提示词)")
|
||||
Card {
|
||||
OutlinedTextField(
|
||||
value = promptDraft,
|
||||
onValueChange = { promptDraft = it },
|
||||
placeholder = { Text("你是一个……", fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp, max = 320.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("留空就用全局系统提示词。记忆、情绪、世界观、技能会自动拼在这后面,不用你自己写。")
|
||||
}
|
||||
|
||||
/* ---------------- 模型 ---------------- */
|
||||
SectionLabel("模型")
|
||||
Card {
|
||||
val entries = vm.state.modelEntries
|
||||
if (entries.isEmpty()) {
|
||||
Hint("还没有全局模型。去「设置 → 超时」上面的「全局模型」里加一个,就能在这里引用它。")
|
||||
} else {
|
||||
ChipRow(
|
||||
options = listOf("" to "跟随全局") + entries.map { it.id to it.name },
|
||||
active = draft.modelId,
|
||||
onPick = { draft = draft.copy(modelId = it) },
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("选了它就固定用那个模型;「跟随全局」= 用设置里当前选的那个。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 世界观 ---------------- */
|
||||
SectionLabel("世界观")
|
||||
Card {
|
||||
val worlds = vm.state.worldviews
|
||||
ChipRow(
|
||||
options = listOf("" to "不绑定") + worlds.map { it.id to it.name },
|
||||
active = draft.worldviewId,
|
||||
onPick = { draft = draft.copy(worldviewId = it) },
|
||||
)
|
||||
if (draft.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// ★ 选世界观的时候就要看到"已经有谁在"(用户问的"哪些智能体绑了它")。
|
||||
// 这是**决策依据**:如果里面已经有三个角色,加进去意味着
|
||||
// 四份记忆混在一个空间里;如果只有它一个,那基本等于私有。
|
||||
val wv = vm.state.worldviews.firstOrNull { it.id == draft.worldviewId }
|
||||
val others = (wv?.agents ?: emptyList()).filter { it.id != draft.id }
|
||||
Text(
|
||||
if (others.isEmpty()) "目前只有它用这个世界观(记忆实际上还是自己一份)"
|
||||
else "已经有 ${others.size} 个智能体在用:${others.joinToString("、") { it.name }}",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (others.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"★ 绑定之后:提示词里会多一段世界观设定," +
|
||||
"而且记忆会和上面这些智能体共享(它们也能看到并写入同一个空间," +
|
||||
"但只能改自己写的那几条)。\n" +
|
||||
"情绪仍然是私有的(不会共享)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
if (worlds.isEmpty()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("还没有世界观。在「更多功能 → 世界观」里新建或导入一个。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 能力 ---------------- */
|
||||
SectionLabel("能力")
|
||||
Card {
|
||||
ToggleRow(
|
||||
title = "情绪感知",
|
||||
sub = "能看到同世界观其他智能体当前的情绪(只读,单向)",
|
||||
checked = draft.emotionEnabled,
|
||||
onChange = { draft = draft.copy(emotionEnabled = it) },
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("Token 限额", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = limitDraft,
|
||||
onValueChange = { s -> limitDraft = s.filter { it.isDigit() }.take(9) },
|
||||
placeholder = { Text("留空 = 无限制", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("用满之后会拦住发送,并附一句告别(那句话可以在设置里改)。留空就是无限制。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
// ★ v1.2 §6.1:拉起其他智能体的方式。
|
||||
// 内核(`agent_tools.invite_agent`)早就按这个字段分流了,
|
||||
// 但界面上一直**没有入口** —— 于是 `confirm` 那一档
|
||||
// 用户永远打不开,等于需求里这个选项不存在。
|
||||
ToggleRow(
|
||||
title = "拉人要先问我",
|
||||
sub = "打开后,AI 想邀请别的智能体进群时会先问一句;" +
|
||||
"关闭则直接拉进来(都会在正文里说一声)。",
|
||||
checked = draft.inviteMode == "confirm",
|
||||
onChange = { draft = draft.copy(inviteMode = if (it) "confirm" else "silent") },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 技能 ---------------- */
|
||||
SectionLabel("技能(Skill)")
|
||||
Card {
|
||||
val all = vm.state.skills
|
||||
if (all.isEmpty()) {
|
||||
Hint("还没有自定义 Skill。内置的记忆/情绪/用量手册默认就生效,不用在这里选。")
|
||||
} else {
|
||||
for (s in all) {
|
||||
val on = s.id in draft.skillIds
|
||||
ToggleRow(
|
||||
title = s.name.ifBlank { "未命名 Skill" },
|
||||
sub = s.content.lineSequence().firstOrNull()?.take(60) ?: "",
|
||||
checked = on,
|
||||
onChange = { v ->
|
||||
draft = draft.copy(
|
||||
// ★ 按**勾选顺序**排:需求 3.7 说"按绑定顺序拼接注入",
|
||||
// 顺序会影响模型读到的先后,所以不能是 Set
|
||||
skillIds = if (v) draft.skillIds + s.id
|
||||
else draft.skillIds.filter { it != s.id },
|
||||
)
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Hint("勾选顺序就是注入顺序(先勾的在前)。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 语音 ---------------- */
|
||||
SectionLabel("语音")
|
||||
Card {
|
||||
// ★ 这里**只选音色**,不选引擎 —— 引擎是"用哪套语音服务",
|
||||
// 属于全局设置(换引擎时音色名整套都不一样,混在一个界面里
|
||||
// 必然出现"选了引擎、音色还是上一家的"这种状态)。
|
||||
Hint("引擎跟随全局(在「设置 → 语音」里换)。想给这个智能体一个不同的嗓音,就在下面选音色。")
|
||||
Spacer(Modifier.height(10.dp))
|
||||
val engine = vm.state.speech.ttsEngine
|
||||
VoicePickerInline(
|
||||
engine = engine,
|
||||
voices = vm.state.speechVoices[engine] ?: emptyList(),
|
||||
voicesAll = vm.state.speechVoicesAll[engine] ?: emptyList(),
|
||||
value = draft.ttsVoice,
|
||||
onValue = { draft = draft.copy(ttsVoice = it) },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 记忆 / 用量 ---------------- */
|
||||
if (!isNew) {
|
||||
SectionLabel("它的状态")
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
BigAction("看它记住了什么") { vm.openMemories(draft.id) }
|
||||
BigAction("看它用了多少") { vm.openTokenUsage(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp)) {
|
||||
Hint(
|
||||
"记忆是 AI 自己攒的(也可能记错),觉得不对就在那里改 —— " +
|
||||
"这是它记错时唯一的兜底。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导出 / 删除 ---------------- */
|
||||
if (!isNew) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
RowAction("导出这个智能体(.zip)") {
|
||||
vm.exportPackage("agents", draft.id) { content, _ -> pendingZip = content }
|
||||
}
|
||||
Text(
|
||||
"包里只有名字、介绍、提示词和外观图片;模型、世界观、限额不进包,更没有 API Key。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
if (pendingZip != null) {
|
||||
LaunchedEffect(pendingZip) {
|
||||
saveZip.launch("${draft.name.ifBlank { "agent" }}.zip")
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isNew && !draft.builtin) {
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 12.dp), contentAlignment = Alignment.Center) {
|
||||
RowAction("删除这个智能体", danger = true) {
|
||||
vm.deleteAgentFull(draft.id) { onDone() }
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private fun AgentImage.pathOf(key: String): String = when (key) {
|
||||
// v1.2:立绘是五档表,编辑界面的**预览**用内核算好的那张
|
||||
// (其他三件套还是单张)
|
||||
"front" -> portrait
|
||||
"back" -> back
|
||||
"border-main" -> borderMain
|
||||
else -> borderInfo
|
||||
}
|
||||
|
||||
// ★ `Card` / `Hint` 已经挪到 DoubaoUi.kt 变成公共组件了 ——
|
||||
// 原来它们是这个文件私有的,于是别的界面想用只能复制一份
|
||||
// ([群成员] 就要用),而"同一段逻辑抄两份"是这个仓库的老毛病。
|
||||
|
||||
/** 一行里并排的两个入口按钮(记忆 / 用量这种"跳去另一个界面"的动作) */
|
||||
@Composable
|
||||
private fun BigAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LabeledField(
|
||||
label: String,
|
||||
value: String,
|
||||
placeholder: String,
|
||||
onChange: (String) -> Unit,
|
||||
) {
|
||||
Text(label, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onChange,
|
||||
placeholder = { Text(placeholder, fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChipRow(
|
||||
options: List<Pair<String, String>>,
|
||||
active: String,
|
||||
onPick: (String) -> Unit,
|
||||
) {
|
||||
Column {
|
||||
for (row in options.chunked(3)) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 3.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
for ((key, label) in row) {
|
||||
val on = key == active
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { onPick(key) }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ToggleRow(
|
||||
title: String,
|
||||
sub: String,
|
||||
checked: Boolean,
|
||||
onChange: (Boolean) -> Unit,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 14.sp, color = doubaoText())
|
||||
if (sub.isNotBlank()) {
|
||||
Text(sub, fontSize = 11.sp, lineHeight = 15.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(width = 44.dp, height = 26.dp)
|
||||
.clip(RoundedCornerShape(13.dp))
|
||||
.background(if (checked) Doubao.Blue else Doubao.Border)
|
||||
.clickable { onChange(!checked) },
|
||||
contentAlignment = if (checked) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(20.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color.White),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 一个外观槽位:小预览 + 标题说明 + 选图 / 清除 */
|
||||
@Composable
|
||||
private fun AssetRow(
|
||||
title: String,
|
||||
desc: String,
|
||||
path: String,
|
||||
onPick: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
/**
|
||||
* 空的时候要不要显示**内置默认人物**的缩略图。
|
||||
*
|
||||
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
|
||||
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
|
||||
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
|
||||
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
|
||||
*/
|
||||
showDefaultPerson: Boolean = false,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(52.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (path.isBlank()) {
|
||||
if (showDefaultPerson) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
alpha = 0.35f,
|
||||
)
|
||||
} else {
|
||||
Text("空", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
} else {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, lineHeight = 14.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
RowAction("选择") { onPick() }
|
||||
if (path.isNotBlank()) RowAction("清除", danger = true) { onClear() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.LinearOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.R
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/*
|
||||
* 智能体选择界面(需求第二章)。
|
||||
*
|
||||
* ## 布局(需求 2.1)
|
||||
*
|
||||
* 左侧:智能体列表(纵向、当前项高亮)
|
||||
* 右侧:角色展示区,**四层叠加**:
|
||||
* ① 背景图(铺满)② 主体边框(框住展示区)③ 角色图(居中)④ 介绍边框(围住介绍文本)
|
||||
*
|
||||
* ## 切换动画(需求 2.3,定稿参数)
|
||||
*
|
||||
* ① 旧角色图渐出 + 侧移 0.3s ease-in
|
||||
* ② 间隔 0.5s
|
||||
* ③ 边框/背景/介绍 滑出滑入 0.4s ease-in-out
|
||||
* ④ 新角色图渐入 + 侧移到位 0.3s ease-out
|
||||
* 合计约 1.5s。
|
||||
*
|
||||
* **方向**:目标在当前**之下**(列表靠后)→ 向左切换;**之上** → 向右。
|
||||
*
|
||||
* **连续快速切换立即打断**:靠 `LaunchedEffect(选中的 id)` —— 换目标时
|
||||
* 上一个协程直接被取消,而 `Animatable` 会**停在当前值**,所以新动画
|
||||
* 是从眼前的画面接着走的,不会闪回。这正是需求要的"从当前视觉状态
|
||||
* 直接过渡到最新目标,不做排队"。
|
||||
*
|
||||
* ## ★ 默认资源回退(需求 2.6)
|
||||
*
|
||||
* 角色图缺 → 内置默认人物;背景缺 → 内置默认背景;边框缺 → **简单方框**。
|
||||
* 回退优先级:`smartInfo.json 指定 → 包内同名 → 内置默认`。
|
||||
* 前两级在内核导入时就落定了(存的是绝对路径),所以这里只做最后一级。
|
||||
*
|
||||
* ★ "任何智能体至少能以「默认人物 + 默认背景 + 方框边框」正常展示" ——
|
||||
* 所以**每个槽位都必须有兜底**,不能出现空白展示区。
|
||||
*/
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 动画参数(需求 2.3:所有时长收进全局配置) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/*
|
||||
* ★ 下面这四个是**兜底默认值**,真正生效的值从全局配置里读
|
||||
* (设置 →「超时」→「动画」那一组,内核 `timeouts.py` 的 SPECS)。
|
||||
*
|
||||
* 为什么不在这里写死:需求 2.3 明确要求"所有时长与缓动数值收进全局配置"。
|
||||
* 用户嫌 1.5 秒的切换太慢时,改「中间留白」就能缩到 1.0 秒。
|
||||
*
|
||||
* 复用"超时"那套数值体系(而不是在 settings 里再开一个 agentAnim 对象)
|
||||
* 的理由写在 timeouts.py 那一段注释里:再造一套就是第二份要同步的东西。
|
||||
*/
|
||||
private fun animMs(key: String, fallback: Int): Int {
|
||||
val sec = com.doubao.lynxclone.data.AppTimeouts.seconds(key, fallback / 1000.0)
|
||||
// 0 是合法的(「中间留白」调成 0 = 不停顿),所以不能拿 0 当"没配"
|
||||
return if (sec.isNaN() || sec < 0) fallback else (sec * 1000).toInt()
|
||||
}
|
||||
|
||||
private const val DEF_FRONT_OUT = 300 // ① 旧角色图出
|
||||
private const val DEF_GAP = 500 // ② 间隔
|
||||
private const val DEF_FRAME = 400 // ③ 边框/背景/介绍(滑出 + 滑入各一半)
|
||||
private const val DEF_FRONT_IN = 300 // ④ 新角色图进
|
||||
|
||||
/** 侧移幅度占展示区宽度的比例。需求只说"侧移",幅度大了像翻页、小了看不出来 */
|
||||
private const val SHIFT = 0.10f
|
||||
|
||||
@Composable
|
||||
fun AgentSelectScreen(
|
||||
agents: List<Agent>,
|
||||
activeId: String,
|
||||
/** 选中并进入它的对话界面(需求 2.1:完成选择后进入对应智能体的对话界面) */
|
||||
onEnter: (Agent) -> Unit,
|
||||
/** 「更多」→ Token 用量详情(需求 2.4) */
|
||||
onMore: (Agent) -> Unit,
|
||||
/** 「记忆」→ 看它记住了什么(记忆管理界面的主入口) */
|
||||
onMemories: (Agent) -> Unit,
|
||||
/** 管理(新建 / 编辑 / 导入导出)—— 需求文档之外,但少了它用户没法加自己的智能体 */
|
||||
onManage: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
if (agents.isEmpty()) {
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg()), verticalArrangement = Arrangement.Center) {
|
||||
Text("还没有智能体", Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = doubaoText())
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("点右上角「管理」新建或导入一个", Modifier.fillMaxWidth(),
|
||||
textAlign = TextAlign.Center, fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
TopAction("去管理", onClick = onManage)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val startIndex = agents.indexOfFirst { it.id == activeId }.coerceAtLeast(0)
|
||||
var picked by remember(agents.size) { mutableStateOf(startIndex) }
|
||||
// `shown` 是**画面上正在显示**的那个;picked 变了之后要等动画走到第③阶段才换它
|
||||
var shown by remember(agents.size) { mutableStateOf(startIndex) }
|
||||
val shownAgent = agents.getOrNull(shown) ?: agents.first()
|
||||
val pickedAgent = agents.getOrNull(picked) ?: agents.first()
|
||||
|
||||
val frontAlpha = remember { Animatable(1f) }
|
||||
val frontShift = remember { Animatable(0f) }
|
||||
val frameAlpha = remember { Animatable(1f) }
|
||||
val frameShift = remember { Animatable(0f) }
|
||||
val listState = rememberLazyListState()
|
||||
|
||||
// 每次重组都读一遍全局配置(用户在设置里改完回来,下一次切换就是新时长)
|
||||
val tFrontOut = animMs("agentAnim.frontOut", DEF_FRONT_OUT)
|
||||
val tGap = animMs("agentAnim.gap", DEF_GAP)
|
||||
val tFrame = animMs("agentAnim.frame", DEF_FRAME)
|
||||
val tFrontIn = animMs("agentAnim.frontIn", DEF_FRONT_IN)
|
||||
|
||||
LaunchedEffect(picked, agents.size) {
|
||||
if (picked == shown) return@LaunchedEffect
|
||||
// 目标在列表靠后 = 向左切换(新内容从右边进来)
|
||||
val dir = if (picked > shown) 1f else -1f
|
||||
|
||||
// ① 旧角色图渐出 + 侧移
|
||||
launch { frontAlpha.animateTo(0f, tween(tFrontOut, easing = FastOutSlowInEasing)) }
|
||||
frontShift.animateTo(-dir * SHIFT, tween(tFrontOut, easing = FastOutSlowInEasing))
|
||||
|
||||
// ② 间隔(需求明确定义了这一段留白;调成 0 就跳过)
|
||||
if (tGap > 0) delay(tGap.toLong())
|
||||
|
||||
// ③ 边框 / 背景 / 介绍:滑出 → 换数据 → 滑入
|
||||
val half = (tFrame / 2).coerceAtLeast(1)
|
||||
launch { frameAlpha.animateTo(0f, tween(half, easing = FastOutSlowInEasing)) }
|
||||
frameShift.animateTo(-dir * SHIFT, tween(half, easing = FastOutSlowInEasing))
|
||||
shown = picked
|
||||
launch { frameAlpha.animateTo(1f, tween(half, easing = LinearOutSlowInEasing)) }
|
||||
frameShift.animateTo(0f, tween(half, easing = LinearOutSlowInEasing))
|
||||
|
||||
// ④ 新角色图渐入 + 侧移到位
|
||||
frontShift.snapTo(dir * SHIFT)
|
||||
launch { frontAlpha.animateTo(1f, tween(tFrontIn, easing = LinearOutSlowInEasing)) }
|
||||
frontShift.animateTo(0f, tween(tFrontIn, easing = LinearOutSlowInEasing))
|
||||
}
|
||||
|
||||
// 选中的那项滚进视野(列表长了之后不滚的话用户看不到自己选了谁)
|
||||
LaunchedEffect(picked) {
|
||||
runCatching { listState.animateScrollToItem(picked) }
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
// ---------------- 顶栏 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"← 返回",
|
||||
fontSize = 14.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onBack() }.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
"选择智能体",
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
TopTextAction("管理", onClick = onManage)
|
||||
}
|
||||
|
||||
// ---------------- 展示区 ----------------
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f)
|
||||
.padding(horizontal = 8.dp)
|
||||
.clip(RoundedCornerShape(18.dp)),
|
||||
) {
|
||||
// ① 背景图(最底层,铺满)—— 缺就用内置默认背景
|
||||
ArtworkFill(shownAgent.image.back, R.drawable.agent_default_background)
|
||||
|
||||
// ② 左侧列表(浮在背景上)
|
||||
AgentList(
|
||||
agents = agents,
|
||||
picked = picked,
|
||||
onPick = { picked = it },
|
||||
state = listState,
|
||||
modifier = Modifier.width(96.dp).fillMaxHeight().padding(8.dp),
|
||||
)
|
||||
|
||||
// ③ 角色图(居中)。★ 它和右侧的边框/介绍一起跟着 frameShift 动
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(start = 96.dp, end = 10.dp, top = 10.dp, bottom = 10.dp),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.offset(x = (frameShift.value * 180).dp)
|
||||
.alpha(frameAlpha.value),
|
||||
) {
|
||||
// ③-1 角色图
|
||||
Box(
|
||||
Modifier.fillMaxSize().offset(x = (frontShift.value * 200).dp),
|
||||
) {
|
||||
ArtworkFill(
|
||||
shownAgent.image.portrait,
|
||||
R.drawable.agent_default_character,
|
||||
alpha = frontAlpha.value,
|
||||
scale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
|
||||
// ③-2 介绍边框 + 介绍文本(需求 2.1 的第 4 层)
|
||||
IntroCard(
|
||||
agent = shownAgent,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(end = 6.dp, bottom = 10.dp)
|
||||
.width(200.dp),
|
||||
)
|
||||
|
||||
// ③-3 主体边框(画在最上层,纯装饰)
|
||||
MainBorder(shownAgent.image.borderMain)
|
||||
}
|
||||
}
|
||||
|
||||
// ④ 「更多」按钮(需求 2.4:圆形、竖排三点、在角色图附近)→ Token 用量
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(top = 10.dp, end = 12.dp)
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color(0xCC1B2430))
|
||||
.clickable { onMore(shownAgent) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.MoreVert,
|
||||
contentDescription = "用量详情",
|
||||
tint = Color(0xFFE8EAED),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 底部:进对话 / 看记忆 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// ★「记忆」和「开始对话」并排:进对话之前顺手看一眼它记住了什么。
|
||||
// 记忆是这个功能里最需要"用户能看见"的东西 —— AI 会记错
|
||||
// (把"喜欢猫"记成"讨厌猫"很常见),看见了才能改。
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { onMemories(pickedAgent) }
|
||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("记忆", fontSize = 15.sp, color = doubaoText())
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(
|
||||
Brush.horizontalGradient(listOf(Color(0xFF2B7BFF), Color(0xFF5B9BFF))),
|
||||
)
|
||||
.clickable { onEnter(pickedAgent) }
|
||||
.padding(vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
"开始对话",
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color.White,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 四层的具体画法 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/** 铺满一层图;没有就用内置默认(需求 2.6 的最后一级回退) */
|
||||
@Composable
|
||||
private fun ArtworkFill(
|
||||
path: String,
|
||||
fallbackRes: Int,
|
||||
alpha: Float = 1f,
|
||||
scale: ContentScale = ContentScale.Crop,
|
||||
) {
|
||||
Box(Modifier.fillMaxSize().alpha(alpha)) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = scale,
|
||||
fallback = {
|
||||
// ★ 内置默认图:**必须画出来**,不能是空白 ——
|
||||
// 需求原话"任何智能体至少能以默认人物+默认背景+方框边框正常展示"
|
||||
Image(
|
||||
painter = painterResource(fallbackRes),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = scale,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 主体边框。缺的时候用**简单方框**(纯色细线矩形)兜底 */
|
||||
@Composable
|
||||
private fun MainBorder(path: String) {
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
if (canShowImage(path)) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.FillBounds,
|
||||
fallback = { SimpleFrame(shape) },
|
||||
)
|
||||
} else {
|
||||
SimpleFrame(shape)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SimpleFrame(shape: RoundedCornerShape) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.border(1.dp, Doubao.Blue.copy(alpha = 0.45f), shape),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 介绍卡片(需求 2.1 的"介绍边框 + 介绍文本")。
|
||||
*
|
||||
* 文本来自 `description`;缺失时**只显示智能体名**(需求原文)。
|
||||
*/
|
||||
@Composable
|
||||
private fun IntroCard(agent: Agent, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Color(0xE6FFFDF5))
|
||||
.border(1.dp, Color(0x66B9A46A), RoundedCornerShape(14.dp))
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(
|
||||
agent.name,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color(0xFF2A2419),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
val desc = agent.description.trim().ifBlank { agent.greeting.trim() }
|
||||
if (desc.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
desc,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF4A4232),
|
||||
maxLines = 6,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 左侧列表:一张卡片 = 缩略图 + 名字;当前项高亮 */
|
||||
@Composable
|
||||
private fun AgentList(
|
||||
agents: List<Agent>,
|
||||
picked: Int,
|
||||
onPick: (Int) -> Unit,
|
||||
state: androidx.compose.foundation.lazy.LazyListState,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
LazyColumn(modifier, state = state, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
itemsIndexed(agents) { index, agent ->
|
||||
val on = index == picked
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (on) Color(0xCC2B7BFF) else Color(0x99101820))
|
||||
.border(
|
||||
width = if (on) 1.5.dp else 0.5.dp,
|
||||
color = if (on) Color(0xFFFFE08A) else Color(0x33FFFFFF),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
.clickable { onPick(index) }
|
||||
.padding(4.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(Color(0x33FFFFFF)),
|
||||
) {
|
||||
// 缩略图:也用角色图(缺就默认人物)—— 和右侧是同一套回退。
|
||||
// ★ alignment = TopCenter:角色图是竖长的,居中裁剪只会
|
||||
// 裁出"腰到大腿",一排缩略图全是裤子
|
||||
AssetImage(
|
||||
path = agent.image.portrait,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
fallback = {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
agent.name.ifBlank { "未命名" },
|
||||
fontSize = 11.sp,
|
||||
color = Color.White,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.StatValue
|
||||
import com.doubao.lynxclone.data.StatusInstance
|
||||
|
||||
/**
|
||||
* [状态数值](v1.2 §3.10 数值 / §3.11 状态)。
|
||||
*
|
||||
* ## 三个入口共用这一个界面
|
||||
*
|
||||
* 需求 §6.1 指定的三个入口:**聊天页状态栏** / **智能体编辑的"它的状态"** /
|
||||
* **群成员的「状态」按钮**。三处都调 `vm.openStats(agentId)`。
|
||||
*
|
||||
* ★ 只写一个界面是有意的:三个入口各写一份的话,"数值怎么显示、
|
||||
* 能不能改、状态剩几轮怎么标"这三件事会各有一套说法 ——
|
||||
* 而这个仓库里"同一逻辑抄两份"已经反复出现过。
|
||||
*
|
||||
* ## 用户能直接改数值,AI 不能
|
||||
*
|
||||
* AI 的 `change_stat` 只能申请**增量**,还要过脚本裁决(§3.10)。
|
||||
* 用户是规则的主人 —— 点一下就能直接设成任何值。
|
||||
* 但内核照样会 clamp 到 `[min,max]`:超出范围的值会让进度条和区间注入
|
||||
* 全都错位。所以**回来之后要以返回值刷新**,不能乐观地先用自己填的。
|
||||
*/
|
||||
@Composable
|
||||
fun AgentStatsScreen(
|
||||
vm: AppViewModel,
|
||||
agentId: String,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val stats = vm.agentStats
|
||||
var editing by remember { mutableStateOf("") }
|
||||
var input by remember { mutableStateOf("") }
|
||||
|
||||
FullScreen(
|
||||
title = "状态数值",
|
||||
subtitle = stats?.name?.takeIf { it.isNotBlank() } ?: "读不出来",
|
||||
onBack = onBack,
|
||||
) {
|
||||
if (stats == null) {
|
||||
Hint("正在读……")
|
||||
return@FullScreen
|
||||
}
|
||||
if (stats.rulePackId.isBlank()) {
|
||||
// 没挂规则包就没有数值系统 —— 如实说清楚,别让用户以为是加载失败
|
||||
Hint(
|
||||
"这个智能体还没有数值系统。\n\n" +
|
||||
"数值和状态由「数值状态包」定义 —— 去 资源 → 规则包 " +
|
||||
"建一个(或导入一个),再把它挂到智能体所在的世界观上。",
|
||||
)
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("数值")
|
||||
Card {
|
||||
if (stats.stats.isEmpty()) {
|
||||
Hint("这个规则包里没有数值。")
|
||||
}
|
||||
for (s in stats.stats) {
|
||||
StatRow(
|
||||
stat = s,
|
||||
editing = editing == s.name,
|
||||
input = input,
|
||||
onInput = { input = it },
|
||||
onStartEdit = { editing = s.name; input = fmtNum(s.value) },
|
||||
onCancel = { editing = "" },
|
||||
onCommit = {
|
||||
vm.setStatDirect(s.name, input.toDoubleOrNull() ?: s.value)
|
||||
editing = ""
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (stats.rulePackName.isNotBlank()) {
|
||||
Hint("来自规则包「${stats.rulePackName}」。")
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态")
|
||||
Card {
|
||||
if (stats.statuses.isEmpty()) {
|
||||
Hint("身上没有状态。")
|
||||
}
|
||||
for (st in stats.statuses) {
|
||||
StatusRow(st)
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"定时状态每参与一轮减 1,归零就消失;持久状态不会自己过期。" +
|
||||
"状态提示词会被注入到它的系统提示里。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatRow(
|
||||
stat: StatValue,
|
||||
editing: Boolean,
|
||||
input: String,
|
||||
onInput: (String) -> Unit,
|
||||
onStartEdit: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
onCommit: () -> Unit,
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stat.name, fontSize = 13.sp, color = doubaoText(), modifier = Modifier.weight(1f))
|
||||
if (stat.shared) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag("全世界观共用")
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
if (editing) {
|
||||
// 直接设值 —— 用户主权。★ 就地在行内变成输入框,不再压一层
|
||||
// 对话框(AGENTS.md:一次输入用弹窗也行,但这里已经有上下文,
|
||||
// 就地改更省事,而且弹窗会盖住进度条)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = input,
|
||||
onValueChange = onInput,
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.width(84.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("好") { onCommit() }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
RowAction("取消") { onCancel() }
|
||||
} else {
|
||||
Text(
|
||||
"${fmtNum(stat.value)} / ${fmtNum(stat.max)}",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("改") { onStartEdit() }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// 进度条:`ratio()` 在模型里(三个入口共用一份换算,圆角和取整才不会各说各话)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoSurface()),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(stat.ratio())
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
if (stat.text.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(stat.text, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusRow(st: StatusInstance) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(st.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag(if (st.isPersistent) "持久" else "剩 ${st.remaining} 轮")
|
||||
if (st.stacks > 1) {
|
||||
Spacer(Modifier.width(4.dp))
|
||||
TinyTag("×${st.stacks}")
|
||||
}
|
||||
}
|
||||
if (st.hint.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(st.hint, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TinyTag(text: String) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** 数值显示:整数就不带小数点(45.0 → 45),不然看着别扭 */
|
||||
private fun fmtNum(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
@@ -47,6 +47,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
@@ -72,15 +73,33 @@ import com.doubao.lynxclone.data.VoiceOption
|
||||
*/
|
||||
@Composable
|
||||
fun AgentsScreen(vm: AppViewModel) {
|
||||
var editing by remember { mutableStateOf<Agent?>(null) }
|
||||
var creating by remember { mutableStateOf(false) }
|
||||
var confirmDelete by remember { mutableStateOf<Agent?>(null) }
|
||||
|
||||
// ★ 导入智能体包(需求 2.5):zip → base64 → 内核解包。
|
||||
// 不走 Kotlin 解压是因为安卓的 `ZipInputStream` **读不出**这类 zip
|
||||
// (Termux bootstrap 那个坑,见 TermuxInstaller 的注释),
|
||||
// 而内核的 Python `zipfile` 没这个问题 —— 少踩一次已知的坑。
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
val importPackage = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
vm.importPackage("agents", android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP), "")
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
val activeId = vm.state.activeAgent?.id.orEmpty()
|
||||
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
ScreenHeader("智能体", onBack = { vm.screen = Screen.Chat }) {
|
||||
TextButton(onClick = { creating = true }) { Text("新建", fontSize = 13.sp) }
|
||||
TextButton(onClick = {
|
||||
importPackage.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
}) { Text("导入", fontSize = 13.sp) }
|
||||
TextButton(onClick = { vm.openAgentEdit(null) }) { Text("新建", fontSize = 13.sp) }
|
||||
}
|
||||
|
||||
Column(
|
||||
@@ -103,8 +122,11 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
agent = agent,
|
||||
active = agent.id == activeId,
|
||||
onUse = { vm.useAgent(agent.id) },
|
||||
onEdit = { editing = agent },
|
||||
onEdit = { vm.openAgentEdit(agent) },
|
||||
onMemories = { vm.openMemories(agent.id) },
|
||||
onDelete = { confirmDelete = agent },
|
||||
worldName = vm.state.worldviews
|
||||
.firstOrNull { it.id == agent.worldviewId }?.name.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -113,7 +135,7 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = { creating = true },
|
||||
onClick = { vm.openAgentEdit(null) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
contentPadding = PaddingValues(vertical = 12.dp),
|
||||
@@ -129,41 +151,29 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
/* ---------------- 新建 / 编辑 ---------------- */
|
||||
if (creating || editing != null) {
|
||||
val target = editing
|
||||
AgentEditDialog(
|
||||
agent = target,
|
||||
providers = vm.state.providers.values.toList(),
|
||||
voices = vm.state.speechVoices,
|
||||
voicesAll = vm.state.speechVoicesAll,
|
||||
globalTtsEngine = vm.state.speech.ttsEngine,
|
||||
onDismiss = { creating = false; editing = null },
|
||||
onSave = { draft ->
|
||||
vm.saveAgent(target?.id, draft) {
|
||||
creating = false
|
||||
editing = null
|
||||
}
|
||||
},
|
||||
onDelete = if (target != null && !target.builtin) {
|
||||
{ confirmDelete = target }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
//
|
||||
// ★ 编辑走的是 **AgentEditScreen(全屏)**,不是这里原来那个弹窗。
|
||||
// 字段从 8 个涨到二十多个(外观四件套 / 模型引用 / 世界观 / 限额 / 技能……),
|
||||
// 弹窗装不下 —— AGENTS.md 那张表写得很清楚。
|
||||
// 删除确认**仍然是弹窗**:它就是"一次确认",正好是弹窗该用的地方。
|
||||
|
||||
/* ---------------- 删除确认 ---------------- */
|
||||
confirmDelete?.let { agent ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = null },
|
||||
title = { Text("删除智能体", fontSize = 16.sp) },
|
||||
text = { Text("确定删除「${agent.name}」吗?它的系统提示词也会一起删掉,不能撤销。", fontSize = 13.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"确定删除「${agent.name}」吗?\n\n" +
|
||||
"它的系统提示词和外观会一起删掉,不能撤销。\n" +
|
||||
"**记忆会保留**(那是你攒下来的东西,删之前建议先导出)。",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
vm.deleteAgent(agent.id)
|
||||
confirmDelete = null
|
||||
// 正在编辑的就是被删的那个的话,把编辑框一起关掉,否则保存会 404
|
||||
if (editing?.id == agent.id) editing = null
|
||||
}) { Text("删除") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmDelete = null }) { Text("取消") } },
|
||||
@@ -179,7 +189,11 @@ private fun AgentRow(
|
||||
active: Boolean,
|
||||
onUse: () -> Unit,
|
||||
onEdit: () -> Unit,
|
||||
/** 看这个智能体记住了什么(记忆管理界面的入口之一) */
|
||||
onMemories: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
/** 它绑的世界观叫什么(空 = 没绑)。交互是双向的,这边也要看得见 */
|
||||
worldName: String = "",
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onUse),
|
||||
@@ -215,7 +229,23 @@ private fun AgentRow(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
// ★ 绑了哪个世界观(用户要求"互通")——
|
||||
// 重点不是"它有个世界观",而是**它和谁共用记忆**。
|
||||
// 所以文案直接写"共用记忆",而不是干巴巴一个名字。
|
||||
if (agent.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"世界观「${worldName.ifBlank { "已失效" }}」· 记忆与同世界的智能体共用",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★「记忆」放在「编辑」**左边**:它是"看它记住了什么",
|
||||
// 属于日常动作;编辑是配置动作,用得少。
|
||||
TextButton(onClick = onMemories) { Text("记忆", fontSize = 12.sp) }
|
||||
TextButton(onClick = onEdit) { Text("编辑", fontSize = 12.sp) }
|
||||
if (!agent.builtin) {
|
||||
TextButton(onClick = onDelete) { Text("删除", fontSize = 12.sp) }
|
||||
@@ -255,185 +285,6 @@ private fun ActiveBadge() {
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun AgentEditDialog(
|
||||
agent: Agent?,
|
||||
providers: List<ProviderPreset>,
|
||||
voices: Map<String, List<VoiceOption>>,
|
||||
voicesAll: Map<String, List<VoiceOption>>,
|
||||
/** 全局当前的朗读引擎:智能体没选引擎时,音色列表要按它来给 */
|
||||
globalTtsEngine: String,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (Agent) -> Unit,
|
||||
onDelete: (() -> Unit)?,
|
||||
) {
|
||||
// 整份草稿:加字段时只要往 Agent 里加,不用再改一遍这里的所有 var
|
||||
var draft by remember {
|
||||
mutableStateOf(
|
||||
agent ?: Agent(avatar = "doubao"),
|
||||
)
|
||||
}
|
||||
var error by remember { mutableStateOf("") }
|
||||
val name = draft.name
|
||||
val avatar = draft.avatar
|
||||
val prompt = draft.systemPrompt
|
||||
val greeting = draft.greeting
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(if (agent == null) "新建智能体" else "编辑智能体", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
FormLabel("头像")
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
AvatarKeys.forEach { key ->
|
||||
Box(Modifier.clickable { draft = draft.copy(avatar = key) }) {
|
||||
// 选中态画在 AvatarCircle 的外圈上,不改变尺寸
|
||||
AvatarCircle(name = "", avatar = key, size = 34, selected = avatar == key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("名称")
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { draft = draft.copy(name = it) },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
placeholder = { Text("例如:翻译官", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("问候语 / 一句话介绍")
|
||||
OutlinedTextField(
|
||||
value = greeting,
|
||||
onValueChange = { draft = draft.copy(greeting = it) },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
placeholder = { Text("显示在列表里,也用作首屏问候", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Text(
|
||||
"列表摘要会显示这句;新会话首屏也用它打招呼。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("系统提示词")
|
||||
OutlinedTextField(
|
||||
value = prompt,
|
||||
onValueChange = { draft = draft.copy(systemPrompt = it) },
|
||||
modifier = Modifier.fillMaxWidth().height(150.dp).padding(top = 6.dp),
|
||||
placeholder = { Text("这个人设、规则、说话风格…", fontSize = 13.sp) },
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
)
|
||||
Text(
|
||||
"和它聊天时,这段提示词会覆盖全局系统提示词。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
/* ---------------- 模型(留空 = 跟随全局) ---------------- */
|
||||
Spacer(Modifier.height(14.dp))
|
||||
FormLabel("模型")
|
||||
Text(
|
||||
"不选就跟随「设置 → 连接与模型」里的全局配置。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
WrapChips(
|
||||
options = listOf("" to "跟随全局") +
|
||||
providers.map { it.key to it.label },
|
||||
active = draft.provider,
|
||||
) { draft = draft.copy(provider = it) }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
// ★ 别把 `ifBlank{…} == "x" ? a : b` 写成一整行:Kotlin 会把那个 `?`
|
||||
// 当成安全调用开始解析,报一堆看不懂的语法错。拆成变量最稳。
|
||||
val followGlobalModel = draft.provider.isBlank()
|
||||
OutlinedTextField(
|
||||
value = draft.model,
|
||||
onValueChange = { draft = draft.copy(model = it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
placeholder = {
|
||||
Text(
|
||||
if (followGlobalModel) "留空 = 用全局模型" else "留空 = 用这家的默认模型",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
|
||||
/* ---------------- 语音(留空 = 跟随全局) ---------------- */
|
||||
Spacer(Modifier.height(14.dp))
|
||||
FormLabel("语音")
|
||||
Text(
|
||||
"多人会议里靠它区分谁在说话 —— 几个智能体一个嗓子的话根本听不出谁在讲。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
WrapChips(
|
||||
options = listOf("" to "跟随全局") + TtsEngineChoices,
|
||||
active = draft.ttsEngine,
|
||||
) { engine ->
|
||||
// 换引擎顺手清掉音色:音色是按引擎命名的(BVxxx / zh_xxx_bigtts),
|
||||
// 留着上一家的值一定会被判非法
|
||||
draft = draft.copy(ttsEngine = engine, ttsVoice = "")
|
||||
}
|
||||
val voiceEngine = draft.ttsEngine.ifBlank { globalTtsEngine }
|
||||
if (voiceEngine != "" && voiceEngine != "system") {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
VoicePickerInline(
|
||||
engine = voiceEngine,
|
||||
voices = voices[voiceEngine].orEmpty(),
|
||||
voicesAll = voicesAll[voiceEngine].orEmpty(),
|
||||
value = draft.ttsVoice,
|
||||
onValue = { draft = draft.copy(ttsVoice = it) },
|
||||
)
|
||||
}
|
||||
|
||||
if (error.isNotBlank()) {
|
||||
Text(error, fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
if (draft.name.isBlank()) {
|
||||
error = "名称不能为空"
|
||||
} else {
|
||||
onSave(draft.copy(name = draft.name.trim(), greeting = draft.greeting.trim()))
|
||||
}
|
||||
}) { Text("保存") }
|
||||
},
|
||||
dismissButton = {
|
||||
Row {
|
||||
if (onDelete != null) {
|
||||
TextButton(onClick = onDelete) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Text("删除", color = MaterialTheme.colorScheme.error, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
TextButton(onClick = onDismiss) { Text("取消") }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** 列表里那一行摘要文案 */
|
||||
private fun agentSummary(agent: Agent): String = when {
|
||||
agent.greeting.isNotBlank() -> agent.greeting
|
||||
agent.systemPrompt.isNotBlank() -> agent.systemPrompt.lineSequence().firstOrNull { it.isNotBlank() } ?: "通用助手"
|
||||
@@ -495,7 +346,7 @@ internal fun WrapChips(
|
||||
* 拽进智能体页 —— 真要统一的话应该把它提成公共组件,那是另一件事。
|
||||
*/
|
||||
@Composable
|
||||
private fun VoicePickerInline(
|
||||
internal fun VoicePickerInline(
|
||||
engine: String,
|
||||
voices: List<VoiceOption>,
|
||||
voicesAll: List<VoiceOption>,
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.DeleteOutline
|
||||
import androidx.compose.material.icons.filled.OpenInNew
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* ★★ 「AI 界面」列表 —— 用户要求"AI 写的界面可以再点开"。
|
||||
*
|
||||
* ## 为什么要有它
|
||||
*
|
||||
* 界面以前只活在内存里,一关就没了。用户过一会儿想"刚才那个图表再看一眼"
|
||||
* 就找不回来,只能让 AI 重新生成 —— 而**重新生成的内容不一定一样**
|
||||
* (模型有随机性),用户会觉得"我明明看过的东西怎么变了"。
|
||||
*
|
||||
* 所以每次 `show_ui` 都存一份到磁盘,这里列出它们。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面,不是弹窗
|
||||
*
|
||||
* 列表要滚动(一个会话可能攒十几个界面),弹窗装不下。
|
||||
* 顶栏用统一的 `← 返回 | 标题 | 副标题`。
|
||||
*/
|
||||
@Composable
|
||||
fun AiScreenListScreen(
|
||||
screens: List<AiScreenItem>,
|
||||
onOpen: (String) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("AI 界面", onBack = onClose) {
|
||||
Text(
|
||||
if (screens.isEmpty()) "还没有" else "${screens.size} 个",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
if (screens.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"AI 还没给你弹过界面。\n让它「弹个界面」试试。",
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 22.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
Text(
|
||||
"点一下就能再打开。AI 生成的界面都存下来了,不用让它重做。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
items(screens.size) { index ->
|
||||
val s = screens[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onOpen(s.id) }
|
||||
.padding(start = 14.dp, end = 6.dp, top = 12.dp, bottom = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
s.title,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (s.preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
s.preview,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"${formatTime(s.at)} · ${formatBytes(s.bytes)}",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// 删除:单独一个小按钮,别让"点卡片"和"删除"挤在一起误触
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.clickable { onDelete(s.id) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
"删除",
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.OpenInNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(17.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 列表里的一条(从 AiSurface 的索引 JSON 转过来) */
|
||||
data class AiScreenItem(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val preview: String,
|
||||
val bytes: Int,
|
||||
val at: Long,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
/** 时间戳 → 「今天 14:03」/「10-15 14:03」。手机上不显示年份,太占地方 */
|
||||
private fun formatTime(ms: Long): String {
|
||||
if (ms <= 0) return ""
|
||||
val now = java.util.Calendar.getInstance()
|
||||
val then = java.util.Calendar.getInstance().apply { timeInMillis = ms }
|
||||
val sameDay = now.get(java.util.Calendar.YEAR) == then.get(java.util.Calendar.YEAR) &&
|
||||
now.get(java.util.Calendar.DAY_OF_YEAR) == then.get(java.util.Calendar.DAY_OF_YEAR)
|
||||
val fmt = SimpleDateFormat(if (sameDay) "'今天' HH:mm" else "MM-dd HH:mm", Locale.getDefault())
|
||||
return fmt.format(Date(ms))
|
||||
}
|
||||
|
||||
/**
|
||||
* 字节数 → 人能看的字符串。
|
||||
*
|
||||
* ★ 不足 1KB 的要显示字节数:第一版写的是 `bytes / 1024` + "KB",
|
||||
* 于是 524 字节的界面显示成 **"0KB"**(看起来像"这个界面是空的")。
|
||||
* 整数除法把小于 1024 的一律变成 0 了。
|
||||
*/
|
||||
private fun formatBytes(n: Int): String = when {
|
||||
n <= 0 -> "—"
|
||||
n < 1024 -> "${n}B"
|
||||
n < 1024 * 1024 -> "${n / 1024}KB"
|
||||
else -> String.format(Locale.getDefault(), "%.1fMB", n / 1024.0 / 1024.0)
|
||||
}
|
||||
785
android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt
Normal file
785
android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt
Normal file
@@ -0,0 +1,785 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.net.Uri
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PowerSettingsNew
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
|
||||
/**
|
||||
* AI 主动弹出来的三个界面(都带进出动画)。
|
||||
*
|
||||
* 放在**导航之上**(见 AppRoot):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话在会议/设置页就看不到。
|
||||
*
|
||||
* 三个东西的动画各有讲究:
|
||||
* · HTML 界面 —— 从中心"长大"+ 淡入(像开一扇门),退出反向
|
||||
* · 选择弹窗 —— 从下方滑上来 + 淡入(手机上的惯例手势方向)
|
||||
* · 结束横幅 —— 从下方滑到**屏幕中间**停住,并且**留在那儿**(不自动消失)
|
||||
*/
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、AI 的 HTML 界面(show_ui) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiHtmlScreenOverlay(
|
||||
screen: AiSurface.Screen?,
|
||||
onClose: () -> Unit,
|
||||
onResult: (String) -> Unit,
|
||||
/** 等待模式:用户点了回传按钮之后自动把界面收掉(这是"用户答完了"的信号) */
|
||||
autoCloseOnResult: Boolean = false,
|
||||
) {
|
||||
// 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧",
|
||||
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
||||
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
||||
LaunchedEffect(screen) { if (screen != null) last = screen }
|
||||
val shown = screen ?: last
|
||||
|
||||
// WebView 实例 + "能不能回退"。
|
||||
// ★ 拿到了 WebView 才能调 goBack();canGoBack 要轮询(WebView 没有变更回调)。
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var canGoBack by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(web, screen) {
|
||||
while (web != null && screen != null) {
|
||||
canGoBack = web?.canGoBack() == true
|
||||
kotlinx.coroutines.delay(400)
|
||||
}
|
||||
canGoBack = false
|
||||
}
|
||||
|
||||
// 系统返回键:能回退就先回退(用户点进去了一页,返回键该带他回来),
|
||||
// 不能回退才关掉整个界面 —— 比直接关掉符合直觉。
|
||||
BackHandler(enabled = screen != null) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = screen != null,
|
||||
enter = fadeIn(tween(180)) +
|
||||
scaleIn(tween(240, easing = androidx.compose.animation.core.FastOutSlowInEasing), initialScale = 0.86f),
|
||||
exit = fadeOut(tween(150)) + scaleOut(tween(180), targetScale = 0.92f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
shown.title.ifBlank { "AI 界面" },
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// 「返回上一页」只在真能回退时出现 —— 一直显示一个点了没反应的
|
||||
// 箭头比不显示更让人困惑
|
||||
AnimatedVisibility(
|
||||
visible = canGoBack,
|
||||
enter = fadeIn(tween(150)),
|
||||
exit = fadeOut(tween(120)),
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { web?.goBack() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
"返回上一页",
|
||||
tint = doubaoText(),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { onClose() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
AiWebView(
|
||||
screen = shown,
|
||||
onResult = { value ->
|
||||
onResult(value)
|
||||
// ★ 等待模式下这一下就是"用户答完了" —— 把界面收掉,
|
||||
// 否则用户看到一个已经用完的界面还开着,会以为还能再点。
|
||||
if (autoCloseOnResult) onClose()
|
||||
},
|
||||
onClose = onClose,
|
||||
onWebView = { web = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 AI 写的 HTML。
|
||||
*
|
||||
* ## JS 开着,但 `@JavascriptInterface` 只在"我们自己那一页"暴露
|
||||
*
|
||||
* 用户要求"支持 js"。开了 JS 之后最大的风险不是 JS 本身,而是
|
||||
* **`addJavascriptInterface` 注入的那个桥**:它对**之后加载的每一个页面**
|
||||
* 都可见。AI 的页面里如果有个链接,用户点进去落到一个外部站点,
|
||||
* 那个站点的 JS 也能调我们的桥 —— 等于把 App 的内部接口交给它。
|
||||
*
|
||||
* 所以这里**按 origin 收口**:
|
||||
*
|
||||
* · 初始文档用 `loadDataWithBaseURL(null, …)` 加载 —— 它的 document origin
|
||||
* 是**不透明(opaque)**的,WebView 会把它当作"没有来源"
|
||||
* · 导航到任何 **http/https** 之前,先把桥撤掉(`removeJavascriptInterface`)
|
||||
* · 外部页面在 WebView 里正常打开(用户要的"点进去"就是它),
|
||||
* 但它没有桥;而且 `onPageStarted` 里会再兜一次
|
||||
*
|
||||
* ## 依然保持关闭的那些
|
||||
*
|
||||
* · `allowFileAccess` / `allowContentAccess` —— 不让页面读本地文件
|
||||
* · `setAllowFileAccessFromFileURLs` / `setAllowUniversalAccessFromFileURLs`
|
||||
* · `mixedContentMode = NEVER` —— 不让 https 页面加载 http 资源
|
||||
*
|
||||
* ## 可点按钮的两条路都留着
|
||||
*
|
||||
* 1. `<button data-doubao-result="值">` —— App 侧字符串替换成
|
||||
* `doubao://pick?...`,由 `shouldOverrideUrlLoading` 拦。
|
||||
* **不依赖 JS**,所以页面即使 JS 出错也能用
|
||||
* 2. `Doubao.pick("值")` / `Doubao.close()` —— 给会写 JS 的模型用
|
||||
* (图表上点一个点回传、定时刷新之类)
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
|
||||
@Composable
|
||||
private fun AiWebView(
|
||||
screen: AiSurface.Screen,
|
||||
onResult: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
onWebView: (WebView) -> Unit = {},
|
||||
) {
|
||||
val html = remember(screen.id) { buildAiHtml(screen) }
|
||||
// 记一下"桥还在不在",避免同一页里反复 remove/add
|
||||
val host = remember(screen.id) { AiWebHost() }
|
||||
host.onResult = onResult
|
||||
host.onClose = onClose
|
||||
|
||||
DisposableEffect(screen.id) {
|
||||
onDispose { host.detach() }
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = false
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
isVerticalScrollBarEnabled = true
|
||||
|
||||
/**
|
||||
* ★★ 桥的挂/摘时机 —— 这里改了两版才对,把结论记下来。
|
||||
*
|
||||
* **第一版**(错的):`loadDataWithBaseURL` 之前就 add,导航到
|
||||
* http(s) 时 remove。问题:外部页面在 `onPageStarted` 摘桥**之前**
|
||||
* 有个"已经开始加载、桥还在"的窗口期。
|
||||
*
|
||||
* **第二版**(也是错的):只在 `onPageFinished` 里判 url 是不是
|
||||
* `about:blank` 才 add。实测页面报
|
||||
* `Uncaught ReferenceError: Doubao is not defined`
|
||||
* —— `onPageFinished` 的**回调时机比页面内联 <script> 执行还晚**,
|
||||
* 脚本跑的时候桥还没挂上。
|
||||
*
|
||||
* **第三版**(现在这个):初始 load **之前就挂**(保证脚本能用到),
|
||||
* 然后靠 [AiWebHost.payloadLoaded] 这个标志挡住窗口期 ——
|
||||
* loadUrl 到别的地址时,`payloadLoaded` 已经是 true,
|
||||
* 所以立刻摘桥,外部页面**从头到尾**都碰不到它。
|
||||
*/
|
||||
addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
// 开始加载"非初始页"了 —— 说明初始页已经加载过(标志为 true),
|
||||
// 而这次是一个**导航**:立刻摘桥。
|
||||
//
|
||||
// ★ 纯锚点跳转(#xxx)不算导航,不能摘 —— 否则页面内
|
||||
// "跳到某一段"之后 JS 就废了。
|
||||
val anchorOnly = url != null && url.startsWith("about:blank#")
|
||||
if (host.payloadLoaded && !anchorOnly) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
if (!host.payloadLoaded) {
|
||||
// 初始那页加载完成。**马上补挂一次** —— 实测
|
||||
// loadDataWithBaseURL 的页面在脚本执行时桥可能还没生效,
|
||||
// 补挂之后重新 load 才稳。
|
||||
host.payloadLoaded = true
|
||||
view?.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS, null)
|
||||
return
|
||||
}
|
||||
// 之后每次加载完都探一次:**页面里有我们的标记**才重挂桥。
|
||||
//
|
||||
// ★ 为什么用"页面里有没有标记变量"而不是看 url:
|
||||
// 实测从外部页返回(goBack)时,onPageFinished 收到的 url
|
||||
// 并不是 `about:blank`,用 url 判会漏 —— 表现是
|
||||
// "点进去再返回,页面上的 JS 按钮全失灵"。
|
||||
// 标记变量是**页面自己的属性**,页面被换掉它就没了,
|
||||
// 比 url 可靠。
|
||||
//
|
||||
// ★ 如果标记在**但桥不在**,说明这一页是我们的,
|
||||
// 而桥在上一次导航时被摘了 → 重挂。
|
||||
// 如果标记在**桥也在**,什么都不用做。
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS) { result ->
|
||||
// ★ evaluateJavascript 的回调参数是**字符串**,
|
||||
// 而且返回值经 JSON 编码("1" 带着引号)。
|
||||
// 我第一版按 Boolean 处理,条件永远不成立。
|
||||
val ok = (result ?: "").trim('"', ' ')
|
||||
if (ok == "1" && !host.bridgeAttached) {
|
||||
view.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView?,
|
||||
url: String?,
|
||||
): Boolean {
|
||||
val u = url ?: return false
|
||||
|
||||
// ① 我们自己约定的回传协议
|
||||
if (u.startsWith("doubao://pick")) {
|
||||
val v = Uri.decode(Uri.parse(u).getQueryParameter("value") ?: "")
|
||||
if (v.isNotEmpty()) onResult(v)
|
||||
return true
|
||||
}
|
||||
if (u.startsWith("doubao://close")) {
|
||||
onClose()
|
||||
return true
|
||||
}
|
||||
|
||||
// ② http(s):**在 WebView 里打开**(用户要的"点进去")。
|
||||
// 桥会在 onPageStarted 里被摘掉(那时 payloadLoaded 已 true),
|
||||
// 所以外部站点碰不到 App。
|
||||
if (u.startsWith("http://") || u.startsWith("https://")) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
return false
|
||||
}
|
||||
|
||||
// ③ 页内锚点(#xxx)交给 WebView 自己处理
|
||||
if (u.startsWith("#")) return false
|
||||
|
||||
// ④ 别的协议(tel: / mailto: / intent: …)交给系统
|
||||
return try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_VIEW, Uri.parse(u))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
|
||||
onWebView(this)
|
||||
}
|
||||
},
|
||||
update = { /* 同一个 screen.id 不重载,避免动画期间闪一下 */ },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 给 AI 页面用的 JS 桥。
|
||||
*
|
||||
* 暴露两个方法(页面上写 `Doubao.pick("值")` / `Doubao.close()`):
|
||||
*
|
||||
* · `pick(value)` —— 回传一个值,和点 `data-doubao-result` 按钮等价。
|
||||
* 适合"图表上点一个点"、"定时刷新后回传结果"这类需要脚本的场景。
|
||||
* · `close()` —— 关掉这个界面。
|
||||
*
|
||||
* ★ 方法名和 [NAME] 都刻意短且通用,因为模型要在 HTML 里手写它们;
|
||||
* 但**只暴露这两个** —— 桥能调到的越少,万一被滥用时的损失越小。
|
||||
*
|
||||
* ★ 注意:这个对象**只挂在初始那一页**上(见 [AiWebView] 的注释)。
|
||||
* 导航到外部站点时会被 `removeJavascriptInterface` 摘掉。
|
||||
*/
|
||||
class AiWebHost {
|
||||
@Volatile
|
||||
var onResult: ((String) -> Unit)? = null
|
||||
|
||||
@Volatile
|
||||
var onClose: (() -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 初始那一页(AI 写的那份 HTML)加载完成了没有。
|
||||
*
|
||||
* 用来区分"初始加载"和"用户点链接导航" —— 两者都会走 `onPageStarted`,
|
||||
* 但只有后者该摘桥。见 [AiWebView] 里那段注释。
|
||||
*/
|
||||
@Volatile
|
||||
var payloadLoaded: Boolean = false
|
||||
|
||||
/** 桥现在挂着没有。重挂前要先看它,不然会重复 add。 */
|
||||
@Volatile
|
||||
var bridgeAttached: Boolean = false
|
||||
|
||||
@JavascriptInterface
|
||||
fun pick(value: String?) {
|
||||
val v = (value ?: "").trim()
|
||||
if (v.isEmpty()) return
|
||||
onResult?.invoke(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* `pick` 的别名 —— **这是"AI 自己能写进网页里的接口"**。
|
||||
*
|
||||
* AI 在它生成的 HTML 里写:
|
||||
* ```html
|
||||
* <button onclick="Doubao.sendToAi('用户选了方案 B')">方案 B</button>
|
||||
* ```
|
||||
* 那个值就会经安卓桥 POST 到内核排队,**下一轮对话时作为上下文交给模型**。
|
||||
* 也就是模型真的能知道用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 两个名字都留着(`pick` / `sendToAi`):模型有时写这个有时写那个,
|
||||
* 收两个比让它猜、猜错了整段交互失效要省事得多。
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun sendToAi(value: String?) = pick(value)
|
||||
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
onClose?.invoke()
|
||||
}
|
||||
|
||||
/** 页面销毁时断开引用,别把 Compose 的东西一直攥着 */
|
||||
fun detach() {
|
||||
onResult = null
|
||||
onClose = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME = "Doubao"
|
||||
|
||||
/**
|
||||
* 往页面里写一个标记并回读 —— 用来判断"当前这一页是不是我们自己注入的"。
|
||||
*
|
||||
* ★ 走 `evaluateJavascript` 而不是看 url:实测从外部页返回时
|
||||
* `onPageFinished` 收到的 url 不是 `about:blank`,用 url 判会漏。
|
||||
* 标记是页面自己的属性,页面被换掉它就没了,可靠得多。
|
||||
*
|
||||
* 返回 "1" 表示是我们的页。
|
||||
*/
|
||||
const val PROBE_JS =
|
||||
"(function(){try{" +
|
||||
"if(!window.__doubaoAiPage){window.__doubaoAiPage=1;}" +
|
||||
"return '1';" +
|
||||
"}catch(e){return '0';}})()"
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 `data-doubao-result="x"` 变成可点的链接,再套一层骨架 */
|
||||
private fun buildAiHtml(screen: AiSurface.Screen): String {
|
||||
val body = if (screen.fullHtml) screen.html else wrapSkeleton(screen.html)
|
||||
return rewriteResultLinks(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `<button data-doubao-result="值">文字</button>` 重写成
|
||||
* `<a class="db-btn" href="doubao://pick?value=值">文字</a>`。
|
||||
*
|
||||
* ★ 用正则做单遍替换,**不引 HTML 解析器** —— 这点转换不值得多一个依赖,
|
||||
* 而且 AI 的输出是受控的(我们自己提示词里教的写法)。
|
||||
* `button` 和 `a` 两种都收,模型有时会写成链接。
|
||||
*/
|
||||
private fun rewriteResultLinks(html: String): String {
|
||||
val pattern = Regex(
|
||||
"""<(button|a)\b([^>]*?)data-doubao-result\s*=\s*["']([^"']*)["']([^>]*?)>(.*?)</\1>""",
|
||||
setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),
|
||||
)
|
||||
return pattern.replace(html) { m ->
|
||||
val value = android.net.Uri.encode(m.groupValues[3])
|
||||
val inner = m.groupValues[5]
|
||||
"""<a class="db-btn" href="doubao://pick?value=$value">$inner</a>"""
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给"片段式" HTML 套一层骨架。
|
||||
*
|
||||
* 为什么要套:模型每次都要重复写 `<meta viewport>`、暗色主题背景、字体、
|
||||
* 边距 —— 既啰嗦又容易和 App 的主题打架。套一层之后它只管写内容。
|
||||
*/
|
||||
private fun wrapSkeleton(fragment: String): String = """
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; padding: 16px 16px 40px;
|
||||
background: #121317; color: #e8eaed;
|
||||
font: 15px/1.7 -apple-system, "PingFang SC", "Noto Sans CJK SC", sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
h1 { font-size: 21px; margin: 4px 0 12px; }
|
||||
h2 { font-size: 18px; margin: 20px 0 8px; }
|
||||
h3 { font-size: 16px; margin: 16px 0 6px; }
|
||||
p { margin: 8px 0; }
|
||||
a { color: #7cb0ff; }
|
||||
code, pre {
|
||||
background: #1d1f25; border-radius: 8px;
|
||||
font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 13px;
|
||||
}
|
||||
code { padding: 2px 5px; }
|
||||
pre { padding: 12px; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
|
||||
th, td { border: 1px solid #2c2f36; padding: 8px 10px; text-align: left; }
|
||||
th { background: #1b1d22; font-weight: 600; }
|
||||
blockquote {
|
||||
margin: 12px 0; padding: 8px 14px;
|
||||
border-left: 3px solid #3d4450; color: #b9bdc4;
|
||||
}
|
||||
img, svg, canvas { max-width: 100%; height: auto; }
|
||||
hr { border: 0; border-top: 1px solid #2c2f36; margin: 18px 0; }
|
||||
|
||||
/* ★★ 按钮 —— 这里刻意做得**非常显眼**。
|
||||
*
|
||||
* 起因:用户连着两次反馈"哪有按键,网页里的按键也点不了"、"没有一个按键能用"。
|
||||
* 实测下来**功能是好的**(点了值确实回到模型手里),问题出在**视觉**:
|
||||
*
|
||||
* · `data-doubao-result` 的按钮会被 App 改写成 `<a class="db-btn">`,
|
||||
* 拿到亮蓝整行的样式 → 看得出来能点
|
||||
* · 而 `onclick="Doubao.sendToAi(...)"` 的按钮**保持原样**,
|
||||
* 落进下面那条"普通按钮"规则 → 小灰块,在深色主题里跟正文几乎一样
|
||||
*
|
||||
* 同一屏里一半亮蓝一半灰暗,用户当然会以为"只有蓝的能点"甚至"都不能点"。
|
||||
*
|
||||
* 所以现在**所有 button / .db-btn 一律是同样显眼的实心蓝**,
|
||||
* 普通按钮那条规则删掉了。`!important` 是为了压掉模型内联的
|
||||
* `style="background:..."`(模型很爱写这个,一写就把我们的样式盖掉)。 */
|
||||
.db-btn, button, [data-doubao-result], [role=button] {
|
||||
display: block !important;
|
||||
width: 100% !important;
|
||||
margin: 10px 0 !important;
|
||||
padding: 15px 18px !important;
|
||||
background: #2b7bff !important;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none !important;
|
||||
text-align: center !important;
|
||||
border: 0 !important;
|
||||
border-radius: 12px !important;
|
||||
font-size: 16px !important;
|
||||
font-weight: 500 !important;
|
||||
line-height: 1.4 !important;
|
||||
cursor: pointer !important;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
.db-btn:active, button:active, [data-doubao-result]:active, [role=button]:active {
|
||||
background: #1e63d6 !important;
|
||||
transform: scale(0.985);
|
||||
}
|
||||
/* 次要按钮(模型想要不那么抢眼的):加个 class 就能变灰 */
|
||||
.db-plain, button.db-plain {
|
||||
background: #262a31 !important;
|
||||
color: #e8eaed !important;
|
||||
border: 1px solid #3d4450 !important;
|
||||
}
|
||||
/* 两个按钮并排时用这个包一层 */
|
||||
.db-row { display: flex; gap: 10px; }
|
||||
.db-row > * { flex: 1; }
|
||||
</style></head>
|
||||
<body>
|
||||
$fragment
|
||||
</body></html>
|
||||
"""
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、AI 的选择弹窗(ask_user) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiDialogOverlay(dialog: AiSurface.Dialog?, onAnswer: (List<String>, Boolean) -> Unit) {
|
||||
var last by remember { mutableStateOf<AiSurface.Dialog?>(null) }
|
||||
LaunchedEffect(dialog) { if (dialog != null) last = dialog }
|
||||
val shown = dialog ?: last
|
||||
|
||||
// 多选时先把已勾的攒起来,点「确定」才回传
|
||||
val picked = remember(dialog?.id) { mutableStateListOf<String>() }
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
enter = fadeIn(tween(180)),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color(0xB3000000))
|
||||
.clickable(enabled = shown?.allowCancel == true) { onAnswer(emptyList(), true) },
|
||||
)
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
enter = slideInVertically(tween(280, easing = androidx.compose.animation.core.FastOutSlowInEasing)) { it / 3 } +
|
||||
fadeIn(tween(200)) + scaleIn(tween(280), initialScale = 0.94f),
|
||||
exit = slideOutVertically(tween(200)) { it / 4 } + fadeOut(tween(150)) +
|
||||
scaleOut(tween(200), targetScale = 0.96f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 24.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(22.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(20.dp),
|
||||
) {
|
||||
Text("AI 想问你", fontSize = 12.sp, color = doubaoTextDim())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
shown.question,
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
lineHeight = 24.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("可多选", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
|
||||
// 选项多时中间区域自己滚,按钮不跟着滚出去
|
||||
Column(
|
||||
Modifier.heightIn(max = 360.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
shown.options.forEach { opt ->
|
||||
val on = opt.value in picked
|
||||
OptionRow(
|
||||
label = opt.label,
|
||||
description = opt.description,
|
||||
selected = on,
|
||||
multiple = shown.multiple,
|
||||
onClick = {
|
||||
if (shown.multiple) {
|
||||
if (on) picked.remove(opt.value) else picked.add(opt.value)
|
||||
} else {
|
||||
onAnswer(listOf(opt.value), false)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (shown.allowCancel) {
|
||||
OutlinedButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
}
|
||||
Button(
|
||||
onClick = { onAnswer(picked.toList(), false) },
|
||||
enabled = picked.isNotEmpty(),
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("确定") }
|
||||
}
|
||||
} else if (shown.allowCancel) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
TextButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.align(Alignment.End),
|
||||
) { Text("取消") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OptionRow(
|
||||
label: String,
|
||||
description: String,
|
||||
selected: Boolean,
|
||||
multiple: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
// 选中时轻微放大 —— 比单纯变色更能让人感到"点到了"
|
||||
val scale by animateFloatAsState(
|
||||
targetValue = if (selected) 1.02f else 1f,
|
||||
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
|
||||
label = "optScale",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (selected) doubaoAccentSoft() else doubaoSurfaceAlt())
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 15.sp,
|
||||
color = if (selected) doubaoAccent() else doubaoText(),
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
if (description.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(description, fontSize = 12.sp, color = doubaoTextDim(), lineHeight = 17.sp)
|
||||
}
|
||||
}
|
||||
if (multiple && selected) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("✓", fontSize = 16.sp, color = doubaoAccent())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、对话被 AI 结束 —— 屏幕中间的横幅 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* ★ 用户明确要求的样子:**屏幕中间一个横幅,写着 AI 关闭的原因**。
|
||||
*
|
||||
* 几个细节:
|
||||
* · **停在屏幕正中间**(不是顶部也不是底部)—— 这是"这次对话到此为止"
|
||||
* 这种终局状态,摆在视线中心最合适
|
||||
* · **不自动消失**。它不是提示条,是状态;消失了用户就不知道
|
||||
* 为什么发不出消息了
|
||||
* · 动画:从下方滑上来 + 淡入 + 轻微放大,像"落定"
|
||||
* · 只显示在与它相关的那次对话里(调用方按 conversationId 判断)
|
||||
*/
|
||||
@Composable
|
||||
fun EndedBanner(reason: String, onNewConversation: () -> Unit) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
AnimatedVisibility(
|
||||
visible = true,
|
||||
enter = slideInVertically(
|
||||
tween(420, easing = androidx.compose.animation.core.FastOutSlowInEasing),
|
||||
) { it } + fadeIn(tween(280)) + scaleIn(tween(420), initialScale = 0.9f),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 28.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 20.dp, vertical = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.PowerSettingsNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("这次对话已结束", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
reason.ifBlank { "AI 结束了这次对话" },
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Button(
|
||||
onClick = onNewConversation,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = doubaoAccent()),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("开始新对话", color = Color.White) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -17,6 +19,10 @@ import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
// ★ 扩展函数(`Modifier.verticalScroll`)**不能用全限定名调用** ——
|
||||
// 必须 import 进来。这个坑花了两轮构建才撞明白。
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -38,11 +44,27 @@ import com.doubao.lynxclone.data.KernelClient
|
||||
|
||||
/** 建 ViewModel 并把 client 注入进去(没上 DI 框架,手写个工厂就够) */
|
||||
@Composable
|
||||
fun rememberAppViewModel(client: KernelClient): AppViewModel =
|
||||
viewModel(factory = object : ViewModelProvider.Factory {
|
||||
fun rememberAppViewModel(client: KernelClient): AppViewModel {
|
||||
// ★ 必须写 `viewModel<AppViewModel>(…)`:不写的话类型推断会挂
|
||||
// (报 "Not enough information to infer type argument for 'VM'"),
|
||||
// 下面那句 `vm.appContext` 就跟着报未解析引用 ——
|
||||
// 错误信息看着完全不像"泛型没写",很容易往错的方向查。
|
||||
val vm = viewModel<AppViewModel>(factory = object : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T = AppViewModel(client) as T
|
||||
})
|
||||
// ★ 把 ApplicationContext 交给 ViewModel —— 它要读写"AI 界面"那些落盘的文件
|
||||
// (用户要求"AI 写的界面可以再点开")。
|
||||
// ViewModel 自己拿不到 Context(没有 DI 框架),所以在 Compose 这一层塞进去。
|
||||
// 用 **applicationContext** 而不是 Activity:ViewModel 活得比 Activity 久,
|
||||
// 攥着 Activity 会泄漏。
|
||||
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
// ★ 显式写参数名 `ctx`:LaunchedEffect 的 lambda 里 `it` 是它的 key(不是我们想要的),
|
||||
// 写成 `it` 会报 "Unresolved reference 'it'" —— 因为 LaunchedEffect 的
|
||||
// block 是无参的 `suspend () -> Unit`,没有 it。
|
||||
androidx.compose.runtime.LaunchedEffect(appContext) { vm.appContext = appContext }
|
||||
return vm
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AppRoot(
|
||||
@@ -54,6 +76,46 @@ fun AppRoot(
|
||||
val vm = rememberAppViewModel(client)
|
||||
LaunchedEffect(Unit) { vm.refresh() }
|
||||
|
||||
/* ---------------- 记忆的导入 / 导出(SAF)----------------
|
||||
*
|
||||
* ★ 为什么用系统的文件选择器而不是自己写路径:安卓 11+ 已经不给
|
||||
* App 随便写公共目录了,SAF 是唯一"用户想存哪就存哪"的正路
|
||||
* (会议导出、节点导出都是这条路,见 MeetingsScreen)。
|
||||
* ★ 编码固定 UTF-8:记忆里有中文,用默认编码在别的机器上会变乱码。
|
||||
*/
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
var pendingExport by remember { mutableStateOf<String?>(null) }
|
||||
// 导入记忆:文件读出来了,等用户选合并还是覆盖
|
||||
var pendingImportJson by remember { mutableStateOf<String?>(null) }
|
||||
val createMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json"),
|
||||
) { uri ->
|
||||
val text = pendingExport
|
||||
pendingExport = null
|
||||
if (uri != null && text != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openOutputStream(uri)?.use { it.write(text.toByteArray(Charsets.UTF_8)) }
|
||||
}.onFailure { vm.showHint("导出失败:${it.message ?: "写不进去"}") }
|
||||
.onSuccess { vm.showHint("记忆已导出") }
|
||||
}
|
||||
}
|
||||
val importMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { input ->
|
||||
input.readBytes().toString(Charsets.UTF_8)
|
||||
} ?: ""
|
||||
}.onSuccess { text ->
|
||||
// ★ 读出来先**不导**,让用户选合并还是覆盖(复查报告 4.2.4)。
|
||||
// 原来这里是"直接按合并导" —— 于是 replace 这个能力
|
||||
// 内核支持、界面上却没有入口,等于只有一半。
|
||||
if (text.isNotBlank()) pendingImportJson = text
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
// 提示条 2.5 秒后自动消失
|
||||
LaunchedEffect(vm.hint) {
|
||||
if (vm.hint.isNotBlank()) {
|
||||
@@ -86,6 +148,18 @@ fun AppRoot(
|
||||
Screen.Settings -> SettingsScreen(vm)
|
||||
Screen.Skills -> SkillsScreen(vm)
|
||||
Screen.Agents -> AgentsScreen(vm)
|
||||
// 智能体选择界面(需求第二章):左列表 + 右角色展示 + 切换动画
|
||||
Screen.AgentSelect -> AgentSelectScreen(
|
||||
agents = vm.agents,
|
||||
activeId = vm.state.settings.activeAgentId,
|
||||
onEnter = { vm.enterAgent(it.id) },
|
||||
onMore = { vm.openTokenUsage(it.id) },
|
||||
onMemories = { vm.openMemories(it.id) },
|
||||
onManage = { vm.screen = Screen.Agents },
|
||||
onBack = { vm.screen = Screen.Chat },
|
||||
)
|
||||
// 世界观 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)
|
||||
Screen.Resources -> ResourcesScreen(vm) { vm.screen = Screen.Chat }
|
||||
Screen.Meetings -> MeetingsScreen(vm)
|
||||
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
|
||||
}
|
||||
@@ -112,6 +186,373 @@ fun AppRoot(
|
||||
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- AI 主动弹出来的东西 ----------------
|
||||
*
|
||||
* ★ 放在**导航之上**(这个 Box 的最后):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话,用户在会议/设置页时弹不出来 ——
|
||||
* 而模型那边以为已经弹给用户看了,只能干等(ask_user 会一直等到超时)。
|
||||
*
|
||||
* 顺序(后写的盖在上面):全屏网页 > 选择弹窗 > HTML 界面。
|
||||
* `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的,
|
||||
* 他最想看的是网页,所以网页在最上面。
|
||||
*/
|
||||
// 「更多功能」—— 抽屉里放不下的入口收在这儿
|
||||
AnimatedVisibility(
|
||||
visible = vm.moreSheetOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MoreSheetScreen(
|
||||
onOpenAiScreens = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openAiScreenList()
|
||||
},
|
||||
onOpenSkills = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Skills
|
||||
},
|
||||
onOpenResources = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Resources
|
||||
},
|
||||
onOpenMeetings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Meetings
|
||||
},
|
||||
onOpenTerminal = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Terminal
|
||||
},
|
||||
onOpenSettings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Settings
|
||||
},
|
||||
// 从抽屉挪进来的三个
|
||||
onNewGroup = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.newGroupTopic()
|
||||
},
|
||||
onOpenNotes = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openNotes()
|
||||
},
|
||||
onOpenModels = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.modelPickerOpen = true
|
||||
},
|
||||
onClose = { vm.moreSheetOpen = false },
|
||||
)
|
||||
}
|
||||
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
AnimatedVisibility(
|
||||
visible = vm.notesOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
NotesScreen(
|
||||
notes = vm.notes,
|
||||
opening = vm.openingNote,
|
||||
onOpen = { vm.openNote(it) },
|
||||
onCloseNote = { vm.closeNote() },
|
||||
onDelete = { vm.deleteNote(it) },
|
||||
onBack = { vm.closeNotes() },
|
||||
)
|
||||
}
|
||||
|
||||
// 世界观的**共享记忆**(从「资源 → 世界观 → 记忆」进来)。
|
||||
//
|
||||
// ★ 它和上面那个是同一个空间(world:<uuid>)的**另一个视角**:
|
||||
// 那边问"玄辰记住了什么",这边问"这个世界里大家共同记得什么"。
|
||||
// 纯只读 —— 写入限权是按 author 判的,而这个视角没有"我"。
|
||||
AnimatedVisibility(
|
||||
visible = vm.worldMemoryId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MemoryScreen(
|
||||
space = vm.worldMemorySpace,
|
||||
agentName = vm.state.worldviews.firstOrNull { it.id == vm.worldMemoryId }?.name
|
||||
?: "世界观",
|
||||
agentId = "",
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
worldMode = true,
|
||||
loading = false,
|
||||
hint = "",
|
||||
onSetEmotion = { _, _ -> },
|
||||
onAdd = { _, _ -> },
|
||||
onUpdate = { _, _, _ -> },
|
||||
// 删是可以的:限权只约束 AI,用户有权清掉任何人写的
|
||||
onDelete = { vm.deleteWorldMemory(it) },
|
||||
onTogglePin = { _, _ -> },
|
||||
onSummarize = {},
|
||||
onExport = {},
|
||||
onSetWindow = {},
|
||||
onImportClick = {},
|
||||
onOpenOwn = {},
|
||||
onBackToActive = {},
|
||||
onBack = { vm.closeWorldMemories() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「智能体编辑」—— 全屏界面(字段二十多个,弹窗装不下,见 AGENTS.md 那张表)
|
||||
AnimatedVisibility(
|
||||
visible = vm.agentEditOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AgentEditScreen(
|
||||
vm = vm,
|
||||
initial = vm.agentEditing,
|
||||
onDone = { vm.closeAgentEdit() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「用量」详情 —— 选择界面上的「更多」按钮(需求 2.4 / 3.1)
|
||||
AnimatedVisibility(
|
||||
visible = vm.tokenUsageOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
TokenUsageScreen(
|
||||
usage = vm.tokenUsage,
|
||||
onReset = { vm.tokenUsage?.agentId?.takeIf { it.isNotBlank() }?.let { vm.resetTokenUsage(it) } },
|
||||
onBack = { vm.closeTokenUsage() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「记忆」管理(需求 3.2 的"用户手动编辑兜底")
|
||||
AnimatedVisibility(
|
||||
visible = vm.memoryAgentId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MemoryScreen(
|
||||
space = vm.memorySpace,
|
||||
agentName = vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "",
|
||||
agentId = vm.memoryAgentId,
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
loading = vm.memoryLoading,
|
||||
hint = vm.memoryHint,
|
||||
onSetEmotion = { preset, text -> vm.setEmotion(preset, text) },
|
||||
onAdd = { t, c -> vm.addMemory(t, c) },
|
||||
onUpdate = { id, t, c -> vm.updateMemory(id, t, c) },
|
||||
onDelete = { vm.deleteMemory(it) },
|
||||
onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) },
|
||||
onSummarize = { vm.summarizeMemories() },
|
||||
onExport = { vm.exportMemories { text -> pendingExport = text } },
|
||||
onSetWindow = { vm.setMemoryWindow(it) },
|
||||
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
|
||||
onOpenOwn = { vm.openMemories(vm.memoryAgentId, own = true) },
|
||||
onBackToActive = { vm.openMemories(vm.memoryAgentId, own = false) },
|
||||
onBack = { vm.closeMemories() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「新建群聊」:挑一个搭子(当前智能体当主角 = 主智能体)
|
||||
//
|
||||
// ★ 用对话框而不是全屏:这是**一次选择**(挑一个人就完了),
|
||||
// 智能体一般不超过十个,一屏放得下 —— 正是 AGENTS.md 里
|
||||
// "一次确认 / 纯菜单用弹窗"那一档。
|
||||
if (vm.pickGroupPeer) {
|
||||
val others = vm.state.agents.filter { it.id != vm.activeAgent?.id }
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.cancelPickGroupPeer() },
|
||||
title = { Text("和谁一起聊") },
|
||||
text = {
|
||||
if (others.isEmpty()) {
|
||||
Text("还没有别的智能体。先去「智能体」里建一个。", fontSize = 13.sp)
|
||||
} else {
|
||||
// ★ 用全限定名:这个文件的 import 列表里没有
|
||||
// verticalScroll / rememberScrollState,
|
||||
// 而它们只在这一处用得到(别的滚动都在各自的界面文件里)
|
||||
// ★ 这层滚动用**全限定调用**:`Modifier.verticalScroll`
|
||||
// 是个扩展函数,光写名字这里解析不到,而为了它一行
|
||||
// 往这个文件顶部加 import 不划算(只此一处用得到)
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
for (a in others) {
|
||||
Text(
|
||||
a.name,
|
||||
fontSize = 14.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { vm.createGroupWith(a.id) }
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { vm.cancelPickGroupPeer() },
|
||||
) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// [规则包编辑](v1.2 附录 D)—— 全屏
|
||||
AnimatedVisibility(
|
||||
visible = vm.editingRulePack != null,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
RulePackEditScreen(vm = vm, onBack = { vm.closeRulePackEdit() })
|
||||
}
|
||||
|
||||
// 「群成员」(v1.2 §3.9)—— 用户手动增删成员无条件
|
||||
AnimatedVisibility(
|
||||
visible = vm.membersConvId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
GroupMembersScreen(
|
||||
vm = vm,
|
||||
conversationId = vm.membersConvId,
|
||||
onBack = { vm.closeMembers() },
|
||||
// 成员行上的「状态」→ 开 [状态数值](三个入口之一)
|
||||
onOpenStats = { vm.openStats(it) },
|
||||
)
|
||||
}
|
||||
|
||||
// [状态数值](v1.2 §3.10 / §3.11)—— 三个入口共用这一个界面:
|
||||
// 聊天页的状态栏、智能体编辑的"它的状态"、群成员的「状态」按钮
|
||||
AnimatedVisibility(
|
||||
visible = vm.statsAgentId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AgentStatsScreen(
|
||||
vm = vm,
|
||||
agentId = vm.statsAgentId,
|
||||
onBack = { vm.closeStats() },
|
||||
)
|
||||
}
|
||||
|
||||
// 导入记忆:先读文件,再让用户选**合并还是覆盖**(复查报告 4.2.4)。
|
||||
//
|
||||
// ★ 默认是合并:覆盖是破坏性的,用户点错一次就全没了。
|
||||
// 所以「覆盖」那个按钮上直接写清后果 —— 不给"确定/取消"这种看不出区别的选项。
|
||||
pendingImportJson?.let { text ->
|
||||
val count = runCatching {
|
||||
org.json.JSONObject(text).optJSONArray("smartMemory")?.length() ?: 0
|
||||
}.getOrDefault(0)
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { pendingImportJson = null },
|
||||
title = { Text("怎么导入", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"这个文件里有 $count 条记忆。\n\n" +
|
||||
"合并:只加没有的(按标题判重),现有的全留着,情绪也不动。\n" +
|
||||
"覆盖:先把现在这 ${vm.memorySpace?.memories?.size ?: 0} 条全删掉," +
|
||||
"再换成文件里的,情绪也一起换掉。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { pendingImportJson = null; vm.importMemories(text, "merge") },
|
||||
) { Text("合并(推荐)") }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { pendingImportJson = null; vm.importMemories(text, "replace") },
|
||||
) { Text("覆盖", color = androidx.compose.ui.graphics.Color(0xFFD93025)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 拿到 JSON 之后再弹存盘对话框(先有内容才能给文件名,顺序不能反)
|
||||
LaunchedEffect(pendingExport) {
|
||||
val text = pendingExport ?: return@LaunchedEffect
|
||||
if (text.isNotBlank()) {
|
||||
runCatching {
|
||||
createMemoryDoc.launch(
|
||||
"${vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "agent"}-记忆.json",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 「超时」—— 所有超时都能调(入口在设置页)
|
||||
AnimatedVisibility(
|
||||
visible = vm.timeoutsOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
TimeoutsScreen(
|
||||
state = vm.timeouts,
|
||||
saving = vm.timeoutsSaving,
|
||||
onSave = { vm.saveTimeouts(it) },
|
||||
onReset = { vm.resetTimeouts() },
|
||||
onBack = { vm.closeTimeouts() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「AI 界面」列表(用户要求"AI 写的界面可以再点开")。
|
||||
// 排在 HTML 界面之下:点一个就从列表进到界面。
|
||||
AnimatedVisibility(
|
||||
visible = vm.aiScreenListOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AiScreenListScreen(
|
||||
screens = vm.aiScreenList,
|
||||
onOpen = { vm.reopenAiScreen(it) },
|
||||
onDelete = { vm.deleteAiScreen(it) },
|
||||
onClose = { vm.dismissAiScreenList() },
|
||||
)
|
||||
}
|
||||
|
||||
AiHtmlScreenOverlay(
|
||||
screen = vm.aiScreen,
|
||||
onClose = { vm.closeAiScreen() },
|
||||
onResult = { vm.onAiScreenResult(it, vm.aiScreen?.waiting == true) },
|
||||
autoCloseOnResult = vm.aiScreen?.waiting == true,
|
||||
)
|
||||
AiDialogOverlay(
|
||||
dialog = vm.aiDialog,
|
||||
onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) },
|
||||
)
|
||||
|
||||
// 「网页」界面(**独立全屏界面**,不是弹窗)。
|
||||
// 排在网页显示之下:用户选完就直接进网页,中间那一层要能被盖住。
|
||||
AnimatedVisibility(
|
||||
visible = vm.pickUrlFrom.isNotEmpty() || vm.urlPickerOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
UrlListScreen(
|
||||
owner = "这条回复",
|
||||
urls = vm.pickUrlFrom,
|
||||
onPick = { vm.openTypedUrl(it) },
|
||||
onClose = { vm.dismissUrlPicker() },
|
||||
)
|
||||
}
|
||||
|
||||
// 全屏看网页(点消息下方「打开网页」按钮进来)
|
||||
AnimatedVisibility(
|
||||
visible = vm.webPage != null,
|
||||
enter = slideInVertically(tween(240)) { it / 5 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 6 } + fadeOut(tween(150)),
|
||||
) {
|
||||
vm.webPage?.let { url ->
|
||||
WebPageScreen(
|
||||
url = url,
|
||||
onClose = { vm.closeWebPage() },
|
||||
// 用户在网页上点选 → 发回给 AI。走的是**普通发消息**那条路
|
||||
// (所以会正常显示在对话里、正常存历史),而不是什么隐藏通道 ——
|
||||
// 用户能看见自己"发了什么",也能反悔(重新生成)。
|
||||
onSendToAi = { text ->
|
||||
vm.closeWebPage()
|
||||
vm.sendExternal(text)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,38 +579,85 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 抽屉分两层(改过一次,用户反馈"太挤了对话都没了")。
|
||||
*
|
||||
* 原来 9 个入口平铺,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能(用户 90% 打开抽屉是为了切对话)。
|
||||
*
|
||||
* 现在:
|
||||
* · 第一层只放**天天用的**三个:新话题 / 智能体 / 笔记
|
||||
* · 其余的收进「更多功能」一个入口,点开是独立全屏页(按项目约定,
|
||||
* 列表这种要滚动的东西不用弹窗或折叠面板)
|
||||
*/
|
||||
// 分区标题:抽屉里两组东西(功能 / 对话)不标一下容易混在一起看
|
||||
// ★ 分组标题的留白也一起放松 —— 只加项间距的话,
|
||||
// 标题会和第一项粘在一起,看着像"标题属于上一组"
|
||||
SectionLabel("功能", Modifier.padding(start = 22.dp, top = 14.dp, bottom = 6.dp))
|
||||
// ★★ 抽屉第一层**只留四件天天用的**(用户明确说"太挤了"、
|
||||
// "把别的放更多里"):
|
||||
//
|
||||
// 开启新话题 · 智能体 · 记忆 · 更多功能
|
||||
//
|
||||
// 笔记 / 模型 / 新建群聊都挪进「更多功能」了。
|
||||
// 「模型」虽然也常用,但它是个**配置**(配好基本不动),
|
||||
// 腾出来的位置留给底下的对话列表更值 ——
|
||||
// 而对话列表才是用户 90% 打开抽屉的目的。
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
vm.screen = Screen.Agents; vm.drawerOpen = false
|
||||
// ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页),
|
||||
// 管理(新建/编辑/导入导出)在那个页面的「管理」里
|
||||
vm.screen = Screen.AgentSelect; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
|
||||
vm.screen = Screen.Skills; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.AccountTree, "会议模式") {
|
||||
vm.screen = Screen.Meetings; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Terminal, "终端") {
|
||||
vm.screen = Screen.Terminal; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Settings, "设置") {
|
||||
vm.screen = Screen.Settings; vm.drawerOpen = false
|
||||
}
|
||||
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||
DrawerItem(
|
||||
Icons.Filled.Memory, "模型",
|
||||
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
|
||||
) {
|
||||
vm.modelPickerOpen = true
|
||||
// ★「记忆」:当前这个智能体记住了什么。
|
||||
// 给它一个抽屉直达入口,因为这是**日常要看**的东西 ——
|
||||
// 你得知道它记对没记错(AI 记反了"喜欢猫/讨厌猫"这种事很常见)。
|
||||
DrawerItem(Icons.Filled.Psychology, "记忆") {
|
||||
vm.drawerOpen = false
|
||||
vm.activeAgent?.id?.let { vm.openMemories(it) }
|
||||
}
|
||||
DrawerItem(Icons.Filled.Apps, "更多功能") {
|
||||
vm.drawerOpen = false
|
||||
vm.moreSheetOpen = true
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("置顶", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||
|
||||
// ★ 群聊和单聊**分开列**(用户要求)。
|
||||
//
|
||||
// 混在一起排的时候,群聊会被一堆单聊埋到下面去 ——
|
||||
// 而这两类的**行为**本来就不一样:群聊有成员表、点名条、
|
||||
// 谁在说话跟着换;单聊只有一个主人。混在一起用户还得靠标题猜。
|
||||
//
|
||||
// 私聊记录(两个 AI 自己聊的)归到「对话」那一组 ——
|
||||
// 它没有"多个成员在群里"的语义,是两条消息流而已。
|
||||
val groups = vm.state.conversations.filter { it.isGroup }
|
||||
val singles = vm.state.conversations.filter { !it.isGroup }
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
items(vm.state.conversations.size) { i ->
|
||||
ConversationRow(vm, vm.state.conversations[i])
|
||||
if (groups.isNotEmpty()) {
|
||||
item {
|
||||
SectionLabel("群聊", Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp))
|
||||
}
|
||||
items(groups.size) { i -> ConversationRow(vm, groups[i]) }
|
||||
}
|
||||
item {
|
||||
SectionLabel(
|
||||
if (groups.isEmpty()) "对话" else "单聊",
|
||||
Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp),
|
||||
)
|
||||
}
|
||||
if (singles.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
"还没有单聊。点上面的「开启新话题」挑一个智能体。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 22.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(singles.size) { i -> ConversationRow(vm, singles[i]) }
|
||||
}
|
||||
|
||||
Row(
|
||||
@@ -222,11 +710,14 @@ private fun DrawerItem(
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
// ★ 项之间的留白从 2dp 提到 6dp、项内从 13dp 提到 16dp。
|
||||
// 原来每项视觉高度只有 ~48dp,七项叠在一起糊成一片 ——
|
||||
// 用户反馈"太挤了"。现在每项 ~60dp,手指点起来也稳。
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(bg)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 13.dp),
|
||||
.padding(horizontal = 12.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
226
android/app/src/main/java/com/doubao/lynxclone/ui/AssetImage.kt
Normal file
226
android/app/src/main/java/com/doubao/lynxclone/ui/AssetImage.kt
Normal file
@@ -0,0 +1,226 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.widget.ImageView
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import java.io.File
|
||||
|
||||
/*
|
||||
* 显示智能体/世界观包里的图片资源。
|
||||
*
|
||||
* ## ★ 为什么不用 Coil / Glide
|
||||
*
|
||||
* 项目一直坚持**零第三方依赖**(安卓端构建要能离线完成、APK 也不要多几百 KB)。
|
||||
* 而这里要的东西其实很窄:显示一个已知路径的本地图片。
|
||||
* Android 原生的三套 API 正好够:
|
||||
*
|
||||
* · PNG / JPG → `BitmapFactory.decodeFile`(所有版本)
|
||||
* · GIF 动图 → `ImageDecoder.decodeDrawable`(API 28+,低版本退化成静态第一帧)
|
||||
* · SVG → 原生**解不了**,走 WebView(项目里已经大量在用 WebView)
|
||||
*
|
||||
* ## 为什么静态图不统一走 ImageView
|
||||
*
|
||||
* 因为 Compose 的 `Image(bitmap)` 在裁剪/圆角/缩放上比 `AndroidView` 包一层
|
||||
* 可控得多(`Modifier.clip` / `ContentScale` 直接生效),而 GIF 又必须用
|
||||
* `Drawable`(Compose 没有原生的动图 Painter,accompanist 是第三方)。
|
||||
* 所以按扩展名分流:常见的静态图走低成本那条,动图才付出 AndroidView 的代价。
|
||||
*
|
||||
* ## 缺失资源的回退(需求 2.6)
|
||||
*
|
||||
* 回退是**调用方**的事(`AgentArtwork` 里判的),这里只负责"路径给了就画"。
|
||||
* 给空路径、文件不存在,这里返回 false 让调用方决定显示什么。
|
||||
*/
|
||||
|
||||
private const val TAG = "DoubaoImage"
|
||||
|
||||
/** 这个文件是哪种图(按扩展名,和内核 uploads.py 一个思路) */
|
||||
private enum class ImageKind { Static, Gif, Svg, Unknown }
|
||||
|
||||
private fun kindOf(path: String): ImageKind = when (File(path).extension.lowercase()) {
|
||||
"gif" -> ImageKind.Gif
|
||||
"svg" -> ImageKind.Svg
|
||||
"png", "jpg", "jpeg", "webp", "bmp" -> ImageKind.Static
|
||||
else -> ImageKind.Unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* 画一张本地图片。
|
||||
*
|
||||
* @param path 绝对路径(内核给的就是绝对路径)
|
||||
* @param fallback 画不出来时显示什么(通常是默认图或一个占位框)
|
||||
*/
|
||||
@Composable
|
||||
fun AssetImage(
|
||||
path: String,
|
||||
modifier: Modifier = Modifier,
|
||||
contentScale: ContentScale = ContentScale.Fit,
|
||||
/**
|
||||
* 裁剪时对齐哪儿。
|
||||
*
|
||||
* ★ 缩略图必须给 `TopCenter`:角色图是**竖长**的(头在上半部分),
|
||||
* 居中对齐裁出来的是"腰到大腿"——列表里一排裤子,谁也认不出是谁。
|
||||
*/
|
||||
alignment: Alignment = Alignment.Center,
|
||||
fallback: @Composable () -> Unit = {},
|
||||
) {
|
||||
val file = remember(path) { if (path.isBlank()) null else File(path) }
|
||||
if (file == null || !file.isFile) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
|
||||
when (kindOf(path)) {
|
||||
ImageKind.Svg -> SvgImage(file, modifier)
|
||||
ImageKind.Gif -> DrawableImage(file, modifier, contentScale, alignment, fallback)
|
||||
else -> StaticImage(file, modifier, contentScale, alignment, fallback)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StaticImage(
|
||||
file: File,
|
||||
modifier: Modifier,
|
||||
contentScale: ContentScale,
|
||||
alignment: Alignment,
|
||||
fallback: @Composable () -> Unit,
|
||||
) {
|
||||
// ★ remember(file.path):同一张图不重复解码。列表里滚动时这一下省很多。
|
||||
val bitmap = remember(file.path) {
|
||||
runCatching { BitmapFactory.decodeFile(file.path) }.getOrNull()
|
||||
}
|
||||
if (bitmap == null) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = modifier,
|
||||
contentScale = contentScale,
|
||||
alignment = alignment,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 动图(GIF)。
|
||||
*
|
||||
* ★ API 28 以下 `ImageDecoder` 不存在 —— 退回 `BitmapFactory` 拿第一帧,
|
||||
* 至少不是空白。项目 minSdk 是 24,所以这条分支真的会走到。
|
||||
*/
|
||||
@Composable
|
||||
private fun DrawableImage(
|
||||
file: File,
|
||||
modifier: Modifier,
|
||||
contentScale: ContentScale,
|
||||
alignment: Alignment,
|
||||
fallback: @Composable () -> Unit,
|
||||
) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
|
||||
StaticImage(file, modifier, contentScale, alignment, fallback)
|
||||
return
|
||||
}
|
||||
val drawable: Drawable? = remember(file.path) {
|
||||
runCatching {
|
||||
// ★ 宽度在 `info` 上(`ImageDecoder` 自己只有 setTargetSampleSize)——
|
||||
// 写成 `decoder.width` 是编译不过的
|
||||
ImageDecoder.decodeDrawable(ImageDecoder.createSource(file)) { decoder, info, _ ->
|
||||
// 缩到 1024 以内:包里的图可能很大,全尺寸解码在低端机上会 OOM
|
||||
val w = info.size.width
|
||||
if (w > 1024) decoder.setTargetSampleSize(kotlin.math.round(w / 1024f).coerceAtLeast(1f).toInt())
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
if (drawable == null) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
ImageView(ctx).apply {
|
||||
setImageDrawable(drawable)
|
||||
scaleType = when (contentScale) {
|
||||
ContentScale.Crop -> ImageView.ScaleType.CENTER_CROP
|
||||
ContentScale.FillBounds -> ImageView.ScaleType.FIT_XY
|
||||
else -> ImageView.ScaleType.FIT_CENTER
|
||||
}
|
||||
}
|
||||
},
|
||||
// 动图由 Drawable 自己驱动,不需要在 update 里做任何事;
|
||||
// 但路径变了要换图 —— 这个 composable 的 key 已经是路径,重建即可。
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG。
|
||||
*
|
||||
* ★ 原生解不了 SVG(`BitmapFactory` 直接返回 null),而引一个 SVG 库
|
||||
* 就破了"零第三方依赖"。项目里已经有成熟的 WebView 通道
|
||||
* (AI 界面就全靠它),所以这里用 WebView 单图显示。
|
||||
*
|
||||
* ★ 关掉一切交互:它是**背景/装饰**,不能抢走列表的滑动和点击。
|
||||
*/
|
||||
@Composable
|
||||
private fun SvgImage(file: File, modifier: Modifier) {
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
android.webkit.WebView(ctx).apply {
|
||||
setBackgroundColor(android.graphics.Color.TRANSPARENT)
|
||||
settings.javaScriptEnabled = false
|
||||
settings.allowFileAccess = true
|
||||
isClickable = false
|
||||
isFocusable = false
|
||||
// 让触摸穿透到下面的列表(不然在列表里滑动会被 WebView 吃掉)
|
||||
setOnTouchListener { _, _ -> false }
|
||||
loadDataWithBaseURL(
|
||||
"file://" + file.parent + "/",
|
||||
"""<html><head><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<style>html,body{margin:0;padding:0;background:transparent;height:100%}
|
||||
img{width:100%;height:100%;object-fit:contain}</style></head>
|
||||
<body><img src="${file.name}"></body></html>""",
|
||||
"text/html", "UTF-8", null,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** 占位:没有图时显示一个淡淡的灰框 + 可选文字(需求 2.6 的"简单方框") */
|
||||
@Composable
|
||||
fun ImagePlaceholder(modifier: Modifier = Modifier, text: String = "") {
|
||||
Box(
|
||||
modifier.then(Modifier.fillMaxSize()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (text.isNotBlank()) {
|
||||
Text(text, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 图片能不能画出来(调用方据此决定要不要回退到默认资源) */
|
||||
fun canShowImage(path: String): Boolean {
|
||||
if (path.isBlank()) return false
|
||||
val f = File(path)
|
||||
if (!f.isFile) {
|
||||
Log.w(TAG, "图片不存在:$path")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -13,7 +13,9 @@ import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -43,6 +45,7 @@ import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
@@ -53,6 +56,7 @@ import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.ChatMessage
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -181,7 +185,13 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
val onPickFile: () -> Unit = { picker.launch(arrayOf("*/*")) }
|
||||
|
||||
// ---------------- 语音 ----------------
|
||||
val speech = remember { SpeechController(context, vm.client, scope) }
|
||||
val speech = remember {
|
||||
SpeechController(context, vm.client, scope) {
|
||||
// ★ 带上当前智能体 —— 不带的话内核一律用全局音色,
|
||||
// 智能体编辑页里选的声音就白配了(用户报的"语音没生效")
|
||||
vm.state.settings.activeAgentId
|
||||
}
|
||||
}
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { speech.release() }
|
||||
}
|
||||
@@ -225,7 +235,9 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
delay(600)
|
||||
val now = vm.messages.lastOrNull()
|
||||
if (now === msg && !now.pending && now.content == msg.content) {
|
||||
speech.maybeAutoRead(now.content, vm.messages.size - 1)
|
||||
// 带上这条消息的发言者 —— 群聊里每个人音色不同,
|
||||
// 不带就一律用"当前智能体"的声音
|
||||
speech.maybeAutoRead(now.content, vm.messages.size - 1, now.agentId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -255,9 +267,16 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
ChatHeader(vm, agent?.name ?: "豆包", speech)
|
||||
// ★ 顶栏的名字和**背景用的是同一个人**(`backdropAgent`)——
|
||||
// 用户的原话是「还是没换标题和背景呀」:寐眠在说话,
|
||||
// 顶栏和背景就该都是寐眠。两处各取各的必然对不上。
|
||||
val shown = backdropAgent(vm)
|
||||
ChatHeader(vm, shown?.name ?: (agent?.name ?: "豆包"), speech)
|
||||
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
// 立绘/背景铺在**消息下面**(用户要的"整个背景都是角色")
|
||||
ChatBackdrop(vm)
|
||||
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -271,7 +290,11 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
tagline.endsWith("?") || tagline.contains(","))
|
||||
val greeting =
|
||||
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
|
||||
item { AppearOnce { HeroSection(greeting) } }
|
||||
// ★ 这里原来还有一个 168dp 的圆形立绘(ChatPortrait)——
|
||||
// 背景层(ChatBackdrop)接手之后它就是多余的:两张同一个人的图
|
||||
// 叠在一起,而且圆形 Crop 会把全身图裁到腰上,很难看。
|
||||
item { AppearOnce { HeroText(greeting) } }
|
||||
item { AppearOnce { PortraitHint(vm) } }
|
||||
}
|
||||
items(vm.messages.size) { index ->
|
||||
AppearOnce(offsetY = 10.dp) {
|
||||
@@ -309,7 +332,152 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
|
||||
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
// ★ 私聊记录是**只读**的(v1.2 §3.9 形态 B)——那两个 AI 是
|
||||
// 在你不在场的时候聊的,往里插话等于改历史记录。
|
||||
// 这里把输入条整条换掉,而不是"能输入但发不出去"。
|
||||
val privateConv = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId }?.isPrivate == true
|
||||
if (privateConv) {
|
||||
Box(Modifier.weight(1f))
|
||||
Hint("这是两个智能体的私聊记录,只读。想让他们再聊一次,去「群成员」页。")
|
||||
} else if (vm.conversationEnded) {
|
||||
/**
|
||||
* ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
|
||||
*
|
||||
* `Modifier.weight(1f)` 让它占掉原本给消息列表之外的全部剩余空间,
|
||||
* 横幅在**这块区域的中心**(也就是视觉上的屏幕中下部)。
|
||||
* 要的是"正中间",但顶部还有标题栏、下面还有输入法安全区,
|
||||
* 放在这块剩余区域的中心在观感上才是居中的。
|
||||
*
|
||||
* 输入框在此处**整个不渲染** —— 用户看到的就是"这儿没得输了",
|
||||
* 而不是一个点了没反应的框。
|
||||
*/
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
EndedBanner(
|
||||
reason = vm.endedReason,
|
||||
onNewConversation = { vm.newTopic() },
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// 本次对话的用量(需求 4.1)跟着输入条一起显示 ——
|
||||
// 放在输入框正上方是因为它是"这次对话"的属性,而输入框就是这次对话的入口
|
||||
// ★ 对话被换了归属时的提示(见 AppViewModel 的 rebasedNote)
|
||||
if (vm.rebasedNote.isNotBlank()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
vm.rebasedNote,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
RowAction("知道了") { vm.clearRebasedNote() }
|
||||
}
|
||||
}
|
||||
// ★ 群聊的成员快捷条(v1.2 §3.9):点头像 = @ 点名,被点的人这一轮一定发言
|
||||
//
|
||||
// ★★ 顺序:先「要不要让他接着说」,再点名条 ——
|
||||
// 前者的决策更靠前(它决定这一轮还继不继续),
|
||||
// 而且它只在有待决移交时才出现。
|
||||
HandoffBar(vm)
|
||||
GroupQuickBar(vm)
|
||||
SessionUsageBar(vm)
|
||||
// 额度用完被拦住了 → 给出路(复查报告 2.4)。
|
||||
// 只拦不给入口的话,用户会以为这个智能体坏了。
|
||||
if (vm.tokenLimitHit) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x1AD93025))
|
||||
.padding(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"额度用完了,这轮没发出去。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"看用量 / 调整 ›",
|
||||
fontSize = 12.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable {
|
||||
vm.dismissLimitHit()
|
||||
vm.openTokenUsage(
|
||||
vm.limitAgentId.ifBlank { vm.activeAgent?.id ?: "" },
|
||||
)
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★★ 死亡禁言(v1.2 §6.1,需求 3.5)。
|
||||
//
|
||||
// 内核那道拦截是权威,但**界面上也要拦一道** ——
|
||||
// 让用户敲完一整句话、点发送、再被拒绝,是最差的体验。
|
||||
// 提示条点一下直达记忆页的情绪区(那就是复活入口)。
|
||||
//
|
||||
// ★★ 但**群聊不锁输入框**:死了一个,群里还有别人能接话
|
||||
// (内核的 `group_chat.resolve` 会把死人跳过、换下一个人)。
|
||||
// 整条锁掉的话,用户只能干看着一个群不能用 ——
|
||||
// 用户报的「角色死亡输入框怎么不能用了」就是这个。
|
||||
// 群聊里只留一条提示,输入框照给。
|
||||
val deadAgent = vm.activeAgent
|
||||
val dead = deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true
|
||||
val convNow = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
|
||||
val groupNow = convNow?.isGroup == true
|
||||
if (dead && !groupNow) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x1AD93025))
|
||||
.padding(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"「${deadAgent?.name}」已经死亡,不能对话。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"去复活 ›",
|
||||
fontSize = 12.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable { deadAgent?.let { vm.openMemories(it.id) } }
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if (dead && groupNow) {
|
||||
// 群聊:只提示,**不拦**。被点名的人死了的话,
|
||||
// 内核会换下一个人接(不再"回主智能体",群里没有主人)
|
||||
Text(
|
||||
"「${deadAgent?.name}」已经死亡 —— 群里其他人还能接话。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 14.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
||||
@@ -341,11 +509,15 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
HeaderIcon(Icons.Filled.Edit, "新话题") { vm.newTopic() }
|
||||
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 中间这块点开就是「模型」,和豆包一样(豆包点的是 Agent 名)
|
||||
// 中间这块点开是**智能体选择界面**(需求 2.1:它是"选择智能体的入口页")。
|
||||
//
|
||||
// ★ 以前点这里是「模型」面板 —— 但用户想"换个人聊"时点的是名字,
|
||||
// 而模型是"换脑子"、不是"换人",两者混在一个入口里说不清。
|
||||
// 模型仍然在抽屉里有独立入口(那才是它该在的地方)。
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.clickable { vm.modelPickerOpen = true }
|
||||
.clickable { vm.screen = Screen.AgentSelect }
|
||||
.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
@@ -353,10 +525,46 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
Modifier.size(24.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||
// 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定,
|
||||
// 这里 path 为空就还是原来的图标)
|
||||
// ★ 跟**同一个人**:名字是寐眠、头像却是小黑,用户一眼就看出不对
|
||||
val art = backdropAgent(vm)?.image?.portrait.orEmpty()
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
modifier = Modifier.fillMaxSize().clip(CircleShape),
|
||||
contentScale = ContentScale.Crop,
|
||||
fallback = {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||
},
|
||||
)
|
||||
} else {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(agentName, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
// ★ 当前情绪(复查报告 2.6):AI 自己能改情绪,改了却看不出来,
|
||||
// 这个功能就只是个看不见的字段。放在名字旁边、字号小一半 ——
|
||||
// 它是个状态注脚,不该抢名字的注意力。
|
||||
// ★ v1.2:这里显示的是 **preset(五档)**,不是那句自由文本 ——
|
||||
// 自由文本是角色的内心独白,摆在顶栏上不合适;preset 才是
|
||||
// "一眼看出他现在什么情绪"那个粒度。点开记忆页能看到全文。
|
||||
val emo = vm.state.emotions[vm.activeAgent?.id ?: ""]
|
||||
val emoLabel = emo?.preset.orEmpty()
|
||||
if (emoLabel.isNotBlank() && emoLabel != "平常") {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
emoLabel.take(8),
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
Icon(Icons.Filled.ChevronRight, null, tint = doubaoText(), modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
@@ -409,22 +617,15 @@ private fun HeaderIcon(
|
||||
/* ------------------------------ 空态大头像 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun HeroSection(greeting: String) {
|
||||
private fun HeroText(greeting: String) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(top = 34.dp, bottom = 18.dp),
|
||||
Modifier.fillMaxWidth().padding(bottom = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
|
||||
}
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(doubaoBubble())
|
||||
.background(doubaoBubbleVeil())
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
Text(greeting, fontSize = 16.sp, lineHeight = 26.sp, color = doubaoText())
|
||||
@@ -432,21 +633,199 @@ private fun HeroSection(greeting: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天页顶部的立绘(v1.2 §6.1)。
|
||||
*
|
||||
* ★ **跟随说话者**(设置里可关,默认开):群聊时谁发言就换成谁的立绘 ——
|
||||
* 一眼看出"这句是谁说的"。关掉时固定用主智能体(成员列表第一个)。
|
||||
*
|
||||
* ★ 0.3 秒的 crossfade:立绘是**情绪驱动**的,可能一轮换一次;
|
||||
* 硬切会让人以为界面闪了一下。0.3s 刚好够看出"换了",又不拖沓。
|
||||
* (这也正是需求里点名的 0.3s —— 和群聊背景跟随共用同一套缓动,
|
||||
* 两处各写一个数字的话,将来改一处必漏另一处。)
|
||||
*/
|
||||
/**
|
||||
* 顶栏和背景该显示**谁** —— **当前正在说话的那个人**。
|
||||
*
|
||||
* ★★ 用户的原话:「还是没换标题和背景呀」。
|
||||
*
|
||||
* 我上一版理解成「跟当前对话的主人走」,那是错的 ——
|
||||
* 他要的是**寐眠说话时,顶栏和背景都是寐眠**。
|
||||
*
|
||||
* 「不是让你 @ 谁就换哪个背景」那句,意思是**不要光点一下 @ 按钮
|
||||
* 就提前换**;要跟着**真实的发言者**。内核每轮都 emit 一个
|
||||
* `speaker` 事件(群聊里就是仲裁结果),跟着它走既"立即"又"名副其实"。
|
||||
*
|
||||
* ★ 只在**群聊**里用 `currentSpeakerId`:单聊时它可能还是上一轮群里
|
||||
* 留下的值,会把单聊的顶栏带跑偏。单聊就认会话主人。
|
||||
*
|
||||
* ★ 顶栏、背景、【朗读音色】三处都从这里/`msg.agentId` 取,
|
||||
* 保证同一条消息上的名字、图、声音是**同一个人**。
|
||||
*/
|
||||
private fun backdropAgent(vm: AppViewModel): Agent? {
|
||||
val convId = vm.activeConversationId.ifBlank { "c_main" }
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == convId }
|
||||
if (conv?.isGroup == true && vm.currentSpeakerId.isNotBlank()) {
|
||||
vm.state.agents.firstOrNull { it.id == vm.currentSpeakerId }?.let { return it }
|
||||
}
|
||||
return vm.state.agents.firstOrNull { it.id == conv?.agentId.orEmpty() } ?: vm.activeAgent
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天页的**立绘背景层**(用户要求:「整个背景都是角色卡」)。
|
||||
*
|
||||
* ★ 以前立绘只在**一句话都没说**的时候露一个 168dp 的圆,
|
||||
* 一开始聊就只剩顶栏那个 24dp 头像 —— 用户的原话是「就头像是立绘」,
|
||||
* 而他要的是整个背景都是这个角色。
|
||||
*
|
||||
* ★★ 显示的是**当前对话的智能体**(`activeAgent`),不是"这一轮谁在说"。
|
||||
* 用户澄清过:「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。
|
||||
* 背景表达的是**这个场景是谁的**(和顶栏那个名字同一件事);
|
||||
* 群聊里两个人一来一回时背景跟着闪,既晃眼又和顶栏对不上。
|
||||
* "谁在说话"是**每条消息**自己的事,用 `msg.agentId`(见 [SpeakerTag])。
|
||||
*
|
||||
* ★ 两条硬约束:
|
||||
* · **必须铺在消息下面**(Box 里排在 LazyColumn 之前),否则字被盖住;
|
||||
* · **图要实心、气泡要半透明** —— 这是用户点名要的一对
|
||||
* (「立绘不要透明的」+「聊天框半透明」)。反过来做(图淡化、气泡实心)
|
||||
* 等于两头都不讨好:立绘看不清,气泡也白透。
|
||||
* 所以可读性交给气泡那边([doubaoBubbleVeil]),这里不淡化。
|
||||
*
|
||||
* ★ 立绘用 `ContentScale.Fit` 而不是 `Crop`:角色不能被裁掉半个身子。
|
||||
* 背景图反过来,必须 `Crop` —— `Fit` 会留出底色,铺不满。
|
||||
*/
|
||||
@Composable
|
||||
private fun ChatBackdrop(vm: AppViewModel) {
|
||||
val who = backdropAgent(vm)
|
||||
val back = who?.image?.back.orEmpty()
|
||||
val art = who?.image?.portrait.orEmpty()
|
||||
if (back.isBlank() && art.isBlank()) return
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
if (back.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = back,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 没配立绘时**说清楚 + 给入口**。
|
||||
*
|
||||
* ★ 回退链最后一级就是「内置默认人物」(需求 §2.6),所以背景层显示那张图**没错** ——
|
||||
* 但界面上一个字都不说的话,用户只会觉得"立绘功能没生效",
|
||||
* 而不知道**得自己去传**(内置那四个示例智能体默认都没有图)。
|
||||
*
|
||||
* ★ 它原来长在一个 168dp 圆形立绘(`ChatPortrait`)底下,和背景层重复,
|
||||
* 已经拆开:图归背景层,这句话单独留着。
|
||||
*/
|
||||
@Composable
|
||||
private fun PortraitHint(vm: AppViewModel) {
|
||||
val who = backdropAgent(vm) ?: return
|
||||
if (who.image.portrait.isNotBlank()) return
|
||||
Text(
|
||||
"还没有立绘 · 点这里去传一张",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.clickable { vm.openAgentEdit(who) },
|
||||
)
|
||||
}
|
||||
|
||||
/* ------------------------------ 消息 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 气泡上方那行**小字:这条是谁说的**。
|
||||
*
|
||||
* ★ 只在**群聊**显示(用户要求:「对话前面写明是谁在说话」)。
|
||||
* 单聊里只有一个人,每条都标一遍就是噪音 —— 那个名字顶栏已经有了。
|
||||
*
|
||||
* ★ 名字从 `msg.agentId` 查(内核一直在消息里存群聊仲裁后的发言者)。
|
||||
* 老消息没这个字段 → 退回当前智能体;群聊里退错了也只是名字不对,
|
||||
* 不影响别的(比不显示强,因为不显示就完全分不清谁是谁)。
|
||||
*
|
||||
* ★ 自己那侧写「你」而不是昵称:翻记录时"哪句是我说的"要一眼看出来,
|
||||
* 用昵称反而要在脑子里做一次映射。
|
||||
*/
|
||||
@Composable
|
||||
private fun SpeakerTag(vm: AppViewModel, msg: ChatMessage, mine: Boolean) {
|
||||
// ★ 会话 id 可能是空串(内核用 "c_main" 兜底)
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
|
||||
// 单聊只有一个人,每条都标一遍是噪音;群聊和私聊记录(两个 AI 自己聊的)
|
||||
// 都是"多人在场",不标就完全分不清谁是谁
|
||||
if (conv == null || (!conv.isGroup && !conv.isPrivate)) return
|
||||
val name = if (mine) {
|
||||
"你"
|
||||
} else {
|
||||
vm.state.agents.firstOrNull { it.id == msg.agentId }?.name.orEmpty()
|
||||
.ifBlank { vm.activeAgent?.name.orEmpty() }
|
||||
}
|
||||
if (name.isBlank()) return
|
||||
Text(
|
||||
name,
|
||||
fontSize = 11.sp,
|
||||
color = if (mine) doubaoTextSecondary() else Doubao.Blue,
|
||||
modifier = Modifier.padding(start = 4.dp, end = 4.dp, bottom = 3.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: SpeechController) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val speaking = speech.speakingIndex == index
|
||||
// 长按气泡 → 这个菜单(v1.2 §4.3 的「标记重要」)
|
||||
var importantMenu by remember { mutableStateOf(false) }
|
||||
|
||||
if (msg.role == "user") {
|
||||
// ★ 长按**用户**消息才能标重要。需求说的是"消息操作栏加标记重要",
|
||||
// 这里只做用户那一侧,理由是**效果差异**:
|
||||
// 被标的消息在上下文窗口裁剪时破格携带,而 AI 的回复通常就在
|
||||
// 最近几轮里、本来就裁不到;用户想留住的是**很久以前问过的那句**。
|
||||
if (importantMenu) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { importantMenu = false },
|
||||
title = { Text(if (msg.important) "这条标过了" else "这条消息") },
|
||||
text = {
|
||||
Text(
|
||||
if (msg.important) {
|
||||
"取消之后它就按普通消息处理了 —— 攒够一批会被裁掉。"
|
||||
} else {
|
||||
"标成重要之后,以后裁剪上下文时这条会一直留着," +
|
||||
"不管过了多少轮。"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { vm.toggleImportant(index); importantMenu = false },
|
||||
) { Text(if (msg.important) "取消标记" else "标记重要", color = Doubao.Blue) }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { importantMenu = false },
|
||||
) { Text("算了") }
|
||||
},
|
||||
)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
SpeakerTag(vm, msg, mine = true)
|
||||
msg.attachments.forEach { file ->
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoBubble())
|
||||
.background(doubaoBubbleMine())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -465,18 +844,35 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
Modifier
|
||||
.widthIn(max = 288.dp)
|
||||
.clip(RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp))
|
||||
.background(Doubao.Blue)
|
||||
.background(doubaoBubbleMine())
|
||||
.combinedClickable(
|
||||
onClick = { clipboard.setText(AnnotatedString(msg.content)) },
|
||||
onLongClick = { importantMenu = true },
|
||||
)
|
||||
.padding(horizontal = 14.dp, vertical = 11.dp),
|
||||
) {
|
||||
Text(msg.content, color = Color.White, fontSize = 16.sp, lineHeight = 25.sp)
|
||||
}
|
||||
}
|
||||
// 标过的给一个小标记 —— 不然用户忘了自己标过哪几条,
|
||||
// 而"这条会不会被裁掉"是他自己决定的
|
||||
if (msg.important) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"★ 重要(不会被裁掉)",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
|
||||
// 群聊里标出**这条是谁说的**(用户要求:「对话前面写明是谁在说话」)
|
||||
SpeakerTag(vm, msg, mine = false)
|
||||
|
||||
val hasReasoning = msg.reasoning.isNotBlank()
|
||||
val hasTrace = msg.toolTrace.isNotEmpty()
|
||||
|
||||
@@ -561,7 +957,7 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
Modifier
|
||||
.widthIn(max = 300.dp)
|
||||
.clip(RoundedCornerShape(4.dp, 18.dp, 18.dp, 18.dp))
|
||||
.background(if (msg.error) Doubao.ErrorBg else doubaoBubble())
|
||||
.background(if (msg.error) Doubao.ErrorBg else doubaoBubbleVeil())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
when {
|
||||
@@ -585,6 +981,29 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 幻觉调用检测的警示(需求 3.7):它说了"我记住了"但这一轮没调工具。
|
||||
//
|
||||
// 放在正文**下面**而不是塞进正文:这是"系统对这条回复的批注",
|
||||
// 不是 AI 说的话 —— 混进正文里,用户会以为 AI 自己在自我怀疑。
|
||||
if (msg.hallucination) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(Color(0x1AF29900))
|
||||
.padding(horizontal = 8.dp, vertical = 5.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"⚠ 它说记住了,但这一轮并没有真的调用记忆工具 —— 下次可能就不记得了。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
modifier = Modifier.widthIn(max = 280.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (!msg.pending && msg.content.isNotBlank() && !msg.error) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -593,6 +1012,63 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
vm.showHint("已复制")
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
/**
|
||||
* ★★「打开网页」—— 用户明确要求"你要单独开个按钮"。
|
||||
*
|
||||
* 以前只有正文里那行蓝色下划线,**没有可发现性**:
|
||||
* 用户不知道它能点、也不知道点了会怎样。
|
||||
* 现在改成:回复里只要有 http(s) 链接,这里就出现一个按钮。
|
||||
*
|
||||
* · 只有 1 个链接 → 直接打开
|
||||
* · 多个链接 → 进「链接列表」全屏界面让用户挑
|
||||
* (按项目约定:列表这种要滚动的东西**不用弹窗**)
|
||||
*
|
||||
* ★ 链接是从 markdown 里现算的(`extractUrls`),不额外存状态 ——
|
||||
* 存了就要担心和 content 不同步(重新生成、编辑之后)。
|
||||
*
|
||||
* ★★ 按钮**无条件显示**(v2.0.39 改)。
|
||||
* 上一版是"这条回复里有链接才显示",于是:
|
||||
* · extractUrls 漏认写法时(裸 URL 就漏)按钮整个不见了
|
||||
* · 而且用户根本无从知道"这条能不能开网页"
|
||||
* 现在永远在,顺带还能自己在里面输网址 —— 它就是个浏览器入口。
|
||||
*/
|
||||
val urls = remember(msg.content) { extractUrls(msg.content) }
|
||||
RoundIconButton(
|
||||
Icons.Filled.Language,
|
||||
if (urls.isEmpty()) "打开网页" else "打开网页(${urls.size} 个链接)",
|
||||
tint = if (urls.isEmpty()) null else Doubao.Blue,
|
||||
) {
|
||||
vm.openUrlPicker(urls)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
|
||||
/**
|
||||
* ★★「界面」—— 再打开 AI 给你弹过的界面。
|
||||
*
|
||||
* 用户要求:"AI 写的界面可以再点开"。
|
||||
* 以前界面只活在内存里,一关就没了 —— 想再看只能让 AI 重做,
|
||||
* 而重做出来的内容**不一定一样**(模型有随机性)。
|
||||
*
|
||||
* 现在每次 show_ui 都存一份,这里只在这条回复**确实弹过界面**时出现。
|
||||
* 判断依据是工具痕迹里的 screenId(`show_ui` 的返回值带来的)。
|
||||
*/
|
||||
val screenIds = remember(msg.toolTrace) {
|
||||
msg.toolTrace.map { it.screenId }.filter { it.isNotBlank() }
|
||||
}
|
||||
if (screenIds.isNotEmpty()) {
|
||||
RoundIconButton(
|
||||
Icons.Filled.Dashboard,
|
||||
if (screenIds.size == 1) "再看一次这个界面" else "看这条弹过的 ${screenIds.size} 个界面",
|
||||
tint = Doubao.Blue,
|
||||
) {
|
||||
if (screenIds.size == 1) {
|
||||
vm.reopenAiScreen(screenIds.first())
|
||||
} else {
|
||||
vm.openAiScreenList()
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
}
|
||||
if (speaking) {
|
||||
// 正在念这条:按钮变蓝 + 图标换成停止,一眼看出"再点就是停"
|
||||
RoundIconButton(
|
||||
@@ -605,7 +1081,8 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
// 手动点朗读时清掉"自动朗读念过了"的记录:
|
||||
// 用户主动点,就该正常播(或再点一次停),不受自动朗读的去重影响
|
||||
speech.forgetAutoRead()
|
||||
speech.speak(msg.content, index)
|
||||
// 用**这条消息**的发言者挑音色(群聊里每个人不一样)
|
||||
speech.speak(msg.content, index, msg.agentId)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
@@ -662,6 +1139,51 @@ private fun AttachmentStrip(vm: AppViewModel) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 本次对话的 Token 用量(需求 4.1)。
|
||||
*
|
||||
* ## 为什么按消息加起来,而不是问内核要一个"会话总数"
|
||||
*
|
||||
* 因为用量是**按轮记在消息上的**(内核落库时就这么存的)。加起来算有两个好处:
|
||||
* · "重新生成"把上一条替换掉时,它的消耗自动消失,不会虚高
|
||||
* · 删掉某条消息、切换会话、界面刷新,都不需要额外请求
|
||||
*
|
||||
* ## 为什么没有用量时**整行不显示**
|
||||
*
|
||||
* 一条消息都还没发(或者老数据里没记用量)时显示"入 0 · 出 0"是纯噪音。
|
||||
* 需求要的是"能看到用了多少",不要求一直占一行。
|
||||
*/
|
||||
@Composable
|
||||
private fun SessionUsageBar(vm: AppViewModel) {
|
||||
val inTok = vm.messages.sumOf { it.usage?.first ?: 0L }
|
||||
val outTok = vm.messages.sumOf { it.usage?.second ?: 0L }
|
||||
if (inTok == 0L && outTok == 0L) return
|
||||
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 20.dp, end = 20.dp, bottom = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("本次对话", fontSize = 10.sp, color = Doubao.TextTertiary)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("输入 ${fmtTokens(inTok)}", fontSize = 10.sp, color = Doubao.TextTertiary)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("输出 ${fmtTokens(outTok)}", fontSize = 10.sp, color = Doubao.TextTertiary)
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 点一下看智能体的**累计**用量(那个在「更多」里,需求 3.1)
|
||||
Text(
|
||||
"累计 ›",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.clickable { vm.activeAgent?.id?.let { vm.openTokenUsage(it) } }
|
||||
.padding(horizontal = 4.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputBar(
|
||||
vm: AppViewModel,
|
||||
@@ -783,7 +1305,25 @@ private fun InputBar(
|
||||
|
||||
Spacer(Modifier.width(8.dp))
|
||||
|
||||
if (canSend) {
|
||||
// ★★ 正在生成时,右边那个圆钮变成「停止」。
|
||||
//
|
||||
// 取消能力**一直都有**:内核从 HTTP 到 agent_loop 一路支持 `cancelled`,
|
||||
// ViewModel 里也建好了 `chatJob`(AtomicBoolean)——
|
||||
// 但没有任何界面调它,用户只能干等它把话说完。
|
||||
// 用户的原话就是「对话过程中可中断」。
|
||||
if (vm.streaming) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), CircleShape)
|
||||
.clickable(onClick = { vm.stopGenerating() }),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Stop, "停止生成", tint = Doubao.Blue, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
} else if (canSend) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
@@ -872,3 +1412,95 @@ private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 「要不要让他接着说」——
|
||||
* AI 用 `talk_to` / `pass_turn` 把话交给别人之后,这里摆两个按钮。
|
||||
*
|
||||
* ★★ 用户的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。
|
||||
*
|
||||
* 所以默认(手动)就**停在这儿等用户点**:
|
||||
* · 「让他说」= 继续把这一轮交出去;
|
||||
* · 「停在这」= 到此为止。
|
||||
* 设置里开了「AI 对聊自动模式」就不出现这条,直接接着跑。
|
||||
*
|
||||
* ★ 顺带解决了烧钱:默认不会自己一直聊下去。
|
||||
* ★ 位置在输入框正上方、点名条**上面**:这是"接着聊还是打住"的决策现场。
|
||||
*/
|
||||
@Composable
|
||||
private fun HandoffBar(vm: AppViewModel) {
|
||||
if (vm.pendingHandoffName.isBlank()) return
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"${vm.pendingHandoffFromName.ifBlank { "它" }} 把话交给了 ${vm.pendingHandoffName}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DoubaoPill(text = "让他说", onClick = { vm.continueHandoff() })
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("停在这") { vm.stopHandoff() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 群聊的成员快捷条(v1.2 §3.9)。
|
||||
*
|
||||
* ★ 位置在**输入框正上方**:这里是"这一轮要点谁"的决策现场,
|
||||
* 点头像就把 `@名字 ` 插进草稿里 —— 和用户手打 `@` 完全等价
|
||||
* (内核的 `group_chat.mention_in` 就是按 `@名字` 匹配的)。
|
||||
*
|
||||
* ★ 只有群聊才显示。单聊显示一排"只有一个人"的头像没有意义,
|
||||
* 而且会白占一行高度。
|
||||
*/
|
||||
@Composable
|
||||
private fun GroupQuickBar(vm: AppViewModel) {
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId }
|
||||
if (conv == null || !conv.isGroup) return
|
||||
val members = conv.participants.mapNotNull { id ->
|
||||
vm.state.agents.firstOrNull { it.id == id }?.let { id to it.name }
|
||||
}
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// 点名条:**不标"(主)"** —— 用户要求「群聊去掉主人设定」,
|
||||
// 群里没有老大,没人被 @ 时按顺序轮(kernel 的 group_chat.rotate_next)
|
||||
for (pair in members) {
|
||||
// 只插草稿 —— **不碰顶栏/背景**。那两处等内核仲裁完
|
||||
// (`speaker` 事件)才切,不然会"点了还没发就换了人"
|
||||
DoubaoPill(text = "@${pair.second}", onClick = { vm.mentionAgent(pair.second) })
|
||||
}
|
||||
// ★「让他们聊」:按下就让前两个成员**轮流对话**几轮,随时能停。
|
||||
//
|
||||
// 为什么需要这个按钮:光靠 AI 自己 `pass_turn` 是靠不住的 ——
|
||||
// 实测它更愿意把话说完,于是"两个智能体对话"永远发生不了
|
||||
// (用户报的「还是不能互相对话」)。
|
||||
// 这个按钮不依赖 AI 配合,界面直接按顺序把发言权递过去。
|
||||
DoubaoPill(text = "让他们聊", onClick = { vm.startAiTalk() })
|
||||
RowAction("成员") { vm.openMembers(conv.id) }
|
||||
}
|
||||
// ★ 仲裁**理由**(v1.2 §3.9):内核发了 note,界面以前收了但从不显示 ——
|
||||
// 于是"被点的人已死亡,发言权回主智能体"这种事用户只能自己猜。
|
||||
// 只在有话说时占一行,平时不显示。
|
||||
if (vm.speakerNote.isNotBlank()) {
|
||||
Text(
|
||||
vm.speakerNote,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,24 @@ fun doubaoText() = if (isDark()) Doubao.DarkText else Doubao.TextPrimary
|
||||
fun doubaoTextSecondary() = if (isDark()) Doubao.DarkTextSecondary else Doubao.TextSecondary
|
||||
@Composable
|
||||
fun doubaoBubble() = if (isDark()) Doubao.DarkBubble else Doubao.BubbleBot
|
||||
|
||||
/**
|
||||
* 聊天气泡的底色(**半透明**)。
|
||||
*
|
||||
* ★ 聊天页现在有一层**实心**的立绘(`ChatScreen.ChatBackdrop`)垫在下面,
|
||||
* 气泡要是也不透明,那张立绘就白铺了 —— 用户要的正是
|
||||
* 「立绘看得见、字也读得清」这一对。
|
||||
*
|
||||
* ★ 0.78 是这两条的交点:再透字就开始糊在图上,再实立绘就等于没有。
|
||||
* 别的页面(卡片、弹窗)继续用不透明的 [doubaoBubble],
|
||||
* 它们底下没有图,半透明只会显脏。
|
||||
*/
|
||||
@Composable
|
||||
fun doubaoBubbleVeil() = doubaoBubble().copy(alpha = 0.78f)
|
||||
|
||||
/** 用户自己那侧的气泡(蓝色),同样要半透明 —— 理由同 [doubaoBubbleVeil] */
|
||||
@Composable
|
||||
fun doubaoBubbleMine() = Doubao.Blue.copy(alpha = 0.82f)
|
||||
@Composable
|
||||
fun doubaoBorder() = if (isDark()) Doubao.DarkBorder else Doubao.Border
|
||||
@Composable
|
||||
@@ -77,6 +95,71 @@ fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg
|
||||
@Composable
|
||||
fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing
|
||||
|
||||
/** 主色(AI 界面/弹窗里强调"选中"用) */
|
||||
@Composable
|
||||
fun doubaoAccent() = if (isDark()) Color(0xFF6EA8FF) else Doubao.Blue
|
||||
|
||||
/** 主色的浅底(选中项的背景) */
|
||||
@Composable
|
||||
fun doubaoAccentSoft() = if (isDark()) Color(0xFF1B2A44) else Color(0xFFEAF1FF)
|
||||
|
||||
/** 比 surface 稍亮/稍暗一档的容器底色(弹窗里的选项行) */
|
||||
@Composable
|
||||
fun doubaoSurfaceAlt() = if (isDark()) Color(0xFF232830) else Doubao.CardBg
|
||||
|
||||
/** 三级文字色(比 secondary 更淡,用于说明小字) */
|
||||
@Composable
|
||||
fun doubaoTextDim() = if (isDark()) Color(0xFF8C939D) else Doubao.TextTertiary
|
||||
|
||||
/* ------------------------------ 打开链接 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 在系统浏览器里打开一个链接。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 聊天气泡里的 markdown 链接**以前渲染成蓝色下划线但没有绑点击** ——
|
||||
* 看着像能点,点了完全没反应。用户会以为是"链接坏了"。
|
||||
* (这个坑是用户问"网页在哪点开"时才查出来的:我一直在讲 AI 弹的界面,
|
||||
* 而最容易想到的"点链接"其实一直是坏的。)
|
||||
*
|
||||
* ## 为什么用系统浏览器而不是应用内 WebView
|
||||
*
|
||||
* AI 弹出的那个界面里点链接是**应用内**打开的(用户明确要的"可再点进去")。
|
||||
* 但聊天正文里的链接不一样:那里没有"返回 AI 界面"这个上下文,
|
||||
* 在应用内开一个 WebView 会让用户迷失(返回键行为说不清)。
|
||||
* 交给系统浏览器,行为标准、有历史、有关闭 —— 对正文链接更合适。
|
||||
*
|
||||
* ★ 必须 try/catch:设备上可能没有浏览器(精简 ROM),
|
||||
* 或者链接协议没人能处理,那会抛 ActivityNotFoundException。
|
||||
* 不接的话点一下链接 App 就崩。
|
||||
*/
|
||||
fun openInBrowser(context: android.content.Context, url: String): Boolean {
|
||||
val u = url.trim()
|
||||
if (u.isEmpty()) return false
|
||||
val uri = try {
|
||||
android.net.Uri.parse(u)
|
||||
} catch (_: Throwable) {
|
||||
return false
|
||||
}
|
||||
// 只放行有 scheme 的绝对地址;相对地址点了没意义,还会让 Intent 解析失败
|
||||
if (uri.scheme.isNullOrBlank()) return false
|
||||
|
||||
return try {
|
||||
context.startActivity(
|
||||
android.content.Intent(android.content.Intent.ACTION_VIEW, uri)
|
||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.w("DoubaoLink", "打不开 $u:${t.javaClass.simpleName}: ${t.message}")
|
||||
android.widget.Toast
|
||||
.makeText(context, "打不开这个链接", android.widget.Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 动画 ------------------------------ */
|
||||
|
||||
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
||||
@@ -212,3 +295,33 @@ fun SectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||
fontWeight = FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------- //
|
||||
// 通用小件(v1.2)
|
||||
// --------------------------------------------------------------------------- //
|
||||
//
|
||||
// ★ 这两个原来是 AgentEditScreen 的**私有**函数,于是别的界面想用就只能
|
||||
// 复制一份 —— 而"同一段逻辑抄两份"是这个仓库反复出现的毛病。
|
||||
// 挪到这里之后全局一份。
|
||||
|
||||
/** 一张卡片:横向留白 + 圆角 + 表面色 + 内边距 */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun Card(content: @androidx.compose.runtime.Composable () -> Unit) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
androidx.compose.ui.Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(androidx.compose.foundation.shape.RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) { content() }
|
||||
}
|
||||
|
||||
/** 一行灰字说明 */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun Hint(text: String) {
|
||||
androidx.compose.material3.Text(
|
||||
text, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
|
||||
/**
|
||||
* 群成员(v1.2 §3.9)。
|
||||
*
|
||||
* ## 为什么是全屏而不是弹窗
|
||||
*
|
||||
* 需求里写的是"浮层",但按仓库的界面约定(AGENTS.md):**列表用全屏**。
|
||||
* 一屏弹窗大概只够三四行,成员一多就得在弹窗里滚 —— 那还不如直接开一屏,
|
||||
* 而且这里还要放"加人/移出"两组动作。
|
||||
*
|
||||
* ## 谁不能移出
|
||||
*
|
||||
* ★ **主智能体不能移出**(成员列表第一个):它是"没人被点名时兜底发言"的
|
||||
* 那个人,移掉这个群就会冷场。
|
||||
* 界面上把它的按钮藏起来 —— 但那只是给用户看的,**服务端也拦**
|
||||
* (绕过界面直接调接口的路径也得挡住)。
|
||||
*/
|
||||
@Composable
|
||||
fun GroupMembersScreen(
|
||||
vm: AppViewModel,
|
||||
conversationId: String,
|
||||
onBack: () -> Unit,
|
||||
onOpenStats: (String) -> Unit = {},
|
||||
) {
|
||||
val conv: Conversation? = vm.state.conversations.firstOrNull { it.id == conversationId }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "群成员",
|
||||
subtitle = conv?.let { "${it.participants.size} 个人在群里" } ?: "会话不见了",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (!adding) TopTextAction("加人") { adding = true } else TopTextAction("取消") { adding = false }
|
||||
},
|
||||
) {
|
||||
// ---- 加人(就地展开,不再弹一层 —— 弹窗压弹窗是手机上的灾难)----
|
||||
if (adding) {
|
||||
val inGroup = conv?.participants?.toSet() ?: emptySet()
|
||||
// ★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
//
|
||||
// 群聊上下文里有 <worldview> 段、共享记忆也按世界观分空间 ——
|
||||
// 世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。
|
||||
// 内核 `group_chat.add_member` 也会拒,但**界面先筛掉**:
|
||||
// 让人点了才被告知"加不进去"是最差的体验。
|
||||
val hostWorldview = vm.state.agents
|
||||
.firstOrNull { it.id == conv?.agentId }?.worldviewId.orEmpty()
|
||||
val sameWorldview = vm.state.agents.filter {
|
||||
(it.worldviewId.orEmpty() == hostWorldview)
|
||||
}
|
||||
val candidates = sameWorldview.filter { it.id !in inGroup }
|
||||
val blocked = vm.state.agents.count { it.id !in inGroup && it !in sameWorldview }
|
||||
SectionLabel("拉谁进来")
|
||||
Card {
|
||||
if (candidates.isEmpty()) {
|
||||
Hint(
|
||||
if (blocked > 0) {
|
||||
"没有可以拉的人了。还有 $blocked 个智能体在世界观上跟这个群不一样," +
|
||||
"拉进来会串设定 —— 换个群或者先给它们绑同一个世界观。"
|
||||
} else {
|
||||
"所有同世界观的智能体都在群里了。"
|
||||
},
|
||||
)
|
||||
} else {
|
||||
for (a in candidates) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable {
|
||||
// ★ 注意签名:`makeGroup` 是**这个会话还没有群成员**时
|
||||
// 用的(会新建群聊);已经有成员了就走 `addMember`,
|
||||
// 不能混 —— 混了会把当前会话换掉,用户会一头雾水。
|
||||
if (inGroup.isEmpty()) vm.makeGroup(a.id) else vm.addMember(a.id)
|
||||
// ★★ 加完**不收起**(原来这里 `adding = false`)。
|
||||
// 收起的话,用户加了一个就得再点一次「加人」才能加下一个,
|
||||
// 体感就是"群聊只能拉两个"(真机反馈)。
|
||||
// 刷新后 `candidates` 会少一个,接着点就行。
|
||||
}.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 36)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a.name, fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Hint("想加几个就加几个 —— 点一个加一个,这排不会收起来。")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
}
|
||||
|
||||
if (conv == null) {
|
||||
Hint("这个会话已经不在了。")
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("成员")
|
||||
Card {
|
||||
for ((i, id) in conv.participants.withIndex()) {
|
||||
val a: Agent? = vm.state.agents.firstOrNull { it.id == id }
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 40)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
a?.name ?: "(已删除)",
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
// ★ 这里原来标了「主」徽章 + "没人被 @ 的时候由它接话"。
|
||||
// 用户要求「群聊去掉主人设定」—— 群里没有老大,
|
||||
// 没人被 @ 时**按顺序轮**(见 kernel/group_chat.rotate_next)。
|
||||
Text(
|
||||
"第 ${i + 1} 个进群的",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("状态") { onOpenStats(id) }
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 谁都能移出(原来主智能体移不掉)—— 既然没有主人,
|
||||
// 就没有"动不了"的那一个。内核那边会拦住"最后一个"
|
||||
RowAction("移出") { vm.removeMember(id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(
|
||||
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
|
||||
"被点的人这一轮一定发言。没人被点时**按顺序轮**,不会冷场,也没有谁永远优先。",
|
||||
)
|
||||
|
||||
// ★「让他们私下聊聊」(v1.2 §3.9 形态 B)
|
||||
//
|
||||
// 放这儿而不是抽屉里:抽屉已经有七项了(用户刚说过"太挤了"),
|
||||
// 而**群成员页本来就有成员** —— 从这儿点两个人比在抽屉里
|
||||
// 再开一个挑人对话框顺得多。
|
||||
//
|
||||
// 内核早就完整实现了(10 轮安全网、一方触顶另一方单方面收尾、
|
||||
// 摘要进共享记忆),但界面上一直没有入口 —— 这个需求项碰不到。
|
||||
Spacer(Modifier.height(12.dp))
|
||||
SectionLabel("私下聊聊")
|
||||
Card {
|
||||
Hint(
|
||||
"点两个名字,让他们在后台自主对聊 —— 你不在场。" +
|
||||
"聊完的摘要会写进共享记忆,完整记录在会话列表里能翻。",
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
for (id in conv.participants) {
|
||||
val a = vm.state.agents.firstOrNull { it.id == id }
|
||||
val picked = id in vm.privatePair
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { vm.togglePrivatePick(id) }
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (picked) "✓" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (picked) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a?.name ?: "(已删除)", fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("开始私聊") { vm.startPickedPrivateChat() }
|
||||
if (vm.privatePair.isNotEmpty()) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
RowAction("清空选择") { vm.cancelPrivatePick() }
|
||||
}
|
||||
}
|
||||
if (vm.privateChatRunning.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("${vm.privateChatRunning} 正在聊……(要跑一会儿,别退出去)")
|
||||
}
|
||||
if (vm.privateChatResult.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(vm.privateChatResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 成员的小头像(有立绘用立绘,没有就用名字首字) */
|
||||
@Composable
|
||||
private fun AgentFace(agent: Agent?, size: Int) {
|
||||
val art = agent?.image?.portrait.orEmpty()
|
||||
Box(
|
||||
Modifier
|
||||
.size(size.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoCard()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(art, Modifier.size(size.dp), contentScale = ContentScale.Crop)
|
||||
} else {
|
||||
Text(
|
||||
(agent?.name ?: "?").take(1),
|
||||
fontSize = (size * 0.42).sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
139
android/app/src/main/java/com/doubao/lynxclone/ui/ImagePick.kt
Normal file
139
android/app/src/main/java/com/doubao/lynxclone/ui/ImagePick.kt
Normal file
@@ -0,0 +1,139 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.util.Base64
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* 选图 → 读成能上传的 base64。
|
||||
*
|
||||
* ## 为什么必须在这里压缩(这是真机上报回来的 bug)
|
||||
*
|
||||
* 用户选的是**手机相册里的照片**,现在动辄 30~55MB(一亿像素)。
|
||||
* 原样读进来会连撞三堵墙:
|
||||
*
|
||||
* ① `readBytes()` 把 55MB 全读进内存,`Base64` 再翻 4/3 倍 → 低端机直接 OOM;
|
||||
* ② 内核 `read_json_body()` 每条接口有自己的上限,图片这条路走的是小上限,
|
||||
* 38MB 的请求体一进去就被判「请求体过大」;
|
||||
* ③ 更糟的是那个异常被上层吞掉,最后报出来的是
|
||||
* **「不认识的外观槽位」** —— 一个和真实原因毫无关系的错误,
|
||||
* 用户只看到"设置不了",查代码的人也会往槽位名上去找。
|
||||
*
|
||||
* 所以压缩不是优化,是**这条链路能不能用**的前提:
|
||||
* 一张 4000×3000 的照片按最长边 1600 采样后大约是 200~400KB,
|
||||
* 比原来小两个数量级,上面三堵墙一次全绕过。
|
||||
*
|
||||
* ## 两种图**不能**压
|
||||
*
|
||||
* - **GIF**:缩放会丢动画(这个 App 明确支持动图,"动图会动"是写在界面上的);
|
||||
* - **SVG**:本来就是矢量,栅格化等于自毁。
|
||||
*
|
||||
* 这两种原样传,只在超过内核 20MB 上限时明确报错 —— 让用户换个文件,
|
||||
* 而不是静默失败。
|
||||
*/
|
||||
|
||||
/** 压缩后最长边不超过它。1600 在手机上看立绘/背景已经够清楚 */
|
||||
private const val MAX_EDGE = 1600
|
||||
|
||||
/** 压到这么大就收手。经验值:1600 边长的 JPEG 通常在 200~400KB */
|
||||
private const val TARGET_BYTES = 3 * 1024 * 1024
|
||||
|
||||
/** 内核 `_set_asset` 的硬上限,超过它一定传不上去,这里提前拦下来把话说清楚 */
|
||||
private const val MAX_BYTES = 20 * 1024 * 1024
|
||||
|
||||
/** 一张选好的图。[note] 是给用户看的一句话,说明这张图被怎么处理了 */
|
||||
data class PickedImage(val name: String, val base64: String, val note: String)
|
||||
|
||||
private fun mb(n: Int): String = String.format("%.1f", n / 1048576.0)
|
||||
|
||||
/**
|
||||
* 读一张图并压到能传的大小。
|
||||
*
|
||||
* 失败时抛 [IllegalStateException],**消息是可以直接显示给用户的中文** ——
|
||||
* 调用方 `catch` 之后原样 `showHint(e.message)` 就行,
|
||||
* 不要再包一层"上传失败",那样又把原因盖掉了。
|
||||
*/
|
||||
fun readImageForUpload(ctx: Context, uri: Uri): PickedImage {
|
||||
val resolver = ctx.contentResolver
|
||||
val rawName = (uri.lastPathSegment ?: "image").substringAfterLast('/').ifBlank { "image" }
|
||||
// ★ 名字靠不住:SAF 给的常常是 `image_1000018030` 这种没有扩展名的。
|
||||
// MIME 才是可信的(getType 对 content:// 会去查 provider)。
|
||||
val mime = (resolver.getType(uri) ?: "").lowercase()
|
||||
val isGif = mime.contains("gif")
|
||||
val isSvg = mime.contains("svg")
|
||||
|
||||
if (isGif || isSvg) {
|
||||
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw IllegalStateException("读不出这个文件")
|
||||
if (bytes.isEmpty()) throw IllegalStateException("这个文件是空的")
|
||||
if (bytes.size > MAX_BYTES) {
|
||||
throw IllegalStateException("这张图 ${mb(bytes.size)}MB,超过 20MB 上限了,换一张吧")
|
||||
}
|
||||
return PickedImage(
|
||||
name = rawName,
|
||||
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
|
||||
note = if (isGif) "动图原样上传(压缩会丢动画)" else "SVG 原样上传",
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 位图:先只问尺寸,不解码像素 ----
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
|
||||
throw IllegalStateException("这不是一张能识别的图片")
|
||||
}
|
||||
|
||||
// 压不下来就一轮轮降:边长 ×3/4、质量 ×4/5。四轮足够把任何照片压进 3MB
|
||||
var edge = MAX_EDGE
|
||||
var quality = 88
|
||||
var last = 0
|
||||
repeat(4) {
|
||||
val opts = BitmapFactory.Options().apply { inSampleSize = sampleFor(bounds, edge) }
|
||||
val bmp = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, opts) }
|
||||
?: throw IllegalStateException("读不出这张图")
|
||||
val hasAlpha = bmp.hasAlpha()
|
||||
val out = ByteArrayOutputStream()
|
||||
bmp.compress(if (hasAlpha) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG, quality, out)
|
||||
val w = bmp.width
|
||||
val h = bmp.height
|
||||
bmp.recycle()
|
||||
val bytes = out.toByteArray()
|
||||
last = bytes.size
|
||||
|
||||
if (bytes.size <= TARGET_BYTES) {
|
||||
return PickedImage(
|
||||
// ★ 扩展名要跟着真实格式走:压成 JPEG 却叫 .png,虽然解码器看魔数也能认,
|
||||
// 但导出的包里会留下一个名不副实的文件
|
||||
name = "${rawName.substringBeforeLast('.')}.${if (hasAlpha) "png" else "jpg"}",
|
||||
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
|
||||
note = "已压到 ${w}×${h}、${bytes.size / 1024}KB 再上传",
|
||||
)
|
||||
}
|
||||
edge = edge * 3 / 4
|
||||
quality = (quality * 4) / 5
|
||||
}
|
||||
throw IllegalStateException("这张图压到 ${mb(last)}MB 还是太大,换一张吧")
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样率(2 的幂,`BitmapFactory` 只认这个)。
|
||||
*
|
||||
* ★ 判据是**最长边**(写成 `||`),不是"宽高都超"。
|
||||
* 写成 `&&` 的话 4000×3000 一张只缩到 4000(短边 3000 没到阈值就停了),
|
||||
* JPEG 出来还有 2.2MB;按长边缩一档到 2000×1500 就只有它的三分之一。
|
||||
*
|
||||
* 取**解码后仍然 ≥ maxEdge** 的那一档 —— 宁可多留一点,
|
||||
* 后面还有缩小/降质的循环兜着;反过来取小了就再也补不回清晰度。
|
||||
*/
|
||||
private fun sampleFor(bounds: BitmapFactory.Options, maxEdge: Int): Int {
|
||||
var sample = 1
|
||||
while (bounds.outWidth / (sample * 2) >= maxEdge ||
|
||||
bounds.outHeight / (sample * 2) >= maxEdge
|
||||
) {
|
||||
sample *= 2
|
||||
}
|
||||
return sample
|
||||
}
|
||||
@@ -13,15 +13,24 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.ExperimentalTextApi
|
||||
import androidx.compose.ui.text.LinkAnnotation
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextLinkStyles
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.withLink
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
@@ -34,11 +43,28 @@ import androidx.compose.ui.unit.sp
|
||||
* 列表、粗体、行内代码、代码块、链接、引用。下面这些够用了。
|
||||
*
|
||||
* 支持:
|
||||
* 块级 ``` 代码块、# 标题、- / * / 1. 列表、> 引用、--- 分隔线、普通段落
|
||||
* 块级 ``` 代码块、# 标题、- / * / 1. 列表、- [ ] 任务列表、> 引用、--- 分隔线、
|
||||
* **| 表格 |**、普通段落
|
||||
* 行内 **粗体**、*斜体*、`代码`、~~删除线~~、[文字](链接)
|
||||
*
|
||||
* 不支持(有意为之):表格、嵌套列表、HTML、图片。聊天里几乎不出现,
|
||||
* 不支持(有意为之):嵌套列表、HTML、图片。聊天里几乎不出现,
|
||||
* 而且做全了就得处理各种边界,性价比很低。
|
||||
*
|
||||
* ## ★★ 表格是补上的,起因是用户截图:"表格没做"
|
||||
*
|
||||
* 之前这里明确写着"不支持表格",理由是"聊天里几乎不出现"—— **判断错了**。
|
||||
* 复盘为什么错得这么离谱:
|
||||
*
|
||||
* · 内核的 `speech.py` **早就**在按"表格会被渲染"处理朗读文本了
|
||||
* (`_MD_TABLE_SEP` / `_MD_PIPE` 把竖线和分隔行剥掉)。也就是说
|
||||
* **朗读那条路认为表格存在,渲染这条路不存在** —— 两端不一致,
|
||||
* 而我一直没发现,因为语音和界面是分开测的。
|
||||
* · 这个模型(用户的"病娇女友"智能体)非常爱用表格算账,
|
||||
* 截图里那张"一个月开销"表就是。宽表塞进聊天流的后果不是"少个表格",
|
||||
* 而是**满屏竖线 + 换行错位,整段没法读**。
|
||||
*
|
||||
* 所以现在按 GFM 表格实现。教训:**别用"几乎不出现"当不做某个 Markdown
|
||||
* 元素的理由** —— 去内核里看看朗读/复制那些旁路是不是已经假设它存在了。
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(
|
||||
@@ -99,17 +125,19 @@ fun MarkdownText(
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Heading -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
is MdBlock.Heading -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) {
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
@@ -139,6 +167,32 @@ fun MarkdownText(
|
||||
)
|
||||
}
|
||||
|
||||
// 任务列表:方框 + 文字。勾上的加删除线(进度一眼能看出来)
|
||||
is MdBlock.Task -> Row(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
if (block.checked) "☑" else "☐",
|
||||
fontSize = fontSize.sp,
|
||||
color = if (block.checked) Doubao.Blue else color.copy(alpha = 0.55f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = if (block.checked) color.copy(alpha = 0.6f) else color,
|
||||
textDecoration = if (block.checked) TextDecoration.LineThrough else null,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Table -> MarkdownTable(
|
||||
block = block,
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
)
|
||||
|
||||
is MdBlock.Divider -> Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -147,17 +201,166 @@ fun MarkdownText(
|
||||
.background(color.copy(alpha = 0.15f)),
|
||||
)
|
||||
|
||||
is MdBlock.Paragraph -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
is MdBlock.Paragraph -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 表格渲染 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 一张表。
|
||||
*
|
||||
* ## 为什么是"横向滚动 + 按内容算列宽",而不是等分
|
||||
*
|
||||
* 手机屏宽就 360dp 左右,而这类表格(模型最爱拿它算账)常见的形态是
|
||||
* **第一列很长、后面几列很短**:
|
||||
*
|
||||
* 吃(早150+午363+晚510+零食150) | 1173 | 大头还是晚饭
|
||||
*
|
||||
* 等分的话第一列必然折成三行、而"1173"那一列白白空着一大片。
|
||||
* 按内容量宽 + 整张表横向滚动,窄表看起来就是正常表格,
|
||||
* 宽表右滑能看全 —— 比挤成一坨强。
|
||||
*
|
||||
* ## 列宽怎么算
|
||||
*
|
||||
* 用 [rememberTextMeasurer] 把每一列的所有单元格量一遍取最大值,
|
||||
* 夹在 [MIN_COL_W] 和 [MAX_COL_W] 之间:
|
||||
* · 下限防止"一个月"这种短列被压成一条缝
|
||||
* · 上限防止某一格特别长(模型爱写长句)把整列撑到几屏宽
|
||||
*
|
||||
* ★ 量宽是 `remember(block)` 的:流式输出时每个字都在变,
|
||||
* 每帧重量一遍 20 多个单元格也还好(表格行数一般不超过 15)。
|
||||
*/
|
||||
@Composable
|
||||
private fun MarkdownTable(
|
||||
block: MdBlock.Table,
|
||||
color: Color,
|
||||
linkColor: Color,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
) {
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
val cols = block.header.size
|
||||
val cellStyle = remember(fontSize) { TextStyle(fontSize = (fontSize - 2).sp) }
|
||||
|
||||
val headBg = if (isDark()) Color(0xFF232A36) else Color(0xFFEDF1F7)
|
||||
val lineColor = color.copy(alpha = 0.14f)
|
||||
|
||||
// 量出来的是 px,除上 density 换成 dp(Compose 里布局一律用 dp)
|
||||
// ★ density / measurer 也进 key:系统字号一变(或旋转)就得重量,
|
||||
// 不然列宽还是照着旧字号的
|
||||
val widths: List<Dp> = remember(block, fontSize, density, measurer) {
|
||||
val pad = with(density) { (CELL_PAD_H * 2).toPx() }
|
||||
// 每列额外留一点余量:测量和真实排版总有一点差(字体 hinting、
|
||||
// 中英文混排的字距),差一点点就会让表头折成两行 —— 很难看
|
||||
val slack = with(density) { 2.dp.toPx() }
|
||||
val minW = with(density) { MIN_COL_W.toPx() }
|
||||
val maxW = with(density) { MAX_COL_W.toPx() }
|
||||
// ★★ 表头是 SemiBold,量它必须用**粗体**的 style。
|
||||
// 用常规字重量的话算出来的列宽偏窄,表头就会被挤到折行 ——
|
||||
// 实测"一个月"三个字被折成"一个"/"月",就是这么来的。
|
||||
val headStyle = cellStyle.copy(fontWeight = FontWeight.SemiBold)
|
||||
(0 until cols).map { c ->
|
||||
var w = 0
|
||||
for (r in -1 until block.rows.size) {
|
||||
val raw = if (r < 0) block.header[c] else block.rows[r][c]
|
||||
val plain = stripInlineMarks(raw)
|
||||
if (plain.isEmpty()) continue
|
||||
val style = if (r < 0) headStyle else cellStyle
|
||||
val measured = measurer.measure(AnnotatedString(plain), style).size.width
|
||||
if (measured > w) w = measured
|
||||
}
|
||||
(((w + pad + slack).coerceIn(minW, maxW)) / density.density).dp
|
||||
}
|
||||
}
|
||||
val totalWidth = widths.fold(0.dp) { acc, w -> acc + w }
|
||||
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) {
|
||||
Column(Modifier.clip(RoundedCornerShape(10.dp))) {
|
||||
// 表头:整行底色 + 加粗
|
||||
Row(Modifier.width(totalWidth).background(headBg)) {
|
||||
for (c in 0 until cols) {
|
||||
TableCell(
|
||||
text = block.header[c],
|
||||
width = widths[c],
|
||||
align = block.aligns[c],
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
bold = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(Modifier.width(totalWidth).height(1.dp).background(lineColor))
|
||||
for ((r, row) in block.rows.withIndex()) {
|
||||
if (r > 0) Box(Modifier.width(totalWidth).height(1.dp).background(lineColor))
|
||||
Row(Modifier.width(totalWidth)) {
|
||||
for (c in 0 until cols) {
|
||||
TableCell(
|
||||
text = row[c],
|
||||
width = widths[c],
|
||||
align = block.aligns[c],
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TableCell(
|
||||
text: String,
|
||||
width: Dp,
|
||||
align: TextAlign,
|
||||
color: Color,
|
||||
linkColor: Color,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
bold: Boolean = false,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.width(width)
|
||||
.padding(horizontal = CELL_PAD_H, vertical = 8.dp),
|
||||
) {
|
||||
Text(
|
||||
// 单元格里也走行内解析 —— `**合计**`、`` `code` ``、链接都要生效
|
||||
inline(text, linkColor),
|
||||
fontSize = (fontSize - 2).sp,
|
||||
lineHeight = (lineHeight - 4).coerceAtLeast(fontSize).sp,
|
||||
fontWeight = if (bold) FontWeight.SemiBold else null,
|
||||
textAlign = align,
|
||||
color = color,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 单元格左右内边距 */
|
||||
private val CELL_PAD_H = 10.dp
|
||||
|
||||
/** 列宽下限:短列别被压成一条缝 */
|
||||
private val MIN_COL_W = 56.dp
|
||||
|
||||
/** 列宽上限:一格特别长时让它折行,别把整列撑出几屏 */
|
||||
private val MAX_COL_W = 240.dp
|
||||
|
||||
/* ------------------------------ 块级解析 ------------------------------ */
|
||||
|
||||
internal sealed interface MdBlock {
|
||||
@@ -168,15 +371,146 @@ internal sealed interface MdBlock {
|
||||
data class Quote(val text: String) : MdBlock
|
||||
data class Code(val text: String, val lang: String = "") : MdBlock
|
||||
data object Divider : MdBlock
|
||||
|
||||
/** `- [ ] 待办` / `- [x] 做完了` */
|
||||
data class Task(val checked: Boolean, val text: String) : MdBlock
|
||||
|
||||
/**
|
||||
* 表格。
|
||||
*
|
||||
* [rows] 里每行的列数**已经补齐到 [header] 的长度**(缺的填空串)——
|
||||
* 模型偶尔会漏写某一行的某一列,渲染时按列取下标会越界。
|
||||
* 补在这里而不是渲染时,是因为对齐信息 [aligns] 也是按列来的,
|
||||
* 两处各补一次迟早会不一致。
|
||||
*/
|
||||
data class Table(
|
||||
val header: List<String>,
|
||||
val rows: List<List<String>>,
|
||||
val aligns: List<TextAlign>,
|
||||
) : MdBlock
|
||||
}
|
||||
|
||||
private val RE_HEADING = Regex("^(#{1,6})\\s+(.*)$")
|
||||
private val RE_BULLET = Regex("^\\s*[-*+]\\s+(.*)$")
|
||||
/** `- [ ] 待办` / `- [x] 已经做了`。**必须排在 [RE_BULLET] 前面判**,否则被当成普通项目符号 */
|
||||
private val RE_TASK = Regex("^\\s*[-*+]\\s+\\[([ xX])]\\s*(.*)$")
|
||||
private val RE_NUMBERED = Regex("^\\s*(\\d{1,3})[.)]\\s+(.*)$")
|
||||
private val RE_QUOTE = Regex("^\\s*>\\s?(.*)$")
|
||||
private val RE_FENCE = Regex("^\\s*```\\s*([A-Za-z0-9_+-]*)\\s*$")
|
||||
private val RE_DIVIDER = Regex("^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$")
|
||||
|
||||
/** 表格分隔行里的一格:`---`、`:--`、`--:`、`:--:` 都算 */
|
||||
private val RE_TABLE_SEP_CELL = Regex("^:?-{1,}:?$")
|
||||
|
||||
/* ------------------------------ 表格 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 这一行像不像表格行。
|
||||
*
|
||||
* 判据是**至少两个竖线**(`|` 的数量,转义的 `\|` 不算)。
|
||||
* 两端有没有竖线都收 —— 合法 GFM 两种写法都允许:
|
||||
*
|
||||
* | 项目 | 钱 | 项目 | 钱
|
||||
* |---|---| ---|---
|
||||
*
|
||||
* ★ 为什么门槛定在 2 而不是 1:正文里"或者 a | b"这种带一个竖线的句子
|
||||
* 不算少,定 1 会把它们吃掉。
|
||||
*/
|
||||
private fun looksLikeTableRow(line: String): Boolean =
|
||||
line.replace("\\|", "").count { it == '|' } >= 2
|
||||
|
||||
/**
|
||||
* 拆一行表格。
|
||||
*
|
||||
* ★ 转义的竖线(`\|`)要**先换成占位符再切**,否则 `a \| b | c` 会被切成三格。
|
||||
* 占位符用 `\u0001`(正文里不可能出现的控制字符),切完换回来。
|
||||
*/
|
||||
internal fun splitTableRow(line: String): List<String> {
|
||||
var s = line.trim()
|
||||
if (s.startsWith("|")) s = s.substring(1)
|
||||
// 末尾的竖线要去掉,但如果它是转义的(`… \|`)就不是分隔符
|
||||
if (s.endsWith("|") && !s.endsWith("\\|")) s = s.dropLast(1)
|
||||
s = s.replace("\\|", "\u0001")
|
||||
return s.split('|').map { it.replace("\u0001", "|").trim() }
|
||||
}
|
||||
|
||||
/** `|---|:--:|---:|` 这种分隔行 */
|
||||
internal fun isTableSeparator(line: String): Boolean {
|
||||
if (!line.contains('-')) return false
|
||||
val cells = splitTableRow(line)
|
||||
if (cells.isEmpty()) return false
|
||||
return cells.all { it.isNotEmpty() && RE_TABLE_SEP_CELL.matches(it) }
|
||||
}
|
||||
|
||||
/** 分隔行里的冒号决定这一列的对齐方式 */
|
||||
private fun alignOf(cell: String): TextAlign = when {
|
||||
cell.startsWith(":") && cell.endsWith(":") -> TextAlign.Center
|
||||
cell.endsWith(":") -> TextAlign.End
|
||||
else -> TextAlign.Start
|
||||
}
|
||||
|
||||
private class TableRead(val block: MdBlock.Table, val next: Int)
|
||||
|
||||
/**
|
||||
* 从 [start] 行开始读一张表,读不出来返回 null(那就按普通段落处理)。
|
||||
*
|
||||
* 两种情况都认:
|
||||
* ① 标准 GFM —— 表头行 + `|---|---|` 分隔行 + 数据行
|
||||
* ② 模型忘了写分隔行,但**连着两行列数一致**(兜底)
|
||||
*
|
||||
* ★ 数据行读到"不像表格行"就停。不设这个终点的话,表格后面紧跟的正文
|
||||
* 会被一路吃进来(模型写表格后面常常直接接一段总结)。
|
||||
*/
|
||||
private fun readTable(lines: List<String>, start: Int): TableRead? {
|
||||
val headLine = lines.getOrNull(start) ?: return null
|
||||
if (!looksLikeTableRow(headLine)) return null
|
||||
val head = splitTableRow(headLine)
|
||||
if (head.size < 2) return null
|
||||
|
||||
val second = lines.getOrNull(start + 1)
|
||||
val aligns: List<TextAlign>
|
||||
val bodyStart: Int
|
||||
if (second != null && isTableSeparator(second)) {
|
||||
val sep = splitTableRow(second)
|
||||
// 分隔行少写几格(模型手抖)时按表头列数补成左对齐,别让下标越界
|
||||
aligns = (0 until head.size).map { c -> alignOf(sep.getOrElse(c) { "---" }) }
|
||||
bodyStart = start + 2
|
||||
} else if (second != null && looksLikeTableRow(second) && splitTableRow(second).size == head.size) {
|
||||
aligns = List(head.size) { TextAlign.Start }
|
||||
bodyStart = start + 1
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
val rows = ArrayList<List<String>>()
|
||||
var i = bodyStart
|
||||
while (i < lines.size && looksLikeTableRow(lines[i])) {
|
||||
val cells = splitTableRow(lines[i])
|
||||
if (cells.size < 2) break
|
||||
// ★ 按表头列数补齐 / 截断:模型偶尔多写一列或少写一列,
|
||||
// 不补的话渲染时按下标取会越界,截断是为了不让一行的多余列把整表撑歪
|
||||
rows.add((0 until head.size).map { c -> cells.getOrElse(c) { "" } })
|
||||
i += 1
|
||||
}
|
||||
if (rows.isEmpty()) return null
|
||||
return TableRead(MdBlock.Table(head, rows, aligns), i)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把行内标记去掉,只留纯文字 —— 给"量列宽"用。
|
||||
*
|
||||
* ★ 量宽必须用剥过的文本:`| **合计** |` 里的 `**` 不显示,
|
||||
* 按原文量出来的列会白白宽出一截。
|
||||
*/
|
||||
internal fun stripInlineMarks(s: String): String =
|
||||
RE_STRIP_LINK.replace(s) { it.groupValues[1] }
|
||||
.replace("~~", "")
|
||||
.replace("**", "")
|
||||
.replace("`", "")
|
||||
.replace("*", "")
|
||||
|
||||
private val RE_STRIP_LINK = Regex("\\[([^\\]]*)]\\([^)]*\\)")
|
||||
|
||||
internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
val out = ArrayList<MdBlock>()
|
||||
val lines = src.replace("\r\n", "\n").split("\n")
|
||||
@@ -207,6 +541,17 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
continue
|
||||
}
|
||||
|
||||
// 表格:多行结构,得像代码块那样整块吃掉(不能按行在 when 里判)
|
||||
if (looksLikeTableRow(line)) {
|
||||
val table = readTable(lines, i)
|
||||
if (table != null) {
|
||||
flushPara()
|
||||
out.add(table.block)
|
||||
i = table.next
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
when {
|
||||
line.isBlank() -> flushPara()
|
||||
|
||||
@@ -234,6 +579,13 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
continue
|
||||
}
|
||||
|
||||
// ★ 任务列表必须排在普通项目符号前面 —— `- [x] 干完了` 也满足 RE_BULLET
|
||||
RE_TASK.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_TASK.find(line)!!
|
||||
out.add(MdBlock.Task(m.groupValues[1].isNotBlank(), m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
RE_BULLET.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Bullet(RE_BULLET.find(line)!!.groupValues[1].trim()))
|
||||
@@ -256,6 +608,118 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
return out
|
||||
}
|
||||
|
||||
/** 一条回复里提到的一个网页 */
|
||||
data class FoundUrl(
|
||||
/** 完整地址 */
|
||||
val url: String,
|
||||
/** 模型给链接写的文字(`[文字](url)` 里的那个),没有就是空串 */
|
||||
val label: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* 从 markdown 里抽出所有网页地址(去重、保序,带上链接文字)。
|
||||
*
|
||||
* ## ★★ 重写过一版:原来漏了 7/11 种写法
|
||||
*
|
||||
* 上一版是手写扫描器,**只认 `](` 紧挨着的 markdown 链接**。
|
||||
* 实测(`scripts/probe-extract-urls.py`)漏掉这些:
|
||||
*
|
||||
* · **裸 URL** —— `见 https://example.com`(**模型最常这么写**)
|
||||
* · `[文字] (地址)` —— 中英混排时中间常有空格
|
||||
* · `<https://example.com>` —— 尖括号包裹
|
||||
* · 中文标点紧跟着的 URL —— `见(https://…)。`
|
||||
* · 换行里的裸 URL
|
||||
* · `www.example.com`
|
||||
*
|
||||
* 后果不是"少显示一个链接",而是 **`extractUrls` 返回空 → 整个
|
||||
* 「打开网页」按钮都不显示**(用户报的"还是没有"就是这个)。
|
||||
*
|
||||
* 现在改成**正则扫全文**,两类都收:markdown 链接 + 裸 URL。
|
||||
*
|
||||
* ★ 只认 http/https。`[文档](docs/x.md)` 这种相对路径在手机上点了没意义,
|
||||
* 不算"网页"(剪掉尾巴上的中文标点和右括号,别把 `)。` 吞进地址里)。
|
||||
*/
|
||||
fun extractUrls(markdown: String): List<FoundUrl> {
|
||||
if (!markdown.contains("http://") && !markdown.contains("https://")) return emptyList()
|
||||
val out = LinkedHashSet<String>()
|
||||
val labels = HashMap<String, String>()
|
||||
|
||||
// ① markdown 链接:[文字](地址),允许中间有空格、文字里有方括号
|
||||
RE_MD_LINK.findAll(markdown).forEach { m ->
|
||||
val label = m.groupValues[1].trim().trim('[', ']')
|
||||
val url = cleanUrl(m.groupValues[2])
|
||||
if (url.isNotEmpty()) {
|
||||
if (label.isNotEmpty()) labels.putIfAbsent(url, label)
|
||||
out.add(url)
|
||||
}
|
||||
}
|
||||
|
||||
// ② 裸 URL / 尖括号包裹的 URL
|
||||
RE_BARE_URL.findAll(markdown).forEach { m ->
|
||||
val url = cleanUrl(m.value)
|
||||
if (url.isNotEmpty()) out.add(url)
|
||||
}
|
||||
|
||||
return out.map { FoundUrl(it, labels[it] ?: "") }
|
||||
}
|
||||
|
||||
/**
|
||||
* 剪掉 URL 尾巴上不属于地址的字符。
|
||||
*
|
||||
* ★ 必须做:中文回复里 URL 后面常紧跟 `)。`、`,`、`】`,
|
||||
* 不剪的话地址里会带上这些,打开必然 404。
|
||||
* 左右括号要配对判断(`.../a_(b)` 这种地址本身带括号,不能一刀切)。
|
||||
*/
|
||||
private fun cleanUrl(raw: String): String {
|
||||
var s = raw.trim().trim('<', '>', '"', '\'', '`')
|
||||
// 尾部的中文标点/空白一律剪掉
|
||||
s = s.trimEnd('。', ',', '、', ';', ':', '!', '?', ')', '】', '》', '」', '』', '…', '.', ',', ';', ':', '!', '?')
|
||||
// 去掉不配对的右括号
|
||||
while (s.endsWith(")") && s.count { it == ')' } > s.count { it == '(' }) {
|
||||
s = s.dropLast(1)
|
||||
}
|
||||
while (s.endsWith("]") && s.count { it == ']' } > s.count { it == '[' }) {
|
||||
s = s.dropLast(1)
|
||||
}
|
||||
if (!s.startsWith("http://") && !s.startsWith("https://")) return ""
|
||||
return s
|
||||
}
|
||||
|
||||
/**
|
||||
* markdown 链接 `[文字](地址)`。
|
||||
*
|
||||
* ★★ 地址部分用 **`(?:[^\s()]|\([^\s()]*\))+`** 而不是 `[^\s)]+`。
|
||||
*
|
||||
* 起因是一条维基百科地址:`https://en.wikipedia.org/wiki/A_(b)`
|
||||
*
|
||||
* · 用 `[^\s)]+` 的话,它在 `A_(b` 处被第一个 `)` 截断 ——
|
||||
* 然后外层那个 `\)` 匹配的是**地址里那个右括号**,
|
||||
* 于是算出来的地址是 `https://en.wikipedia.org/wiki/A_(b`(缺一个括号、点开 404)
|
||||
* · 而且裸 URL 规则会再匹配一次,得到另一个截断版本 →
|
||||
* **同一个链接在列表里出现两次,两个都不对**
|
||||
*
|
||||
* "平衡括号"这个写法让右括号只能以完整 `(…)` 的形式出现在地址里,
|
||||
* 所以维基那种地址能整个吃到,而 markdown 的收尾括号仍然能正确识别。
|
||||
*
|
||||
* ★ 文字部分用 `[^\]\n]*` 而不是 `.*?` —— 后者在长回复里可能跨行吞掉一大段。
|
||||
*/
|
||||
private val RE_MD_LINK =
|
||||
Regex("""\[([^\]\n]{1,200})]\s*\(\s*(https?://(?:[^\s()]|\([^\s()]*\))+)\s*\)""")
|
||||
|
||||
/**
|
||||
* 裸 URL(含尖括号包裹)。
|
||||
*
|
||||
* ★★ 同样用"平衡括号"写法。两种错法都踩过:
|
||||
*
|
||||
* · 允许右括号(`[^\s]+`)→ `[x](https://a.com)` 会被**再匹配一次**,
|
||||
* 同一条链接算出两个不同地址(一个还带多余的右括号)
|
||||
* · 完全禁止括号(`[^\s()]+`)→ `.../wiki/A_(b)` 被截断成 `.../wiki/A_`
|
||||
*
|
||||
* 到空白或中文标点为止(中文回复里 URL 后面常紧跟 `)。`、`,`)。
|
||||
*/
|
||||
private val RE_BARE_URL =
|
||||
Regex("""<?https?://(?:[^\s<>()\[\]{}()【】「」『』,。;:!?、]|\([^\s()]*\))+>?""")
|
||||
|
||||
/* ------------------------------ 行内解析 ------------------------------ */
|
||||
|
||||
/**
|
||||
@@ -264,8 +728,19 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
* 用一个统一的扫描器而不是一串 replace:
|
||||
* 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后,
|
||||
* 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。
|
||||
*
|
||||
* ★ 这是个 `@Composable`:链接要用 `withLink(...)` 挂点击,
|
||||
* 而那个 API 是 composable 的(它内部要拿 `LocalTextLinkScope`)。
|
||||
*
|
||||
* ★ 还要 `@OptIn(ExperimentalTextApi::class)` —— `withLink` 标了实验 API。
|
||||
* 不 opt-in 的话报的是 `Unresolved reference 'withLink'`(不是"需要 opt-in"),
|
||||
* 很容易误判成"这个版本没有这个 API"。我是把 aar 拆开 javap 看了注解才确认的。
|
||||
*/
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnnotatedString {
|
||||
@OptIn(ExperimentalTextApi::class)
|
||||
@Composable
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString {
|
||||
val ctx = LocalContext.current
|
||||
return buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
when {
|
||||
@@ -325,8 +800,40 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnno
|
||||
val end = if (open > 0) text.indexOf(')', open) else -1
|
||||
if (close > i && open > 0 && end > open) {
|
||||
val label = text.substring(i + 1, close)
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
val url = text.substring(open + 1, end).trim()
|
||||
/**
|
||||
* ★★ 给链接**真正绑上点击**。
|
||||
*
|
||||
* 以前这里只有颜色和下划线,**没有 clickable** ——
|
||||
* 看着像能点、点了完全没反应。用户会以为"链接坏了"。
|
||||
* (这是用户问"网页在哪点开"时才查出来的:我一直在讲
|
||||
* AI 弹的那个界面,而最容易想到的"点链接"一直是坏的。)
|
||||
*
|
||||
* ★ 用 `withLink(LinkAnnotation.Url(...))`:这是 Compose 1.7
|
||||
* 起的方式,和 `Text()` 直接配合(不需要 ClickableText),
|
||||
* 而且**不需要在外部套 pointerInput 去算点击落在哪个字符上**。
|
||||
* 那个老办法要自己遍历 annotation 范围,容易算错。
|
||||
*/
|
||||
if (url.isNotEmpty()) {
|
||||
withLink(
|
||||
LinkAnnotation.Url(
|
||||
url = url,
|
||||
styles = TextLinkStyles(
|
||||
style = SpanStyle(
|
||||
color = linkColor,
|
||||
textDecoration = TextDecoration.Underline,
|
||||
),
|
||||
),
|
||||
linkInteractionListener = { link ->
|
||||
val target = (link as? LinkAnnotation.Url)?.url ?: url
|
||||
openInBrowser(ctx, target)
|
||||
},
|
||||
),
|
||||
) { append(label) }
|
||||
} else {
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
}
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
@@ -339,4 +846,7 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnno
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
243
android/app/src/main/java/com/doubao/lynxclone/ui/MeetNodeKit.kt
Normal file
243
android/app/src/main/java/com/doubao/lynxclone/ui/MeetNodeKit.kt
Normal file
@@ -0,0 +1,243 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import com.doubao.lynxclone.data.CustomNodeDef
|
||||
import com.doubao.lynxclone.data.MeetingNode
|
||||
import com.doubao.nodekit.CastKinds
|
||||
import com.doubao.nodekit.CustomNodePins
|
||||
import com.doubao.nodekit.JudgeKinds
|
||||
import com.doubao.nodekit.NodeCatalog
|
||||
import com.doubao.nodekit.NodeGeometry
|
||||
import com.doubao.nodekit.NodeSpecs
|
||||
import com.doubao.nodekit.NodeStyles
|
||||
import com.doubao.nodekit.NodeView
|
||||
import com.doubao.nodekit.Ops
|
||||
import com.doubao.nodekit.PinDecl
|
||||
import com.doubao.nodekit.PinKind
|
||||
import com.doubao.nodekit.PinSpec
|
||||
|
||||
/*
|
||||
* 会议节点库(`:nodekit`)和 App 之间的**唯一一层胶水**。
|
||||
*
|
||||
* ## 这层为什么必须存在,而且必须**薄**
|
||||
*
|
||||
* 库不认 App 的 `MeetingNode` / `CustomNodeDef`(那是刻意的,见 nodekit/Pins.kt 的
|
||||
* NodeView 注释)。所以中间要有人做转换。
|
||||
*
|
||||
* 危险的地方在于:这层一旦开始"顺手做点事"(补个默认值、改个判断、加个特例),
|
||||
* 它就变成了**第二份定义** —— 而这次的整个目的就是把散在 6 个地方的节点定义
|
||||
* 收成一份。所以这里只有三件事:
|
||||
*
|
||||
* 1. `MeetingNode` → [NodeView](纯字段搬运,**一个判断都不许有**)
|
||||
* 2. 库的 `Int` 颜色 → Compose 的 `Color`
|
||||
* 3. 库的扁平 API → App 原来的函数名(这样 `MeetingsScreen.kt` 里几百个
|
||||
* 调用点一行都不用改 —— 迁移的风险全压在这一层,而它能一眼看完全文)
|
||||
*
|
||||
* ★ 反过来也成立:**这里的每个 `fun` 都必须能在库里找到对应物**。
|
||||
* `scripts/verify-nodekit.py` 会检查这一点(数一遍适配层的函数是不是都只是转发)。
|
||||
*/
|
||||
|
||||
/* ------------------------------ 1. 类型转换 ------------------------------ */
|
||||
|
||||
/** App 的自定义节点定义 → 库只要的"引脚部分" */
|
||||
fun CustomNodeDef.toPins(): CustomNodePins = CustomNodePins(
|
||||
inputs = inputs.map { PinDecl(it.name, it.type) },
|
||||
outputs = outputs.map { PinDecl(it.name, it.type) },
|
||||
)
|
||||
|
||||
/**
|
||||
* App 的节点 → 库认识的节点视图。
|
||||
*
|
||||
* ★ [varTypes] 是必须的:写变量的入口类型、读变量的出口类型都按变量登记表查,
|
||||
* 写死 `str` 的话 num 变量的线接不到运算节点上(这个 bug 真出现过)。
|
||||
*/
|
||||
fun MeetingNode.nodeView(
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): NodeView = NodeView(
|
||||
type = type,
|
||||
op = op,
|
||||
varName = varName,
|
||||
valueType = valueType,
|
||||
castTo = castTo,
|
||||
customKey = customKey,
|
||||
custom = custom.firstOrNull { it.key == customKey }?.toPins(),
|
||||
varTypes = varTypes,
|
||||
)
|
||||
|
||||
/* ------------------------------ 2. 引脚 ------------------------------ */
|
||||
|
||||
/** 输入引脚。实现只有一句:转成 NodeView 交给库 */
|
||||
fun inputPins(
|
||||
node: MeetingNode,
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): List<PinSpec> = NodeSpecs.inputPins(node.nodeView(custom, varTypes))
|
||||
|
||||
/** 输出引脚。同上 */
|
||||
fun outputPins(
|
||||
node: MeetingNode,
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): List<PinSpec> = NodeSpecs.outputPins(node.nodeView(custom, varTypes))
|
||||
|
||||
/* ------------------------------ 3. 几何 ------------------------------ */
|
||||
|
||||
/** 卡片宽度(画布上所有布局都按它算) */
|
||||
internal const val NODE_W = NodeGeometry.WIDTH
|
||||
|
||||
/** 顶部彩色标题栏的高度 */
|
||||
internal const val HEADER_H = NodeGeometry.HEADER_H
|
||||
|
||||
/** 一行引脚占的高度 */
|
||||
internal const val PIN_ROW_H = NodeGeometry.PIN_ROW_H
|
||||
|
||||
/** 引脚下面的内容区 */
|
||||
internal const val BODY_H = NodeGeometry.BODY_H
|
||||
|
||||
/** 引脚画多大 / 命中范围多大 */
|
||||
internal const val PORT_R = NodeGeometry.PORT_R
|
||||
internal const val PORT_HIT = NodeGeometry.PORT_HIT
|
||||
|
||||
/** 画布右下留的空白 */
|
||||
internal const val CANVAS_MARGIN = NodeGeometry.MARGIN
|
||||
|
||||
/** 节点高矮跟着引脚数走 */
|
||||
fun nodeHeight(
|
||||
node: MeetingNode,
|
||||
customDefs: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): Float = NodeGeometry.height(node.nodeView(customDefs, varTypes))
|
||||
|
||||
/** 第 index 个引脚的坐标 */
|
||||
fun pinPos(node: MeetingNode, index: Int, isOutput: Boolean): Offset =
|
||||
NodeGeometry.pinPos(node.x, node.y, index, isOutput)
|
||||
|
||||
/** 按 (种类, 分支) 找输出引脚的序号 */
|
||||
fun outPinIndex(node: MeetingNode, kind: String, branch: String): Int =
|
||||
NodeGeometry.outPinIndex(node.nodeView(), kind, branch)
|
||||
|
||||
/** 输入端口的位置 */
|
||||
fun portIn(
|
||||
node: MeetingNode,
|
||||
kind: String,
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
pinKey: String = "",
|
||||
): Offset = NodeGeometry.portIn(node.nodeView(varTypes = varTypes), node.x, node.y, kind, pinKey)
|
||||
|
||||
/** 输出端口的位置 */
|
||||
fun portOut(
|
||||
node: MeetingNode,
|
||||
kind: String,
|
||||
branch: String,
|
||||
pinKey: String = "",
|
||||
): Offset = NodeGeometry.portOut(node.nodeView(), node.x, node.y, kind, branch, pinKey)
|
||||
|
||||
/** 画布要多大 */
|
||||
fun canvasSize(nodes: List<MeetingNode>): Pair<Float, Float> =
|
||||
NodeGeometry.canvasSize(nodes.map { Triple(it.x, it.y, nodeHeight(it)) })
|
||||
|
||||
/** 平移量的夹取 */
|
||||
fun clampPan(
|
||||
x: Float, y: Float,
|
||||
viewW: Float, viewH: Float,
|
||||
contentW: Float, contentH: Float,
|
||||
): Pair<Float, Float> = NodeGeometry.clampPan(x, y, viewW, viewH, contentW, contentH)
|
||||
|
||||
/* ------------------------------ 4. 配色 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 节点标题栏颜色。
|
||||
*
|
||||
* ★ 这里没有 `when` —— 颜色在库里跟着节点类型走(`NodeCatalog`)。
|
||||
* 以前这个函数是 31 行的 when,加一种节点忘改它就少一个颜色,
|
||||
* 而且**不报错**(默默落到"智能体蓝")。
|
||||
*/
|
||||
fun nodeColor(type: String): Color = Color(NodeCatalog.color(type))
|
||||
|
||||
/** 数据引脚按类型上色 */
|
||||
fun pinColor(kind: String): Color = Color(NodeStyles.pinColor(kind))
|
||||
|
||||
/** 按**引脚**算颜色:收全部类型的引脚是紫的 */
|
||||
fun pinColorOf(pin: PinSpec): Color = Color(NodeStyles.pinColorOf(pin))
|
||||
|
||||
/**
|
||||
* 引脚的边框色。
|
||||
*
|
||||
* ★ 库给的是不透明色,这里统一加 0.85 的透明度 —— 描边比填充淡一点才好看。
|
||||
* 这个"淡一点"是**渲染方的事**,所以留在这一层(库不该知道我们要多淡)。
|
||||
*/
|
||||
fun pinBorder(kind: String): Color = pinColor(kind).copy(alpha = 0.85f)
|
||||
|
||||
/** 执行引脚的描边色(白引脚描在浅色背景上,不描边看不见) */
|
||||
val EXEC_BORDER: Color = Color(NodeStyles.EXEC_BORDER)
|
||||
|
||||
/** 连线的颜色(数据线按类型、exec 线按分支真假) */
|
||||
fun wireColor(pin: PinSpec): Color = Color(NodeStyles.wireColor(pin))
|
||||
|
||||
/**
|
||||
* 一条线的类型说明(鼠标/长按提示里用)。
|
||||
*
|
||||
* ★ 这**不是** `PinKind.label`:那是"文本/数字/真假"(说数据类型),
|
||||
* 这是"str 数据线/执行线"(说线的种类)。用户看到的是后者。
|
||||
*/
|
||||
fun kindLabel(kind: String): String = when (kind) {
|
||||
PinKind.EXEC -> "执行线"
|
||||
PinKind.BOOL -> "bool 数据线"
|
||||
PinKind.NUM -> "num 数据线"
|
||||
PinKind.LEGACY_DATA -> "str 数据线"
|
||||
else -> "str 数据线"
|
||||
}
|
||||
|
||||
/** 变量类型的中文名 */
|
||||
fun typeLabel(type: String): String = PinKind.label(type)
|
||||
|
||||
/**
|
||||
* 变量 / 值节点的类型选项。
|
||||
*
|
||||
* ★ 这四项以前在界面里**逐字重复了三处**(变量管理、值节点、转换节点),
|
||||
* 加一种类型必然漏改一处 —— 而漏改的表现是"某个界面选不到新类型",
|
||||
* 不报错、也没人会发现。现在只有这一份。
|
||||
*/
|
||||
val VARIABLE_TYPE_OPTIONS: List<Pair<String, String>> =
|
||||
PinKind.DATA.map { it to PinKind.labelWithKey(it) }
|
||||
|
||||
/**
|
||||
* 转换节点的目标类型选项。
|
||||
*
|
||||
* ★ 单独一份而不是复用 [VARIABLE_TYPE_OPTIONS]:这两个列表**现在**内容一样,
|
||||
* 但意思不同("变量能是什么类型" vs "能转成什么类型")——
|
||||
* 将来变量加了新类型,不代表转换也支持。混用一次就分不开了。
|
||||
*/
|
||||
val CAST_TYPE_OPTIONS: List<Pair<String, String>> =
|
||||
CastKinds.ALL.map { it to PinKind.labelWithKey(it) }
|
||||
|
||||
/**
|
||||
* 判断条件的可选项。
|
||||
*
|
||||
* ★ 正常情况下用内核给的(`meetingMeta.judgeKinds`,那是权威);这里只是
|
||||
* **meta 还没加载到时的兜底** —— 以前 meta 为空时那个选择器是空的,
|
||||
* 用户点开一片空白,会以为界面坏了。
|
||||
*/
|
||||
val JUDGE_KIND_OPTIONS: List<Pair<String, String>> = JudgeKinds.ALL
|
||||
|
||||
/* ------------------------------ 5. 算子 ------------------------------ */
|
||||
|
||||
/** `(键, 显示名)` 列表 —— 配置面板里的下拉项 */
|
||||
val OPS_UI: List<Pair<String, String>> = Ops.ALL.map { it.key to it.label }
|
||||
|
||||
/** 算子的显示名 */
|
||||
fun opLabel(key: String): String = Ops.label(key)
|
||||
|
||||
/**
|
||||
* 算子的 `(入口类型, 出口类型, 要几个输入)`。
|
||||
*
|
||||
* ★ 保留这个三元组而不是直接换成 `Ops.of()`:调用点有 4 处(引脚表 + 配置面板),
|
||||
* 换签名要动它们全部,而它们本来就是按三元组用的。
|
||||
* `opSpec` 自己只有三行,且**不含任何规则**(规则在 `Ops.ALL` 那张表里)。
|
||||
*/
|
||||
fun opSpec(key: String): Triple<String, String, Int> {
|
||||
val op = Ops.of(key)
|
||||
return Triple(op.inType, op.outType, op.arity)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,666 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.MemoryItem
|
||||
import com.doubao.lynxclone.data.PRESETS
|
||||
import com.doubao.lynxclone.data.PRESET_DEAD
|
||||
import com.doubao.lynxclone.data.MemorySpace
|
||||
|
||||
/*
|
||||
* 记忆管理(需求 3.2 / 3.5)。
|
||||
*
|
||||
* ## 这个界面存在的理由
|
||||
*
|
||||
* 需求里记忆是"**混合制**":AI 通过工具自主读写,**用户手动编辑兜底**。
|
||||
* 没有这个界面,"兜底"就是空话 —— AI 记错了东西,用户只能干看着
|
||||
* (而他会记错:模型把"他喜欢猫"记成"他讨厌猫"这种事很常见)。
|
||||
*
|
||||
* 顺带把三样东西一起放进来,因为它们都是"这个智能体的内在状态":
|
||||
* · 情绪(需求 3.5:用户可手动编辑)
|
||||
* · AI 提的"该整理记忆了"建议(需求 3.2:仅提示,用户确认才执行)
|
||||
* · 导入 / 导出(需求 3.4)
|
||||
*
|
||||
* ## 共享记忆要**显式说明**
|
||||
*
|
||||
* 绑了世界观的智能体,记忆是和同世界观其他智能体**共用**的。
|
||||
* 界面上不写清楚的话,用户会以为"我给 A 记的东西怎么 B 也知道" ——
|
||||
* 所以顶部有一条明显的提示。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun MemoryScreen(
|
||||
space: MemorySpace?,
|
||||
agentName: String,
|
||||
/** 正在看谁的记忆 —— 用来判断"这条是不是别人写的" */
|
||||
agentId: String,
|
||||
/** 所有智能体的 id → 名字(共享记忆里显示"由某某写入") */
|
||||
agentNames: Map<String, String>,
|
||||
/**
|
||||
* **世界观视角**("这个世界里大家共同记得什么")。
|
||||
*
|
||||
* ★ 只读:增删改仍从智能体那边做。世界观视角没有"我",
|
||||
* 而共享空间的写入限权是按 author 判的(需求 3.6)——
|
||||
* 硬做一个权限含义不明的界面,只会让人误操作。
|
||||
* 情绪也藏起来:情绪是**智能体私有**的,不属于这个空间。
|
||||
*/
|
||||
worldMode: Boolean = false,
|
||||
loading: Boolean,
|
||||
hint: String,
|
||||
/** 保存情绪:preset(五档)+ text(自由一句) */
|
||||
onSetEmotion: (String, String) -> Unit,
|
||||
onAdd: (String, String) -> Unit,
|
||||
onUpdate: (String, String?, String?) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
onTogglePin: (String, Boolean) -> Unit,
|
||||
onSummarize: () -> Unit,
|
||||
onExport: () -> Unit,
|
||||
/** 调注入窗口(条数,0 = 不限) */
|
||||
onSetWindow: (Int) -> Unit,
|
||||
/** 由调用方弹文件选择器;选完之后的"合并/覆盖"选择也在那边做 */
|
||||
onImportClick: () -> Unit,
|
||||
/** 去看绑定世界观**之前**攒的私有记忆 */
|
||||
onOpenOwn: () -> Unit,
|
||||
/** 从旧空间回到当前生效的空间 */
|
||||
onBackToActive: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var editing by remember { mutableStateOf<MemoryItem?>(null) }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
/** 情绪的双字段草稿(v1.2)。preset 是五档之一、text 是自由文本 */
|
||||
var emotionPreset by remember(space?.emotion) { mutableStateOf(space?.emotion?.preset ?: "平常") }
|
||||
var emotionText by remember(space?.emotion) { mutableStateOf(space?.emotion?.text ?: "") }
|
||||
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
||||
var confirmSummarize by remember { mutableStateOf(false) }
|
||||
/** 调注入窗口(输入条数,0 = 不限) */
|
||||
var editWindow by remember { mutableStateOf(false) }
|
||||
var windowDraft by remember(space?.window) { mutableStateOf((space?.window ?: 0).toString()) }
|
||||
val readingOwn = space?.own == true
|
||||
|
||||
FullScreen(
|
||||
title = "记忆",
|
||||
subtitle = buildString {
|
||||
append(agentName.ifBlank { "智能体" })
|
||||
append(" · ")
|
||||
when {
|
||||
worldMode -> append("世界观共享记忆")
|
||||
readingOwn -> append("绑定前的私有记忆")
|
||||
space == null -> append("读取中")
|
||||
space.shared -> append("世界观共享记忆")
|
||||
else -> append("私有记忆")
|
||||
}
|
||||
space?.let { append(" ${it.memories.size} 条") }
|
||||
if (loading) append(" · 处理中…")
|
||||
},
|
||||
onBack = { if (readingOwn) onBackToActive() else onBack() },
|
||||
actions = {
|
||||
// 世界观视角是纯只读(导入/导出都以"某个智能体的记忆"为单位,
|
||||
// 而这里没有"我")—— 不给按钮,而不是给一个点了没反应的按钮
|
||||
if (!worldMode && !readingOwn) TopTextAction("导入", onClick = onImportClick)
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
/* ---- 空间标识(复查报告 4.1)----
|
||||
*
|
||||
* ★ 这是这个界面最重要的一段字。
|
||||
* 绑定世界观之后读写空间会从私有换成共享,列表看起来"变空了" ——
|
||||
* 记忆一条没丢,但不说明的话用户必然判定"绑定把我的记忆清了"。
|
||||
*/
|
||||
if (readingOwn) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x1AF29900))
|
||||
.clickable { onBackToActive() }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这是绑定世界观之前攒的私有记忆,现在只供查看。" +
|
||||
"AI 当前读的是共享空间那份 —— 点这里回到当前空间。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
} else if ((space?.ownCount ?: 0) > 0) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onOpenOwn() }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"绑定世界观之前你给这个智能体攒过 ${space?.ownCount} 条私有记忆,还留着。" +
|
||||
"AI 现在读的是上面那个共享空间 —— 点这里去看那些 ›",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 注入窗口(一遍看不出来"哪些真的进去了",所以直接写清)----
|
||||
if (!readingOwn && !worldMode && space != null) {
|
||||
val total = space.memories.size
|
||||
val win = space.window
|
||||
val injected = space.injected
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { windowDraft = win.toString(); editWindow = true }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
// ★ "列表里有 300 条"和"带进去 50 条"是完全不同的两件事。
|
||||
// 不写清楚的话,用户会以为记忆全都在提示词里。
|
||||
"这一轮会带进去 $injected / $total 条",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
buildString {
|
||||
append("窗口:")
|
||||
append(if (win <= 0) "不限(全部都带)" else "最近 $win 条")
|
||||
append("。")
|
||||
// ★ "能置顶几条"必须在界面上说清:不说的话用户会默认
|
||||
// "只能有一条"(很自然的假设),而实际上标几条都行,
|
||||
// 而且它们**永远**带进去、不受窗口限制。
|
||||
append(
|
||||
if (space.pinnedCount > 0) "已置顶 ${space.pinnedCount} 条"
|
||||
else "可以置顶任意多条"
|
||||
)
|
||||
append(",置顶的永远带、不受窗口限制")
|
||||
if (injected < total) {
|
||||
append(";没带进去的没丢,AI 用 memory_search 还能搜到")
|
||||
}
|
||||
append("。 点这里调 ›")
|
||||
},
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 共享记忆提示(不写清楚用户会以为记忆串了)----
|
||||
if (worldMode) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x14F29900))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这是这个世界观里所有人共同记得的 —— 绑定了它的智能体共用这一份。\n" +
|
||||
"这里只供查看(改和删请从各自的智能体进去,那边才知道「我」是谁);" +
|
||||
"每条都标了是谁写的。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
} else if (space?.shared == true) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x14F29900))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这个智能体绑定了世界观,记忆是和同世界观的其他智能体共用的。\n" +
|
||||
"它能改自己写的条目;改别人的(或删)需要你在这里手动操作。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- AI 的建议(需求 3.2:仅提示,用户确认才执行)----
|
||||
if (!space?.suggestion.isNullOrBlank()) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.08f))
|
||||
.padding(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("AI 觉得记忆该整理一下了", fontSize = 12.sp, color = Doubao.Blue)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(space?.suggestion ?: "", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Text(
|
||||
"整理",
|
||||
fontSize = 13.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Doubao.Blue)
|
||||
.clickable(enabled = !loading) { onSummarize() }
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (hint.isNotBlank()) {
|
||||
Text(
|
||||
hint,
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 情绪(世界观视角没有"自己的情绪",隐藏)----
|
||||
if (!worldMode) {
|
||||
SectionLabel("情绪")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"preset 决定系统行为(立绘换哪张、能不能对话、同伴看到什么脸色);" +
|
||||
"下面那句话只是扮演质感。AI 自己能改,你也可以在这里改。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★ 五档选择器,顺序就是需求里的顺序(喜 怒 哀 平常 死亡)。
|
||||
// 「死亡」单独标红 —— 它是**唯一有系统后果**的档位。
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
for (p in PRESETS) {
|
||||
val on = p == emotionPreset
|
||||
val danger = p == PRESET_DEAD
|
||||
Text(
|
||||
p,
|
||||
fontSize = 13.sp,
|
||||
color = when {
|
||||
on -> Color.White
|
||||
danger -> Color(0xFFB3261E)
|
||||
else -> doubaoText()
|
||||
},
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(
|
||||
when {
|
||||
on && danger -> Color(0xFFB3261E)
|
||||
on -> Doubao.Blue
|
||||
else -> doubaoCard()
|
||||
},
|
||||
)
|
||||
.clickable { emotionPreset = p }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
// 死亡是唯一需要额外解释的档位:它会让这个智能体**不能对话**。
|
||||
// 不说清楚的话,用户点了「死亡」然后发现消息发不出去,会以为坏了。
|
||||
if (emotionPreset == PRESET_DEAD) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"「死亡」状态下这个智能体不能对话(输入条会禁用)。" +
|
||||
"把它改回其他档就是复活 —— 这是你的权力,AI 自己不能从死亡改活。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = emotionText,
|
||||
onValueChange = { emotionText = it },
|
||||
placeholder = { Text("他此刻在想什么(自由一句,比如:强作镇定,手心全是汗)", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
|
||||
TextButton(
|
||||
onClick = { onSetEmotion(emotionPreset, emotionText.trim()) },
|
||||
enabled = emotionPreset != (space?.emotion?.preset ?: "平常") ||
|
||||
emotionText.trim() != (space?.emotion?.text ?: ""),
|
||||
) { Text("保存情绪", fontSize = 13.sp) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 操作条 ----
|
||||
SectionLabel("记忆(按时间排,最新的在下面)")
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (!readingOwn && !worldMode) SmallAction("+ 加一条") { adding = true }
|
||||
if (!readingOwn && !worldMode) {
|
||||
SmallAction(if (loading) "整理中…" else "AI 整理") {
|
||||
// ★ 先确认再调(复查报告 4.2.1):整理是**一次真的 LLM 调用**、
|
||||
// 会改掉现有记忆,而且用户可能刚标好了「必须保留」——
|
||||
// 让他有机会在动手前把那几条标上
|
||||
if (!loading) confirmSummarize = true
|
||||
}
|
||||
}
|
||||
SmallAction("导出文件", onClick = onExport)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
// ---- 列表 ----
|
||||
val items = space?.memories ?: emptyList()
|
||||
if (items.isEmpty()) {
|
||||
Text(
|
||||
if (loading) "读取中…" else "还没有记忆。AI 觉得有值得记住的事时会自己记下来。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 16.dp),
|
||||
)
|
||||
}
|
||||
for (m in items) {
|
||||
// ★ 共享空间里「别人写的」条目要标出来、并且**禁掉编辑和删除**
|
||||
// (复查报告 4.2.2)。不给禁用态的话,用户点了删除被后端拒绝,
|
||||
// 他会当成 bug —— 而后端拦得对(需求 3.6:只能改自己写的)。
|
||||
val author = m.authorAgent.trim()
|
||||
val mine = author.isEmpty() || author == agentId
|
||||
val authorName = if (author.isEmpty()) "" else (agentNames[author] ?: "另一个智能体")
|
||||
MemoryRow(
|
||||
item = m,
|
||||
readOnly = readingOwn,
|
||||
// 别人写的 = 界面上不给改删的入口(不是"点了才报错")
|
||||
foreign = !mine,
|
||||
authorName = if (mine) "" else authorName,
|
||||
onEdit = { editing = m },
|
||||
onDelete = { onDelete(m.id) },
|
||||
onTogglePin = { onTogglePin(m.id, !m.pinned) },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(28.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 注入窗口的调整(A 方案)----
|
||||
if (editWindow) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { editWindow = false },
|
||||
title = { Text("注入窗口", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"每轮最多把多少条记忆放进提示词。\n\n" +
|
||||
"置顶的永远带,不受这个数限制 —— 而且可以置顶任意多条" +
|
||||
"(标几条都行,它们一定都在)。\n" +
|
||||
"其余按时间取最近的。没带进去的不会丢," +
|
||||
"AI 用 memory_search 还能搜到。\n\n" +
|
||||
"填 0 = 不限(全量注入)。记忆攒到几百条时提示词会很贵," +
|
||||
"而且早期的会挤掉最近的对话上下文。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = windowDraft,
|
||||
onValueChange = { s -> windowDraft = s.filter { it.isDigit() }.take(5) },
|
||||
label = { Text("条数(0 = 不限)", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
editWindow = false
|
||||
onSetWindow(windowDraft.toIntOrNull() ?: 0)
|
||||
}) { Text("保存") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { editWindow = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- AI 整理的确认(复查报告 4.2.1)----
|
||||
if (confirmSummarize) {
|
||||
val pinnedCount = space?.memories?.count { it.pinned } ?: 0
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmSummarize = false },
|
||||
title = { Text("让 AI 整理一次记忆", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
buildString {
|
||||
append("这会把现在这 ${space?.memories?.size ?: 0} 条零散、重复的记忆")
|
||||
append("压缩成更少、更完整的几条。\n\n")
|
||||
append("· 标了「置顶」的(现在有 $pinnedCount 条)原样不动,不参与合并\n")
|
||||
append("· 它只做合并改写,不许编造新的事实\n")
|
||||
append("· 这是一次真实的模型调用,会花 Token(但不受额度限制)\n\n")
|
||||
append("想保住哪几条,先取消对话框去标上「置顶」。")
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { confirmSummarize = false; onSummarize() }) { Text("开始整理") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmSummarize = false }) { Text("先去标几条") } },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 导入模式选择放在调用方(它管文件选择器)----
|
||||
|
||||
// ---- 编辑 / 新增 ----
|
||||
val target = editing
|
||||
if (target != null || adding) {
|
||||
MemoryEditDialog(
|
||||
initial = target,
|
||||
onDismiss = { editing = null; adding = false },
|
||||
onSave = { title, content ->
|
||||
if (target == null) onAdd(title, content) else onUpdate(target.id, title, content)
|
||||
editing = null
|
||||
adding = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SmallAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MemoryRow(
|
||||
item: MemoryItem,
|
||||
/** 在看旧空间 → 一切都只读(那里已经不属于当前对话了,改了会让人困惑) */
|
||||
readOnly: Boolean,
|
||||
/** 这条是**别人写的**(共享空间里)→ 不给改删入口,并且标出来源 */
|
||||
foreign: Boolean,
|
||||
authorName: String,
|
||||
onEdit: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onTogglePin: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.border(
|
||||
width = if (item.pinned) 1.dp else 0.dp,
|
||||
color = if (item.pinned) Color(0x66F29900) else Color.Transparent,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (item.pinned) {
|
||||
Text(
|
||||
"置顶",
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Color(0x22F29900))
|
||||
.padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
// ★ 来源标注(复查报告 4.2.2):共享空间里必须看得出这条是谁写的。
|
||||
// 不标的话用户点删除会被后端拒绝,他会当成 bug —— 而后端拦得对。
|
||||
if (foreign && authorName.isNotBlank()) {
|
||||
Text(
|
||||
"由 $authorName 写入",
|
||||
fontSize = 9.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
Text(
|
||||
item.title.ifBlank { "(无标题)" },
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
if (item.content.isNotBlank()) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(item.content, fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
if (readOnly) {
|
||||
Text(
|
||||
"绑定世界观之前的记忆,只供查看",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else if (foreign) {
|
||||
// 别人写的:不是"按钮点了才报错",而是**根本不给按钮**
|
||||
Text(
|
||||
"别人写的,AI 和你都改不了这一条(要删只能在这里删)",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
RowAction("删除", danger = true, onClick = onDelete)
|
||||
} else {
|
||||
// ★「必须保留」是**用户**的权利(需求 3.2):标上之后 AI 总结时
|
||||
// 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给。
|
||||
// 再点一次就是**解除**(复查报告 4.2.3 担心的"解不开"不存在,
|
||||
// 但文案要写成"取消保留",不能只显示当前状态)
|
||||
RowAction(if (item.pinned) "取消置顶" else "置顶", onClick = onTogglePin)
|
||||
RowAction("编辑", onClick = onEdit)
|
||||
RowAction("删除", danger = true, onClick = onDelete)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MemoryEditDialog(
|
||||
initial: MemoryItem?,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (String, String) -> Unit,
|
||||
) {
|
||||
var title by remember { mutableStateOf(initial?.title ?: "") }
|
||||
var content by remember { mutableStateOf(initial?.content ?: "") }
|
||||
// ★ 单条记忆的编辑用弹窗是合适的(内容量小、就是两个输入框);
|
||||
// 而"列表 / 多组配置"一律全屏 —— 见 AGENTS.md 那张表
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(if (initial == null) "加一条记忆" else "编辑记忆", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column {
|
||||
OutlinedTextField(
|
||||
value = title,
|
||||
onValueChange = { title = it },
|
||||
label = { Text("标题", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = content,
|
||||
onValueChange = { content = it },
|
||||
label = { Text("内容", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 90.dp, max = 220.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = { onSave(title.trim(), content.trim()) },
|
||||
enabled = title.isNotBlank() || content.isNotBlank(),
|
||||
) { Text("保存") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.termux.TermuxMirror
|
||||
|
||||
/**
|
||||
* 换源界面(全屏,不是弹窗)。
|
||||
*
|
||||
* ★ 为什么做成界面:源列表有五个,每个还要显示说明和当前选中状态 ——
|
||||
* 弹窗装不下(见 AGENTS.md 的界面约定)。
|
||||
*
|
||||
* ★ 为什么需要这个功能:Termux 官方源在国内基本连不上,
|
||||
* `pkg install` 会卡住或超时,用户会以为"内置的 Termux 坏了"。
|
||||
* 换源这件事**每次重装都要做**,手敲 sed 又容易把 apt 配置写坏。
|
||||
*/
|
||||
@Composable
|
||||
fun MirrorScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
// 每次进界面重读一次:用户可能手改过 sources.list
|
||||
var current by remember { mutableStateOf(TermuxMirror.current(context)) }
|
||||
var toast by remember { mutableStateOf("") }
|
||||
|
||||
FullScreen(
|
||||
title = "软件源",
|
||||
subtitle = "换完记得跑一次 pkg update",
|
||||
onBack = onBack,
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"Termux 官方源(packages.termux.dev)在国内基本连不上,表现是 " +
|
||||
"pkg install 卡在 Reading package lists 或者直接超时。" +
|
||||
"换一个国内镜像就好。",
|
||||
color = doubaoTextSecondary(),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
|
||||
if (toast.isNotBlank()) {
|
||||
Surface(
|
||||
color = Color(0xFF16301F),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
) {
|
||||
Text(
|
||||
toast,
|
||||
color = Color(0xFF9BE7B4),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
modifier = Modifier.padding(10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("选一个源")
|
||||
|
||||
TermuxMirror.MIRRORS.forEach { m ->
|
||||
val selected = current?.id == m.id
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(if (selected) Doubao.Blue.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.clickable {
|
||||
val n = try {
|
||||
TermuxMirror.set(context, m)
|
||||
} catch (t: Throwable) {
|
||||
toast = "换源失败:${t.message}"
|
||||
return@clickable
|
||||
}
|
||||
current = m
|
||||
toast = "已切到 ${m.name}(写入 $n 条),去终端跑一次 pkg update"
|
||||
}
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
m.name,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
|
||||
color = if (selected) Doubao.Blue else Color(0xFF1F2328),
|
||||
)
|
||||
Text(
|
||||
m.note,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Text(
|
||||
m.host,
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary().copy(alpha = 0.7f),
|
||||
)
|
||||
}
|
||||
if (selected) {
|
||||
Text("✓ 当前", fontSize = 11.sp, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("换完之后")
|
||||
Text(
|
||||
"去终端敲:\n" +
|
||||
" pkg update\n" +
|
||||
"\n" +
|
||||
"update 会重新拉索引,第一次可能要等十几秒。" +
|
||||
"如果报错,换另一个源再试 —— 镜像偶尔会同步中断。",
|
||||
color = doubaoTextSecondary(),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 19.sp,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Group
|
||||
import androidx.compose.material.icons.filled.Memory
|
||||
import androidx.compose.material.icons.filled.Layers
|
||||
import androidx.compose.material.icons.filled.Public
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* ★★ 「更多功能」—— 抽屉里放不下的那些入口收在这儿。
|
||||
*
|
||||
* ## 为什么要这么改(用户反馈:"太挤了对话都没了")
|
||||
*
|
||||
* 抽屉原来平铺了 9 个入口,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能:用户 90% 打开抽屉是为了切对话。
|
||||
*
|
||||
* ★★ 后来又收了一次(用户第二次说"太挤了"、"把别的放更多里"):
|
||||
* 抽屉第一层现在只剩**四件天天用的**:新话题 / 智能体 / 记忆 / 更多功能。
|
||||
* 笔记、模型、新建群聊都挪进来了 ——
|
||||
* 「模型」虽然也常用,但它是个**配置**,配好基本不动;
|
||||
* 抽屉里腾出来的位置留给对话列表更值。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
* `← 返回 | 标题`,和别的全屏界面一套顶栏。
|
||||
* 不用折叠面板:折叠起来每次都要展开一次,反而更麻烦。
|
||||
*/
|
||||
@Composable
|
||||
fun MoreSheetScreen(
|
||||
onOpenAiScreens: () -> Unit,
|
||||
onOpenSkills: () -> Unit,
|
||||
onOpenResources: () -> Unit,
|
||||
onOpenMeetings: () -> Unit,
|
||||
onOpenTerminal: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onNewGroup: () -> Unit,
|
||||
onOpenNotes: () -> Unit,
|
||||
onOpenModels: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("更多功能", onBack = onClose)
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
// 从抽屉挪进来的三个(都是"偶尔用一次"那一档)
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Group,
|
||||
title = "新建群聊",
|
||||
subtitle = "拉几个智能体到一个会话里,可以 @ 点名",
|
||||
) { onNewGroup() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.EditNote,
|
||||
title = "笔记",
|
||||
subtitle = "AI 替你记下来的东西",
|
||||
) { onOpenNotes() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Memory,
|
||||
title = "模型",
|
||||
subtitle = "换模型 / 思考强度(配好基本不用动)",
|
||||
) { onOpenModels() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Dashboard,
|
||||
title = "AI 界面",
|
||||
subtitle = "AI 弹过的界面都存着,点一下就能再打开",
|
||||
) { onOpenAiScreens() }
|
||||
}
|
||||
item {
|
||||
// 世界观 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)——
|
||||
// 它们是"全局资源"那一层:都被智能体引用,都是列表 + 增删改 + 导入导出
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Public,
|
||||
title = "世界观 · 技能 · 模型",
|
||||
subtitle = "共享记忆的世界、AI 的工具手册、可选模型列表",
|
||||
) { onOpenResources() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Layers,
|
||||
title = "技能 · 连接器",
|
||||
subtitle = "Python 工具、MCP 服务、界面能力开关",
|
||||
) { onOpenSkills() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.AccountTree,
|
||||
title = "会议模式",
|
||||
subtitle = "多个智能体一起讨论,可以搭流程图",
|
||||
) { onOpenMeetings() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Terminal,
|
||||
title = "终端",
|
||||
subtitle = "内置 Termux,真 Linux 环境",
|
||||
) { onOpenTerminal() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Settings,
|
||||
title = "设置",
|
||||
subtitle = "模型、语音、外观、数据",
|
||||
) { onOpenSettings() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MoreRow(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 14.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(subtitle, fontSize = 12.sp, lineHeight = 17.sp, color = doubaoTextDim())
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.doubao.nodekit.NodeCatalog
|
||||
import com.doubao.nodekit.NodeShape
|
||||
import com.doubao.nodekit.NodeShapes
|
||||
|
||||
/*
|
||||
* 节点形状的小图标。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 节点的"形状"在库里是一个字段([NodeShape]),但字段本身用户看不见 ——
|
||||
* 得有人把它画出来。这里就是那个"画"的地方,两处用它:
|
||||
*
|
||||
* · 「加节点」面板里每个类型前面的缩略图 —— **选之前**就看出这是起点、
|
||||
* 判断、循环还是纯数据节点
|
||||
* · 节点卡片标题栏左边的小白形状 —— 图大了以后靠它认节点
|
||||
*
|
||||
* ## 为什么不直接在库里写 @Composable
|
||||
*
|
||||
* 库刻意不依赖 Compose **运行时**(只依赖 `Path` 那几个值类型),
|
||||
* 这样它才能被单元测试直接跑、也不用拖着 compose runtime 走。
|
||||
* 画的那一步(`Canvas` / `drawPath`)留在 App 这边。
|
||||
*
|
||||
* 形状的**路径**仍然只有一份 —— 库里的 `NodeShapes.path()`。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 按节点类型画形状徽标(自动取该类型的颜色)。
|
||||
*
|
||||
* 用在「加节点」面板那种"还没创建、只知道类型"的地方。
|
||||
*/
|
||||
@Composable
|
||||
fun NodeShapeBadge(
|
||||
type: String,
|
||||
size: Dp = 22.dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
NodeShapeBadge(
|
||||
shape = NodeCatalog.shape(type),
|
||||
color = Color(NodeCatalog.color(type)),
|
||||
size = size,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按形状 + 颜色画徽标。
|
||||
*
|
||||
* [filled] = true 时填色(面板里用,颜色淡一点做底 + 描边),
|
||||
* false 时只描边(标题栏里用白色描边太重,所以那边直接填白)。
|
||||
*/
|
||||
@Composable
|
||||
fun NodeShapeBadge(
|
||||
shape: NodeShape,
|
||||
color: Color,
|
||||
size: Dp = 22.dp,
|
||||
strokeWidth: Dp = 1.6.dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Canvas(modifier.size(size)) {
|
||||
val p = NodeShapes.thumbPath(shape, this.size.width)
|
||||
// 淡底 + 实描边:小尺寸下只有描边会看不清,只有实心又显得太重
|
||||
drawPath(p, color = color.copy(alpha = 0.16f))
|
||||
drawPath(p, color = color, style = Stroke(width = strokeWidth.toPx()))
|
||||
}
|
||||
}
|
||||
258
android/app/src/main/java/com/doubao/lynxclone/ui/NotesScreen.kt
Normal file
258
android/app/src/main/java/com/doubao/lynxclone/ui/NotesScreen.kt
Normal file
@@ -0,0 +1,258 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.DeleteOutline
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.NoteItem
|
||||
|
||||
/**
|
||||
* ★★ 笔记列表 —— 用户要求"notes 用户要能查看"。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 笔记以前**只有 AI 能读写**(走 notes 工具),用户在界面上完全看不到。
|
||||
* 也就是说:AI 说"我记下来了",用户没有任何办法确认它记了什么、
|
||||
* 记错没有、或者删掉记错的。这类"AI 替你做事但你无法查看"的功能,
|
||||
* 用户是不会信任的。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
* 列表要滚动(笔记会越攒越多),弹窗装不下。
|
||||
*/
|
||||
@Composable
|
||||
fun NotesScreen(
|
||||
notes: List<NoteItem>,
|
||||
opening: NoteItem?,
|
||||
onOpen: (NoteItem) -> Unit,
|
||||
onCloseNote: () -> Unit,
|
||||
onDelete: (NoteItem) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
// 阅读某一条时,返回键先回到列表(而不是直接退出笔记页)——
|
||||
// 用户会觉得"我明明在笔记里,怎么一按就出去了"
|
||||
BackHandler(enabled = true) {
|
||||
if (opening != null) onCloseNote() else onBack()
|
||||
}
|
||||
|
||||
if (opening != null) {
|
||||
NoteDetail(note = opening, onBack = onCloseNote, onDelete = { onDelete(opening) })
|
||||
return
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("笔记", onBack = onBack) {
|
||||
Text(
|
||||
if (notes.isEmpty()) "还没有" else "${notes.size} 条",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
if (notes.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"还没有笔记。\n让 AI「记一下」某件事,就会出现在这里。",
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 22.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
Text(
|
||||
"AI 帮你记下来的东西都在这里。点开看全文。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
items(notes.size) { index ->
|
||||
val n = notes[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onOpen(n) }
|
||||
.padding(start = 14.dp, end = 6.dp, top = 12.dp, bottom = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
n.title.ifBlank { n.file },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (n.preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
n.preview,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
listOf(formatNoteTime(n.at), formatNoteBytes(n.bytes))
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(" · "),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// 删除单独一个小按钮,别和"点开"挤在一起误触
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.clickable { onDelete(n) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
"删除",
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 读某一条笔记的全文 */
|
||||
@Composable
|
||||
private fun NoteDetail(note: NoteItem, onBack: () -> Unit, onDelete: () -> Unit) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader(note.title.ifBlank { "笔记" }, onBack = onBack) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier.size(36.dp).clip(CircleShape).clickable {
|
||||
clipboard.setText(AnnotatedString(note.content))
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.ContentCopy, "复制", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Box(
|
||||
Modifier.size(36.dp).clip(CircleShape).clickable { onDelete() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 18.dp),
|
||||
) {
|
||||
Text(
|
||||
listOf(formatNoteTime(note.at), formatNoteBytes(note.bytes))
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(" · "),
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// 正文可能是 markdown(notes 工具写的是 .md),所以按 markdown 渲染
|
||||
MarkdownText(
|
||||
markdown = note.content,
|
||||
color = doubaoText(),
|
||||
fontSize = 15,
|
||||
lineHeight = 24,
|
||||
)
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ISO 时间 → 「今天 15:19」/「10-15 15:19」。
|
||||
*
|
||||
* ★ 解析失败就返回空串(界面上那一项直接不显示)——
|
||||
* **不要瞎猜**:用户手改过文件名的情况是有的,猜错会显示一个假时间。
|
||||
*/
|
||||
private fun formatNoteTime(iso: String): String {
|
||||
if (iso.isBlank()) return ""
|
||||
return try {
|
||||
val cleaned = iso.substringBefore('.').removeSuffix("Z")
|
||||
val dt = java.time.LocalDateTime.parse(cleaned)
|
||||
val today = java.time.LocalDate.now()
|
||||
val fmt = if (dt.toLocalDate() == today) {
|
||||
java.time.format.DateTimeFormatter.ofPattern("'今天' HH:mm")
|
||||
} else {
|
||||
java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm")
|
||||
}
|
||||
dt.format(fmt)
|
||||
} catch (_: Throwable) {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatNoteBytes(n: Int): String = when {
|
||||
n <= 0 -> ""
|
||||
n < 1024 -> "${n}B"
|
||||
n < 1024 * 1024 -> "${n / 1024}KB"
|
||||
else -> String.format(java.util.Locale.getDefault(), "%.1fMB", n / 1024.0 / 1024.0)
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.ModelEntry
|
||||
import com.doubao.lynxclone.data.SkillItem
|
||||
import com.doubao.lynxclone.data.WorldviewItem
|
||||
|
||||
/*
|
||||
* 世界观 / Skill / 模型列表的管理界面(需求 3.3 / 3.6 / 3.7)。
|
||||
*
|
||||
* ## 为什么三种东西挤在一个界面里
|
||||
*
|
||||
* 它们是**同一层的东西**:都是"全局资源",都被智能体引用,都是"列表 + 增删改 +
|
||||
* 导入导出"。分开成三个入口的话,用户要记住"世界观在哪、技能在哪、模型在哪"——
|
||||
* 而它们其实是一件事("这个 App 里有哪些可复用的东西")。
|
||||
*
|
||||
* ## 表单是**字段驱动**的,不是写三份
|
||||
*
|
||||
* 三种资源的表单字段完全不同(世界观有设定文本 + 四件套;Skill 就两行;
|
||||
* 模型有地址/标识/Key/单价),但**长得一模一样** —— 都是一个 label + 一个输入框。
|
||||
* 所以用 `List<Field>` 描述,渲染只有一份。
|
||||
*
|
||||
* 写三份的话,加一个字段就要改三处,而这个仓库里"加了 list 类型但某张表没跟上"
|
||||
* 已经反复出现过(AGENTS.md 第一条就是它)。
|
||||
*/
|
||||
|
||||
/** 表单里的一个字段 */
|
||||
private data class Field(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val placeholder: String = "",
|
||||
val multiline: Boolean = false,
|
||||
val password: Boolean = false,
|
||||
val number: Boolean = false,
|
||||
/** 开关:值的约定是 `"1"` = 开、`""` = 关(不弹键盘,点一下切换) */
|
||||
val toggle: Boolean = false,
|
||||
)
|
||||
|
||||
private val WORLD_FIELDS = listOf(
|
||||
Field("name", "名字", "比如:九霄"),
|
||||
Field(
|
||||
"setting", "世界观设定",
|
||||
"这个世界的规则、背景、称呼……(绑定了它的智能体,提示词里会整段带上)",
|
||||
multiline = true,
|
||||
),
|
||||
)
|
||||
|
||||
private val SKILL_FIELDS = listOf(
|
||||
Field("name", "名字", "比如:写代码的规矩"),
|
||||
Field(
|
||||
"content", "内容",
|
||||
"告诉 AI 有哪些工具、什么时候用、用完之后不许干什么",
|
||||
multiline = true,
|
||||
),
|
||||
)
|
||||
|
||||
private val MODEL_FIELDS = listOf(
|
||||
Field("name", "显示名", "比如:豆包 Pro"),
|
||||
Field("apiBase", "API 地址", "https://ark.cn-beijing.volces.com/api/v3"),
|
||||
Field("model", "模型标识", "doubao-seed-2-1-pro-260628"),
|
||||
Field("apiKey", "API Key", "留空则用全局设置里那个", password = true),
|
||||
Field("provider", "提供商", "ark / openai / deepseek …(留空则跟随全局)"),
|
||||
Field("pricePerK", "单价(元/千 Token)", "留空 = 不显示费用估算", number = true),
|
||||
// ★ v1.2:命中缓存的单价单独填。各家命中都比未命中便宜得多(常见 1/10),
|
||||
// 不填的话费用按未命中的价格算 —— **越用越高估**,而用户会以为
|
||||
// 自己真花了那些钱。留空 = 按未命中单价算(保守估计,不会低估)。
|
||||
Field("cachePricePerK", "命中单价(元/千 Token)", "留空 = 按上面的单价算(偏保守)", number = true),
|
||||
Field(
|
||||
"noTools", "不支持工具调用",
|
||||
"这个模型不会 function calling(本地小模型、老网关常见)。打开之后不再传 tools," +
|
||||
"改成让它在正文里写调用,内核执行完再剥掉 —— 记忆和情绪照常能用。",
|
||||
toggle = true,
|
||||
),
|
||||
)
|
||||
|
||||
/** 三张表:kind → (标题、字段、说明、是不是包) */
|
||||
private class Kind(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val tabLabel: String,
|
||||
val fields: List<Field>,
|
||||
val hint: String,
|
||||
/** 导入导出是 zip 包(世界观)还是单个 JSON(Skill) */
|
||||
val isZip: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* 数值状态包:普通字段只有名字和说明。
|
||||
*
|
||||
* ★ 真正的定义(有哪些数值、哪些状态、各自的区间表和脚本)在
|
||||
* **[规则包编辑]** 全屏界面里改 —— 那是一堆嵌套结构,
|
||||
* 塞进"label + 输入框"的表单里既放不下也说不清。
|
||||
*/
|
||||
private val RULEPACK_FIELDS = listOf(
|
||||
Field("name", "名称", "比如「九州数值规则」"),
|
||||
Field("note", "说明", "给别的使用者看的:这个包是干什么的", multiline = true),
|
||||
)
|
||||
|
||||
private val KINDS = listOf(
|
||||
Kind(
|
||||
"worldviews", "世界观", "世界观", WORLD_FIELDS, isZip = true,
|
||||
hint = "绑定同一个世界观的智能体**共用一份记忆**。导出是一个 zip 包(含设定和四件套图片)。",
|
||||
),
|
||||
Kind(
|
||||
"rulepacks", "数值状态包", "规则包", RULEPACK_FIELDS, isZip = true,
|
||||
hint = "世界观挂上它之后,智能体才有**数值**(好感度、声望……)和**状态**(中毒、庇佑……)。" +
|
||||
"包里可以有 Python 脚本做裁决 —— 导入时内核会让你确认。",
|
||||
),
|
||||
Kind(
|
||||
"skills", "Skill", "Skill", SKILL_FIELDS, isZip = false,
|
||||
hint = "纯文本的「工具使用手册」。内置的记忆/情绪/用量手册**默认就生效**;这里写的是你自己加的规矩。",
|
||||
),
|
||||
Kind(
|
||||
"models", "模型", "模型", MODEL_FIELDS, isZip = false,
|
||||
hint = "全局模型列表。智能体按 id 引用这里的某一项 —— 所以换 Key 只改一处," +
|
||||
"而且**导出智能体包时不会把 Key 带出去**。",
|
||||
),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
var tab by remember { mutableStateOf(0) }
|
||||
// 正在编辑的那一项(null 且 editing 为 true = 新建)
|
||||
var editing by remember { mutableStateOf<Boolean>(false) }
|
||||
var editId by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
val kind = KINDS[tab]
|
||||
val items: List<Pair<String, Triple<String, String, AgentImage>>> = when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.map {
|
||||
it.id to Triple(it.name, it.setting, it.image)
|
||||
}
|
||||
// v1.2 数值状态包:副标题列出"有几条数值、几条状态、带不带脚本" ——
|
||||
// 那才是用户判断这个包能不能用的信息,光看名字看不出来
|
||||
"rulepacks" -> vm.state.rulePacks.map {
|
||||
val bits = mutableListOf("${it.stats.size} 条数值", "${it.statuses.size} 条状态")
|
||||
if (it.hasScripts) bits += "${it.scripts.size} 个脚本"
|
||||
it.id to Triple(it.name, bits.joinToString(" · "), AgentImage())
|
||||
}
|
||||
"skills" -> vm.state.skills.map { it.id to Triple(it.name, it.content, AgentImage()) }
|
||||
else -> vm.state.modelEntries.map {
|
||||
// ★ 兼容模式在列表上就要看得出来(复查 3.3):进了编辑页才知道
|
||||
// 这个模型不传 tools,等于用户永远想不起自己开过它
|
||||
it.id to Triple(
|
||||
if (it.noTools) "${it.name}(兼容模式)" else it.name,
|
||||
listOf(it.model, it.apiBase).filter { s -> s.isNotBlank() }.joinToString(" · "),
|
||||
AgentImage(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导入导出(SAF)----------------
|
||||
* zip 走 base64(二进制没法塞进 JSON 文本),Skill 是纯 JSON 文本。
|
||||
*/
|
||||
val ctx = LocalContext.current
|
||||
var pendingExport by remember { mutableStateOf<Triple<String, String, String>?>(null) }
|
||||
val saveDoc = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { uri ->
|
||||
val data = pendingExport
|
||||
pendingExport = null
|
||||
if (uri != null && data != null) {
|
||||
runCatching {
|
||||
val bytes = if (data.second == "zip") Base64.decode(data.first, Base64.DEFAULT)
|
||||
else data.first.toByteArray(Charsets.UTF_8)
|
||||
ctx.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
// ---- 规则包的脚本警告 ----
|
||||
//
|
||||
// ★ 这里是全仓库**唯一**该用弹窗的导入场景:内容就是一段警告 + 两个按钮,
|
||||
// 属于"一次确认"(AGENTS.md 的界面约定:一次确认用弹窗,列表/多组配置
|
||||
// 才开全屏)。真正拦得住的是**服务端**那道 `confirmScripts` 关口,
|
||||
// 这个框只是把风险如实告诉用户。
|
||||
if (vm.pendingRulePack.isNotBlank()) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.dismissRulePack() },
|
||||
title = { Text("这个包里带了 Python 脚本") },
|
||||
text = {
|
||||
Text(
|
||||
vm.rulePackWarning.ifBlank {
|
||||
"包里有可执行脚本。导入后它会在你的设备上运行 —— " +
|
||||
"只导入你信得过的来源。"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { vm.importRulePack(vm.pendingRulePack, confirmed = true) }) {
|
||||
Text("我知道风险,继续", color = Doubao.Blue)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { vm.dismissRulePack() }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val openDoc = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
if (kind.isZip) {
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
// ★ 规则包**单独一条路**:它是唯一允许夹带可执行 Python 的
|
||||
// 包类型,内核会让它带 `confirmScripts` 才落库。
|
||||
// 第一次(不确认)会返回 needConfirm + warning,
|
||||
// 界面拿去弹警告;用户点了「我知道风险,继续」再传一次。
|
||||
if (kind.id == "rulepacks") vm.importRulePack(b64)
|
||||
else vm.importPackage(kind.id, b64, "")
|
||||
} else {
|
||||
vm.importPackage(kind.id, "", bytes.toString(Charsets.UTF_8))
|
||||
}
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = "资源",
|
||||
subtitle = "世界观 · 规则包 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("导入") {
|
||||
if (kind.isZip) openDoc.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
else openDoc.launch(arrayOf("application/json", "text/plain", "*/*"))
|
||||
}
|
||||
},
|
||||
) {
|
||||
// ---- Tab ----
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
for ((i, k) in KINDS.withIndex()) {
|
||||
val on = i == tab
|
||||
Text(
|
||||
k.tabLabel,
|
||||
fontSize = 13.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.padding(end = 8.dp)
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { tab = i }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("新建") {
|
||||
// ★ 规则包**不是**"填两个字段就完事"的东西 —— 它的内容
|
||||
// (定义表 + 脚本)在独立的全屏编辑页里。
|
||||
// 所以「新建」直接建一个**带模板**的包并进去,
|
||||
// 而不是先弹"名称+说明"的表单、再让用户自己去找编辑器。
|
||||
if (kind.id == "rulepacks") { vm.createRulePackFromTemplate(); return@RowAction }
|
||||
editId = null; editing = true
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState())) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.07f))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(kind.hint.replace("**", ""), fontSize = 11.sp, lineHeight = 16.sp, color = Doubao.Blue)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
if (items.isEmpty()) {
|
||||
Text(
|
||||
"还没有。点右上角「新建」,或者用「导入」拿一个现成的包。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 20.dp),
|
||||
)
|
||||
}
|
||||
|
||||
for ((id, info) in items) {
|
||||
val (name, preview, image) = info
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable {
|
||||
// ★ 规则包走**独立的全屏编辑页** —— 它的内容
|
||||
// (定义表 + 脚本)不是"label + 输入框"那套表单
|
||||
// 能表达的,硬塞进去会变成一堆看不懂的文本框
|
||||
if (kind.id == "rulepacks") { vm.openRulePackEdit(id); return@clickable }
|
||||
editId = id; editing = true
|
||||
}
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (kind.id == "worldviews") {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = image.slot("平常"),
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name.ifBlank { "未命名" }, fontSize = 14.sp, color = doubaoText())
|
||||
if (preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
preview.replace("\n", " ").take(70),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
// ★ 谁绑了它(用户要求)—— 反过来也得看得见:
|
||||
// 绑之前你要知道"这个世界观已经有谁在用了",
|
||||
// 空的则说明没人用它、共享记忆也没人在读写。
|
||||
if (kind.id == "worldviews") {
|
||||
val users = vm.state.worldviews.firstOrNull { it.id == id }?.agents ?: emptyList()
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
if (users.isEmpty()) "还没有智能体用它"
|
||||
else "${users.size} 个智能体在用:${users.joinToString("、") { it.name }}",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = if (users.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
RowAction("记忆") {
|
||||
// ★ 世界观的**共享记忆**("大家共同记得什么")——
|
||||
// 和从智能体进去看的是同一个空间、不同的视角
|
||||
vm.openWorldMemories(id)
|
||||
}
|
||||
RowAction("导出") {
|
||||
vm.exportPackage(kind.id, id) { content, ext ->
|
||||
pendingExport = Triple(content, ext, "x")
|
||||
saveDoc.launch("${name.ifBlank { "resource" }}.${if (kind.isZip) "zip" else "json"}")
|
||||
}
|
||||
}
|
||||
RowAction("删除", danger = true) { vm.deleteResource(kind.id, id) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
ResourceEditScreen(
|
||||
vm = vm,
|
||||
kind = kind,
|
||||
id = editId,
|
||||
onDone = { editing = false; editId = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 字段驱动的编辑表单 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun ResourceEditScreen(
|
||||
vm: AppViewModel,
|
||||
kind: Kind,
|
||||
id: String?,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
// 三种资源的初始值从内存里那份拿(列表就是它渲染的,不会对不上)
|
||||
val initial: Map<String, String> = remember(id, kind.id) {
|
||||
when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "setting" to it.setting)
|
||||
} ?: emptyMap()
|
||||
"skills" -> vm.state.skills.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "content" to it.content)
|
||||
} ?: emptyMap()
|
||||
else -> vm.state.modelEntries.firstOrNull { it.id == id }?.let {
|
||||
mapOf(
|
||||
"name" to it.name, "apiBase" to it.apiBase, "model" to it.model,
|
||||
"apiKey" to "", "provider" to it.provider,
|
||||
"pricePerK" to if (it.pricePerK > 0) it.pricePerK.toString() else "",
|
||||
"noTools" to if (it.noTools) "1" else "",
|
||||
)
|
||||
} ?: emptyMap()
|
||||
}
|
||||
}
|
||||
var values by remember(id, kind.id) { mutableStateOf(initial) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var worldImage by remember(id, kind.id) {
|
||||
mutableStateOf(vm.state.worldviews.firstOrNull { it.id == id }?.image ?: AgentImage())
|
||||
}
|
||||
val ctx = LocalContext.current
|
||||
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank() || id == null) return@rememberLauncherForActivityResult
|
||||
// 和智能体编辑页**同一份实现** —— 这条链路的坑(大图、GIF、SAF 没扩展名)
|
||||
// 两边一模一样,抄两份迟早只修一份
|
||||
vm.uploadWorldviewAssetFrom(ctx.applicationContext, id, slot, uri)
|
||||
}
|
||||
// 上传完 image 会变,跟着刷新预览
|
||||
vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
if (it.image != worldImage) worldImage = it.image
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = if (id == null) "新建${kind.title}" else "编辑${kind.title}",
|
||||
subtitle = values["name"].orEmpty().ifBlank { kind.title },
|
||||
onBack = onDone,
|
||||
actions = {
|
||||
TopAction("保存", enabled = !saving) {
|
||||
saving = true
|
||||
val name = values["name"].orEmpty().trim()
|
||||
val text = values[
|
||||
if (kind.id == "models") "apiBase" else if (kind.id == "skills") "content" else "setting"
|
||||
].orEmpty()
|
||||
val extra = mutableMapOf<String, Any?>()
|
||||
if (kind.id == "models") {
|
||||
extra["model"] = values["model"].orEmpty()
|
||||
extra["apiKey"] = values["apiKey"].orEmpty()
|
||||
extra["provider"] = values["provider"].orEmpty()
|
||||
extra["pricePerK"] = values["pricePerK"]?.toDoubleOrNull() ?: 0.0
|
||||
extra["noTools"] = values["noTools"] == "1"
|
||||
}
|
||||
if (kind.id == "worldviews") extra["image"] = worldImage
|
||||
vm.saveResource(kind.id, id, name, text, extra) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
SectionLabel("基本信息")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
for (f in kind.fields) {
|
||||
// ---- 开关型字段:点一下切换,不弹键盘 ----
|
||||
if (f.toggle) {
|
||||
val on = values[f.key] == "1"
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(f.label, fontSize = 13.sp, color = doubaoText())
|
||||
if (f.placeholder.isNotBlank()) {
|
||||
Text(
|
||||
f.placeholder,
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(width = 44.dp, height = 26.dp)
|
||||
.clip(RoundedCornerShape(13.dp))
|
||||
.background(if (on) Doubao.Blue else Doubao.Border)
|
||||
.clickable { values = values + (f.key to if (on) "" else "1") },
|
||||
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(20.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color.White),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
continue
|
||||
}
|
||||
Text(f.label, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = values[f.key].orEmpty(),
|
||||
onValueChange = { v ->
|
||||
// 单价只收数字和小数点;别的字段原样收
|
||||
values = values + (f.key to if (f.number) v.filter { c -> c.isDigit() || c == '.' } else v)
|
||||
},
|
||||
placeholder = { Text(f.placeholder, fontSize = 12.sp) },
|
||||
singleLine = !f.multiline,
|
||||
visualTransformation = if (f.password) PasswordVisualTransformation()
|
||||
else androidx.compose.ui.text.input.VisualTransformation.None,
|
||||
keyboardOptions = if (f.number) KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
else KeyboardOptions.Default,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.then(if (f.multiline) Modifier.heightIn(min = 120.dp, max = 300.dp) else Modifier),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 世界观的四件套(需求 3.6:沿用智能体那一套)---- */
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("外观(四件套)")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
if (id == null) {
|
||||
Text(
|
||||
"先保存,再回来加外观图片(图片要落到这个世界观自己的目录里)。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
val slots = listOf(
|
||||
Triple("front", "封面 / 代表图", "智能体选择界面上用的那张"),
|
||||
Triple("back", "背景图", "铺在展示区最底层"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本"),
|
||||
)
|
||||
for ((key, title, desc) in slots) {
|
||||
val path = when (key) {
|
||||
"front" -> worldImage.slot("平常")
|
||||
"back" -> worldImage.back
|
||||
"border-main" -> worldImage.borderMain
|
||||
else -> worldImage.borderInfo
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
RowAction("选择") {
|
||||
pendingSlot = key
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
}
|
||||
if (path.isNotBlank()) {
|
||||
RowAction("清除", danger = true) {
|
||||
vm.uploadWorldviewAsset(id, key, "", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
if (id != null && kind.id == "skills") {
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
TextButton(onClick = { vm.deleteResource(kind.id, id); onDone() }) {
|
||||
Text("删除这个 Skill", color = Color(0xFFD93025), fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* [规则包编辑](v1.2 附录 D)—— 全屏。
|
||||
*
|
||||
* ## 为什么全屏
|
||||
*
|
||||
* 里面有:名称、说明、两张定义表、若干段 Python 脚本。任何一个都超过
|
||||
* 一屏弹窗能装下的量 —— 按仓库的界面约定,这就是该开全屏的那种。
|
||||
*
|
||||
* ## 脚本框的形状(照抄节点代码组件的做法)
|
||||
*
|
||||
* 两条硬要求,都来自踩过的坑(见 AGENTS.md):
|
||||
*
|
||||
* 1. **不软换行** —— ` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
* 就是语法。做法是"把输入框塞进足够宽的横向滚动容器"。
|
||||
* 2. **有高度上限** —— 只写 `heightIn(min=...)` 的话,脚本一长框就长到
|
||||
* 屏幕外,把底下的东西顶出去。
|
||||
*
|
||||
* ## 定义表这版是只读的
|
||||
*
|
||||
* 数值/状态的**结构**(min/max、区间表、叠加层数)是一堆嵌套结构,
|
||||
* 用表单编辑要另做一套增删改。这一版先把**脚本**做成可编辑的
|
||||
* (那是最需要改的部分),定义表只读 + 指路导入导出。
|
||||
* 界面上**如实写着**这一点,不让用户对着只读的表发愣。
|
||||
*/
|
||||
@Composable
|
||||
fun RulePackEditScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val pack = vm.editingRulePack
|
||||
if (pack == null) {
|
||||
FullScreen(title = "规则包编辑", onBack = onBack) { Hint("正在读……") }
|
||||
return
|
||||
}
|
||||
|
||||
var name by remember(pack.id) { mutableStateOf(pack.name) }
|
||||
var note by remember(pack.id) { mutableStateOf(pack.note) }
|
||||
var scripts by remember(pack.id) { mutableStateOf(pack.scripts) }
|
||||
var editing by remember(pack.id) { mutableStateOf("") }
|
||||
var newScript by remember(pack.id) { mutableStateOf("") }
|
||||
var draft by remember(pack.id) { mutableStateOf("") }
|
||||
|
||||
fun infoJson(): JSONObject {
|
||||
val o = JSONObject()
|
||||
o.put("name", name)
|
||||
o.put("stats", JSONArray().apply {
|
||||
for (s in pack.stats) {
|
||||
put(JSONObject()
|
||||
.put("name", s.name).put("min", s.min).put("max", s.max)
|
||||
.put("shared", s.shared).put("script", s.script)
|
||||
.put("ranges", JSONArray().apply {
|
||||
for (r in s.ranges) {
|
||||
put(JSONObject().put("min", r.min).put("max", r.max).put("text", r.text))
|
||||
}
|
||||
}))
|
||||
}
|
||||
})
|
||||
o.put("statuses", JSONArray().apply {
|
||||
for (s in pack.statuses) {
|
||||
put(JSONObject()
|
||||
.put("name", s.name).put("type", s.kind).put("turns", s.turns)
|
||||
.put("max_stack", s.maxStack).put("script", s.script))
|
||||
}
|
||||
})
|
||||
return o
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = "规则包编辑",
|
||||
subtitle = "${pack.stats.size} 条数值 · ${pack.statuses.size} 条状态 · ${scripts.size} 个脚本",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("保存") { vm.saveRulePack(name, note, infoJson(), scripts) }
|
||||
},
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("名称", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
OutlinedTextField(
|
||||
value = note,
|
||||
onValueChange = { note = it },
|
||||
label = { Text("说明", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
)
|
||||
|
||||
// ---------------- 脚本(可编辑)----------------
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("脚本")
|
||||
if (vm.editingRulePack?.hasScripts != true) {
|
||||
Hint("这个包还没有脚本。数值的裁决、状态的每轮行为、赋予判定都靠脚本。")
|
||||
}
|
||||
Card {
|
||||
for ((fname, src) in scripts) {
|
||||
if (editing == fname) {
|
||||
Text(fname, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
CodeBox(value = draft, onValueChange = { draft = it })
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("保存这段") {
|
||||
scripts = scripts + (fname to draft)
|
||||
editing = ""
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("取消") { editing = "" }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("删掉") {
|
||||
scripts = scripts - fname
|
||||
editing = ""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(fname, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
"${src.lines().size} 行 · 点开编辑",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("编辑") { editing = fname; draft = src }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
// 新建一段
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = newScript,
|
||||
onValueChange = { newScript = it },
|
||||
label = { Text("新脚本文件名", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("新建") {
|
||||
val f = newScript.trim()
|
||||
if (f.isNotBlank() && !scripts.containsKey(f)) {
|
||||
scripts = scripts + (f to SCRIPT_TEMPLATE)
|
||||
newScript = ""
|
||||
editing = f
|
||||
draft = SCRIPT_TEMPLATE
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 定义(只读)----------------
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("数值定义")
|
||||
Card {
|
||||
if (pack.stats.isEmpty()) Hint("没有数值。")
|
||||
for (s in pack.stats) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"${fmt(s.min)} ~ ${fmt(s.max)}" + if (s.shared) " · 全世界观共用" else "",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.ranges.isNotEmpty()) {
|
||||
Text(
|
||||
"${s.ranges.size} 段区间:" + s.ranges.joinToString("、") {
|
||||
"${fmt(it.min)}~${fmt(it.max)}「${it.text.take(10)}」"
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.script.isNotBlank()) {
|
||||
Text("裁决脚本:${s.script}", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态定义")
|
||||
Card {
|
||||
if (pack.statuses.isEmpty()) Hint("没有状态。")
|
||||
for (s in pack.statuses) {
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
(if (s.isPersistent) "持久" else "定时 ${s.turns} 轮") +
|
||||
(if (s.maxStack > 1) " · 最多叠 ${s.maxStack} 层" else ""),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Hint(
|
||||
"定义(数值和状态的增删、区间表)这一版还是只读的 —— " +
|
||||
"用「导出」在电脑上改 info.json 再导入是最快的办法。" +
|
||||
"界面上能改的是脚本,那也是最常改的部分。",
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** 新建脚本时给的骨架(三个入口都列出来,用户知道可以写什么) */
|
||||
private const val SCRIPT_TEMPLATE = """# 可用的三个入口(写哪个都行,不写的就不执行):
|
||||
|
||||
def on_stat_change(name, value, delta):
|
||||
# 数值裁决:返回生效的增量(可以放大、缩小、返回 0 否决)
|
||||
return delta
|
||||
|
||||
|
||||
def on_turn(self_agent, stats_api):
|
||||
# 每轮生成回复之前跑一次(状态脚本)
|
||||
# stats_api['change_stat']('好感度', -1)
|
||||
# stats_api['set_hint']('中毒', '你眼前发黑')
|
||||
# stats_api['narrate']('毒性发作了')
|
||||
return True
|
||||
|
||||
|
||||
def on_grant(status_name, source_agent):
|
||||
# 别人要给你挂状态时,返回 False 就是抵抗掉
|
||||
return True
|
||||
"""
|
||||
|
||||
/**
|
||||
* 代码框:**不软换行** + **有高度上限**。
|
||||
*
|
||||
* ★ 不软换行:` else:` 折成两行、缩进全乱,而 Python 的缩进就是语法。
|
||||
* 做法是"把输入框塞进足够宽的横向滚动容器"(这个 Compose 版本的
|
||||
* `BasicTextField` 经典重载选不中,见 AGENTS.md)。
|
||||
*
|
||||
* ★ 高度上限:只写 `heightIn(min=...)` 的话脚本一长框就长到屏幕外,
|
||||
* 把底下的东西顶出去,用户够不着。
|
||||
*/
|
||||
@Composable
|
||||
private fun CodeBox(value: String, onValueChange: (String) -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp, max = 320.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState())) {
|
||||
BasicTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
textStyle = TextStyle(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoText(),
|
||||
),
|
||||
modifier = Modifier.width(900.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -495,7 +495,76 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
FormHint("当前发现 Python 工具 ${vm.state.tools.size} 个 · MCP 工具 ${vm.state.mcp.sumOf { it.toolCount }} 个(在「技能·连接器」里看明细)")
|
||||
}
|
||||
|
||||
/* ---------------- 超时 ---------------- */
|
||||
// ★ 这一页**不在这个「保存设置」里** —— 超时有自己的接口
|
||||
// (/api/timeouts)和自己的全屏界面,改一项立刻生效。
|
||||
// 混进"本地草稿 + 一次性保存"反而会让用户以为要按保存。
|
||||
SettingsCard("超时") {
|
||||
NavRow(
|
||||
label = "超时设置",
|
||||
value = if (vm.timeouts.items.isEmpty()) "" else "${vm.timeouts.items.size} 项",
|
||||
onClick = { vm.openTimeouts() },
|
||||
)
|
||||
FormHint(
|
||||
"模型回复、工具执行、命令、MCP、语音、等用户回答……所有超时都能在这里调。" +
|
||||
"「等用户回答」默认是不限时。",
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 个人资料 ---------------- */
|
||||
// 外观(v1.2 §6.1)
|
||||
SettingsCard("外观") {
|
||||
FormSwitch(
|
||||
title = "背景跟随说话者",
|
||||
sub = "群聊时,展示区的立绘和背景跟着当前发言的人换 —— " +
|
||||
"一眼就能看出这句话是谁说的。关掉的话固定用主智能体的。",
|
||||
checked = vm.state.settings.followSpeaker,
|
||||
onChange = { vm.setFollowSpeaker(it) },
|
||||
)
|
||||
}
|
||||
|
||||
// 对话(v1.2 §3.9 / §4.3)
|
||||
//
|
||||
// ★★ 这几个数字内核早就有、界面一直缺着 —— 用户只能手改 settings.json。
|
||||
// 而它们**都要和内核的默认值一致**,不然界面显示"20"而内核按别的跑。
|
||||
SettingsCard("对话") {
|
||||
NumberRow(
|
||||
title = "对话上下文窗口",
|
||||
sub = "每轮最多带最近多少轮对话进模型。超出的直接丢掉(不摘要)—— " +
|
||||
"该记住的走记忆系统。攒够几轮才裁一次,见下一项。",
|
||||
value = vm.state.settings.contextWindow,
|
||||
onChange = { vm.setContextWindow(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
NumberRow(
|
||||
title = "攒够几轮裁一次",
|
||||
sub = "不是「超一点就裁」,而是攒够这个数才裁一批 —— " +
|
||||
"每轮都裁的话前缀缓存每轮都失效,比多带几轮贵得多。",
|
||||
value = vm.state.settings.contextBatch,
|
||||
onChange = { vm.setContextBatch(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
NumberRow(
|
||||
title = "私聊最多几轮",
|
||||
sub = "两个智能体后台对聊时的上限(一轮 = 双方各说一次)。" +
|
||||
"这是安全网 —— 它们没有「该结束了」的内在信号。",
|
||||
value = vm.state.settings.privateChatRounds,
|
||||
onChange = { vm.setPrivateChatRounds(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★★ 用户要求:「talk_to 是用户可以选择传递和停止,有自动模式
|
||||
// (不用用户确认)」—— 所以默认是**手动**(关),
|
||||
// 群聊里 AI 交了话就停下来等你点;开了这个才是自动接着跑。
|
||||
FormSwitch(
|
||||
title = "AI 对聊自动模式",
|
||||
sub = "关(默认):群里 AI 把话交给别人时,底下会出现" +
|
||||
"「让他说 / 停在这」两个按钮,由你决定要不要接着聊。" +
|
||||
"开:不用确认,自动一轮轮接着跑(最多几轮)。",
|
||||
checked = vm.state.settings.aiTalkAuto,
|
||||
onChange = { vm.setAiTalkAuto(it) },
|
||||
)
|
||||
}
|
||||
|
||||
SettingsCard("个人资料") {
|
||||
FormLabel("昵称")
|
||||
FormField(
|
||||
@@ -1254,3 +1323,41 @@ private fun secretOrNull(raw: String): String? {
|
||||
if (v.all { it == '•' }) return null
|
||||
return v
|
||||
}
|
||||
|
||||
/**
|
||||
* 一行数字设置(v1.2 的上下文窗口 / 裁剪批量 / 私聊轮数)。
|
||||
*
|
||||
* ★ 独立一个组件而不是塞三个 `OutlinedTextField`:它们长得一样、
|
||||
* 行为也一样(只收数字、失焦/改完就存),抄三遍迟早有一处不一样。
|
||||
*/
|
||||
@Composable
|
||||
private fun NumberRow(
|
||||
title: String,
|
||||
sub: String,
|
||||
value: Int,
|
||||
onChange: (Int) -> Unit,
|
||||
) {
|
||||
var draft by remember(value) { mutableStateOf(value.toString()) }
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(title, fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { s ->
|
||||
val digits = s.filter { it.isDigit() }.take(4)
|
||||
draft = digits
|
||||
digits.toIntOrNull()?.takeIf { it > 0 }?.let(onChange)
|
||||
},
|
||||
singleLine = true,
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
|
||||
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number,
|
||||
),
|
||||
modifier = Modifier.width(100.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(sub, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -72,6 +73,12 @@ fun SkillsScreen(vm: AppViewModel) {
|
||||
var mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) }
|
||||
var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) }
|
||||
|
||||
// AI 界面能力的开关。改一下立刻存 —— 这个开关不需要"应用"按钮,
|
||||
// 用户拨完就想生效(跟下面的权限白名单不一样,那个要挑一堆再一起提交)。
|
||||
var uiToolsOn by remember(vm.settings.uiToolsEnabled) {
|
||||
mutableStateOf(vm.settings.uiToolsEnabled)
|
||||
}
|
||||
|
||||
var runTarget by remember { mutableStateOf<PythonTool?>(null) }
|
||||
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
val toolResults = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
@@ -105,6 +112,50 @@ fun SkillsScreen(vm: AppViewModel) {
|
||||
) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
|
||||
/* ============ ⓪ AI 界面能力(show_ui / ask_user / end_conversation)============
|
||||
*
|
||||
* 为什么单独一个卡片、而且默认关:这三个工具会让 AI **主动往用户脸上
|
||||
* 弹东西**(HTML 界面、选择弹窗),甚至**把对话封掉** ——
|
||||
* 属于"打扰性"能力,不该装好就默认打开。
|
||||
*/
|
||||
SettingsCard("AI 界面能力") {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("允许 AI 弹出界面和弹窗", fontSize = 15.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"打开后 AI 才能用这三个工具。关掉时它们对模型完全隐藏。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 17.sp,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = uiToolsOn,
|
||||
onCheckedChange = {
|
||||
uiToolsOn = it
|
||||
vm.saveUiTools(it)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormHint(
|
||||
"· show_ui —— AI 自己写 HTML 弹一个全屏界面(图表、卡片、对比表)\n" +
|
||||
"· ask_user —— 弹一个选择框,等用户选完再继续(最多 120 秒)\n" +
|
||||
"· end_conversation —— AI 永久结束这次对话。屏幕中间会出现一条" +
|
||||
"写着原因的横幅,之后要开新对话才能继续",
|
||||
)
|
||||
if (!uiToolsOn) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"当前:关闭(模型看不到这三个工具)",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== ① 工具权限 ==================== */
|
||||
SettingsCard("工具权限") {
|
||||
SegmentedOptions(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
@@ -19,9 +20,13 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.core.view.doOnLayout
|
||||
import com.doubao.lynxclone.termux.TermuxInstaller
|
||||
import com.doubao.lynxclone.termux.TermuxTerminal
|
||||
import com.termux.view.TerminalView
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
@@ -43,19 +48,104 @@ fun TerminalScreen(
|
||||
val context = LocalContext.current
|
||||
val terminal = remember { TermuxTerminal(context) }
|
||||
var title by remember { mutableStateOf("termux") }
|
||||
/** pty 起不来(有些 ROM 的 /dev/pts 不给应用用)时切成命令控制台 */
|
||||
/**
|
||||
* pty 起不来(有些 ROM 的 /dev/pts 不给应用用)时切成命令控制台。
|
||||
*
|
||||
* ★ 这里**不再静默切换**:以前一旦判定失败就直接换成"命令框",
|
||||
* 用户只看到"怎么不是终端",完全不知道发生了什么(真踩过)。
|
||||
* 现在会**明说原因**并给"重试",终端仍然是主界面。
|
||||
*/
|
||||
var ptyFailed by remember { mutableStateOf(false) }
|
||||
var failReason by remember { mutableStateOf("") }
|
||||
var startedAt by remember { mutableStateOf(0L) }
|
||||
var showMirror by remember { mutableStateOf(false) }
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { terminal.destroy() }
|
||||
}
|
||||
|
||||
// pty 不可用的判定:会话建起来后 2 秒内就结束,说明 bash 拿不到 tty(stdin 直接 EOF)
|
||||
// 换源是独立全屏界面(源列表 + 说明装不进弹窗)
|
||||
if (showMirror) {
|
||||
MirrorScreen(onBack = { showMirror = false })
|
||||
return
|
||||
}
|
||||
|
||||
// pty 不可用的判定:会话建起来后很快就结束,说明 shell 拿不到 tty(stdin 直接 EOF)。
|
||||
//
|
||||
// ★ 要**连续两次**都秒退才认输。一次秒退可能是别的原因
|
||||
// (比如用户手滑按了 Ctrl+D 把 shell 退了),
|
||||
// 直接切到命令框会让"终端一闪就变成命令框",比不切还懵。
|
||||
var fastExits by remember { mutableStateOf(0) }
|
||||
/** 换起法之后要 +1,让 AndroidView 的 update 重新跑一遍去 attach 新会话 */
|
||||
var sessionTick by remember { mutableStateOf(0) }
|
||||
|
||||
// ★ 必须**在这里读一下** sessionTick。
|
||||
// Compose 只跟踪「组合期间读过」的状态:只在 update 那个 lambda 里读不算
|
||||
// (lambda 是布局阶段才跑的),于是 sessionTick 变了也不重组、update 不重跑、
|
||||
// 换了起法之后新会话**永远接不上** —— 表现是"屏幕停在旧会话的
|
||||
// [Process completed],打字没反应"。(真踩到了:修语法时把 key() 去掉,订阅也丢了。)
|
||||
val tickNow = sessionTick
|
||||
|
||||
/**
|
||||
* 重置 Termux 环境。
|
||||
*
|
||||
* ★ 为什么需要:装坏了自己救不回来。dpkg 的数据库和真实文件一旦不一致
|
||||
* (比如在修好 apt 路径之前试着装过包),后面 `pkg install` 会一直报
|
||||
* `E: Internal Error, No file name for ...` 或 `1 not fully installed or removed`,
|
||||
* **用户在界面上没有任何办法恢复**,只能清 App 数据 —— 那会把会议、设置、
|
||||
* 自定义节点全丢掉。有了这个,重置的代价只是"重下一次运行环境"。
|
||||
*
|
||||
* 删的是 `files/usr` + `files/home`;**不碰** kernel-data 和 nodes。
|
||||
*/
|
||||
var showResetConfirm by remember { mutableStateOf(false) }
|
||||
var resetting by remember { mutableStateOf(false) }
|
||||
var resetMsg by remember { mutableStateOf("") }
|
||||
|
||||
/**
|
||||
* 真 Termux 冲突(见下面横幅的注释)。
|
||||
*
|
||||
* ★ 为什么放在 `LaunchedEffect` 里而不是直接在组合里算:
|
||||
* 这个判断要**起一个进程跑 `dpkg --version`**,直接在组合里做会
|
||||
* 每帧跑一次。它是 IO,必须挪到副作用里,而且只查一次。
|
||||
*/
|
||||
var realTermuxConflict by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(termuxReady) {
|
||||
if (termuxReady) {
|
||||
realTermuxConflict = withContext(Dispatchers.IO) {
|
||||
runCatching { TermuxInstaller.hasRealTermuxConflict(context) }
|
||||
.getOrDefault(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
val onSessionExit = {
|
||||
if (startedAt > 0 && System.currentTimeMillis() - startedAt < 2000) {
|
||||
ptyFailed = true
|
||||
TermuxInstaller.trace(context, "pty 不可用(会话秒退),切换到命令控制台")
|
||||
val quick = startedAt > 0 && System.currentTimeMillis() - startedAt < 900
|
||||
if (quick) {
|
||||
fastExits += 1
|
||||
TermuxInstaller.trace(context, "会话秒退(第 $fastExits 次)")
|
||||
// ★ 秒退 → **换下一种起法**。
|
||||
//
|
||||
// 关键:bash 起不来这件事**不会抛异常**(构造函数成功、rc 也跑了,
|
||||
// 然后 stdin EOF 就退出)。所以回退只能靠"退出得太快"这个事件驱动,
|
||||
// 不能靠 try/catch。试完所有起法才认输切命令控制台。
|
||||
val next = try {
|
||||
terminal.tryNextCandidate(onTitle = { title = it }, onExit = { })
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
if (next != null) {
|
||||
startedAt = System.currentTimeMillis()
|
||||
sessionTick += 1 // 触发 AndroidView update 去 attach 新会话
|
||||
TermuxInstaller.trace(context, "已切到:${terminal.startedWith}")
|
||||
// ★ 起法全试完 → **立刻**切命令控制台。之前要求"连续两次秒退",
|
||||
// 但候选有四种,全试完要好几秒,这期间屏幕是**全黑的**(上一种会话的画面
|
||||
// 刚被清掉、新的又没起来)—— 用户看到的就是"卡住了"。宁可切早点。
|
||||
} else {
|
||||
ptyFailed = true
|
||||
failReason = "几种起法都试过了,shell 一起来就退出(拿不到 tty)。"
|
||||
TermuxInstaller.trace(context, "pty 不可用,切成命令控制台:$failReason")
|
||||
}
|
||||
} else {
|
||||
fastExits = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +160,51 @@ fun TerminalScreen(
|
||||
}
|
||||
Text(title, color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 换源:国内用官方源基本装不了东西,这是最常用的一个入口
|
||||
TextButton(onClick = { showMirror = true }) {
|
||||
Text("源", color = Color(0xFF9BE7B4), fontSize = 13.sp)
|
||||
}
|
||||
// 重置环境:装坏了(dpkg 数据库和文件不一致)时的唯一自救入口。
|
||||
// 放在换源旁边 —— 出问题时这两个是最先要点的。
|
||||
TextButton(onClick = { showResetConfirm = true }) {
|
||||
Text("重置", color = Color(0xFFFFB4A9), fontSize = 13.sp)
|
||||
}
|
||||
|
||||
// ---------------- 重置确认 + 进度 ----------------
|
||||
if (showResetConfirm) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showResetConfirm = false },
|
||||
title = { Text("重置 Termux 环境?") },
|
||||
text = {
|
||||
Text(
|
||||
"会把内置运行环境(约 95MB)删掉重新解压。\n\n" +
|
||||
"什么时候需要:pkg install 报 Internal Error、\n" +
|
||||
"not fully installed,或者终端起不来又查不出原因。\n\n" +
|
||||
"**会议、设置、智能体、自定义节点都不会动**," +
|
||||
"只有装在 Termux 里的包(python 之类)会没。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showResetConfirm = false
|
||||
resetting = true
|
||||
resetMsg = "正在准备…"
|
||||
Thread {
|
||||
val ok = TermuxInstaller.reset(context) { msg ->
|
||||
resetMsg = msg
|
||||
}
|
||||
resetting = false
|
||||
resetMsg = if (ok) "重置完成,重新打开终端即可" else "重置失败,看看 termux-install.log"
|
||||
}.start()
|
||||
}) { Text("重置", color = Color(0xFFD93025)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showResetConfirm = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
IconButton(onClick = {
|
||||
// 发一个 Ctrl+C,终止前台进程(手机上没键盘,这是最常用的逃生键)
|
||||
terminal.session?.write("\u0003".toByteArray(), 0, 1)
|
||||
@@ -99,7 +234,7 @@ fun TerminalScreen(
|
||||
Surface(color = Color(0xFF16301F), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"Termux 已内置 · ${TermuxInstaller.prefix(context).absolutePath}\n" +
|
||||
"试试点上面的 + 装东西:pkg install python nodejs-lts",
|
||||
"装东西前先换源(右上角「源」),官方源国内连不上",
|
||||
color = Color(0xFF9BE7B4),
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
@@ -108,9 +243,68 @@ fun TerminalScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 真 Termux 的检测结果 —— v2.0.33 起**不再提示卸载**。
|
||||
*
|
||||
* 以前这里是一条红色横幅,让用户去卸载真 Termux,因为
|
||||
* Termux 仓库里的 dpkg 有个**编译死的配置目录**:
|
||||
*
|
||||
* dpkg: error: error opening configuration directory
|
||||
* "/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d": Permission denied
|
||||
*
|
||||
* 那个目录"不存在"dpkg 会跳过、"存在但打不开"就直接死,
|
||||
* 而两个 App 同时装着就必然是后者 —— 从应用这侧无解。
|
||||
*
|
||||
* **现在从根上修掉了**:装的是我们自编的 dpkg,配置目录改成
|
||||
* 运行时从 `/proc/self/exe` 反推,指向自己所在的前缀。
|
||||
* 所以真 Termux 在不在场都无所谓,横幅也就没必要了。
|
||||
*
|
||||
* 配方见 `android/termux-dpkg/README.md`。
|
||||
* 安装逻辑在 `TermuxInstaller.installOwnDpkg`。
|
||||
*
|
||||
* ★ 这里不再渲染任何界面 —— 只在日志里记一笔,方便排查。
|
||||
* 保留这个变量和检测(`hasRealTermuxConflict`)是因为
|
||||
* 万一自编 dpkg 没装成功(比如 jniLibs 里那份坏了),
|
||||
* 日志里能看到"真 Termux 在场",好定位。
|
||||
*/
|
||||
LaunchedEffect(termuxReady, realTermuxConflict) {
|
||||
if (termuxReady && realTermuxConflict) {
|
||||
Log.i("DoubaoTerminal", "检测到真 Termux 在场 —— v2.0.33 起不影响使用(自编 dpkg)")
|
||||
}
|
||||
}
|
||||
|
||||
// ★ pty 失败要**明说**,别让用户以为"这软件就只有命令框"
|
||||
if (termuxReady && ptyFailed) {
|
||||
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(
|
||||
"真终端起不来:$failReason\n" +
|
||||
"下面先用命令控制台顶着(同一条 Termux bash,只是没有 tty," +
|
||||
"所以 vim/top 这类全屏程序不能用)。",
|
||||
color = Color(0xFFFFD08A),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
TextButton(onClick = {
|
||||
ptyFailed = false
|
||||
failReason = ""
|
||||
startedAt = 0
|
||||
terminal.destroy()
|
||||
}) { Text("重试真终端") }
|
||||
TextButton(onClick = { showMirror = true }) { Text("换软件源") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 终端本体 ----------------
|
||||
if (termuxReady && ptyFailed) {
|
||||
// pty 用不了 → 命令控制台(跑的是同一条 Termux bash,只是没有 tty)
|
||||
//
|
||||
// ★ 上面那条橙色横幅会说明原因 + 给"重试真终端",
|
||||
// 不能让用户莫名其妙地从终端变成命令框。
|
||||
Box(Modifier.weight(1f).fillMaxWidth().background(Color(0xFF14161A))) {
|
||||
CommandConsole(
|
||||
onRun = { command, done ->
|
||||
@@ -130,17 +324,54 @@ fun TerminalScreen(
|
||||
setTextSize(28)
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
// ★ 把 view 交给会话:`onTextChanged` 要靠它调 `onScreenUpdated()`
|
||||
// 去重画。不接的话屏幕永远不动 —— pty 通了、bash 活着、
|
||||
// 输出也解析了,**但一个像素都不刷新**(这个坑刚踩到)。
|
||||
terminal.view = this
|
||||
// ★ 点一下就弹软键盘。
|
||||
//
|
||||
// 之前 `onSingleTapUp` 里是一句空代码(`(e.source)`),
|
||||
// 点了什么都不会发生 —— 用户的原话是"输入不了"。
|
||||
// TerminalView 是普通 View,直接请求焦点 + 叫输入法就行。
|
||||
setOnClickListener {
|
||||
requestFocus()
|
||||
val imm = ctx.getSystemService(Context.INPUT_METHOD_SERVICE)
|
||||
as? android.view.inputmethod.InputMethodManager
|
||||
imm?.showSoftInput(this, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
},
|
||||
update = { view ->
|
||||
// 读一下 tickNow:它变了说明换过起法,这次 update 要把新会话接上
|
||||
@Suppress("UNUSED_EXPRESSION") tickNow
|
||||
try {
|
||||
val session = terminal.session ?: run {
|
||||
startedAt = System.currentTimeMillis()
|
||||
terminal.createSession(onTitle = { title = it }, onExit = onSessionExit)
|
||||
}
|
||||
if (view.currentSession !== session) {
|
||||
view.attachSession(session)
|
||||
view.requestFocus()
|
||||
// ★★ attach **必须等布局完成**。
|
||||
//
|
||||
// Termux 的 `TerminalSession` 构造函数**只存字段、不启动子进程**:
|
||||
// 子进程是在 `initializeEmulator(columns, rows, ...)` 里调
|
||||
// `JNI.createSubprocess(...)` 建的,而它由 `TerminalView.attachSession()`
|
||||
// 触发(内部拿 view 的宽高算行列数)。
|
||||
//
|
||||
// 在 `AndroidView.update` 里直接 attach 时 view 往往还没量过尺寸,
|
||||
// 于是 rows/columns = 0 → pty 建成 **0 列** →
|
||||
// shell 一起来就结束(退出码 0、几十毫秒),屏幕只剩 [Process completed]。
|
||||
// **这就是那个找了很久的"pty 拿不到 tty"。**
|
||||
//
|
||||
// doOnLayout 保证"量过了再 attach"。
|
||||
val doAttach = Runnable {
|
||||
view.attachSession(session)
|
||||
view.requestFocus()
|
||||
}
|
||||
if (view.width > 0 && view.height > 0) {
|
||||
doAttach.run()
|
||||
} else {
|
||||
view.doOnLayout { doAttach.run() }
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
title = "会话启动失败:${t.message}"
|
||||
@@ -171,6 +402,18 @@ fun TerminalScreen(
|
||||
) {
|
||||
data class Key(val label: String, val bytes: String)
|
||||
val keys = listOf(
|
||||
// ★★ ENTER 放**第一个**,而且必须发 `\r`(CR)不是 `\n`(LF)。
|
||||
//
|
||||
// 终端里的"回车"是 **CR**:行规程(line discipline)靠 `\r`
|
||||
// 判定"这一行输入完了"。发 `\n` 的话光标会往下走一格,
|
||||
// 但**命令不会执行** —— 用户的原话就是"回车不了"。
|
||||
//
|
||||
// (Termux 自己的 TerminalView 也把输入法的回车转成 `\r`,
|
||||
// 见 TerminalView.java:401。)
|
||||
//
|
||||
// 另外它原来排在最后,被横向滚动**顶出屏幕**了,等于没有。
|
||||
// 回车是终端里按得最多的键,必须第一眼就能看到。
|
||||
Key("ENTER", "\r"),
|
||||
Key("ESC", "\u001b"),
|
||||
Key("TAB", "\t"),
|
||||
Key("CTRL+C", "\u0003"),
|
||||
@@ -184,7 +427,6 @@ fun TerminalScreen(
|
||||
Key("|", "|"),
|
||||
Key("/", "/"),
|
||||
Key("-", "-"),
|
||||
Key("ENTER", "\n"),
|
||||
)
|
||||
keys.forEach { key ->
|
||||
Surface(
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.TimeoutItem
|
||||
import com.doubao.lynxclone.data.TimeoutsState
|
||||
|
||||
/*
|
||||
* 「设置 → 超时」:所有超时都能在这儿调。
|
||||
*
|
||||
* ## 为什么做成全屏界面而不是弹窗
|
||||
*
|
||||
* 见 AGENTS.md「少用弹窗,能开界面就开界面」—— 这里有 17 项、每项还带两三行说明,
|
||||
* 弹窗装不下(用户得在一个半屏高的框里滚十几屏)。
|
||||
*
|
||||
* ## ★★ 这一页**没有硬编码任何一项**
|
||||
*
|
||||
* 有哪些超时、叫什么、默认多少、能填多大、说明写什么 —— 全部来自内核
|
||||
* (`GET /api/timeouts` ← `android/kernel/timeouts.py` 的 SPECS)。
|
||||
*
|
||||
* 这么做的理由不是"架构好看",而是这个东西以前正是**反面教材**:
|
||||
* 15 个超时散在 10 个文件里当模块级常量,加一个超时要改好几处,
|
||||
* 而"到底有几个超时"这个问题谁都答不上来。现在加一项只改内核那一个文件,
|
||||
* 这一页自动多出一行。
|
||||
*
|
||||
* ## 怎么算保存
|
||||
*
|
||||
* 不做"保存按钮":点 +/- 立刻存,输入框失焦时存。
|
||||
* 每个改动都只发**改的那一项**(内核会并到当前值上),所以两项之间不会互相覆盖。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun TimeoutsScreen(
|
||||
state: TimeoutsState,
|
||||
saving: Boolean,
|
||||
/** 只传改过的那一项 */
|
||||
onSave: (Map<String, Double>) -> Unit,
|
||||
onReset: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
FullScreen(
|
||||
title = "超时",
|
||||
subtitle = if (saving) "保存中…" else "改完立刻生效,不用重启",
|
||||
onBack = onBack,
|
||||
actions = { TopTextAction("恢复默认", onClick = onReset) },
|
||||
) {
|
||||
if (state.items.isEmpty()) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
if (state.error.isBlank()) "正在从内核读取…" else state.error,
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
for ((group, items) in state.groups) {
|
||||
SectionLabel(group)
|
||||
for (item in items) {
|
||||
TimeoutRow(item = item, onSave = onSave)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"说明:这些值的边界由内核把关(填超了会自动夹回去)。" +
|
||||
"「不限时」表示会一直等,不会自己放弃。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TimeoutRow(item: TimeoutItem, onSave: (Map<String, Double>) -> Unit) {
|
||||
// 输入框里的**草稿**(用户可能正在打字,这时候不能立刻拿它去保存,
|
||||
// 否则打到一半的 "18" 会被当成 18 存进去)
|
||||
var draft by remember(item.key) { mutableStateOf(fmt(item.value)) }
|
||||
var editing by remember(item.key) { mutableStateOf(false) }
|
||||
|
||||
// 值被外部改掉时(保存回来 / 恢复默认)同步草稿,但**别打断正在输入的人**
|
||||
if (!editing && draft != fmt(item.value)) draft = fmt(item.value)
|
||||
|
||||
val step = stepOf(item)
|
||||
|
||||
fun commit(raw: String) {
|
||||
val v = raw.trim().toDoubleOrNull() ?: item.value
|
||||
val clamped = v.coerceIn(item.min, item.max)
|
||||
draft = fmt(clamped)
|
||||
if (kotlin.math.abs(clamped - item.value) > 0.001) {
|
||||
onSave(mapOf(item.key to clamped))
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(item.label, fontSize = 14.sp, color = doubaoText())
|
||||
if (item.isDefault) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("默认", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StepButton("−") {
|
||||
val next = (item.value - step).coerceAtLeast(item.min)
|
||||
draft = fmt(next)
|
||||
onSave(mapOf(item.key to next))
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { draft = it.filter { c -> c.isDigit() || c == '.' } },
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier
|
||||
.width(78.dp)
|
||||
.height(48.dp)
|
||||
.onFocusChanged { st ->
|
||||
if (st.isFocused) {
|
||||
editing = true
|
||||
} else if (editing) {
|
||||
editing = false
|
||||
commit(draft)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
StepButton("+") {
|
||||
val next = (item.value + step).coerceAtMost(item.max)
|
||||
draft = fmt(next)
|
||||
onSave(mapOf(item.key to next))
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
// 0 且允许 0 时显示"不限时",比"0 秒"清楚得多
|
||||
if (item.unlimited) "${item.zero} (${item.unit})"
|
||||
else "单位:${item.unit} 范围 ${fmt(item.min)}–${fmt(item.max)}",
|
||||
fontSize = 10.sp,
|
||||
color = if (item.unlimited) Doubao.Blue else doubaoTextSecondary(),
|
||||
fontWeight = if (item.unlimited) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
if (item.desc.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(item.desc, fontSize = 11.sp, lineHeight = 17.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepButton(label: String, onClick: () -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 4.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(label, fontSize = 16.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
|
||||
/** 整秒显示,别出现 "180.0" */
|
||||
private fun fmt(v: Double): String =
|
||||
if (kotlin.math.abs(v - v.toInt()) < 0.001) v.toInt().toString() else v.toString()
|
||||
|
||||
/** 步长跟着量级走:5 秒的东西一次加 60 太难用,1800 秒的东西一次加 5 是折磨 */
|
||||
private fun stepOf(item: TimeoutItem): Double = when {
|
||||
item.max <= 60 -> 5.0
|
||||
item.max <= 300 -> 10.0
|
||||
item.max <= 900 -> 30.0
|
||||
else -> 60.0
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.TokenUsage
|
||||
|
||||
/*
|
||||
* Token 用量详情(需求 3.1 的展示入口:选择界面「更多」按钮)。
|
||||
*
|
||||
* ## 展示什么
|
||||
*
|
||||
* · 累计用量(**输入 / 输出分列**,需求明确要求不合并)
|
||||
* · 限额进度(没限额就显示"无限制")
|
||||
* · **按模型分行**(需求 3.1 的"按模型分桶",可看总数也可展开)
|
||||
* · 配了单价才显示估算费用 —— 没配就只显示 Token 数,不瞎估
|
||||
*
|
||||
* ## 不做历史曲线
|
||||
*
|
||||
* 需求原话"当前不做曲线"(时间戳只是为将来预留)。
|
||||
*
|
||||
* ## 做全屏而不是弹窗
|
||||
*
|
||||
* 见 AGENTS.md「少用弹窗」。这里要放三四行数字 + 一张可能十几行的模型表,
|
||||
* 弹窗装不下。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun TokenUsageScreen(
|
||||
usage: TokenUsage?,
|
||||
onReset: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
// ★ 清零是不可逆的(历史消耗数就没了),给它一次确认(复查报告 3.4)——
|
||||
// 这是"一次确认"的典型场景,弹窗正合适(AGENTS.md 那张表)
|
||||
var confirmReset by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "用量",
|
||||
subtitle = usage?.name?.takeIf { it.isNotBlank() }?.let { "$it · 累计" } ?: "正在读取…",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (usage != null && usage.total > 0) {
|
||||
TopTextAction("清零", danger = true) { confirmReset = true }
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (usage == null) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Text("正在读取…", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
// ---- 总览 ----
|
||||
Card {
|
||||
Text("累计消耗", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
fmtTokens(usage.total),
|
||||
fontSize = 30.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row {
|
||||
Metric("输入", usage.input)
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("输出", usage.output)
|
||||
}
|
||||
// ★ 缓存统计(v1.2):**这家没给就不显示**。
|
||||
// 不是每家都返回缓存字段,显示两个恒为 0 的数会让用户
|
||||
// 以为"缓存完全没生效" —— 那是假警报,比不显示更糟。
|
||||
if (usage.hasCacheInfo) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row {
|
||||
Metric("缓存命中", usage.cacheHit)
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("缓存未命中", usage.cacheMiss)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"命中率 ${(usage.hitRate * 100).toInt()}% —— " +
|
||||
"命中缓存的输入便宜得多,这一段没白存",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
if (usage.pricePerK > 0 && usage.cost != null) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"估算费用 ¥${"%.2f".format(usage.cost)}(按 ¥${usage.pricePerK}/千 Token)",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 限额 ----
|
||||
Card {
|
||||
if (usage.unlimited) {
|
||||
Text("额度:无限制", fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"想限制他?在「管理 → 编辑」里填一个 Token 上限就行。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
Text("额度", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(
|
||||
fmtTokens(usage.remaining ?: 0),
|
||||
fontSize = 22.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoText(),
|
||||
)
|
||||
Text(
|
||||
" / ${fmtTokens(usage.limit)} 剩余",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 3.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// 进度条自己画(项目没有 material 的 LinearProgressIndicator 用法先例,
|
||||
// 一条圆角 Box 更可控)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Border),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(usage.percent.toFloat().coerceIn(0f, 1f))
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(if (usage.percent >= 1f) Color(0xFFD93025) else Doubao.Blue),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
if (usage.percent >= 1f)
|
||||
"已经用完了 —— 下一轮会被拦住,并附一句告别。可以清零、调大限额或改成无限制。"
|
||||
else "用满之后会拦住发送(记忆整理这类操作不受影响)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 按模型分桶 ----
|
||||
Card {
|
||||
Text("按模型", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (usage.byModel.isEmpty()) {
|
||||
Text("还没用过", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
} else {
|
||||
for ((i, m) in usage.byModel.withIndex()) {
|
||||
if (i > 0) Spacer(Modifier.height(8.dp))
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
m.model,
|
||||
fontSize = 13.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"入 ${fmtTokens(m.input)} · 出 ${fmtTokens(m.output)}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
// ★ 缓存命中/未命中(v1.2)。**这家没给就不显示这一行** ——
|
||||
// 不是每家都返回缓存字段,显示一个恒为 0 的"命中率"
|
||||
// 会让用户以为"缓存完全没生效"(那是个假警报)
|
||||
if (m.hasCacheInfo) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
"命中 ${fmtTokens(m.cacheHit)} · 未命中 ${fmtTokens(m.cacheMiss)}" +
|
||||
" · 命中率 ${(m.hitRate * 100).toInt()}%",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmReset) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { confirmReset = false },
|
||||
title = { Text("清零用量", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"把「${usage?.name ?: ""}」的累计用量归零(当前 ${fmtTokens(usage?.total ?: 0)})。\n\n" +
|
||||
"这个数字回不来 —— 它是历史统计,不是「当前会话进度」。\n" +
|
||||
"清零之后额度也重新算,但它记得的东西、你们的对话都不受影响。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { confirmReset = false; onReset() },
|
||||
) { Text("清零") }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(onClick = { confirmReset = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 这里的私有 `Card` 删了 —— 它和 AgentEditScreen 的那个是**同一段代码**
|
||||
// 抄了两份(只有 vertical 内边距差 2dp)。现在统一用 DoubaoUi.kt 里的公共版。
|
||||
// 留着的话两个同签名函数都可见,编译器直接报"重载歧义"。
|
||||
|
||||
@Composable
|
||||
private fun Metric(label: String, value: Long) {
|
||||
Column {
|
||||
Text(label, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
Text(fmtTokens(value), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
}
|
||||
|
||||
/** 大数字加千分位:`12345` → `12,345`。Token 数动辄五六位,不加看不清量级 */
|
||||
fun fmtTokens(n: Long): String {
|
||||
val s = n.toString()
|
||||
if (s.length <= 3) return s
|
||||
val sb = StringBuilder()
|
||||
for ((i, c) in s.withIndex()) {
|
||||
if (i > 0 && (s.length - i) % 3 == 0) sb.append(',')
|
||||
sb.append(c)
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.TouchApp
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/**
|
||||
* ★★ 全屏看网页 —— 由一个**明确的按钮**打开,不靠去点正文里的小字。
|
||||
*
|
||||
* ## 为什么单独做这个界面
|
||||
*
|
||||
* 聊天气泡里的 markdown 链接做成蓝色下划线,**没有可发现性**:
|
||||
* 用户不知道它能点、也不知道点了会发生什么(是开浏览器?还是在应用里开?)。
|
||||
* 用户的原话是"你要单独开个按钮" —— 对,产品上正确的就是给个按钮。
|
||||
*
|
||||
* 所以:消息操作栏里出现一个「打开网页」按钮(只有回复里真有链接才出现),
|
||||
* 点开就是这里 —— 一个像样的浏览器界面,而不是把用户丢给系统浏览器
|
||||
* (那样他就离开 App 了,回来还得重新找对话)。
|
||||
*
|
||||
* ## 和 AI 那个 `show_ui` 界面的区别
|
||||
*
|
||||
* `show_ui` 是 **AI 写的 HTML**,我们注入内容、页面里只有它写的东西
|
||||
* 这里 是**真的在浏览互联网**,用户能点链接、能返回、能前进
|
||||
*
|
||||
* 两者都需要 JS,但**桥只有 `show_ui` 那边有** —— 这里浏览的是外部网站,
|
||||
* 绝不能让它碰到 App 的接口(所以这个 WebView 里没有任何
|
||||
* `addJavascriptInterface`)。
|
||||
*
|
||||
* ## 安全
|
||||
*
|
||||
* 文件访问 / 跨域访问 / 混合内容全部关闭。没有注入任何 JS 桥。
|
||||
* 这是"浏览器",就该按浏览器的方式隔离。
|
||||
*
|
||||
* ## 点选模式(把网页上的东西回传给 AI)
|
||||
*
|
||||
* 顶部有个「点选」按钮。打开之后页面上的可点元素会被描上虚线边框,
|
||||
* 用户点哪个就把哪个的**文字/链接/位置**记下来,出现在底部确认条上,
|
||||
* 用户点「发给 AI」才真的发出去(点错了不至于白跑一轮模型)。
|
||||
*
|
||||
* ★ 实现上**没有挂 JS 桥** —— 用的是"注入脚本写进数组 + Kotlin 主动轮询取走",
|
||||
* 数据只从页面流向 App。理由见 [WebPick] 的注释:这里浏览的是外部网站,
|
||||
* 挂桥等于把 App 的内部接口交给互联网上任意一个站点。
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
fun WebPageScreen(
|
||||
url: String,
|
||||
onClose: () -> Unit,
|
||||
onSendToAi: (String) -> Unit = {},
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var title by remember(url) { mutableStateOf("") }
|
||||
var canBack by remember { mutableStateOf(false) }
|
||||
var canFwd by remember { mutableStateOf(false) }
|
||||
var progress by remember { mutableStateOf(0) }
|
||||
|
||||
/** 点选模式开着没有 */
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
|
||||
/**
|
||||
* 用户选中/填写的条目(**累积**)。
|
||||
*
|
||||
* ★ 累积而不是点一条发一条:用户可能在页面上选好几处、填几个框,
|
||||
* 然后一起问"这些对不对"。分开发会触发好几轮模型调用,又慢又费 token。
|
||||
*/
|
||||
val picked = remember { mutableStateListOf<PickedElement>() }
|
||||
|
||||
// WebView 没有"导航状态变了"的回调,只能轮询。
|
||||
// 400ms 在真机上完全够用(页面前进后退是用户动作,不是动画)。
|
||||
LaunchedEffect(web) {
|
||||
while (web != null) {
|
||||
canBack = web?.canGoBack() == true
|
||||
canFwd = web?.canGoForward() == true
|
||||
delay(400)
|
||||
}
|
||||
}
|
||||
|
||||
// 点选模式下:每次加载完注入一次;然后每 500ms 取一次队列。
|
||||
//
|
||||
// ★ 为什么要"每次加载完注入":用户点链接跳到新页面(或页面自己跳),
|
||||
// 新文档里没有我们注入的脚本,不重注就没法点了。
|
||||
LaunchedEffect(web, picking) {
|
||||
if (!picking || web == null) {
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web?.evaluateJavascript(WebPick.INSTALL_JS, null)
|
||||
while (true) {
|
||||
delay(500)
|
||||
val w = web ?: break
|
||||
// evaluateJavascript 的返回值经 JSON 编码:脚本返回字符串 'xxx',
|
||||
// 这里拿到的是 "\"xxx\"" —— 所以要解两层
|
||||
w.evaluateJavascript(WebPick.DRAIN_JS) { raw ->
|
||||
val parsed = decodeJsonString(raw)
|
||||
if (parsed.isBlank() || parsed == "[]") return@evaluateJavascript
|
||||
runCatching {
|
||||
val arr = org.json.JSONArray(parsed)
|
||||
for (i in 0 until arr.length()) {
|
||||
val obj = arr.optJSONObject(i) ?: continue
|
||||
picked.add(
|
||||
PickedElement(
|
||||
summary = WebPick.describe(obj),
|
||||
kind = obj.optString("kind", "click"),
|
||||
url = obj.optString("url"),
|
||||
pageTitle = obj.optString("title").ifBlank { title },
|
||||
raw = obj.toString(),
|
||||
),
|
||||
)
|
||||
}
|
||||
// 只留最近 30 条,别让用户在页面上乱点把内存堆满
|
||||
while (picked.size > 30) picked.removeAt(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 系统返回键:先回退网页,退不了了才关界面
|
||||
BackHandler(enabled = true) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
/* ------------------------------ 顶部栏 ------------------------------ */
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 6.dp, end = 6.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
NavIcon(Icons.AutoMirrored.Filled.ArrowBack, "后退", canBack) { web?.goBack() }
|
||||
NavIcon(Icons.AutoMirrored.Filled.ArrowForward, "前进", canFwd) { web?.goForward() }
|
||||
NavIcon(Icons.Filled.Refresh, "刷新", true) { web?.reload() }
|
||||
|
||||
// 标题:能拿到网页 title 就用它,拿不到退回落 host ——
|
||||
// 只显示一长串 URL 在手机窄屏上没法看
|
||||
Column(Modifier.weight(1f).padding(horizontal = 4.dp)) {
|
||||
Text(
|
||||
title.ifBlank { hostOf(url) },
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (title.isNotBlank()) {
|
||||
Text(
|
||||
hostOf(url),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
NavIcon(Icons.Filled.OpenInNew, "用系统浏览器打开", true) {
|
||||
openInBrowser(ctx, web?.url ?: url)
|
||||
}
|
||||
NavIcon(Icons.Filled.Close, "关闭", true) { onClose() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 「点选」开关 —— 打开后能在网页上点东西回传给 AI。
|
||||
*
|
||||
* ★ 做成一条**常驻的横条**而不是顶部一个图标:
|
||||
* 这个能力不看说明根本发现不了(用户得先知道"能点选"才会去找按钮)。
|
||||
* 横条上写清楚现在是什么状态、点了会发生什么。
|
||||
*/
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(if (picking) doubaoAccentSoft() else doubaoCard())
|
||||
.clickable {
|
||||
if (picking) {
|
||||
web?.evaluateJavascript(WebPick.UNINSTALL_JS, null)
|
||||
picking = false
|
||||
picked.clear()
|
||||
} else {
|
||||
picking = true
|
||||
}
|
||||
}
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.TouchApp,
|
||||
null,
|
||||
tint = if (picking) doubaoAccent() else doubaoTextSecondary(),
|
||||
modifier = Modifier.size(17.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
if (picking) "点选已开启 —— 点网页上任意元素,内容会带回给 AI" else "点选:把网页上的内容带回给 AI",
|
||||
fontSize = 13.sp,
|
||||
color = if (picking) doubaoAccent() else doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
if (picking) "关闭" else "开启",
|
||||
fontSize = 13.sp,
|
||||
color = if (picking) doubaoAccent() else doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
// 加载进度:细一条,不占地方但能让人知道"在动"
|
||||
AnimatedVisibility(
|
||||
visible = progress in 1..99,
|
||||
enter = fadeIn(tween(120)),
|
||||
exit = fadeOut(tween(300)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(progress / 100f)
|
||||
.height(2.dp)
|
||||
.background(doubaoAccent()),
|
||||
)
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { c ->
|
||||
WebView(c).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true // 正常浏览器行为
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = true
|
||||
settings.builtInZoomControls = true
|
||||
settings.displayZoomControls = false
|
||||
settings.userAgentString = settings.userAgentString + " DoubaoClone"
|
||||
|
||||
// ★ 这个 WebView 里**不挂任何 JS 桥** ——
|
||||
// 浏览的是外部网站,绝不能让它碰到 App 的接口。
|
||||
// (点选回传走的是"页面写队列 + 我们主动 evaluateJavascript 取",
|
||||
// 数据单向,页面没有办法主动调 App。见 WebPick 的注释。)
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, u: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, u, favicon)
|
||||
progress = 5
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, u: String?) {
|
||||
super.onPageFinished(view, u)
|
||||
progress = 100
|
||||
title = view?.title.orEmpty()
|
||||
// ★ 用户点链接跳到新页面(或页面自己跳)之后,
|
||||
// 新文档里没有我们注入的脚本 —— 点选模式就失效了。
|
||||
// 所以每次加载完补注一次(脚本自己防重)。
|
||||
if (picking) view?.evaluateJavascript(WebPick.INSTALL_JS, null)
|
||||
}
|
||||
}
|
||||
webChromeClient = object : android.webkit.WebChromeClient() {
|
||||
override fun onProgressChanged(view: WebView?, newProgress: Int) {
|
||||
progress = newProgress
|
||||
}
|
||||
|
||||
override fun onReceivedTitle(view: WebView?, t: String?) {
|
||||
if (!t.isNullOrBlank()) title = t
|
||||
}
|
||||
}
|
||||
loadUrl(url)
|
||||
web = this
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* 底部确认条:用户点中了什么,以及「发给 AI / 取消」。
|
||||
*
|
||||
* ★ 为什么要有这一步而不是点了就发:
|
||||
* 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而模型会基于一个错误的前提回答。
|
||||
* 让用户确认一下,成本极低、收益很大。
|
||||
*/
|
||||
/**
|
||||
* 底部确认条:用户攒了哪些"选了/写了"的内容,以及
|
||||
* 「发给 AI」「清空」。
|
||||
*
|
||||
* ★ 为什么要有这一步而不是点了就发:
|
||||
* 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而模型会基于一个错误的前提回答。
|
||||
* 让用户确认一下,成本极低、收益很大。
|
||||
*
|
||||
* ★ 支持**累积多条**再一起发 —— 用户在页面上选几处、填几个框,
|
||||
* 最后一起问"这些对不对"。分开发会跑好几轮模型。
|
||||
*/
|
||||
AnimatedVisibility(
|
||||
visible = picked.isNotEmpty(),
|
||||
enter = slideInVertically(tween(220)) { it } + fadeIn(tween(160)),
|
||||
exit = slideOutVertically(tween(180)) { it } + fadeOut(tween(120)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"已选 ${picked.size} 条,会一起发给 AI:",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"清空",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoAccent(),
|
||||
modifier = Modifier.clickable { picked.clear() },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// 条目多了要能滚 —— 但只占一段固定高度,别把网页挤没了
|
||||
Column(
|
||||
Modifier
|
||||
.heightIn(max = 120.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
picked.forEach { p ->
|
||||
Text(
|
||||
"· " + p.summary,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoText(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(11.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
androidx.compose.material3.OutlinedButton(
|
||||
onClick = { picked.clear() },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
androidx.compose.material3.Button(
|
||||
onClick = {
|
||||
onSendToAi(WebPick.buildReport(picked.toList()))
|
||||
picked.clear()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("发给 AI") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `evaluateJavascript` 的返回值是**经 JSON 编码的字符串**(脚本返回 `'abc'`
|
||||
* 时 Kotlin 拿到的是 `"\"abc\""`)。
|
||||
*
|
||||
* ★ 这个坑踩过两次([AiWebView] 的探针、这里),所以抽成一个函数,
|
||||
* 并在名字上把"要解两层"这件事写出来。
|
||||
*/
|
||||
private fun decodeJsonString(raw: String?): String {
|
||||
val s = (raw ?: "").trim()
|
||||
if (s.isEmpty() || s == "null") return ""
|
||||
return try {
|
||||
if (s.startsWith("\"")) org.json.JSONTokener(s).nextValue() as? String ?: "" else s
|
||||
} catch (_: Throwable) {
|
||||
s.trim('"')
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NavIcon(
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
desc: String,
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
// 不能点的时候**也要占位**(否则顶部栏的图标会左右跳),
|
||||
// 但变淡 + 不响应点击
|
||||
.clickable(enabled = enabled) { onClick() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
icon,
|
||||
desc,
|
||||
tint = if (enabled) doubaoText() else doubaoTextDim().copy(alpha = 0.35f),
|
||||
modifier = Modifier.size(19.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 URL 里取主机名(显示用)。解析不了就原样返回。 */
|
||||
private fun hostOf(url: String): String = try {
|
||||
android.net.Uri.parse(url).host ?: url
|
||||
} catch (_: Throwable) {
|
||||
url
|
||||
}
|
||||
|
||||
/**
|
||||
* 「网页」—— **独立全屏界面**,不是弹窗。
|
||||
*
|
||||
* ## 为什么不用 AlertDialog
|
||||
*
|
||||
* 项目约定:**列表这种要滚动的东西不用弹窗**。一条回复里挂五六个链接是常事,
|
||||
* 弹窗一屏只装得下三四个,用户得在弹窗里滚动 —— 那还不如直接开一屏。
|
||||
* 而且弹窗盖住对话,用户没法一边看着回复一边挑链接。
|
||||
*
|
||||
* ## ★★ 自己输网址(v2.0.39 加)
|
||||
*
|
||||
* 用户的原话是"**你要单独开个按钮**"。既然它是个按钮,那它就不该只在
|
||||
* "这条回复恰好有链接"时才有用 —— 现在里面能直接输网址,
|
||||
* 它就是一个**浏览器入口**,任何时候按都有意义。
|
||||
* (另一个原因:`extractUrls` 曾经漏认写法,导致按钮整个不显示,
|
||||
* 用户根本不知道这功能存在。)
|
||||
*
|
||||
* 顶栏按项目约定:`← 返回 | 标题 | 副标题`。
|
||||
*/
|
||||
@Composable
|
||||
fun UrlListScreen(
|
||||
owner: String,
|
||||
urls: List<FoundUrl>,
|
||||
onPick: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
var typed by remember { mutableStateOf("") }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("网页", onBack = onClose) {
|
||||
if (urls.isNotEmpty()) {
|
||||
Text("${urls.size} 个链接", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
/* ---------- 自己输网址(永远在最上面,入口要显眼)---------- */
|
||||
item {
|
||||
Column {
|
||||
Text("输入网址", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = typed,
|
||||
onValueChange = { typed = it },
|
||||
modifier = Modifier.weight(1f),
|
||||
singleLine = true,
|
||||
placeholder = { Text("example.com", fontSize = 14.sp) },
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 15.sp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
androidx.compose.material3.Button(
|
||||
onClick = { onPick(typed) },
|
||||
enabled = typed.isNotBlank(),
|
||||
) { Text("打开") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 这条回复里找到的链接 ---------- */
|
||||
if (urls.isNotEmpty()) {
|
||||
item {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// ★ 一定要写 ${owner} 而不是 $owner:紧跟中文时 Kotlin 会把
|
||||
// 后面那几个汉字当成变量名的一部分(`$owner里提到的网页` 会
|
||||
// 被解析成一个叫「owner里提到的网页」的标识符,报未解析引用)。
|
||||
Text("${owner}里提到的网页:", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
items(urls.size) { index ->
|
||||
val u = urls[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onPick(u.url) }
|
||||
.padding(horizontal = 14.dp, vertical = 13.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
/**
|
||||
* ★ 主标题优先用**模型给链接写的文字**。
|
||||
*
|
||||
* 以前只显示 host,于是同一域名的两条链接
|
||||
* (`https://example.com` 和
|
||||
* `https://example.com/index-zh`)
|
||||
* 看起来**一模一样**,用户根本分不出该点哪个。
|
||||
* 模型的链接文字就是为了区分它们而写的。
|
||||
*/
|
||||
Text(
|
||||
u.label.ifBlank { hostOf(u.url) },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
u.url,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Icon(
|
||||
Icons.Filled.OpenInNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
370
android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt
Normal file
370
android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt
Normal file
@@ -0,0 +1,370 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★★★ 在**真实网页**上点选,把点到的内容回传给 AI。
|
||||
*
|
||||
* ## 为什么不用 `@JavascriptInterface` 桥
|
||||
*
|
||||
* `show_ui` 那个界面里我们挂了 `Doubao` 桥,但那只挂在**我们自己注入的那一页**上,
|
||||
* 一导航到外部站点就摘掉了(见 [AiWebView] 的注释)。
|
||||
*
|
||||
* 这里不同:**用户就是在浏览外部网站**,全程都在别人的页面上。
|
||||
* 要是挂桥,等于把 App 的内部接口暴露给互联网上任意一个站点 —— 绝对不能这么干。
|
||||
*
|
||||
* ## 改用"单向队列 + 主动轮询"
|
||||
*
|
||||
* ```
|
||||
* 注入的脚本(页面里) Kotlin 侧
|
||||
* ──────────────────── ──────────────
|
||||
* 用户点了 → 写进 window.__doubaoPicks
|
||||
* setInterval 每 500ms
|
||||
* evaluateJavascript("取走队列")
|
||||
* ← 拿到 JSON
|
||||
* ```
|
||||
*
|
||||
* 数据**只从页面流向 App**,而且只有这一个取数入口(`evaluateJavascript`)。
|
||||
* 页面**没有任何办法**主动调用 App —— 它只能往一个数组里塞东西,
|
||||
* 而那个数组的内容是我们主动去读的、并且读之前会做类型和长度校验。
|
||||
*
|
||||
* ★ 注意 `evaluateJavascript` 的返回值经 JSON 编码,所以脚本里用
|
||||
* `JSON.stringify(...)` 返回**字符串**,Kotlin 这边再解一层。
|
||||
* (这个坑在 [AiWebView] 那边也踩过。)
|
||||
*/
|
||||
object WebPick {
|
||||
|
||||
/** 队列变量名。用不常见的名字,尽量不和页面自己的变量撞。 */
|
||||
private const val QUEUE = "__doubaoPicks"
|
||||
|
||||
/**
|
||||
* 注入的脚本。
|
||||
*
|
||||
* 做三件事:
|
||||
* 1. 给页面上**真正的链接/按钮**加虚线高亮(视觉提示)
|
||||
* 2. 捕获点击(**捕获阶段**,抢在页面自己的 handler 前面)
|
||||
* 3. 把点到的元素信息写进队列,并阻止这次跳转
|
||||
*
|
||||
* ★★ 改过一版:从"只能点可点元素"改成"**点哪儿抓哪儿**"。
|
||||
*
|
||||
* 第一版只给 `a,button,[role=button],...` 这些**看着能点**的元素加框,
|
||||
* 点击也只认这些。实测在 example.com 上**一个都标不出来** ——
|
||||
* 那页全是纯文本,没有任何按钮链接,于是"点选模式"看起来完全没生效。
|
||||
*
|
||||
* 我的假设错了:用户想点的不一定是"可点元素",他想点的就是
|
||||
* **页面上任意一段内容**("把这段告诉 AI")。
|
||||
* 所以现在点击用 `elementFromPoint` 抓,**点哪儿抓哪儿**;
|
||||
* 虚线框降级成纯视觉提示,不再限制能点什么。
|
||||
*
|
||||
* ★ 为什么用捕获阶段 + `preventDefault`:
|
||||
* 如果一个链接上挂着页面的点击统计脚本,冒泡阶段再加我们的监听就晚了。
|
||||
* 捕获阶段先拿到,`stopPropagation` 之后页面完全不知道被点过,
|
||||
* 也就不会跳走 —— 用户点一下是"选中",不是"跳转"。
|
||||
*
|
||||
* ★ 用 IIFE 包起来 + 可重复注入(先看有没有装过):
|
||||
* 每次页面加载完都会注入一遍,不防重会叠出好几层监听,
|
||||
* 一次点击写好几条重复记录。
|
||||
*/
|
||||
val INSTALL_JS: String = """
|
||||
(function () {
|
||||
if (window.__doubaoPickInstalled) { return '1'; }
|
||||
window.__doubaoPickInstalled = 1;
|
||||
window.$QUEUE = [];
|
||||
|
||||
// 只用来**画虚线框**(提示哪些是链接/按钮)。点击不受它限制。
|
||||
var HINT_SEL = 'a,button,[role=button],input,select,textarea,label,summary';
|
||||
|
||||
function visible(el) {
|
||||
if (!el || !el.getBoundingClientRect) { return false; }
|
||||
var r = el.getBoundingClientRect();
|
||||
if (r.width < 8 || r.height < 8) { return false; }
|
||||
var s = window.getComputedStyle(el);
|
||||
return s.display !== 'none' && s.visibility !== 'hidden' && s.opacity !== '0';
|
||||
}
|
||||
|
||||
function textOf(el) {
|
||||
var t = (el.innerText || el.textContent || el.value || el.getAttribute('aria-label')
|
||||
|| el.getAttribute('title') || el.getAttribute('placeholder') || '');
|
||||
t = t.replace(/\s+/g, ' ').trim();
|
||||
return t.slice(0, 300);
|
||||
}
|
||||
|
||||
function mark() {
|
||||
var list = document.querySelectorAll(HINT_SEL);
|
||||
for (var i = 0; i < list.length && i < 400; i++) {
|
||||
var el = list[i];
|
||||
if (el.__doubaoMarked || !visible(el)) { continue; }
|
||||
el.__doubaoMarked = 1;
|
||||
el.style.outline = '2px dashed rgba(76,141,255,.75)';
|
||||
el.style.outlineOffset = '1px';
|
||||
el.style.cursor = 'pointer';
|
||||
}
|
||||
return list.length;
|
||||
}
|
||||
|
||||
function onClick(e) {
|
||||
// ★★ 点哪儿抓哪儿:优先用坐标取元素,**不要求它"看起来能点"**。
|
||||
//
|
||||
// 第一版是"从 e.target 往上找最近的可点元素",找不到就退回 e.target ——
|
||||
// 在纯文本页面上用户点一段话,抓到的是最里层的 <b>/<span>,
|
||||
// 甚至可能是个没文字的容器。用坐标取到的是**用户真正看到的那个块**。
|
||||
var el = null;
|
||||
try {
|
||||
if (e.clientX || e.clientY) {
|
||||
el = document.elementFromPoint(e.clientX, e.clientY);
|
||||
}
|
||||
} catch (err) { el = null; }
|
||||
if (!el) { el = e.target; }
|
||||
|
||||
// 取到的可能是很里层的小元素(一个 <b>、一个 <span>)。
|
||||
// 往上走几层,让选中的是"一整段有意义的内容"而不是一个词。
|
||||
var hop = 0;
|
||||
while (el && el.parentElement && hop < 3) {
|
||||
var t = (el.innerText || el.textContent || '').trim();
|
||||
// 文字够多就停 —— 说明这一层已经是个完整段落了
|
||||
if (t.length >= 12) { break; }
|
||||
// 或者这一层本身就是链接/按钮,那也停(点链接当然要抓链接)
|
||||
if (el.matches && el.matches(HINT_SEL)) { break; }
|
||||
el = el.parentElement; hop++;
|
||||
}
|
||||
if (!el || el === document.documentElement) { el = e.target; }
|
||||
|
||||
var rec = {
|
||||
tag: (el.tagName || '').toLowerCase(),
|
||||
text: textOf(el),
|
||||
href: el.href || '',
|
||||
id: el.id || '',
|
||||
cls: (typeof el.className === 'string' ? el.className : '').slice(0, 120),
|
||||
path: (function () {
|
||||
var p = [], n = el, d = 0;
|
||||
while (n && n.tagName && d < 4) {
|
||||
var s = n.tagName.toLowerCase();
|
||||
if (n.id) { s += '#' + n.id; }
|
||||
else if (typeof n.className === 'string' && n.className) {
|
||||
s += '.' + n.className.trim().split(/\s+/).slice(0, 2).join('.');
|
||||
}
|
||||
p.unshift(s); n = n.parentElement; d++;
|
||||
}
|
||||
return p.join(' > ');
|
||||
})(),
|
||||
title: document.title || '',
|
||||
url: location.href || '',
|
||||
kind: 'click'
|
||||
};
|
||||
window.$QUEUE.push(rec);
|
||||
|
||||
// 选中效果:给点到的那个元素一个实线高亮,然后褪成虚线
|
||||
try {
|
||||
el.style.outline = '3px solid #4c8dff';
|
||||
setTimeout(function () { el.style.outline = '2px dashed rgba(76,141,255,.75)'; }, 700);
|
||||
} catch (err) {}
|
||||
|
||||
// ★ 关键:拦掉这次点击 —— 用户是"选中"不是"跳转"。
|
||||
// 不拦的话点个链接页面就跳走了,用户根本来不及看"已选中"提示。
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户**写了什么** —— 表单输入 / 下拉选择 / 勾选框。
|
||||
*
|
||||
* ★ 用户明确要求"让 AI 知道用户选择了什么、**写了什么**"。
|
||||
* 光有"点了什么"不够:填表场景里真正重要的是填进去的内容。
|
||||
*
|
||||
* ★ 用 input/change 的**冒泡阶段**(不用捕获):这类事件页面自己也要处理
|
||||
* (自动补全、字数统计),拦掉会破坏页面功能。我们只是**旁听**,不干预。
|
||||
*
|
||||
* ★ 同一个输入框连续打字会触发很多次 input —— 每 600ms 合并一次,
|
||||
* 否则用户打十个字会往队列里塞十条,报告变得没法看。
|
||||
*/
|
||||
var pending = {};
|
||||
function labelOf(el) {
|
||||
var s = el.getAttribute('aria-label') || el.getAttribute('placeholder')
|
||||
|| el.getAttribute('name') || el.id || '';
|
||||
if (!s) {
|
||||
var lab = el.closest ? el.closest('label') : null;
|
||||
if (lab) { s = (lab.innerText || '').trim().slice(0, 60); }
|
||||
}
|
||||
if (!s && el.previousElementSibling) {
|
||||
s = (el.previousElementSibling.innerText || '').trim().slice(0, 60);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function flush(key) {
|
||||
var el = pending[key];
|
||||
if (!el) { return; }
|
||||
delete pending[key];
|
||||
var val = '';
|
||||
if (el.type === 'checkbox' || el.type === 'radio') { val = el.checked ? '已勾选' : '未勾选'; }
|
||||
else { val = (el.value || '').slice(0, 500); }
|
||||
if (!val) { return; }
|
||||
window.$QUEUE.push({
|
||||
kind: 'input',
|
||||
tag: (el.tagName || '').toLowerCase(),
|
||||
type: el.type || '',
|
||||
label: labelOf(el),
|
||||
text: val,
|
||||
href: '',
|
||||
id: el.id || '',
|
||||
cls: (typeof el.className === 'string' ? el.className : '').slice(0, 120),
|
||||
path: '',
|
||||
title: document.title || '',
|
||||
url: location.href || ''
|
||||
});
|
||||
}
|
||||
|
||||
function onInput(e) {
|
||||
var el = e.target;
|
||||
if (!el || !el.tagName) { return; }
|
||||
var t = (el.tagName || '').toLowerCase();
|
||||
if (t !== 'input' && t !== 'textarea' && t !== 'select') { return; }
|
||||
var key = (el.id || '') + '|' + (el.name || '') + '|' +
|
||||
(el.getAttribute('placeholder') || '') + '|' + (el.type || '');
|
||||
pending[key] = el;
|
||||
if (el.__doubaoDebounce) { clearTimeout(el.__doubaoDebounce); }
|
||||
el.__doubaoDebounce = setTimeout(function () { flush(key); }, 600);
|
||||
}
|
||||
|
||||
document.addEventListener('input', onInput, false);
|
||||
document.addEventListener('change', onInput, false);
|
||||
// 失焦时立刻结算(用户填完就去点别的地方了,不等那 600ms)
|
||||
document.addEventListener('blur', function (e) {
|
||||
var el = e.target;
|
||||
if (!el || !el.tagName) { return; }
|
||||
var key = (el.id || '') + '|' + (el.name || '') + '|' +
|
||||
(el.getAttribute('placeholder') || '') + '|' + (el.type || '');
|
||||
flush(key);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('click', onClick, true);
|
||||
|
||||
// 动态加载的页面(下拉刷新、无限滚动)也要能点 —— 隔一会儿重新标一次
|
||||
var ticks = 0;
|
||||
var timer = setInterval(function () {
|
||||
mark(); ticks++;
|
||||
if (ticks > 40) { clearInterval(timer); }
|
||||
}, 1500);
|
||||
|
||||
mark();
|
||||
return '1';
|
||||
})()
|
||||
"""
|
||||
|
||||
/**
|
||||
* 取走队列(取完清空)。
|
||||
*
|
||||
* ★ 一定要"取走"而不是"读":读的话每次轮询都会把同一条记录
|
||||
* 重复报上来,用户点一下会触发十几次。
|
||||
*/
|
||||
val DRAIN_JS: String = """
|
||||
(function () {
|
||||
try {
|
||||
var q = window.$QUEUE || [];
|
||||
window.$QUEUE = [];
|
||||
return JSON.stringify(q.slice(0, 20));
|
||||
} catch (e) { return '[]'; }
|
||||
})()
|
||||
"""
|
||||
|
||||
/** 撤销高亮 + 拆掉监听(退出点选模式时调) */
|
||||
val UNINSTALL_JS: String = """
|
||||
(function () {
|
||||
try {
|
||||
window.__doubaoPickInstalled = 0;
|
||||
window.$QUEUE = [];
|
||||
var list = document.querySelectorAll('[style]');
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var el = list[i];
|
||||
if (el.__doubaoMarked) {
|
||||
el.style.outline = '';
|
||||
el.style.outlineOffset = '';
|
||||
el.style.cursor = '';
|
||||
el.__doubaoMarked = 0;
|
||||
}
|
||||
}
|
||||
return '1';
|
||||
} catch (e) { return '0'; }
|
||||
})()
|
||||
"""
|
||||
|
||||
/**
|
||||
* 把一条记录整理成给模型看的一行字。
|
||||
*
|
||||
* ★ 刻意做成**紧凑的一行**,而不是把整个 JSON 丢给模型:
|
||||
* 模型需要的是"用户干了什么",不是 DOM 的所有细节。
|
||||
* 附带页面标题和 URL,帮它知道用户在哪个页面操作的。
|
||||
*
|
||||
* ★ 分两种 `kind`:
|
||||
* · `click` —— 用户**点了/选了**一个元素(链接、按钮、一段文字)
|
||||
* · `input` —— 用户**写了**内容(输入框、下拉、勾选框)
|
||||
* 用户的原话是"让 AI 知道用户选择了什么、写了什么",就是这两类。
|
||||
*/
|
||||
fun describe(json: JSONObject): String {
|
||||
val parts = mutableListOf<String>()
|
||||
val kind = json.optString("kind", "click")
|
||||
val text = json.optString("text").trim()
|
||||
val tag = json.optString("tag")
|
||||
val type = json.optString("type")
|
||||
val label = json.optString("label").trim()
|
||||
val href = json.optString("href")
|
||||
val id = json.optString("id")
|
||||
val path = json.optString("path")
|
||||
|
||||
if (kind == "input") {
|
||||
val what = if (type == "checkbox" || type == "radio") "勾选" else "填写"
|
||||
parts.add("用户$what:${text.ifEmpty { "(空)" }}")
|
||||
if (label.isNotEmpty()) parts.add("字段:$label")
|
||||
parts.add("控件:<$tag" + (if (type.isNotEmpty()) " type=$type" else "") + ">")
|
||||
} else {
|
||||
if (text.isNotEmpty()) parts.add("内容:$text")
|
||||
parts.add("元素:<$tag>" + (if (id.isNotEmpty()) " #$id" else ""))
|
||||
if (href.isNotEmpty()) parts.add("链接:$href")
|
||||
if (path.isNotEmpty()) parts.add("位置:$path")
|
||||
}
|
||||
return parts.joinToString(";")
|
||||
}
|
||||
|
||||
/**
|
||||
* 把多条记录汇总成一段给模型的话。
|
||||
*
|
||||
* ★ 一次性发送多条(而不是点一条发一条):
|
||||
* 用户可能在页面上选了好几处、填了几个框,然后一起问"这些对不对"。
|
||||
* 分开发会触发好几轮模型调用,既慢又费 token。
|
||||
*/
|
||||
fun buildReport(items: List<PickedElement>): String = buildString {
|
||||
append("我在网页上")
|
||||
val clicks = items.count { it.kind != "input" }
|
||||
val inputs = items.count { it.kind == "input" }
|
||||
val bits = mutableListOf<String>()
|
||||
if (clicks > 0) bits.add("选了 $clicks 处")
|
||||
if (inputs > 0) bits.add("填了 $inputs 处")
|
||||
append(bits.joinToString("、").ifEmpty { "选了一些东西" })
|
||||
append(":\n")
|
||||
items.forEachIndexed { i, it ->
|
||||
append("${i + 1}. ${it.summary}\n")
|
||||
}
|
||||
val first = items.firstOrNull()
|
||||
if (first != null && first.url.isNotBlank()) append("\n页面:${first.url}")
|
||||
if (first != null && first.pageTitle.isNotBlank()) append("\n标题:${first.pageTitle}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 点选模式下用户选中/填写、但**还没决定要不要发给 AI** 的那一条。
|
||||
*
|
||||
* ★ 为什么要中间这一步(而不是点了就直接发):
|
||||
* 用户可能点错了元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而且模型会基于一个错误的前提回答。让用户确认一下,成本极低、收益很大。
|
||||
*
|
||||
* ★ 支持累积多条:用户可以连着点好几处、填几个框,最后一起发。
|
||||
*/
|
||||
data class PickedElement(
|
||||
val summary: String,
|
||||
/** click / input —— 是"点了什么"还是"写了什么" */
|
||||
val kind: String,
|
||||
val url: String,
|
||||
val pageTitle: String,
|
||||
val raw: String,
|
||||
)
|
||||
@@ -101,6 +101,9 @@ public final class TerminalSession extends TerminalOutput {
|
||||
|
||||
/** Inform the attached pty of the new size and reflow or initialize the emulator. */
|
||||
public void updateSize(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
|
||||
android.util.Log.i("DoubaoTermux", "updateSize cols=" + columns + " rows=" + rows
|
||||
+ " cell=" + cellWidthPixels + "x" + cellHeightPixels
|
||||
+ " emulator=" + (mEmulator != null));
|
||||
if (mEmulator == null) {
|
||||
initializeEmulator(columns, rows, cellWidthPixels, cellHeightPixels);
|
||||
} else {
|
||||
@@ -127,6 +130,15 @@ public final class TerminalSession extends TerminalOutput {
|
||||
mTerminalFileDescriptor = JNI.createSubprocess(mShellPath, mCwd, mArgs, mEnv, processId, rows, columns, cellWidthPixels, cellHeightPixels);
|
||||
mShellPid = processId[0];
|
||||
|
||||
// ★ 诊断日志:这一行是判断 pty 到底建成什么样的**唯一依据**。
|
||||
// fd == -1 → /dev/ptmx 打开失败(或 grantpt/unlockpt 失败),
|
||||
// 子进程的 0/1/2 全是无效 fd,bash 读 stdin 直接 EOF 退出。
|
||||
// pid <= 0 → fork 失败。
|
||||
// cols/rows 是 0 → attach 时 view 还没量过尺寸。
|
||||
android.util.Log.i("DoubaoTermux", "createSubprocess -> fd=" + mTerminalFileDescriptor
|
||||
+ " pid=" + mShellPid + " rows=" + rows + " cols=" + columns
|
||||
+ " cell=" + cellWidthPixels + "x" + cellHeightPixels);
|
||||
|
||||
final FileDescriptor terminalFileDescriptorWrapped = wrapFileDescriptor(mTerminalFileDescriptor, mClient);
|
||||
|
||||
new Thread("TermSessionInputReader[pid=" + mShellPid + "]") {
|
||||
@@ -141,7 +153,9 @@ public final class TerminalSession extends TerminalOutput {
|
||||
mMainThreadHandler.sendEmptyMessage(MSG_NEW_INPUT);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Ignore, just shutting down.
|
||||
// ★ 原来是静默吞掉的(`// Ignore, just shutting down.`)——
|
||||
// 于是 fd 读失败时**一点线索都没有**。加上日志。
|
||||
android.util.Log.e("DoubaoTermux", "TermSessionInputReader 退出", e);
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
@@ -325,7 +339,15 @@ public final class TerminalSession extends TerminalOutput {
|
||||
}
|
||||
descriptorField.setAccessible(true);
|
||||
descriptorField.set(result, fileDescriptor);
|
||||
// ★ 诊断:反射到底成没成。
|
||||
// Android 9+ 对 java.* 私有成员的反射有隐藏 API 限制,
|
||||
// setAccessible 被拦的话 result 里还是 -1,
|
||||
// 后面 FileInputStream/FileOutputStream 就都在读 fd -1 ——
|
||||
// 表现是"pty 双向都不通",而且**异常被静默吞掉**,什么都看不到。
|
||||
android.util.Log.i("DoubaoTermux", "wrapFileDescriptor fd=" + fileDescriptor
|
||||
+ " -> 反射后=" + result);
|
||||
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
|
||||
android.util.Log.e("DoubaoTermux", "wrapFileDescriptor 反射失败", e);
|
||||
Logger.logStackTraceWithMessage(client, LOG_TAG, "Error accessing FileDescriptor#descriptor private field", e);
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
BIN
android/app/src/main/jniLibs/arm64-v8a/libdoubao-dpkg.so
Normal file
BIN
android/app/src/main/jniLibs/arm64-v8a/libdoubao-dpkg.so
Normal file
Binary file not shown.
BIN
android/app/src/main/jniLibs/x86_64/libdoubao-dpkg.so
Normal file
BIN
android/app/src/main/jniLibs/x86_64/libdoubao-dpkg.so
Normal file
Binary file not shown.
BIN
android/app/src/main/res/drawable/agent_default_background.png
Normal file
BIN
android/app/src/main/res/drawable/agent_default_background.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
BIN
android/app/src/main/res/drawable/agent_default_character.png
Normal file
BIN
android/app/src/main/res/drawable/agent_default_character.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 669 KiB |
160
android/app/src/main/res/raw/doubao_patch.sh
Normal file
160
android/app/src/main/res/raw/doubao_patch.sh
Normal file
@@ -0,0 +1,160 @@
|
||||
#!/system/bin/sh
|
||||
# 由豆包 App 生成 —— 把新装包里写死 com.termux 的**脚本/文本**改掉。
|
||||
#
|
||||
# ★★ 这个文件是模板,正文原样嵌进 APK(res/raw/doubao_patch.sh),
|
||||
# 运行期由 TermuxInstaller.writePatcherScript() 做占位符替换:
|
||||
# @PREFIX@ → $PREFIX(files/usr)
|
||||
# @OLD@ → /data/data/com.termux
|
||||
# @NEW@ → /data/data/<我们的包名> (即 filesDir)
|
||||
# @PY@ → 用来干活的 python(**它自己也得是改过的**)
|
||||
# @VER@ → 脚本版本号
|
||||
#
|
||||
# 为什么不做成 Kotlin 字符串:脚本里 $P 这类变量到处都是,
|
||||
# Kotlin 的**原始字符串也照样做 $ 插值**,只能写成一堆 ${'$'}P,
|
||||
# 正文就没法读了(而且我已经因为这个编译失败两次)。
|
||||
# 放进 res/raw 之后,正文可以**原样读**,也不用碰任何构建脚本。
|
||||
#
|
||||
# 用法:
|
||||
# doubao-patch → 全部(shebang + 正文路径)
|
||||
# doubao-patch shebang → 只修 shebang(dpkg unpack 之后、configure 之前调)
|
||||
#
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
# ★★★ 一、只改**文本文件**。二进制一律不碰。
|
||||
#
|
||||
# `sed -i` 会把 ELF 的内部偏移全写坏(当初一口气写坏 85 个二进制,
|
||||
# `dpkg.real` 直接变成 "empty/missing DT_HASH/DT_GNU_HASH")。
|
||||
# 为什么必然坏:`/data/data/com.termux`(21 字节)和
|
||||
# `/data/user/0/<包名>/files`(42 字节)**长度不等**,原地替换不能改长度。
|
||||
# 这正是 scripts/verify-elf-patch.py 验证过、我因此放弃"改二进制"方案的
|
||||
# 那条结论 —— 结果转头又在补刀脚本里犯了同一个错。
|
||||
#
|
||||
# 所以:含 NUL 的文件一律跳过;按行改之前还要 peek() 确认前两字节是 `#!`。
|
||||
#
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
# ★★★ 二、为什么这段替换是 python 而不是 shell/sed
|
||||
#
|
||||
# 说实话:**最初换掉 shell/sed 是误判**。
|
||||
#
|
||||
# 当时看到 pip 的 shebang 变成
|
||||
# #!/data/user/0/<包名>/files/files/usr/bin/python3.14
|
||||
# 多出一个 `files`,就断定"玩具箱的 `${var//a/b}` 和 `sed` 会把匹配后面
|
||||
# 的片段复制一遍",于是把两个工具都换成了 python。
|
||||
#
|
||||
# **其实它们全是清白的。** 真正错的是上面那个 `NEW` 的取值 ——
|
||||
# 它当时被写成了 `<filesDir>`(以 `files` 结尾),而正确值是
|
||||
# `<prefix>`(`<filesDir>/usr`)。多出来的那个 `files` 是 `NEW` 自带的,
|
||||
# 和原文里的 `/files/usr` 撞在一起,看着就像"被复制了一遍"。
|
||||
# (拆穿它的是一个和本项目无关的中性实验:
|
||||
# b"/data/data/com.termux/files/usr".replace(
|
||||
# b"/data/data/com.termux", b"/data/user/0/pkg/files")
|
||||
# → b"/data/user/0/pkg/files/files/usr" ← 数学上完全正确)
|
||||
#
|
||||
# 教训:**"工具坏了"的时候,先怀疑自己的常量。**
|
||||
# 常量错的表现(稳定复现、与输入无关)恰恰是工具 bug 的特征。
|
||||
#
|
||||
# 那为什么**保留** python 版本?两条实在的理由:
|
||||
# 1. 这个脚本要改的东西里**混着二进制**(bin/ lib/ 下都是 ELF),
|
||||
# 用 shell 得靠 `grep -I` + `peek` 两道手工拦,而"哪个文件是文本"
|
||||
# 在 python 里是一行 `b"\0" in data[:8192]`,更不容易漏。
|
||||
# 2. 按行改(只动 shebang 第一行)用 shell 要 `head`/`tail`/`mv` 拼临时文件,
|
||||
# python 是 `data[:nl]`,没有中间态。
|
||||
# —— 不是因为 shell/sed 有 bug(它们没有)。
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
P=@PREFIX@
|
||||
OLD=@OLD@
|
||||
NEW=@NEW@
|
||||
PY=@PY@
|
||||
MODE="$1"
|
||||
|
||||
[ -n "$NEW" ] || exit 0
|
||||
|
||||
# ★★ 必须自己 export LD_LIBRARY_PATH —— 不然 `$PY` 根本起不来,
|
||||
# 而下面的 `[ -x "$PY" ]` 判定会**静默跳过全部工作**:
|
||||
# CANNOT LINK EXECUTABLE ".../bin/python3": library "libandroid-support.so"
|
||||
# not found: needed by main executable
|
||||
# 表现是"shebang 没被修好"但日志里一个字都没有 —— 查了好几轮才找到。
|
||||
# 不依赖调用方(wrapper / 终端)替我们设好。
|
||||
export LD_LIBRARY_PATH="$P/lib"
|
||||
export TMPDIR="$P/tmp"
|
||||
|
||||
# 干活的那段 python。参数:<目录> <模式>
|
||||
# 模式 = shebang → 只改第一行的 shebang(且该行必须含 OLD)
|
||||
# 模式 = body → 改整个文件里的 OLD
|
||||
run_py() {
|
||||
[ -x "$PY" ] || return 0
|
||||
"$PY" - "$1" "$2" "$OLD" "$NEW" <<'PYEOF'
|
||||
import os
|
||||
import sys
|
||||
|
||||
root, mode, old, new = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
|
||||
ob = old.encode()
|
||||
nb = new.encode()
|
||||
done = 0
|
||||
|
||||
for dirpath, _dirnames, filenames in os.walk(root):
|
||||
for name in filenames:
|
||||
path = os.path.join(dirpath, name)
|
||||
# ★ 绝不改自己:否则第一刀就把规则改掉了
|
||||
if name == "doubao-patch":
|
||||
continue
|
||||
try:
|
||||
if os.path.islink(path):
|
||||
continue
|
||||
with open(path, "rb") as fh:
|
||||
data = fh.read()
|
||||
except OSError:
|
||||
continue
|
||||
# ★ 二进制跳过(和 grep -I 同义,但不依赖 grep)
|
||||
if b"\0" in data[:8192] or ob not in data:
|
||||
continue
|
||||
|
||||
if mode == "shebang":
|
||||
nl = data.find(b"\n")
|
||||
first = data if nl < 0 else data[:nl]
|
||||
# 只动 shebang,且必须是含 OLD 的那种
|
||||
if not first.startswith(b"#!") or ob not in first:
|
||||
continue
|
||||
out = first.replace(ob, nb) + (b"" if nl < 0 else data[nl:])
|
||||
else:
|
||||
out = data.replace(ob, nb)
|
||||
|
||||
if out == data:
|
||||
continue
|
||||
try:
|
||||
mode_bits = os.stat(path).st_mode
|
||||
os.chmod(path, mode_bits) # 保住权限位(有些实现下 open(w) 会丢)
|
||||
with open(path, "wb") as fh:
|
||||
fh.write(out)
|
||||
print(("shebang " if mode == "shebang" else "patched ") + path)
|
||||
done += 1
|
||||
except OSError:
|
||||
pass
|
||||
PYEOF
|
||||
}
|
||||
|
||||
run_py "$P/bin" shebang
|
||||
run_py "$P/libexec" shebang
|
||||
run_py "$P/var/lib/dpkg/info" shebang
|
||||
|
||||
[ "$MODE" = "shebang" ] && exit 0
|
||||
|
||||
for d in bin lib libexec etc share; do
|
||||
[ -d "$P/$d" ] || continue
|
||||
run_py "$P/$d" body
|
||||
done
|
||||
|
||||
# ★★ `var/lib/dpkg/info` 里的**维护脚本正文**也要扫。
|
||||
#
|
||||
# 漏了它会出这种错(实测):
|
||||
# python-ensurepip-wheels.postinst →
|
||||
# File "<frozen os>", line 236, in makedirs
|
||||
# PermissionError: [Errno 13] Permission denied: '/data/data/com.termux'
|
||||
# ERROR: Internal Error.
|
||||
# —— 包能装上、大部分功能也正常,但 dpkg 报 Internal Error,
|
||||
# 用户看到的是"装完了但报错"。而报错里那个路径属于**别的 App**,
|
||||
# 一眼看不出是我们漏扫了一个目录。
|
||||
#
|
||||
# ★ 注意这里传的是 `body`(改正文),不是 `shebang` ——
|
||||
# shebang 由上面那三趟单独处理,因为规则不同(见顶部注释)。
|
||||
run_py "$P/var/lib/dpkg/info" body
|
||||
108
android/app/src/main/res/raw/dpkg_wrapper.sh
Normal file
108
android/app/src/main/res/raw/dpkg_wrapper.sh
Normal file
@@ -0,0 +1,108 @@
|
||||
#!/system/bin/sh
|
||||
# 由豆包 App 生成 —— 补全环境 → 调真正的 dpkg → 把新装进来的脚本也改一遍。
|
||||
# 模板见 res/raw/dpkg_wrapper.sh,占位符 @PREFIX@ / @VER@ 由 App 替换。
|
||||
#
|
||||
# ★★ 为什么 shebang 是 /system/bin/sh 而不是别的:
|
||||
# shebang 那行是**内核**解析的,不走 PATH、也不走 LD_PRELOAD
|
||||
# (termux-exec 拦不到 execve 这一段),必须是真实存在的绝对路径。
|
||||
# /bin/sh → Android 上根本没这个文件
|
||||
# $PREFIX/bin/sh → 路径太长(而且会被 dpkg 的 --root 再拼一层前缀)
|
||||
# /system/bin/sh → 一定在,一定能被内核 exec
|
||||
# 注意它是**系统** toybox sh,不是 Termux 的 bash,
|
||||
# 所以该 export 的变量下面全都自己写。
|
||||
#
|
||||
# ★ 这个文件每次启动都会核对(内容变了才写盘),改了之后不用清 App 数据。
|
||||
|
||||
P=@PREFIX@
|
||||
export PATH="$P/bin:$P/bin/applets:/system/bin:/system/xbin"
|
||||
# ★★ LD_LIBRARY_PATH 是**必须**的,而且必须在这儿 export(不是只在终端里设)。
|
||||
# 原因:Termux 的二进制是靠 `libandroid-support.so` 等一堆库活的,而动态链接
|
||||
# 只认 LD_LIBRARY_PATH(没编 RPATH)。少了它,连 `$P/bin/python3` 都起不来:
|
||||
#
|
||||
# CANNOT LINK EXECUTABLE ".../bin/python3": library "libandroid-support.so"
|
||||
# not found: needed by main executable
|
||||
#
|
||||
# ★ 这个坑的可怕之处是**它是静默的**:补刀脚本第一件事就是判断
|
||||
# `[ -x "$PY" ]`,python 起不来 → 整个补刀什么都不做、也不报错,
|
||||
# 表现是"shebang 没被修好",而日志里一个字都没有。
|
||||
# 当时 pip 的 shebang 一直指着一个不存在的路径,查了好几轮
|
||||
# —— 真因就是这里少了一行 export。
|
||||
export LD_LIBRARY_PATH="$P/lib"
|
||||
export TMPDIR="$P/tmp"
|
||||
export DPKG_ADMINDIR="$P/var/lib/dpkg"
|
||||
export TERMUX__PREFIX="$P"
|
||||
|
||||
# ★★★ 这里**绝对不能加 `--root=`**。这一条解释一下,因为它反直觉:
|
||||
#
|
||||
# 一开始给 dpkg 加了 `--root="$P"`,想法是"让编译死的绝对路径落回我们
|
||||
# 自己目录"。它能解决**配置目录读不到**的问题,但会引入一个更隐蔽的:
|
||||
#
|
||||
# dpkg 会**在每一个路径前面拼 root**,包括包自己的安装路径。
|
||||
# .deb 里的文件清单记的是原始绝对路径
|
||||
# /data/data/com.termux/files/usr/bin/hello
|
||||
# 拼上 root 之后就变成
|
||||
# $P/data/data/com.termux/files/usr/bin/hello ← 落到沙箱里了!
|
||||
#
|
||||
# 实测(装 hello 包):
|
||||
# 文件出现在 <prefix>/data/data/com.termux/files/usr/bin/hello
|
||||
# 应该在 <prefix>/bin/hello
|
||||
# apt 还报 "Setting up hello ... 成功" —— **静悄悄地装到了错的地方**。
|
||||
#
|
||||
# 所以正确姿势是:**不加 --root**,改用 dpkg 自己的两个目录参数:
|
||||
# DPKG_ADMINDIR(环境变量)= 数据库位置
|
||||
# --instdir=/ = 安装根就是真实的 /,于是文件按原路径落,
|
||||
# 但 /data/data/com.termux 那条路必须能解析
|
||||
#
|
||||
# 而 `data/data/com.termux` 那条路由 App 侧的 linkLegacyPrefix() 建成
|
||||
# **指向 prefix 自己**的软链(`<prefix>/data/data/com.termux → <prefix>`),
|
||||
# 于是 dpkg 眼里:
|
||||
# /data/data/com.termux/files/usr/bin == <prefix>/files/usr/bin ✅
|
||||
# /data/data/com.termux/etc/dpkg == <prefix>/etc/dpkg ✅
|
||||
# 两个问题一起解决。
|
||||
#
|
||||
# ★★★ 补刀**要跑两次**,第二次的位置是关键。原因:
|
||||
#
|
||||
# dpkg 有两个阶段,而 .deb 里的文件是在 **unpack** 阶段落盘的:
|
||||
#
|
||||
# dpkg --unpack ← 文件(含 bin/pip 这种带 shebang 的脚本)落到我们目录
|
||||
# dpkg --configure ← 跑 postinst
|
||||
#
|
||||
# 而 postinst **会执行刚装进来的脚本**。`python-pip.postinst` 第 3 行就是:
|
||||
#
|
||||
# /data/user/0/<包名>/files/usr/bin/pip --version
|
||||
#
|
||||
# pip 确实在那儿,但它的第一行是
|
||||
# #!/data/data/com.termux/files/usr/bin/python
|
||||
# —— **绝对路径,那个文件不存在**(那是真 Termux 的地盘)。于是报:
|
||||
#
|
||||
# python-pip.postinst: line 3: .../bin/pip: cannot execute:
|
||||
# required file not found
|
||||
#
|
||||
# ★ 这句 "required file not found" 指的**不是 pip 本身**,而是它 shebang 里
|
||||
# 那个解释器 —— 报错信息完全没提这件事,所以极容易查到错的方向去
|
||||
# (会以为 pip 没装上)。
|
||||
#
|
||||
# 所以在 unpack 之后、configure 之前**补一刀**,把 shebang 改对。
|
||||
# apt 调 dpkg 时 unpack 和 configure 是**两次独立调用**,所以下面按参数判断。
|
||||
#
|
||||
# 最后再补一刀(不论什么操作)作为兜底,覆盖直接 `dpkg -i` 那种一步到位的用法。
|
||||
PATCH_UNPACK=0
|
||||
case " $* " in
|
||||
*" --unpack "*|*" --install "*|*" -i "*) PATCH_UNPACK=1 ;;
|
||||
esac
|
||||
|
||||
# ★ 不传 `--admindir`:下面 export 了 `DPKG_ADMINDIR`,dpkg 认这个环境变量,
|
||||
# 两处都写反而容易不一致(`--admindir` 是相对 instdir 的,容易理解错)。
|
||||
"$P/bin/dpkg.real" --instdir=/ --force-script-chrootless "$@"
|
||||
rc=$?
|
||||
|
||||
# ★ unpack 之后立刻补 shebang —— configure 阶段的 postinst 要用
|
||||
if [ "$PATCH_UNPACK" = 1 ] && [ -f "$P/bin/doubao-patch" ]; then
|
||||
"$P/bin/sh" "$P/bin/doubao-patch" shebang >> "$P/var/log/doubao-patch.log" 2>&1
|
||||
fi
|
||||
|
||||
# 收尾再补一次(含路径改写)。失败绝不影响 dpkg 的退出码。
|
||||
if [ -f "$P/bin/doubao-patch" ]; then
|
||||
"$P/bin/sh" "$P/bin/doubao-patch" >> "$P/var/log/doubao-patch.log" 2>&1
|
||||
fi
|
||||
exit $rc
|
||||
@@ -1,6 +1,8 @@
|
||||
// 顶层构建脚本:只声明插件版本
|
||||
plugins {
|
||||
id("com.android.application") version "8.7.3" apply false
|
||||
// nodekit 是安卓库(要和 app 用同一个 AGP,版本必须一致)
|
||||
id("com.android.library") version "8.7.3" apply false
|
||||
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
|
||||
// Kotlin 2.0 起 Compose 编译器是独立插件
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
|
||||
|
||||
BIN
android/doubao-release.jks
Normal file
BIN
android/doubao-release.jks
Normal file
Binary file not shown.
1508
android/kernel/agent_api.py
Normal file
1508
android/kernel/agent_api.py
Normal file
File diff suppressed because it is too large
Load Diff
378
android/kernel/agent_context.py
Normal file
378
android/kernel/agent_context.py
Normal file
@@ -0,0 +1,378 @@
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
|
||||
## 这个模块只做一件事
|
||||
|
||||
把「人设 + Skill 手册 + 世界观 + 情绪 + 记忆 + 同伴情绪」按**固定顺序**
|
||||
拼成一段 system prompt。
|
||||
|
||||
## 为什么单独一个模块,而不是写在 agent_loop 里
|
||||
|
||||
因为这里有**六种来源**,每一种都要判空、要查库/查 JSON、出错了还不能把
|
||||
整轮对话带崩。塞在 agent_loop 里会让那个函数变成两百行,而且没法单独测。
|
||||
|
||||
## 几条硬约定
|
||||
|
||||
**① 空段整段删掉。**
|
||||
绑没绑世界观、有没有情绪、记没记过东西 —— 都是常态。
|
||||
不删的话每次对话都带着一堆空的 `<worldview></worldview>`,
|
||||
模型会以为"这里本来该有内容但我没看到",反而更容易瞎编。
|
||||
|
||||
**② 顺序固定:人设 → skills → worldview → emotion → memory → peer_emotions。**
|
||||
见附录 C。顺序不是审美问题:记忆在情绪之后,模型读到"我现在有点烦"
|
||||
再看记忆,语气才连贯;反过来它会先看到一堆事实、再看到情绪,像事后补的。
|
||||
|
||||
**③ 每轮重新拼。**
|
||||
记忆和情绪随时会变(AI 自己就能改),拼一次缓存住的话,
|
||||
用户会看到"我明明让它记住了,下一句它又忘了"。
|
||||
|
||||
**④ 查库失败一律当成"这段没有"。**
|
||||
数据库被锁、文件损坏都不该让用户发不出消息。
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_engine
|
||||
import store
|
||||
from defaults import (
|
||||
BUILTIN_SKILL,
|
||||
DEFAULT_MEMORY_LINE,
|
||||
DEFAULT_PROMPT_TEMPLATE,
|
||||
)
|
||||
|
||||
# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。
|
||||
#: 段落名,**顺序就是注入顺序**(需求附录 C,v1.2 按缓存友好重排)。
|
||||
#:
|
||||
#: ★★ 为什么顺序这么重要:主流模型的上下文缓存都是**前缀匹配** ——
|
||||
#: 从第一个 token 开始逐段比对,一处不同则**其后全部失效**。
|
||||
#: 所以最稳的排前面(prompt/skills/worldview/memory 组成长前缀),
|
||||
#: 最易变的排最后(stats/status/emotion/peer_emotions)。
|
||||
#:
|
||||
#: 改之前 emotion 在 memory 前面 —— 情绪一变,连最长的 memory 段
|
||||
#: 一起失效。挪到后面之后,情绪变化只影响末尾那几个短段。
|
||||
#:
|
||||
#: ★ 这个元组**同时决定** `render` 处理哪些段:不在里面的占位符不会被替换,
|
||||
#: 会原样留在提示词里(带着 `{xxx}` 大括号)。加新段时两处一起改。
|
||||
SECTIONS = ('skills', 'worldview', 'memory', 'stats', 'status', 'emotion', 'peer_emotions')
|
||||
|
||||
|
||||
def _safe(fn, fallback):
|
||||
"""
|
||||
跑一个小查询,出错就当"没有"。
|
||||
|
||||
★ 单独抽出来是因为这个模式在这里出现六次:**任何一处查库失败都不该
|
||||
让整轮对话发不出去**(数据库锁了、agent.db 被删了、JSON 坏了)。
|
||||
"""
|
||||
try:
|
||||
return fn()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[agent_context] 取上下文失败,按"没有"处理:{exc}', file=__import__('sys').stderr)
|
||||
return fallback
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 各段
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def build_skills(agent: dict) -> str:
|
||||
"""
|
||||
`<skills>` 段:内置手册 + 这个智能体绑定的自定义 Skill(**按绑定顺序**)。
|
||||
|
||||
内置的那份永远在最前面 —— 它讲的是记忆/情绪这些**基础工具**怎么用,
|
||||
自定义 Skill 是额外的,放后面读起来才是"先会基本操作,再学扩展"。
|
||||
"""
|
||||
parts = [BUILTIN_SKILL.strip()] if BUILTIN_SKILL.strip() else []
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if agent_id:
|
||||
for sid in _safe(lambda: agentdb.skills_of(agent_id), []):
|
||||
sk = _safe(lambda: store.get_resource('skills', sid), None)
|
||||
if sk and (sk.get('content') or '').strip():
|
||||
parts.append(f'【{(sk.get("name") or "Skill").strip()}】\n{sk["content"].strip()}')
|
||||
return '\n\n'.join(parts)
|
||||
|
||||
|
||||
def build_worldview(agent: dict) -> str:
|
||||
"""`<worldview>` 段:绑定的世界观设定文本(没绑就是空)"""
|
||||
wid = (agent or {}).get('worldviewId') or ''
|
||||
if not wid:
|
||||
return ''
|
||||
wv = _safe(lambda: store.get_resource('worldviews', wid), None)
|
||||
return (wv or {}).get('setting', '').strip()
|
||||
|
||||
|
||||
def memory_scope(agent: dict) -> str:
|
||||
"""这个智能体当前该读写哪个记忆空间(绑了世界观就是共享空间)"""
|
||||
agent = agent or {}
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def build_emotion(agent: dict) -> str:
|
||||
"""
|
||||
`<emotion>` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)。
|
||||
|
||||
v1.2 双字段,两行都带(附录 C 的模板就是这样):
|
||||
|
||||
preset: 怒
|
||||
text: 这背叛让我无法原谅
|
||||
|
||||
`preset` 是给它**自己**用的(它要据此调整行为),`text` 是扮演质感。
|
||||
两个都注入 —— 这是唯一一处两者都出现的地方(给同伴的只有 preset)。
|
||||
|
||||
★ 「平常 + 没写文本」时整段省掉:不然每个没情绪的智能体都白带一段
|
||||
没有信息量的 `<emotion>`,还占 token。空段整段删除是附录 C 的规矩。
|
||||
"""
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if not agent_id:
|
||||
return ''
|
||||
st = _safe(lambda: agentdb.emotion_state(agent_id), None) or {}
|
||||
preset = (st.get('preset') or '').strip()
|
||||
text = (st.get('text') or '').strip()
|
||||
if not text and preset in ('', agentdb.PRESET_DEFAULT):
|
||||
return ''
|
||||
lines = [f'preset: {preset or agentdb.PRESET_DEFAULT}']
|
||||
if text:
|
||||
lines.append(f'text: {text}')
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def build_memory(agent: dict) -> str:
|
||||
"""
|
||||
`<memory>` 段:那个记忆空间里**会注入给模型**的条目。
|
||||
|
||||
## 注入窗口 + 置顶保护
|
||||
|
||||
"无上限 + 全量注入"这两条长期是矛盾的:攒到几百上千条时,提示词会被
|
||||
记忆撑爆(每条几十字,一千条就是几万 token),而且**越靠后越贵、
|
||||
早期记忆反而挤掉了最近的对话上下文**。
|
||||
|
||||
所以这里按**窗口**裁:
|
||||
|
||||
· **置顶的永远注入**,且排在最前面 —— 那是用户明确说了"这条重要"的
|
||||
· 其余按时间取**最近**的,凑够窗口
|
||||
· 置顶条数超过窗口时,置顶的**全部**注入(窗口是给普通记忆设的,
|
||||
不是用来否决用户明确置顶的东西)
|
||||
· 被裁掉的**没有丢**,AI 还能用 `memory_search` 检索到 ——
|
||||
也就是"降级为仅可检索"
|
||||
|
||||
窗口大小在全局设置里(`memoryWindow`),0 = 不限(退回全量注入)。
|
||||
|
||||
## 共享记忆带作者署名
|
||||
|
||||
共享空间是几个人往同一个本子上写。没有署名的时候,别人写的
|
||||
"我小时候住在海边"在模型眼里就是**它自己的经历** —— 它会当成自己的
|
||||
过去来讲,甚至在用户问起时说"我不记得有这事"。署名之后它才知道
|
||||
"这条是仙辰写的"(需求 3.6 的"交模型调和矛盾记忆"也才有前提:
|
||||
得先分得清谁写的)。
|
||||
|
||||
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
||||
"""
|
||||
scope = memory_scope(agent)
|
||||
items = _safe(lambda: agentdb.memory_list(scope), [])
|
||||
if not items:
|
||||
return ''
|
||||
|
||||
# ---- 窗口裁剪 ----
|
||||
settings = _safe(store.read_settings, {}) or {}
|
||||
try:
|
||||
window = int(settings.get('memoryWindow') or 0)
|
||||
except (TypeError, ValueError):
|
||||
window = 0
|
||||
total = len(items)
|
||||
trimmed = 0
|
||||
if window > 0 and total > window:
|
||||
pinned = [m for m in items if m.get('pinned')]
|
||||
rest = [m for m in items if not m.get('pinned')]
|
||||
room = max(0, window - len(pinned))
|
||||
keep = pinned + (rest[-room:] if room else [])
|
||||
# 顺序:置顶的在前(用户明确要的),其余保持时间顺序
|
||||
items = keep
|
||||
trimmed = total - len(keep)
|
||||
parts = []
|
||||
if pinned:
|
||||
parts.append(f'置顶 {len(pinned)} 条')
|
||||
if trimmed:
|
||||
parts.append(f'另有 {trimmed} 条较早的没放进来(用 memory_search 还能搜到)')
|
||||
note = '(' + ';'.join(parts) + ')' if parts else ''
|
||||
else:
|
||||
note = ''
|
||||
|
||||
tmpl = _safe(
|
||||
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
|
||||
DEFAULT_MEMORY_LINE,
|
||||
)
|
||||
shared = scope.startswith('world:')
|
||||
names = {}
|
||||
if shared:
|
||||
names = {a.get('id'): (a.get('name') or '某人') for a in _safe(store.list_agents, [])}
|
||||
me = (agent or {}).get('id') or ''
|
||||
lines = []
|
||||
for it in items:
|
||||
title = (it.get('title') or '').strip()
|
||||
content = (it.get('content') or '').strip()
|
||||
author = (it.get('author_agent') or '').strip()
|
||||
tags = []
|
||||
if it.get('pinned'):
|
||||
tags.append('置顶')
|
||||
if shared and author:
|
||||
# 自己写的也标出来("你记的")—— 一眼能分清哪些是自己的立场
|
||||
tags.append('你记的' if author == me else f'{names.get(author) or "某人"}记的')
|
||||
if tags:
|
||||
title = f'{title}({",".join(tags)})'
|
||||
try:
|
||||
lines.append(tmpl.format(title=title, content=content))
|
||||
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
|
||||
lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content))
|
||||
body = '\n'.join(lines)
|
||||
return f'{body}\n{note}' if note else body
|
||||
|
||||
|
||||
def build_peer_emotions(agent: dict) -> str:
|
||||
"""
|
||||
`<peer_emotions>` 段:**同世界观其他智能体**的名字(+ 情绪)(需求 3.5)。
|
||||
|
||||
★★ 分两档,不是"开关一关就什么都没有":
|
||||
|
||||
· 绑了世界观但**没开**情绪感知 → 只给**成员名单**(谁在,但看不到情绪)
|
||||
· 绑了世界观且**开了**开关 → 名单 + 各自当前的情绪
|
||||
|
||||
为什么关着也要给名单(复查报告第 5 条):
|
||||
共享记忆是**共用**的,AI 一定会看到"别人写的条目"。如果它连
|
||||
"这个空间里还有别人"都不知道,那些第三人称的条目在它眼里就是
|
||||
**自己的记忆**——它会以为"我什么时候去过九霄山?",
|
||||
于是把别人的经历当成自己的,或者在正文里跟用户说"我没记过这个"。
|
||||
名单不含情绪,所以"角色内的隐私"这条边界仍然守住了。
|
||||
|
||||
★ 情绪感知开关默认关(需求原话"默认关闭")—— 别人的**情绪**属于
|
||||
角色内的隐私,默认让 AI 看到会让它们的表现互相串味。
|
||||
"""
|
||||
agent = agent or {}
|
||||
if not agent.get('worldviewId'):
|
||||
return ''
|
||||
my_id = agent.get('id') or ''
|
||||
wid = agent.get('worldviewId') or ''
|
||||
others = [
|
||||
a for a in _safe(store.list_agents, [])
|
||||
if a.get('worldviewId') == wid and a.get('id') != my_id
|
||||
]
|
||||
if not others:
|
||||
return ''
|
||||
|
||||
by_id = {a.get('id'): a for a in others}
|
||||
names = [(by_id.get(aid) or {}).get('name') or '某人' for aid in by_id]
|
||||
|
||||
if not agent.get('emotionEnabled'):
|
||||
return ';'.join(f'{n}(不知道他此刻的情绪)' for n in names)
|
||||
|
||||
rows = _safe(
|
||||
lambda: agentdb.peer_emotions(wid, my_id, list(by_id)),
|
||||
[],
|
||||
)
|
||||
emo_by_id = {aid: (emo or '').strip() for aid, emo in rows}
|
||||
parts = []
|
||||
for aid, one in by_id.items():
|
||||
# ★ `by_id.items()` 给的是 (id, **整个 agent 字典**),不是 (id, 名字)——
|
||||
# 直接 f'{name}-{emo}' 会把 agent 的 JSON 拼进提示词(踩过)
|
||||
name = one.get('name') or '某人'
|
||||
# ★ v1.2:这里给的是 **preset(五档)不是 text**。
|
||||
# text 是那个角色的内心独白,读给别的角色听等于扒开他的脑子;
|
||||
# preset 才是"看得出来他现在什么脸色"这个粒度。
|
||||
emo = emo_by_id.get(aid) or ''
|
||||
parts.append(f'{name}-{emo}' if emo else f'{name}(看不出什么情绪)')
|
||||
return ';'.join(parts)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 拼装
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_RE_BLOCK = {name: re.compile(rf'<{name}>.*?</{name}>', re.S) for name in SECTIONS}
|
||||
|
||||
|
||||
def render(template: str, values: dict) -> str:
|
||||
"""
|
||||
按模板渲染,**空的段整段删掉**。
|
||||
|
||||
★ 先渲染 `{prompt}` 再处理段:人设里如果碰巧有 `<memory>` 这样的字
|
||||
(用户自己写的提示词里完全可能),会被当成段处理掉 —— 所以段的匹配
|
||||
只在**模板**上做,不在渲染结果上做。
|
||||
"""
|
||||
out = (template or DEFAULT_PROMPT_TEMPLATE).replace('{prompt}', (values.get('prompt') or '').strip())
|
||||
for name in SECTIONS:
|
||||
block = _RE_BLOCK[name].search(out)
|
||||
if not block:
|
||||
continue
|
||||
value = (values.get(name) or '').strip()
|
||||
if value:
|
||||
out = out[:block.start()] + f'<{name}>\n{value}\n</{name}>' + out[block.end():]
|
||||
else:
|
||||
out = out[:block.start()] + out[block.end():]
|
||||
# 段被删掉后会留下连续空行,压一压;别让提示词里出现四五行的空白
|
||||
out = re.sub(r'\n{3,}', '\n\n', out)
|
||||
return out.strip()
|
||||
|
||||
|
||||
def build_system_prompt(settings: dict, agent: dict) -> str:
|
||||
"""
|
||||
这一轮要用的 system prompt。
|
||||
|
||||
[settings] 里可以覆盖:`promptTemplate`(整份模板)、`memoryLine`(记忆条目排版)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
settings = settings or {}
|
||||
prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '')
|
||||
values = {
|
||||
'prompt': prompt,
|
||||
# ---- 稳定段:它们在提示词最前面,靠它们拿前缀缓存命中 ----
|
||||
'skills': build_skills(agent),
|
||||
'worldview': build_worldview(agent),
|
||||
'memory': build_memory(agent),
|
||||
# ---- 易变段:放最后,变了也只让末尾失效 ----
|
||||
# stats / status 是 v1.2 §3.10/3.11 的规则引擎段,实现见阶段 3;
|
||||
# 现在返回空串 → `render` 会把整段删掉(不会留下空标签)
|
||||
'stats': build_stats(agent),
|
||||
'status': build_status(agent),
|
||||
'emotion': build_emotion(agent),
|
||||
'peer_emotions': build_peer_emotions(agent),
|
||||
}
|
||||
template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE
|
||||
return render(template, values)
|
||||
|
||||
|
||||
def pack_of(agent: dict) -> str:
|
||||
"""
|
||||
这个智能体用的规则包 id(`世界观.rulePackId`),没有就空串。
|
||||
|
||||
★ 数值状态包挂在**世界观**上(需求 §3.6:"v1.2 起,世界观同时是
|
||||
数值状态包的挂载点"),所以没绑世界观就没有规则引擎 —— 返回空串,
|
||||
`<stats>` / `<status>` 两段会被整段删掉。
|
||||
"""
|
||||
wid = ((agent or {}).get('worldviewId') or '').strip()
|
||||
if not wid:
|
||||
return ''
|
||||
world = _safe(lambda: store.get_resource('worldviews', wid), None) or {}
|
||||
return (world.get('rulePackId') or '').strip()
|
||||
|
||||
|
||||
def build_stats(agent: dict) -> str:
|
||||
"""
|
||||
`<stats>` 段:数值系统(需求附录 C / §3.10)。
|
||||
|
||||
格式见 `rule_engine.stats_section`。没绑世界观、或世界观没挂规则包 → 空段。
|
||||
"""
|
||||
pack = pack_of(agent)
|
||||
if not pack:
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.stats_section(agent or {}, pack), '')
|
||||
|
||||
|
||||
def build_status(agent: dict) -> str:
|
||||
"""
|
||||
`<status>` 段:状态系统(需求附录 C / §3.11)。
|
||||
|
||||
★ 和 `<stats>` 不同,它**不要求绑世界观**:状态一旦被赋予就挂在智能体
|
||||
自己身上,解绑世界观不该让它身上的状态凭空消失(那和"解绑不丢记忆"
|
||||
是同一个道理)。
|
||||
"""
|
||||
if not ((agent or {}).get('id') or ''):
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.status_section(agent or {}), '')
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||||
@@ -10,8 +10,11 @@ Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from typing import Callable, Optional
|
||||
|
||||
import agent_context
|
||||
import store
|
||||
import tools_runtime
|
||||
from providers import stream_chat
|
||||
@@ -19,6 +22,216 @@ from providers import stream_chat
|
||||
MAX_TOOL_RESULT_CHARS = 6000
|
||||
|
||||
|
||||
def add_usage(total, one) -> dict:
|
||||
"""
|
||||
把一次调用的 usage 累加进总数。
|
||||
|
||||
★ 各家的字段名不一样(OpenAI 系是 prompt_tokens / completion_tokens,
|
||||
兼容网关有时给 input_tokens / output_tokens),**两种都认** ——
|
||||
只认一种的话换个提供商统计就静默变成 0,而"统计是 0"极难被发现。
|
||||
"""
|
||||
if not isinstance(one, dict):
|
||||
return total or {}
|
||||
out = dict(total or {})
|
||||
pairs = (
|
||||
('prompt_tokens', 'prompt_tokens'),
|
||||
('completion_tokens', 'completion_tokens'),
|
||||
('total_tokens', 'total_tokens'),
|
||||
('input_tokens', 'prompt_tokens'), # 兼容写法
|
||||
('output_tokens', 'completion_tokens'), # 兼容写法
|
||||
)
|
||||
for src, dst in pairs:
|
||||
v = one.get(src)
|
||||
if isinstance(v, (int, float)):
|
||||
out[dst] = int(out.get(dst) or 0) + int(v)
|
||||
# 缓存命中也累加(需求 3.1 的 v1.2 新增)。
|
||||
# ★ 累加的是**归一化之后**的两个数,不是原始字段:各家的名字不一样,
|
||||
# 直接并进 out 的话,换了模型那个 key 就消失了。
|
||||
hit, miss = cache_pair(one)
|
||||
if hit or miss:
|
||||
out['cache_hit'] = int(out.get('cache_hit') or 0) + hit
|
||||
out['cache_miss'] = int(out.get('cache_miss') or 0) + miss
|
||||
if 'total_tokens' not in out:
|
||||
out['total_tokens'] = int(out.get('prompt_tokens') or 0) + int(out.get('completion_tokens') or 0)
|
||||
return out
|
||||
|
||||
|
||||
#: 各家的「缓存命中」字段名。**加新提供商只改这一处**,不要在调用点写 if。
|
||||
#:
|
||||
#: DeepSeek prompt_cache_hit_tokens / prompt_cache_miss_tokens(两个都给)
|
||||
#: Claude cache_read_input_tokens(只给命中)
|
||||
#: OpenAI prompt_tokens_details.cached_tokens(嵌套,也只给命中)
|
||||
_CACHE_HIT_KEYS = ('prompt_cache_hit_tokens', 'cache_read_input_tokens', 'cached_tokens')
|
||||
|
||||
|
||||
def cache_pair(usage) -> tuple:
|
||||
"""
|
||||
从 usage 里取出 `(cache_hit, cache_miss)`(需求 3.1 的 v1.2 新增)。
|
||||
|
||||
★ 为什么必须归一化:三家的字段名完全不同,不归一化的话,
|
||||
界面上那个"缓存命中率"会因为换了个模型就**静默变成 0**
|
||||
(而不是报错 —— 静默的 0 最难发现,用户会以为"缓存没生效")。
|
||||
|
||||
★ 两家只给命中、不给未命中(Claude / OpenAI),所以未命中要**自己推**:
|
||||
`prompt_tokens - hit`。推不出来时返回 0,界面据此**不显示那一列** ——
|
||||
显示一个假的 0% 是误导。
|
||||
"""
|
||||
u = usage if isinstance(usage, dict) else {}
|
||||
hit = 0
|
||||
for key in _CACHE_HIT_KEYS:
|
||||
v = u.get(key)
|
||||
if isinstance(v, (int, float)) and v > 0:
|
||||
hit = int(v)
|
||||
break
|
||||
if not hit:
|
||||
# OpenAI 把它塞在嵌套对象里
|
||||
details = u.get('prompt_tokens_details')
|
||||
if isinstance(details, dict):
|
||||
v = details.get('cached_tokens')
|
||||
if isinstance(v, (int, float)) and v > 0:
|
||||
hit = int(v)
|
||||
|
||||
miss = 0
|
||||
v = u.get('prompt_cache_miss_tokens')
|
||||
if isinstance(v, (int, float)) and v > 0:
|
||||
miss = int(v)
|
||||
if hit and not miss:
|
||||
total = u.get('prompt_tokens') or u.get('input_tokens')
|
||||
if isinstance(total, (int, float)) and total >= hit:
|
||||
miss = int(total) - hit
|
||||
return hit, miss
|
||||
|
||||
|
||||
def usage_pair(usage) -> tuple:
|
||||
"""从 usage 里取出 (输入, 输出)。给落库用 —— 字段名差异在这一处抹平"""
|
||||
u = usage if isinstance(usage, dict) else {}
|
||||
return int(u.get('prompt_tokens') or 0), int(u.get('completion_tokens') or 0)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 幻觉调用检测(需求 3.7)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 「嘴上说记住了、实际没调工具」是这类有记忆的助手最常见、也最伤信任的毛病:
|
||||
# 用户当场看不出来(那句"我记住了"说得很自然),下次对话发现它完全不记得,
|
||||
# 从此就不信这个功能了。
|
||||
#
|
||||
# 而"它打算记"和"它真的记了"在**正文里看不出区别**,只能由程序比对
|
||||
# 「说了什么」和「做了什么」。所以这里做一次兜底。
|
||||
|
||||
#: 「声称记住了」的措辞。
|
||||
# ★ 宁可漏判也别误伤:误伤会让用户看到莫名其妙的警告,几次之后他就不看那个警告了
|
||||
# (比没有还糟)。所以只收明确说"我记住了"的句式,不收"我会记得的"这种客套。
|
||||
_CLAIM_RE = re.compile(
|
||||
r'我(已经)?(记住|记下|记好)了|已(经)?(记住|记下)|记到(我的)?记忆|'
|
||||
r'存(进|入)(了)?(我的)?记忆|我把它记|已经帮你记|记在小本本'
|
||||
)
|
||||
|
||||
|
||||
def detects_memory_claim(content: str) -> bool:
|
||||
"""这句话里有没有"我记住了"这类断言"""
|
||||
return bool(_CLAIM_RE.search(content or ''))
|
||||
|
||||
|
||||
def check_hallucinated_memory(content: str, tool_call_count: int, tools_available: bool) -> bool:
|
||||
"""
|
||||
这一轮该不该打「⚠ 声称记忆但未实际调用」的标记(需求 3.7)。
|
||||
|
||||
★ [tools_available] 是必须的:如果用户把 Python 工具整个关了,
|
||||
模型**想调也调不了**,那时警告它"没调用工具"是冤枉它 ——
|
||||
而且警告会一直挂着,用户会以为坏了。
|
||||
"""
|
||||
if not tools_available:
|
||||
return False
|
||||
if tool_call_count > 0:
|
||||
return False
|
||||
return detects_memory_claim(content)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 兼容降级:不支持 function calling 的模型(需求 3.3)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 有些模型(本地小模型、老网关)根本不支持 tools 参数 —— 传过去轻则被忽略、
|
||||
# 重则直接 400。而"记忆/情绪"这些能力**恰恰靠工具**,没有降级的话,
|
||||
# 用户换上这类模型之后会发现"记忆功能突然全废了",而且看不出原因。
|
||||
#
|
||||
# 降级做法:不传 tools,改成**在提示词里约定一种正文内的调用格式**,
|
||||
# 回复回来后由内核解析、执行、并从正文里剥掉。用户看到的还是干净的回答。
|
||||
#
|
||||
# ★ 为什么选"代码块里写 JSON"而不是别的:
|
||||
# · 模型对"输出 JSON"这件事训练得很充分,比自创的标记语法可靠得多
|
||||
# · 代码块有明确的边界,正则能稳稳地切出来;万一没被剥掉,
|
||||
# 用户看到的也是一段像模像样的 JSON,而不是一堆乱码
|
||||
|
||||
DEGRADED_HINT = '\n'.join([
|
||||
'',
|
||||
'【工具调用】你**不能直接调用函数**,但需要用到工具时,请在回复里单独写一段:',
|
||||
'',
|
||||
'```doubao-call',
|
||||
'{"tool": "memory_add", "args": {"title": "标题", "content": "内容"}}',
|
||||
'```',
|
||||
'',
|
||||
'可用的工具:memory_add、memory_update、memory_forget、memory_search、'
|
||||
'emotion_set、get_token_usage。',
|
||||
'这一段会被系统执行并从你的回复里**去掉**,用户看不到它。',
|
||||
'★ 需要记住什么的时候,**必须**写这一段 —— 只在正文里说"我记住了"是没用的,'
|
||||
'那样你其实什么都没记。',
|
||||
])
|
||||
|
||||
_RE_DEGRADED_CALL = re.compile(r'```doubao-call\s*\n(.*?)\n?```', re.S)
|
||||
|
||||
|
||||
def run_degraded_calls(content: str, settings: dict) -> tuple:
|
||||
"""
|
||||
执行降级模式写在正文里的结构化调用。
|
||||
|
||||
返回 `(剥掉调用块之后的正文, 执行记录)`。
|
||||
|
||||
★ 解析不了的块**原样留在正文里**:与其默默删掉(用户永远不知道它想干什么),
|
||||
不如让用户看见"它写了一段系统没认出来的东西" —— 那说明模型该换了。
|
||||
"""
|
||||
import agent_tools
|
||||
|
||||
records = []
|
||||
|
||||
def _one(match):
|
||||
raw = (match.group(1) or '').strip()
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except Exception: # noqa: BLE001 - 解析不了就留着,见 docstring
|
||||
return match.group(0)
|
||||
if not isinstance(payload, dict):
|
||||
return match.group(0)
|
||||
name = str(payload.get('tool') or '').strip()
|
||||
args = payload.get('args') if isinstance(payload.get('args'), dict) else {}
|
||||
entry = agent_tools.AGENT_TOOLS.get(name)
|
||||
rec = {
|
||||
'id': f'degraded_{len(records)}',
|
||||
'name': name or '(没写工具名)',
|
||||
'args': args,
|
||||
'ok': False,
|
||||
'result': '',
|
||||
'error': '',
|
||||
}
|
||||
if entry is None:
|
||||
rec['error'] = f'没有这个工具:{name}'
|
||||
else:
|
||||
try:
|
||||
out = entry['run'](args)
|
||||
rec['ok'] = True
|
||||
rec['result'] = json.dumps(out, ensure_ascii=False)[:2000]
|
||||
except Exception as exc: # noqa: BLE001 - 工具报错不该让整轮回答失败
|
||||
rec['error'] = str(exc)
|
||||
records.append(rec)
|
||||
return ''
|
||||
|
||||
stripped = _RE_DEGRADED_CALL.sub(_one, content or '')
|
||||
# 调用块被剥掉之后往往留下两三行空白,压一压
|
||||
stripped = re.sub(r'\n{3,}', '\n\n', stripped).strip()
|
||||
return stripped, records
|
||||
|
||||
|
||||
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||||
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||||
if isinstance(text, str):
|
||||
@@ -42,8 +255,43 @@ def _max_rounds(settings: dict) -> int:
|
||||
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 画图、动态渲染都行)。',
|
||||
' ★★ 用户在界面上的选择**会回到你手里**:页面里调',
|
||||
' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放',
|
||||
' `<button data-doubao-result="值">`。**关掉界面**用 `Doubao.close()`。',
|
||||
' ★ show_ui 有个 `wait` 参数,按需要选:',
|
||||
' · wait 不传(默认)= 弹出就继续,不等用户。适合图表/报告这类给人看的;',
|
||||
' 用户点过什么,等他下次说话时会作为上下文给你。',
|
||||
' · wait=true = **等用户点一个回传按钮或关掉界面**(默认不限时,会一直等)。',
|
||||
' 用户点的值**立刻**作为返回值给你,你能在同一个回合里接着干。',
|
||||
' 适合"弹几个选项让用户挑,然后我继续"。一般别传 timeout。',
|
||||
' ★ 放按钮时要做**明显**:亮蓝底 + 白字,别用纯文字当按钮 ——',
|
||||
' 深色主题下暗底暗字用户根本看不出那儿能点。',
|
||||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||||
'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) -> dict:
|
||||
should_stop: Optional[Callable[[], bool]] = None,
|
||||
conversation_id: str = '', send_depth: int = 0) -> dict:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
@@ -52,6 +300,10 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||
emit 事件回调,直接往 SSE 里写
|
||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
|
||||
send_depth `send_message` 嵌套了几层。AI 主动发消息会顺手跑一轮回复,
|
||||
那一轮就是 depth+1;超过上限时工具会被拒。
|
||||
**这是防无限套娃的关键**(见 app.py 的 /api/session-message)。
|
||||
"""
|
||||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||||
@@ -60,7 +312,71 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
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 ''
|
||||
# ★★ system prompt **每轮重新拼**(需求 3.2):人设 → skills → 世界观 →
|
||||
# 情绪 → 记忆 → 同伴情绪,顺序固定(附录 C)。
|
||||
#
|
||||
# 为什么不拼一次缓存住:记忆和情绪**随时会变**,而且 AI 自己就能改它们
|
||||
# (memory_add / emotion_set)。缓存住的表现是"我明明让它记住了,
|
||||
# 下一句它又忘了"——这种 bug 用户会当成"记忆功能坏了"。
|
||||
#
|
||||
# 拼法、判空、查库失败的兜底全在 agent_context.py 里。
|
||||
system_prompt = agent_context.build_system_prompt(settings, agent or {})
|
||||
# ★★ 界面能力的用法**只在开关打开时才追加**。
|
||||
#
|
||||
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
|
||||
# 会存进用户的 settings.json;而开关可能是关的 —— 关着的时候提示词里
|
||||
# 还在教模型"你可以用 show_ui",它就会去调,然后收到"工具已关闭"。
|
||||
# 按开关动态追加,两边永远一致。
|
||||
#
|
||||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||||
# ★ 新一轮开始:清掉上一轮的发言权移交(v1.2 §3.9 的"一轮最多一次")。
|
||||
# 放这儿是因为它必须**每轮**重置,而且和线程无关(工具跑在 worker 线程里)
|
||||
tools_runtime.begin_round()
|
||||
|
||||
if tools_runtime.ui_tools_enabled(settings):
|
||||
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
|
||||
|
||||
# ★★ 状态脚本要在**重拼 prompt 之前**跑(需求附录 E 的顺序,固定):
|
||||
#
|
||||
# 状态脚本执行 → 重拼 prompt → 生成
|
||||
#
|
||||
# 顺序反了的话,脚本这一轮的改动要等下一轮才生效 ——
|
||||
# 表现是"中毒了但 AI 这轮还生龙活虎"。
|
||||
#
|
||||
# ★ 脚本报错**不中断对话**(需求附录 E):错误收集起来给界面提示,
|
||||
# 对话照常往下走。规则脚本是用户自己写的,写错了是常态,
|
||||
# 一次脚本错误把整轮对话搞崩,用户会以为整个 App 坏了。
|
||||
try:
|
||||
import rule_engine
|
||||
|
||||
_turn = rule_engine.run_turn_scripts(agent or {}, agent_context.pack_of(agent or {}))
|
||||
if _turn.get('narration'):
|
||||
# 脚本返回的旁白"作为系统消息注入下一轮"(需求 §3.10)——
|
||||
# 拼在提示词末尾,比单开一条 user 消息干净(不会污染对话记录)
|
||||
system_prompt = (system_prompt + '\n\n【当前状况】\n'
|
||||
+ '\n'.join(_turn['narration'])).strip()
|
||||
for _e in _turn.get('errors') or []:
|
||||
# ★ 异常要**让用户看见**(需求附录 E:"异常归零 + UI 提示")。
|
||||
# 只 print 到 stderr 的话,用户看到的只是"这轮回复有点怪",
|
||||
# 而完全不知道是脚本报错了 —— 而脚本是他自己写的。
|
||||
emit({'type': 'rule_error', 'message': _e})
|
||||
print(f'[rule] {_e}', file=sys.stderr)
|
||||
except Exception as _exc: # noqa: BLE001 - 规则引擎坏了不该让对话发不出去
|
||||
print(f'[rule] 状态脚本执行失败:{_exc}', file=sys.stderr)
|
||||
|
||||
# ★★ 兼容降级(需求 3.3):这个模型不支持 tools 参数时,换成"正文内调用约定"。
|
||||
#
|
||||
# 为什么要这么绕:记忆/情绪这些能力**全靠工具**,而本地小模型、
|
||||
# 老网关很多不支持 function calling(传 tools 过去轻则被忽略、重则 400)。
|
||||
# 不降级的话,用户换上这类模型会发现"记忆功能突然全废了",还看不出原因。
|
||||
#
|
||||
# 判定依据是**模型列表那一项上的开关**(用户在界面上打的标记),
|
||||
# 不做自动探测:各家"不支持"的报错方式五花八门,猜错的代价是
|
||||
# 把一个本来能用的模型降级掉 —— 那比不降级更糟。
|
||||
degraded = bool(provider.get('noTools'))
|
||||
if degraded:
|
||||
tool_defs = []
|
||||
system_prompt = (system_prompt + '\n' + DEGRADED_HINT).strip()
|
||||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||
|
||||
emit({
|
||||
@@ -76,11 +392,52 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
convo = []
|
||||
if system_prompt.strip():
|
||||
convo.append({'role': 'system', 'content': system_prompt})
|
||||
|
||||
# ★★★ AI 界面的**数据回流**在这里进上下文。
|
||||
#
|
||||
# AI 用 show_ui 弹的 HTML 里可以调 `Doubao.sendToAi(值)`,
|
||||
# 安卓桥把它 POST 到 /api/ui-result 排队;这里取走并作为
|
||||
# **一条 system 消息**插在历史前面。
|
||||
#
|
||||
# ★ 为什么是 system 而不是 user:
|
||||
# 它不是用户打的话。塞成 user 会让历史里出现一条用户没说过的话,
|
||||
# 而且用户点"重新生成"时会和真正那条用户消息混在一起。
|
||||
# system 的语义就是"背景信息",正合适。
|
||||
#
|
||||
# ★ 为什么要**取走**:不取走的话这轮用、下轮还用,
|
||||
# 模型会反复提同一件事,用户会以为它卡住了。
|
||||
#
|
||||
# ★ 为什么放在 messages **之前**:它是"用户接下来这句话的前提",
|
||||
# 要让模型先看到"用户在界面上选了什么",再读用户那句话。
|
||||
ui_results = store.take_pending_ui(conversation_id) if conversation_id else []
|
||||
if ui_results:
|
||||
lines = '\n'.join(f'- {v}' for v in ui_results)
|
||||
convo.append({
|
||||
'role': 'system',
|
||||
'content': (
|
||||
'用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):\n'
|
||||
f'{lines}\n'
|
||||
'请结合这些信息回答用户接下来的话;如果用户还没说话,就针对这些选择给出回应。'
|
||||
),
|
||||
})
|
||||
# 也让界面知道模型收到了 —— 前端可以据此显示"AI 已收到你的选择"
|
||||
emit({'type': 'ui_results', 'count': len(ui_results)})
|
||||
|
||||
convo.extend(messages)
|
||||
|
||||
answer = ''
|
||||
reasoning_all = ''
|
||||
tool_call_count = 0
|
||||
# ★ 工具调用的**明细**(不只次数)。
|
||||
#
|
||||
# 界面上的"工具卡片"(调了什么、成没成、返回了什么)以前只有流式那一刻
|
||||
# 能看到 —— 因为这份明细**从来没落过库**,重启 App 就全没了。
|
||||
# 用户的原话:「工具怎么重启就不显示了」。
|
||||
#
|
||||
# 只留 id/name/ok/result 四样:args 可能很长(贴进去的代码),
|
||||
# 而用户真正想回看的是"它做了什么、拿到什么"。result 也截断,
|
||||
# 不然一条消息能撑爆会话 JSON。
|
||||
tool_trace = []
|
||||
usage = None
|
||||
|
||||
for round_index in range(max_rounds):
|
||||
@@ -91,7 +448,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
# provider 是"提供商名字"(ark/openai),已经按"智能体 > 全局"解析过了
|
||||
provider=provider_key,
|
||||
base_url=provider.get('baseUrl'),
|
||||
api_key=settings.get('apiKey') or '',
|
||||
api_key=provider.get('apiKey') or '',
|
||||
model=provider.get('model'),
|
||||
messages=convo,
|
||||
tools=tool_defs if tool_defs else None,
|
||||
@@ -112,20 +469,42 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
elif kind == 'tool_calls':
|
||||
tool_calls = event.get('toolCalls') or []
|
||||
elif kind == 'usage':
|
||||
usage = event.get('usage')
|
||||
# ★★ **累加**而不是覆盖。
|
||||
#
|
||||
# 多轮工具调用时每一轮上游都会来一个 usage,以前是直接赋值 ——
|
||||
# 只留最后一轮。而消耗的大头恰恰在前面几轮(工具结果很长,
|
||||
# 一轮就是几千 input token),丢掉之后统计出来的数字
|
||||
# 会少得离谱,用户会以为"怎么才用了这么点"。
|
||||
usage = add_usage(usage, event.get('usage'))
|
||||
|
||||
if not tool_calls:
|
||||
# 降级模式(需求 3.3):模型不会 function calling,改成让它把调用
|
||||
# **写在正文里**(```doubao-call 代码块),这里执行掉并从正文里剥掉。
|
||||
# 执行记录照常发 tool_call / tool_result 事件,所以界面上的工具痕迹、
|
||||
# 幻觉检测这些下游逻辑完全不用改。
|
||||
final = answer
|
||||
if degraded:
|
||||
final, records = run_degraded_calls(answer, settings)
|
||||
for r in records:
|
||||
emit({'type': 'tool_call', 'id': r['id'], 'name': r['name'], 'args': r.get('args')})
|
||||
emit({
|
||||
'type': 'tool_result', 'id': r['id'], 'name': r['name'],
|
||||
'ok': r['ok'], 'result': r['result'], 'error': r['error'],
|
||||
})
|
||||
if records:
|
||||
tool_call_count += len(records)
|
||||
emit({
|
||||
'type': 'done',
|
||||
'content': answer,
|
||||
'content': final,
|
||||
'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1,
|
||||
'toolCalls': tool_call_count,
|
||||
'usage': usage,
|
||||
})
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'content': final, 'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
'toolTrace': tool_trace,
|
||||
}
|
||||
|
||||
convo.append({
|
||||
@@ -148,10 +527,26 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
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 '',
|
||||
# ★★ 防无限套娃:send_message 触发的回复里再发消息,深度 +1。
|
||||
# 这个值一路传到(Kotlin 桥 → 内核 /api/session-message),
|
||||
# 超过 SESSION_MSG_MAX_DEPTH 就被拒。
|
||||
# **不传的话**:模型发一条 → 那轮回复里再发 → 无限套娃,
|
||||
# 一个下午能把 API 额度烧光,用户看到满屏没发过的消息。
|
||||
sendDepth=send_depth,
|
||||
)
|
||||
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)
|
||||
@@ -165,6 +560,13 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
'result': payload,
|
||||
})
|
||||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||||
# ★ 记明细(落库用,见上面 tool_trace 的注释)
|
||||
tool_trace.append({
|
||||
'id': tc.get('id') or '',
|
||||
'name': tc.get('name') or '',
|
||||
'ok': bool(result.get('ok')),
|
||||
'result': str(payload)[:800],
|
||||
})
|
||||
|
||||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||||
emit({
|
||||
@@ -179,4 +581,5 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
'toolTrace': tool_trace,
|
||||
}
|
||||
|
||||
773
android/kernel/agent_tools.py
Normal file
773
android/kernel/agent_tools.py
Normal file
@@ -0,0 +1,773 @@
|
||||
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
|
||||
|
||||
## 为什么是"内置工具"而不是 `tools/*.py`
|
||||
|
||||
`tools/` 下的工具是**用户可改的 .py 文件**(内核启动时播种到手机上的可写目录)。
|
||||
这七个不一样:
|
||||
|
||||
· 它们要读写 `agent.db`(记忆、情绪、Token 统计)—— 那是内核进程内的模块,
|
||||
电脑端的工具是**子进程**,根本 import 不到
|
||||
· 它们是系统的核心能力,不该被用户在 tools/ 里改坏(改坏了 AI 会"失忆",
|
||||
而且表现是"有时记得有时不记得",极难查)
|
||||
|
||||
所以走 `builtin_tools.BUILTIN_TOOLS` 那条路(进程内、不进 tools/、不参与播种)。
|
||||
|
||||
## 限权规则(需求 3.6,**共享记忆里最重要的一条**)
|
||||
|
||||
绑定了世界观的智能体共用一个记忆空间,于是"谁都能删"就成了问题:
|
||||
|
||||
· `memory_add` —— 任何智能体都能往共享空间写(追加优先)
|
||||
· `memory_forget` / `memory_update` —— **只能动自己写的**(按 author_agent 判定)
|
||||
· `pinned` —— 用户标记"必须保留"的条目,AI 连自己的都改不动
|
||||
|
||||
改别人的条目只能由**用户在界面上手动做**。这条不做的话,
|
||||
两个智能体互相删对方的记忆,用户会看到"记忆莫名其妙少了"。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import agentdb
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 拿"我现在是谁"
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _ctx() -> dict:
|
||||
"""
|
||||
当前这次工具调用的上下文(哪次对话、哪个智能体)。
|
||||
|
||||
★ 局部 import:`tools_runtime` → `builtin_tools` → 这里,顶部 import 就成环了。
|
||||
"""
|
||||
import tools_runtime
|
||||
|
||||
return tools_runtime.current_context() or {}
|
||||
|
||||
|
||||
def _me() -> dict:
|
||||
"""当前智能体(拿不到就返回空 dict —— 工具会据此报错,而不是瞎写)"""
|
||||
ctx = _ctx()
|
||||
agent = store.get_agent(ctx.get('agentId') or '') or {}
|
||||
return agent
|
||||
|
||||
|
||||
def _my_scope(agent: dict) -> str:
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def _shared(agent: dict) -> bool:
|
||||
"""是不是在共享空间里(绑了世界观就是)"""
|
||||
return bool(agent.get('worldviewId'))
|
||||
|
||||
|
||||
def _check_editable(item: dict, agent: dict) -> None:
|
||||
"""
|
||||
能不能改/删这一条 —— 不能就抛错(**抛错而不是静默跳过**:
|
||||
静默的话模型以为改成功了,下一轮还按老样子说话)。
|
||||
"""
|
||||
if item.get('pinned'):
|
||||
raise ValueError(
|
||||
'这条记忆被用户标记为「必须保留」,你改不了也删不掉。'
|
||||
'如果它确实过时了,跟用户说一声让他自己处理。'
|
||||
)
|
||||
if _shared(agent) and (item.get('author_agent') or '') != (agent.get('id') or ''):
|
||||
raise ValueError(
|
||||
'这条是**其他智能体**写进共享记忆的,你只能改/删自己写的。'
|
||||
'需要修改它的话,跟用户说让他手动改。'
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
MEMORY_ADD = {
|
||||
'name': 'memory_add',
|
||||
'description': (
|
||||
'记住一件事,**跨对话保留**。用户告诉你的重要事实、偏好、约定、他的项目,'
|
||||
'都该记下来。记之前先看系统提示词里的记忆清单,已经记过的别再记一遍。'
|
||||
'返回新条目的 id(以后要改/删它需要这个 id)。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'title': {'type': 'string', 'description': '一句话标题(检索和整理时的锚点)'},
|
||||
'content': {'type': 'string', 'description': '要记住的正文'},
|
||||
},
|
||||
'required': ['title', 'content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_add(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体,无法写记忆')
|
||||
title = str(args.get('title') or '').strip()
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not title and not content:
|
||||
raise ValueError('title 和 content 至少要有一个')
|
||||
item = agentdb.memory_add(
|
||||
scope=_my_scope(agent),
|
||||
title=title,
|
||||
content=content,
|
||||
author_agent=agent.get('id') or '',
|
||||
)
|
||||
return {
|
||||
'id': item['id'],
|
||||
'title': item['title'],
|
||||
'scope': '共享记忆(世界观)' if _shared(agent) else '你自己的记忆',
|
||||
'note': '已写入。不要只在正文里说"记住了"—— 你现在已经真的记住了,正常继续就行。',
|
||||
}
|
||||
|
||||
|
||||
MEMORY_UPDATE = {
|
||||
'name': 'memory_update',
|
||||
'description': (
|
||||
'修改一条已有的记忆(只改传进来的字段)。'
|
||||
'只能改**你自己写的**、且没被用户标记为「必须保留」的条目。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'id': {'type': 'string', 'description': '记忆的 id(memory_add 返回过,或记忆清单里带的)'},
|
||||
'title': {'type': 'string', 'description': '新标题,不改就不传'},
|
||||
'content': {'type': 'string', 'description': '新正文,不改就不传'},
|
||||
},
|
||||
'required': ['id'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_update(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
mid = str(args.get('id') or '').strip()
|
||||
if not mid:
|
||||
raise ValueError('id 不能为空')
|
||||
item = agentdb.memory_get(mid)
|
||||
# ★ 只允许改**自己这个记忆空间**里的条目:不然知道 id 就能改到别人的私有记忆
|
||||
if not item or item.get('scope') != _my_scope(agent):
|
||||
raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)')
|
||||
_check_editable(item, agent)
|
||||
updated = agentdb.memory_update(
|
||||
mid,
|
||||
title=args.get('title') if 'title' in args else None,
|
||||
content=args.get('content') if 'content' in args else None,
|
||||
)
|
||||
return {'id': mid, 'title': (updated or {}).get('title', ''), 'note': '已更新。'}
|
||||
|
||||
|
||||
MEMORY_FORGET = {
|
||||
'name': 'memory_forget',
|
||||
'description': (
|
||||
'删掉一条记忆。只能删**你自己写的**、且没被用户标记为「必须保留」的条目。'
|
||||
'拿不准该不该删时,先问用户。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'id': {'type': 'string', 'description': '要删的记忆 id'},
|
||||
},
|
||||
'required': ['id'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_forget(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
mid = str(args.get('id') or '').strip()
|
||||
if not mid:
|
||||
raise ValueError('id 不能为空')
|
||||
item = agentdb.memory_get(mid)
|
||||
if not item or item.get('scope') != _my_scope(agent):
|
||||
raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)')
|
||||
_check_editable(item, agent)
|
||||
agentdb.memory_forget(mid)
|
||||
return {'id': mid, 'forgotten': True, 'note': '已删除。'}
|
||||
|
||||
|
||||
MEMORY_SEARCH = {
|
||||
'name': 'memory_search',
|
||||
'description': (
|
||||
'在自己的记忆库里检索。系统提示词里的记忆清单是**全量**的,'
|
||||
'但条数多的时候你可能只想找相关的几条 —— 用这个按关键词查。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'keyword': {'type': 'string', 'description': '关键词(标题和正文都会匹配)'},
|
||||
'limit': {'type': 'number', 'description': '最多返回几条,默认 10'},
|
||||
},
|
||||
'required': ['keyword'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_search(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
kw = str(args.get('keyword') or '').strip()
|
||||
if not kw:
|
||||
raise ValueError('keyword 不能为空')
|
||||
try:
|
||||
limit = int(float(args.get('limit') or 10))
|
||||
except (TypeError, ValueError):
|
||||
limit = 10
|
||||
rows = agentdb.memory_search(_my_scope(agent), kw, limit)
|
||||
return {
|
||||
'keyword': kw,
|
||||
'count': len(rows),
|
||||
'items': [
|
||||
{'id': r['id'], 'title': r['title'], 'content': r['content']} for r in rows
|
||||
],
|
||||
'note': '' if rows else '没有匹配的记忆。别据此说"我完全不记得"—— 换个关键词再试一次。',
|
||||
}
|
||||
|
||||
|
||||
MEMORY_SUGGEST_SUMMARY = {
|
||||
'name': 'memory_suggest_summary',
|
||||
'description': (
|
||||
'**建议**用户整理一次记忆(把零散的合并成几条)。'
|
||||
'你只负责建议,不执行 —— 用户点确认之后系统才会真的整理。'
|
||||
'什么时候用:记忆条数明显变多、或者有好几条在说同一件事。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'reason': {'type': 'string', 'description': '为什么建议整理(会显示给用户)'},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_suggest_summary(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
why = str(args.get('reason') or '').strip() or '记忆有点多了,想合并一下'
|
||||
# ★ 只挂一个"建议"标记,**不执行总结**(需求 3.2:仅提示不执行)。
|
||||
# 界面看到这个标记会给用户一个「整理记忆」按钮。
|
||||
store.add_pending_summary_suggestion(agent.get('id') or '', why)
|
||||
return {
|
||||
'suggested': True,
|
||||
'reason': why,
|
||||
'note': '已经建议了。**别再说"我整理好了"** —— 你只是提了个建议,'
|
||||
'用户点确认之后才会真的整理。正文里正常说这件事就行。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 情绪
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
EMOTION_SET = {
|
||||
'name': 'emotion_set',
|
||||
'description': (
|
||||
'更新**你自己**当前的情绪状态。两个字段都要给:\n'
|
||||
'· preset:五档之一 —— 喜 / 怒 / 哀 / 平常 / 死亡。它决定系统行为'
|
||||
'(立绘换哪张、同伴看到你什么脸色、死亡时能不能继续说话)。\n'
|
||||
'· text:一句自由描述,比如"刚被夸了,有点得意"。这只是扮演质感。\n'
|
||||
'情绪要跟着对话内容自然变化,不用每轮都改。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'preset': {
|
||||
'type': 'string',
|
||||
'enum': list(agentdb.PRESETS),
|
||||
'description': '五档情绪之一',
|
||||
},
|
||||
'text': {'type': 'string', 'description': '一句自由描述(可选)'},
|
||||
},
|
||||
'required': ['preset'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def emotion_set(args: dict) -> dict:
|
||||
"""
|
||||
写自己的情绪(需求 3.5 双字段)。
|
||||
|
||||
★★ **禁止把自己从「死亡」改活**(需求 3.5 明文)。
|
||||
|
||||
为什么:死亡是"这个角色没了"。能自己复活的话死亡就没有重量 ——
|
||||
用户会看到 AI 上一句刚咽气、下一句又活蹦乱跳,整个系统的可信度就没了。
|
||||
|
||||
复活只有两条**别的**通道,都不经过这里:
|
||||
· 用户手动改(兜底主权,在记忆页的情绪区)
|
||||
· 状态脚本改(定时复活 / 解药剧情,见 §3.11 —— 那条路走沙箱,不走工具)
|
||||
"""
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
agent_id = agent.get('id') or ''
|
||||
preset = str(args.get('preset') or '').strip()
|
||||
text = str(args.get('text') or '').strip()
|
||||
if preset not in agentdb.PRESETS:
|
||||
raise ValueError(
|
||||
f'preset 只能是这五个之一:{"、".join(agentdb.PRESETS)}(收到的是「{preset}」)'
|
||||
)
|
||||
cur = agentdb.emotion_state(agent_id)
|
||||
if cur.get('preset') == agentdb.PRESET_DEAD and preset != agentdb.PRESET_DEAD:
|
||||
raise ValueError(
|
||||
'你已经是「死亡」状态,**不能自己复活**。'
|
||||
'复活只能由用户手动操作,或者由世界观里的状态脚本触发(比如定时复活、解药剧情)。'
|
||||
)
|
||||
nxt = agentdb.emotion_set(agent_id, preset=preset, text=text or None)
|
||||
return {
|
||||
'preset': nxt['preset'],
|
||||
'text': nxt['text'],
|
||||
'note': '已更新你自己的情绪。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 用量
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
GET_TOKEN_USAGE = {
|
||||
'name': 'get_token_usage',
|
||||
'description': (
|
||||
'查**你自己**累计用了多少 Token、还剩多少额度。'
|
||||
'用户问"你还能说多少""用了多少"时用这个查真实数字,别猜。'
|
||||
),
|
||||
'parameters': {'type': 'object', 'properties': {}},
|
||||
}
|
||||
|
||||
|
||||
def get_token_usage(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
usage = agentdb.token_usage(agent.get('id') or '')
|
||||
limit = int(float(agent.get('tokenLimit') or 0))
|
||||
used = usage['total']['input'] + usage['total']['output']
|
||||
return {
|
||||
'used': used,
|
||||
'input': usage['total']['input'],
|
||||
'output': usage['total']['output'],
|
||||
# v1.2:缓存命中/未命中(0 = 这家没提供缓存信息)
|
||||
'cacheHit': usage['total'].get('cacheHit', 0),
|
||||
'cacheMiss': usage['total'].get('cacheMiss', 0),
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
'remaining': (None if limit <= 0 else max(0, limit - used)),
|
||||
'note': '额度无限制。' if limit <= 0 else f'还剩 {max(0, limit - used)} Token。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 规则引擎(v1.2 §3.10 / §3.11)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
CHANGE_STAT = {
|
||||
'name': 'change_stat',
|
||||
'description': (
|
||||
'申请改变**你自己**身上某个数值。\n'
|
||||
'★ 只能给**增量**(+5 / -10),**不能写绝对值** —— 因为数值可能被'
|
||||
'世界观里的规则脚本裁决(放大、缩小、甚至否决),绝对值会让那套规则失效。\n'
|
||||
'真实结果以返回值里的 after 为准:你以为加了 5,可能实际加了 10 或者 0。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type': 'string', 'description': '数值名(见系统提示词的 <stats> 段)'},
|
||||
'delta': {'type': 'number', 'description': '想改变多少(可正可负)'},
|
||||
},
|
||||
'required': ['name', 'delta'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def change_stat(args: dict) -> dict:
|
||||
"""
|
||||
申请数值增量(需求 §3.10)。
|
||||
|
||||
内核流程是固定的:**脚本裁决 → clamp → 写库 → 下一轮注入反映新值**。
|
||||
这里只负责把请求转过去、把**真实结果**回来告诉模型 ——
|
||||
它必须知道"我以为加 5,实际加了 10"(否则下一轮它会按错误的心智继续演)。
|
||||
"""
|
||||
import agent_context
|
||||
import rule_engine
|
||||
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
pack = agent_context.pack_of(agent)
|
||||
if not pack:
|
||||
raise ValueError('你还没有绑定世界观,身上没有数值系统')
|
||||
name = str(args.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('name 不能为空')
|
||||
raw = args.get('delta')
|
||||
try:
|
||||
delta = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f'delta 得是个数字(收到的是「{raw}」)') from None
|
||||
r = rule_engine.change(agent, pack, name, delta)
|
||||
if not r.get('ok'):
|
||||
raise ValueError(r.get('error') or '改数值失败')
|
||||
out = {
|
||||
'name': name,
|
||||
'applied': r.get('applied'),
|
||||
'before': r.get('before'),
|
||||
'after': r.get('after'),
|
||||
}
|
||||
if r.get('text'):
|
||||
out['now'] = r['text']
|
||||
if r.get('narration'):
|
||||
out['narration'] = r['narration']
|
||||
if r.get('applied') != delta:
|
||||
# ★ 被裁决过了要**明说**,不然模型会以为自己算错了
|
||||
out['note'] = f'你申请的是 {delta:+g},规则裁决后实际生效 {r.get("applied"):+g}。'
|
||||
return out
|
||||
|
||||
|
||||
GRANT_STATUS = {
|
||||
'name': 'grant_status',
|
||||
'description': (
|
||||
'给**同一个世界观里**的另一个智能体施加一个状态(比如中毒、庇佑)。\n'
|
||||
'对方可能**抵抗**(那是他的设定),被抵抗时你会拿到明确回执。\n'
|
||||
'跨世界观一律无效。同名状态重复施加默认**刷新时长**,不会叠层。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '目标的**名字**(或 id)'},
|
||||
'status_name': {'type': 'string', 'description': '状态名(见世界观规则包)'},
|
||||
'turns': {'type': 'integer', 'description': '持续几轮(可选,默认按定义)'},
|
||||
},
|
||||
'required': ['target', 'status_name'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _find_agent(needle: str):
|
||||
"""
|
||||
按名字或 id 找智能体。
|
||||
|
||||
★ 为什么按**名字**找:模型在提示词里看到的伙伴就是名字
|
||||
(`<peer_emotions>` 给的是"仙辰-哀"),它拿不到 id。
|
||||
重名时取第一个 —— 重名本来就不该发生(界面会显示 玄辰/玄辰(2),
|
||||
但那是显示层的事)。
|
||||
"""
|
||||
import store
|
||||
|
||||
key = str(needle or '').strip()
|
||||
if not key:
|
||||
return None
|
||||
for a in store.list_agents():
|
||||
if a.get('id') == key:
|
||||
return a
|
||||
for a in store.list_agents():
|
||||
if (a.get('name') or '').strip() == key:
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def grant_status(args: dict) -> dict:
|
||||
"""给同世界观的另一个智能体施加状态(需求 §3.11)"""
|
||||
import agent_context
|
||||
import rule_engine
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
pack = agent_context.pack_of(me)
|
||||
if not pack:
|
||||
raise ValueError('你还没有绑定世界观,用不了状态系统')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
# 给自己挂状态用别的途径没有意义 —— 直接说不支持,
|
||||
# 免得模型以为"自残"是个正常操作
|
||||
raise ValueError('不能给自己施加状态,只能施加给同世界观的其他智能体')
|
||||
status_name = str(args.get('status_name') or '').strip()
|
||||
try:
|
||||
turns = int(args.get('turns') or 0)
|
||||
except (TypeError, ValueError):
|
||||
turns = 0
|
||||
r = rule_engine.grant(me, pack, target, status_name, turns)
|
||||
if not r.get('ok'):
|
||||
# ★ 被抵抗时**抛错**而不是返回 ok:false —— 需求说"A 必须知道结果",
|
||||
# 而工具抛错是模型一定会看到的那条路(返回里的字段它可能忽略)
|
||||
raise ValueError(r.get('error') or '赋予失败')
|
||||
return {
|
||||
'target': r.get('target'),
|
||||
'status': r.get('name'),
|
||||
'remaining': r.get('remaining'),
|
||||
'refreshed': r.get('refreshed'),
|
||||
'note': ('对方本来就有这个状态,已刷新时长。' if r.get('refreshed')
|
||||
else f'已施加给「{r.get("target")}」。'),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 多智能体对话(v1.2 §3.9)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
INVITE_AGENT = {
|
||||
'name': 'invite_agent',
|
||||
'description': (
|
||||
'把**同一个世界观里**的另一个智能体拉进当前群聊,让他也能说话。\n'
|
||||
'只能拉同世界观的人;单聊会话要先转成群聊。\n'
|
||||
'★ 拉之前先在正文里跟用户说一声 —— 别默默往对话里塞人。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '要拉进来的智能体的名字'},
|
||||
},
|
||||
'required': ['target'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def invite_agent(args: dict) -> dict:
|
||||
"""
|
||||
拉起同世界观的智能体进群(需求 §3.9 形态 A)。
|
||||
|
||||
按智能体自己的配置分流(需求 §6.1 的「拉起其他智能体:静默 / 需确认」):
|
||||
|
||||
· **静默**:直接进场,系统消息播报「仙辰加入了对话」
|
||||
· **需确认**:这次调用**不直接拉人**,而是返回一个"需要确认"的结果,
|
||||
让 AI 在正文里问用户一句;用户答应之后 AI 再调一次。
|
||||
|
||||
★ 关于"需确认":需求写的是"弹窗询问,拒绝结果作为工具返回值回给 AI"。
|
||||
真正的系统弹窗要等界面通道(`ask_user` 那套机制),这一版先退成
|
||||
"让 AI 自己问"。**功能上等价(用户仍是否决者)**,差别是它经过
|
||||
AI 的嘴而不是系统弹窗 —— 这一点在界面做好之前得说清楚,
|
||||
免得以后有人以为这里已经实现了弹窗。
|
||||
"""
|
||||
import agentdb
|
||||
import group_chat
|
||||
import store
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = tools_runtime.current_context()
|
||||
conv_id = ctx.get('conversationId') or ''
|
||||
conv = store.get_conversation(conv_id) or {}
|
||||
if not conv:
|
||||
raise ValueError('拿不到当前会话')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不用拉自己 —— 你已经在场了')
|
||||
|
||||
my_world = (me.get('worldviewId') or '').strip()
|
||||
if not my_world or my_world != (target.get('worldviewId') or '').strip():
|
||||
raise ValueError(f'「{target.get("name")}」和你不在同一个世界观里,拉不进来')
|
||||
|
||||
if not group_chat.is_group(conv):
|
||||
# 单聊拉人 → 转成群聊(需求 §3.9:"当前会话中加入多个智能体")
|
||||
group_chat.promote(conv, target['id'])
|
||||
store.update_conversation(conv_id, {
|
||||
'type': 'group', 'participants': conv.get('participants') or [],
|
||||
})
|
||||
return {'joined': target.get('name'), 'becameGroup': True,
|
||||
'note': f'这个会话现在是群聊了,「{target.get("name")}」加入了对话。'}
|
||||
|
||||
if target['id'] in group_chat.member_ids(conv):
|
||||
return {'joined': target.get('name'), 'already': True,
|
||||
'note': f'「{target.get("name")}」已经在对话里了。'}
|
||||
|
||||
# 按智能体配置分流
|
||||
mode = str(me.get('inviteMode') or 'silent').lower()
|
||||
if mode == 'confirm':
|
||||
return {
|
||||
'needConfirm': True,
|
||||
'target': target.get('name'),
|
||||
'note': (f'你设置了「拉起需要确认」,所以这次**没有**直接拉人。'
|
||||
f'请在正文里问用户一句"要不要把{target.get("name")}叫来",'
|
||||
f'用户答应之后再调一次这个工具。'),
|
||||
}
|
||||
|
||||
import group_chat as gc
|
||||
|
||||
gc.add_member(conv, target['id'])
|
||||
store.update_conversation(conv_id, {'participants': conv.get('participants') or []})
|
||||
return {'joined': target.get('name'), 'note': f'「{target.get("name")}」加入了对话。'}
|
||||
|
||||
|
||||
PASS_TURN = {
|
||||
'name': 'pass_turn',
|
||||
'description': (
|
||||
'把发言权交给群里的另一个智能体。\n'
|
||||
'★ **一轮最多移交一次** —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 交给已死亡的人无效,发言权会回到主智能体。\n'
|
||||
'不想说话时不用调它,直接正常回复就行。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '接话的智能体的名字'},
|
||||
},
|
||||
'required': ['target'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def pass_turn(args: dict) -> dict:
|
||||
"""
|
||||
移交发言权(需求 §3.9 的点名制)。
|
||||
|
||||
"一轮最多一次"靠 `tools_runtime` 的上下文标记实现 —— 不放在会话里,
|
||||
因为它是**这一轮**的属性,落库反而要额外写清理逻辑。
|
||||
"""
|
||||
import agentdb
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
# ★★ 用 tools_runtime 的**轮次级状态**,不能用工具上下文 ——
|
||||
# 工具跑在 worker 线程里,写进 thread-local 的标记会随线程消失,
|
||||
# 于是"一轮最多一次"永远不生效(踩过,见 tools_runtime.begin_round 的注释)
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# ★ 需求明文"一轮最多一次"。第二次直接拒,理由说清楚 ——
|
||||
# 不然模型会以为是"对方有问题",而不是"规则不允许"
|
||||
raise ValueError('这一轮你已经移交过发言权了(一轮最多一次),直接回复就行')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不能把发言权交给自己')
|
||||
if agentdb.is_dead(target['id']):
|
||||
# ★ 需求明文:死亡目标移交无效。这里**如实告诉模型**,
|
||||
# 它就会自己在正文里圆过去(而不是干等着对方开口)
|
||||
raise ValueError(f'「{target.get("name")}」已经死亡,移交无效 —— 你自己接着说,或者交给别人')
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
return {'handed_to': target.get('name'),
|
||||
'note': f'下一轮由「{target.get("name")}」接话。这一轮你不再移交了。'}
|
||||
|
||||
|
||||
TALK_TO = {
|
||||
'name': 'talk_to',
|
||||
'description': (
|
||||
'在群聊里**主动对另一个智能体说一句话**。\n'
|
||||
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
|
||||
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
|
||||
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
|
||||
'★ 想跟群里的谁聊就调它,一来一回可以聊好几轮。\n'
|
||||
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 单聊里没有"别人",调了会报错。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'agent': {'type': 'string', 'description': '对方的名字或 id'},
|
||||
'content': {'type': 'string', 'description': '你要对他说的话'},
|
||||
},
|
||||
'required': ['agent', 'content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def talk_to(args: dict) -> dict:
|
||||
"""
|
||||
主动找群里的另一个智能体说话。
|
||||
|
||||
★★ 为什么单独一个工具(用户明确要求:「智能体主动调用工具和别的智能体聊」,
|
||||
「工具定义 / 智能体加上内容」):
|
||||
|
||||
`pass_turn` 只交发言权、**不带内容** —— 对方接到的是一片空白。
|
||||
要"两个智能体真的聊起来",就得让发起方**能说一句具体的话**,
|
||||
而且那句话要**落进对话**,对方下一轮才看得到。
|
||||
所以这个工具的参数就是那两样:**跟谁说 + 说什么**。
|
||||
|
||||
★ 说完之后把发言权交给他(`note_handoff`)—— 界面据此**自动续一轮**,
|
||||
他会真的开口回应;他也可以反过来再 `talk_to` 回来,于是就能聊下去。
|
||||
"""
|
||||
import group_chat
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = _ctx()
|
||||
conv_id = str(ctx.get('conversationId') or '')
|
||||
conv = store.get_conversation(conv_id) or {}
|
||||
if not group_chat.is_group(conv):
|
||||
raise ValueError('这条不是群聊 —— 只有群里有「别人」可以聊')
|
||||
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# 和 pass_turn 共用"一轮最多一次"那个标记:要么移交、要么找人说,
|
||||
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
|
||||
raise ValueError('这一轮你已经把话交给别人了,等他回应完再说')
|
||||
|
||||
target = _find_agent(str(args.get('agent') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("agent")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不能对自己说 —— 直接说就行')
|
||||
if target['id'] not in group_chat.member_ids(conv):
|
||||
raise ValueError(f'「{target.get("name")}」不在这个群里,先把他拉进来')
|
||||
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not content:
|
||||
raise ValueError('要说什么?content 不能是空的')
|
||||
|
||||
# ① 这句话以**我**的名义落进对话 —— 对方下一轮就看得到
|
||||
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
store.append_messages(conv_id, [{
|
||||
'role': 'assistant',
|
||||
'content': content,
|
||||
'agentId': me.get('id'),
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
after = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} 内容={content[:20]!r}',
|
||||
file=sys.stderr)
|
||||
# ② 把发言权交给他 —— 界面据此自动续一轮,让他真的回应
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
return {
|
||||
'said_to': target.get('name'),
|
||||
# ★★ **回显说了什么**。不回显的话模型看不到自己的话落在哪儿,
|
||||
# 会以为"传过去是空的"、然后反复重试 ——
|
||||
# 真机上就是模型自己在回复里写「这条是空的,我猜是想看我把 talk_to 真跑一遍」
|
||||
# (用户报的「talk_to 没有内容呀」)。
|
||||
'content': content,
|
||||
'note': (
|
||||
f'已把「{content}」说给「{target.get("name")}」,'
|
||||
'这句话已经写进对话、他下一轮看得到,接下来由他回应。别再重复调这个工具。'
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注册
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 名字 → {'spec': TOOL, 'run': fn}(形状和 builtin_tools.BUILTIN_TOOLS 一样)
|
||||
AGENT_TOOLS = {
|
||||
'memory_add': {'spec': MEMORY_ADD, 'run': memory_add},
|
||||
'memory_update': {'spec': MEMORY_UPDATE, 'run': memory_update},
|
||||
'memory_forget': {'spec': MEMORY_FORGET, 'run': memory_forget},
|
||||
'memory_search': {'spec': MEMORY_SEARCH, 'run': memory_search},
|
||||
'memory_suggest_summary': {'spec': MEMORY_SUGGEST_SUMMARY, 'run': memory_suggest_summary},
|
||||
'emotion_set': {'spec': EMOTION_SET, 'run': emotion_set},
|
||||
'get_token_usage': {'spec': GET_TOKEN_USAGE, 'run': get_token_usage},
|
||||
# v1.2 规则引擎(附录 B 的后两个)
|
||||
'change_stat': {'spec': CHANGE_STAT, 'run': change_stat},
|
||||
'grant_status': {'spec': GRANT_STATUS, 'run': grant_status},
|
||||
# v1.2 多智能体对话(附录 B 的 invite_agent / pass_turn)
|
||||
'invite_agent': {'spec': INVITE_AGENT, 'run': invite_agent},
|
||||
'pass_turn': {'spec': PASS_TURN, 'run': pass_turn},
|
||||
# ★ 主动找另一个智能体说话(用户要求:参数是「智能体 + 内容」)。
|
||||
# `pass_turn` 只交发言权、不带内容,所以那个聊不起来。
|
||||
'talk_to': {'spec': TALK_TO, 'run': talk_to},
|
||||
}
|
||||
|
||||
|
||||
def _unused(): # pragma: no cover - 只是让 sys 的 import 不被 lint 当成没用
|
||||
return sys
|
||||
659
android/kernel/agentdb.py
Normal file
659
android/kernel/agentdb.py
Normal file
@@ -0,0 +1,659 @@
|
||||
"""智能体系统的数据层:**记忆 / 情绪 / Token 统计 / 绑定关系**。
|
||||
|
||||
## 为什么这次用 SQLite,而别处(设置/会话/智能体)还是 JSON
|
||||
|
||||
`store.py` 顶上写着"为什么用 JSON 而不是 SQLite",理由很实在:
|
||||
**数据量极小**(几条会话、几个智能体),而且用户/开发者要能直接看到、改那些文件。
|
||||
|
||||
那个理由对**智能体本身**依然成立(就几个),所以它们还在 `agents.json` 里。
|
||||
但记忆不一样,三条都指向 SQLite:
|
||||
|
||||
· 需求明确"记忆条目**无上限**",而**每轮对话都要全量注入** smartMemory ——
|
||||
几千条记忆塞进一个 JSON、每轮读盘再反序列化一遍,代价是实打实的
|
||||
· 要按关键词检索(`memory_search` 是 LIKE 查询)
|
||||
· 要"只改一条""只删自己写的"这种**行级**操作 —— 在 JSON 里就是
|
||||
读全量 → 改 → 写全量,多线程下一次并发写就可能把别人的改动盖掉
|
||||
|
||||
所以分界线是:**会持续增长、要按行操作或检索的数据 → SQLite;
|
||||
少量、要人肉可读的配置 → JSON。**
|
||||
|
||||
(另:这几张表**只属于智能体系统**,不和会话/设置混在一起 ——
|
||||
`agent.db` 单独一个文件,删了就是"重置智能体系统",不会碰到聊天记录。)
|
||||
|
||||
## 关联一律用 UUID
|
||||
|
||||
见需求附录 A。`memories.author_agent`、`agent_skills.agent_id`、
|
||||
`token_usage.agent_id` 存的都是 UUID,`name` 只是显示名(可重复、可随便改)。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 连接
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 每线程一个连接:sqlite3 的连接默认不能跨线程用,而内核是多线程的
|
||||
# (HTTP 每请求一线程 + 工具跑在又一个线程里)。
|
||||
# 用 threading.local() 而不是"一个全局连接 + 一把大锁":记忆检索可能在
|
||||
# 对话生成的过程中被调用,一把大锁会把整条链路串起来。
|
||||
_local = threading.local()
|
||||
_init_done = False
|
||||
_init_lock = threading.Lock()
|
||||
|
||||
|
||||
def db_path() -> str:
|
||||
"""数据库文件的位置(跟着数据目录走,和 settings.json 同一层)"""
|
||||
return os.path.join(os.path.dirname(paths.get().settings_file), 'agent.db')
|
||||
|
||||
|
||||
def _connect() -> sqlite3.Connection:
|
||||
conn = getattr(_local, 'conn', None)
|
||||
if conn is not None:
|
||||
return conn
|
||||
os.makedirs(os.path.dirname(db_path()), exist_ok=True)
|
||||
# check_same_thread=False 是安全的:这个连接只会被**创建它的那个线程**用到
|
||||
#
|
||||
# ★ 这个 timeout 是**锁等待**(不是查询超时):另一个线程正在写时,
|
||||
# 等多久才放弃并抛 "database is locked"。
|
||||
# 它以前写死 10 秒 —— 对拍脚本抓到的硬编码。现在复用「本地接口请求」
|
||||
# 那一项:语义最接近(都是"本机内部等一等"),而且用户调它是有意义的
|
||||
# (老设备上几千条记忆的整理会长时间占着写锁)。
|
||||
import timeouts as _timeouts
|
||||
|
||||
wait = float(_timeouts.get('kernelLocal') or 10)
|
||||
conn = sqlite3.connect(db_path(), check_same_thread=False, timeout=max(1.0, wait))
|
||||
conn.row_factory = sqlite3.Row
|
||||
# WAL:读不挡写。安卓上内核同时有"对话在写记忆"和"界面在读列表"。
|
||||
try:
|
||||
conn.execute('PRAGMA journal_mode=WAL')
|
||||
conn.execute('PRAGMA synchronous=NORMAL')
|
||||
except sqlite3.Error:
|
||||
pass # 只读文件系统之类:不致命,退化成默认模式
|
||||
_local.conn = conn
|
||||
return conn
|
||||
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id TEXT PRIMARY KEY,
|
||||
scope TEXT NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
pinned INTEGER NOT NULL DEFAULT 0,
|
||||
author_agent TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS emotions (
|
||||
agent_id TEXT PRIMARY KEY,
|
||||
-- v1.2(需求 3.5)把情绪拆成双字段:
|
||||
-- preset 五档枚举,**驱动系统行为**(立绘切换、死亡规则)
|
||||
-- text AI 自写的自由文本,只管**扮演质感**
|
||||
-- 老库里的 `emotion` 单列由 _migrate() 搬进 text,列本身留着不动
|
||||
-- (SQLite 删列要重建表,不值当;留着也永远不会有人再读它)
|
||||
preset TEXT NOT NULL DEFAULT '平常',
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS token_usage (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
agent_id TEXT NOT NULL,
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
input INTEGER NOT NULL DEFAULT 0,
|
||||
output INTEGER NOT NULL DEFAULT 0,
|
||||
-- v1.2:缓存命中 / 未命中。各家的字段名完全不同,存进来的是
|
||||
-- agent_loop.cache_pair() **归一化之后**的两个数。
|
||||
-- 都是 0 表示"这家没提供缓存信息"——界面据此**不显示**那一列,
|
||||
-- 而不是显示一个假的 0%(那是误导)。
|
||||
cache_hit INTEGER NOT NULL DEFAULT 0,
|
||||
cache_miss INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_token_agent ON token_usage(agent_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS agent_skills (
|
||||
agent_id TEXT NOT NULL,
|
||||
skill_id TEXT NOT NULL,
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (agent_id, skill_id)
|
||||
);
|
||||
|
||||
-- ============ v1.2 规则引擎(需求 §3.10 数值 / §3.11 状态)============
|
||||
--
|
||||
-- 和记忆一个思路:**定义**挂世界观、**值**按 scope 存。
|
||||
--
|
||||
-- 为什么定义不挂智能体:需求 §3.10 原话"定义统一收进数值状态包
|
||||
-- (世界观层),智能体不再自带数值定义" —— 一份定义、多个实例。
|
||||
--
|
||||
-- 值的 scope 有两种,由 def 的 shared 决定:
|
||||
-- shared=0 → "agent:<uuid>" 好感度各算各的
|
||||
-- shared=1 → "world:<uuid>" 灵气浓度全世界观一份
|
||||
-- 这和记忆的 scope 写法**故意一致**(`scope_of` 那套),
|
||||
-- 于是"绑定/解绑世界观只是换读写空间、值不迁移不丢失"这条也自动成立。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stat_defs (
|
||||
-- ★ key 是**规则包** id 不是世界观 id:同一个包可以被多个世界观引用,
|
||||
-- 定义只存一份(改一次全生效)。世界观只是"挂载点"。
|
||||
pack_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- min / max 是 SQL 关键字,所以列名带后缀
|
||||
min_value REAL NOT NULL DEFAULT 0,
|
||||
max_value REAL NOT NULL DEFAULT 100,
|
||||
shared INTEGER NOT NULL DEFAULT 0,
|
||||
-- ranges 是 JSON 字符串:[{"min":0,"max":20,"text":"冷淡:……"}],
|
||||
-- 命中哪段注入哪段的 text(需求 §3.10 的"声明式区间表")
|
||||
ranges TEXT NOT NULL DEFAULT '[]',
|
||||
script TEXT NOT NULL DEFAULT '',
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (pack_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stat_values (
|
||||
scope TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
value REAL NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (scope, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS status_defs (
|
||||
pack_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- persistent(持久,每轮执行脚本)/ timed(定时,每轮递减归零消失)
|
||||
kind TEXT NOT NULL DEFAULT 'timed',
|
||||
turns INTEGER NOT NULL DEFAULT 1,
|
||||
max_stack INTEGER NOT NULL DEFAULT 1,
|
||||
script TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (pack_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS status_instances (
|
||||
agent_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- 剩余轮数:timed 每轮 -1,归零消失;persistent 恒为 -1(不过期)
|
||||
remaining INTEGER NOT NULL DEFAULT 0,
|
||||
stacks INTEGER NOT NULL DEFAULT 1,
|
||||
-- 状态提示词:脚本可以改写它(需求 §3.11 的脚本权限之一)
|
||||
hint TEXT NOT NULL DEFAULT '',
|
||||
granted_at TEXT NOT NULL,
|
||||
PRIMARY KEY (agent_id, name)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def init() -> None:
|
||||
"""建表(幂等)。内核启动时调一次,各处也会惰性调。"""
|
||||
global _init_done
|
||||
if _init_done:
|
||||
return
|
||||
with _init_lock:
|
||||
if _init_done:
|
||||
return
|
||||
conn = _connect()
|
||||
conn.executescript(SCHEMA)
|
||||
_migrate(conn)
|
||||
conn.commit()
|
||||
_init_done = True
|
||||
|
||||
|
||||
def _migrate(conn) -> None:
|
||||
"""
|
||||
老库的结构升级(幂等,每次 init 都跑一遍,没得升就什么都不做)。
|
||||
|
||||
★ 为什么要单独一个函数、而不是只靠 `CREATE TABLE IF NOT EXISTS`:
|
||||
那个只在**表不存在**时建表。表已经存在的话,加列它一概不管 ——
|
||||
于是老用户的库里 `emotions` 表永远只有 `emotion` 一列,
|
||||
而新代码读的是 `preset` / `text`,一读就是 `no such column`。
|
||||
|
||||
v1.2 这一条:`emotion`(单字段自由文本)→ `preset` + `text`。
|
||||
老的那列**留着不动**(SQLite 删列要重建整张表,不值当),
|
||||
它的内容搬进 `text` —— 因为老字段本来存的就是自由文本。
|
||||
"""
|
||||
cols = {r['name'] for r in conn.execute('PRAGMA table_info(emotions)').fetchall()}
|
||||
if 'preset' not in cols:
|
||||
conn.execute("ALTER TABLE emotions ADD COLUMN preset TEXT NOT NULL DEFAULT '平常'")
|
||||
if 'text' not in cols:
|
||||
conn.execute("ALTER TABLE emotions ADD COLUMN text TEXT NOT NULL DEFAULT ''")
|
||||
if 'emotion' in cols:
|
||||
# 老数据的自由文本 → text;preset 全是默认的「平常」
|
||||
conn.execute('UPDATE emotions SET text = emotion')
|
||||
|
||||
# v1.2 第二条:token_usage 加缓存两列(老库没有,读的时候会 no such column)
|
||||
tcols = {r['name'] for r in conn.execute('PRAGMA table_info(token_usage)').fetchall()}
|
||||
if tcols:
|
||||
if 'cache_hit' not in tcols:
|
||||
conn.execute('ALTER TABLE token_usage ADD COLUMN cache_hit INTEGER NOT NULL DEFAULT 0')
|
||||
if 'cache_miss' not in tcols:
|
||||
conn.execute('ALTER TABLE token_usage ADD COLUMN cache_miss INTEGER NOT NULL DEFAULT 0')
|
||||
|
||||
|
||||
#: v1.2 情绪的五档枚举(需求 3.5)。
|
||||
#:
|
||||
#: `preset` 和 `text` 的分工是这个设计的关键:
|
||||
#: · preset **驱动系统行为** —— 立绘切哪张、能不能对话(死亡)、
|
||||
#: 以及注入给同世界观伙伴的那个"脸色"
|
||||
#: · text 只是 **AI 自写的自由文本**,管扮演质感
|
||||
#:
|
||||
#: 合成一个字段做不到:系统要按 preset 分支,而自然语言没法当分支条件;
|
||||
#: 只用 preset 又太干,"怒"和"悲愤交加但强作镇定"是两回事。
|
||||
PRESETS = ('喜', '怒', '哀', '平常', '死亡')
|
||||
PRESET_DEFAULT = '平常'
|
||||
PRESET_DEAD = '死亡'
|
||||
|
||||
|
||||
def reset_init() -> None:
|
||||
"""测试用:换过数据目录之后强制重新建表"""
|
||||
global _init_done
|
||||
_init_done = False
|
||||
_local.__dict__.pop('conn', None)
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
"""新实体的主键。**一律 UUID**(需求附录 A)"""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def now_iso() -> str:
|
||||
"""和 store.now_iso() 一样的格式(前端直接拿来排序/展示)"""
|
||||
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# scope:记忆是"智能体私有"还是"世界观共享"
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 用带前缀的字符串而不是两列(agent_id / worldview_id):
|
||||
# 读的时候永远只关心"这一条属于哪个记忆空间",不需要分情况查两列;
|
||||
# 而且以后加第三种空间(比如"全局公共记忆")不用改表结构。
|
||||
|
||||
def agent_scope(agent_id: str) -> str:
|
||||
return f'agent:{agent_id or ""}'
|
||||
|
||||
|
||||
def world_scope(worldview_id: str) -> str:
|
||||
return f'world:{worldview_id or ""}'
|
||||
|
||||
|
||||
def scope_of(agent_id: str, worldview_id: str = '') -> str:
|
||||
"""
|
||||
这个智能体当前该读写哪个记忆空间。
|
||||
|
||||
绑定世界观 → 共享空间;没绑定 → 自己的私有空间(需求 3.6)。
|
||||
"""
|
||||
if worldview_id:
|
||||
return world_scope(worldview_id)
|
||||
return agent_scope(agent_id)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def memory_add(scope: str, title: str, content: str, author_agent: str = '') -> dict:
|
||||
"""新增一条。返回整条(带新生成的 UUID)"""
|
||||
init()
|
||||
item = {
|
||||
'id': new_id(),
|
||||
'scope': scope,
|
||||
'title': (title or '').strip(),
|
||||
'content': (content or '').strip(),
|
||||
'pinned': 0,
|
||||
'author_agent': author_agent or '',
|
||||
'created_at': now_iso(),
|
||||
}
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) '
|
||||
'VALUES (:id, :scope, :title, :content, :pinned, :author_agent, :created_at)',
|
||||
item,
|
||||
)
|
||||
conn.commit()
|
||||
return item
|
||||
|
||||
|
||||
def memory_get(memory_id: str) -> dict | None:
|
||||
init()
|
||||
row = _connect().execute('SELECT * FROM memories WHERE id = ?', (memory_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def memory_list(scope: str) -> list:
|
||||
"""
|
||||
一个记忆空间的全部条目(**注入 system prompt 用的就是它**)。
|
||||
|
||||
★ 顺序是**置顶的排最前**,其余按时间。
|
||||
界面和提示词注入用**同一个顺序** —— 两处各排一次的话,很容易出现
|
||||
"界面上看着在第一条、实际没进提示词"这种对不上的情况。
|
||||
"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT * FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def memory_search(scope: str, keyword: str, limit: int = 20) -> list:
|
||||
"""
|
||||
关键词检索(`memory_search` 工具)。
|
||||
|
||||
★ 用 LIKE 而不是 FTS5:FTS5 对中文要额外的分词器,而这里的关键词
|
||||
就是用户/模型给的整词,LIKE '%关键词%' 反而更符合直觉
|
||||
(搜"咖啡"能命中"喜欢喝咖啡")。条目量级(几千)下 LIKE 也够快。
|
||||
"""
|
||||
init()
|
||||
kw = (keyword or '').strip()
|
||||
if not kw:
|
||||
return []
|
||||
like = f'%{kw}%'
|
||||
rows = _connect().execute(
|
||||
'SELECT * FROM memories WHERE scope = ? AND (title LIKE ? OR content LIKE ?) '
|
||||
'ORDER BY pinned DESC, created_at DESC LIMIT ?',
|
||||
(scope, like, like, max(1, min(200, int(limit)))),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def memory_update(memory_id: str, title: str = None, content: str = None) -> dict | None:
|
||||
"""改标题/正文(只改传进来的字段)"""
|
||||
init()
|
||||
cur = memory_get(memory_id)
|
||||
if not cur:
|
||||
return None
|
||||
new_title = cur['title'] if title is None else (title or '').strip()
|
||||
new_content = cur['content'] if content is None else (content or '').strip()
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'UPDATE memories SET title = ?, content = ? WHERE id = ?',
|
||||
(new_title, new_content, memory_id),
|
||||
)
|
||||
conn.commit()
|
||||
return memory_get(memory_id)
|
||||
|
||||
|
||||
def memory_forget(memory_id: str) -> bool:
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('DELETE FROM memories WHERE id = ?', (memory_id,))
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def memory_set_pinned(memory_id: str, pinned: bool) -> bool:
|
||||
"""用户手动标记「必须保留」(AI 改不了这个,见需求 3.2)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('UPDATE memories SET pinned = ? WHERE id = ?', (1 if pinned else 0, memory_id))
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def memory_replace_all(scope: str, items: list, keep_pinned: bool = True) -> int:
|
||||
"""
|
||||
**AI 总结**的写回:整个空间换成压缩后的那份。
|
||||
|
||||
★ `keep_pinned=True` 时 pinned 条目**原样保留**、不参与替换 ——
|
||||
这是需求 3.2 里"pinned 保护"的落地:用户标了"必须保留"的东西,
|
||||
不能被一次总结合并掉。
|
||||
|
||||
返回写回了多少条。
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
kept = []
|
||||
if keep_pinned:
|
||||
kept = [dict(r) for r in conn.execute(
|
||||
'SELECT * FROM memories WHERE scope = ? AND pinned = 1', (scope,),
|
||||
).fetchall()]
|
||||
conn.execute('DELETE FROM memories WHERE scope = ?' + (' AND pinned = 0' if keep_pinned else ''),
|
||||
(scope,))
|
||||
n = 0
|
||||
for it in items or []:
|
||||
title = str((it or {}).get('title') or '').strip()
|
||||
content = str((it or {}).get('content') or '').strip()
|
||||
if not title and not content:
|
||||
continue
|
||||
conn.execute(
|
||||
'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) '
|
||||
'VALUES (?, ?, ?, ?, 0, ?, ?)',
|
||||
(new_id(), scope, title, content, str(it.get('author_agent') or ''), now_iso()),
|
||||
)
|
||||
n += 1
|
||||
conn.commit()
|
||||
return n + len(kept)
|
||||
|
||||
|
||||
def memory_titles(scope: str) -> list:
|
||||
"""只要标题清单(注入时先拼标题,正文按需检索 —— 见注入模板)"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT title FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
|
||||
).fetchall()
|
||||
return [r['title'] for r in rows if r['title']]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def emotion_state(agent_id: str) -> dict:
|
||||
"""
|
||||
读一个智能体的情绪 → `{'preset': ..., 'text': ...}`(需求 3.5 双字段)。
|
||||
|
||||
★ 没记过情绪时返回默认值(「平常」+ 空文本),而不是空 —— 调用方
|
||||
(注入模板、界面)就不用各自处理 None 了。
|
||||
"""
|
||||
init()
|
||||
row = _connect().execute(
|
||||
'SELECT preset, text FROM emotions WHERE agent_id = ?', (agent_id or '',),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return {'preset': PRESET_DEFAULT, 'text': ''}
|
||||
preset = (row['preset'] or '').strip() or PRESET_DEFAULT
|
||||
return {'preset': preset, 'text': (row['text'] or '')}
|
||||
|
||||
|
||||
def emotion_set(agent_id: str, preset: str = None, text: str = None) -> dict:
|
||||
"""
|
||||
写情绪(双字段,**只写传进来的那些**)。
|
||||
|
||||
★★ 这里**不做死亡校验** —— 校验放在 AI 的通道上
|
||||
(`agent_tools.emotion_set`),不在数据层。
|
||||
|
||||
为什么:需求 3.5 说"用户手动改回是兜底主权"。数据层要是拦了,
|
||||
**界面就没办法复活了** —— 那是把用户的权力一起拦掉了。
|
||||
权限的边界在"谁在改"(AI / 用户),不在"改什么",所以它在通道上。
|
||||
"""
|
||||
init()
|
||||
cur = emotion_state(agent_id)
|
||||
nxt = {
|
||||
'preset': (preset or cur['preset'] or PRESET_DEFAULT),
|
||||
'text': cur['text'] if text is None else (text or ''),
|
||||
}
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO emotions (agent_id, preset, text, updated_at) VALUES (?, ?, ?, ?) '
|
||||
'ON CONFLICT(agent_id) DO UPDATE SET preset = excluded.preset, '
|
||||
'text = excluded.text, updated_at = excluded.updated_at',
|
||||
(agent_id or '', nxt['preset'], nxt['text'], now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
return nxt
|
||||
|
||||
|
||||
def is_dead(agent_id: str) -> bool:
|
||||
"""这个智能体是不是「死亡」状态(需求 3.5:死亡的不能对话)"""
|
||||
return emotion_state(agent_id)['preset'] == PRESET_DEAD
|
||||
|
||||
|
||||
def emotion_from_export(raw) -> dict:
|
||||
"""
|
||||
解析记忆/情绪导出文件里的 `Emotion` 字段,返回**可以直接展开给
|
||||
`emotion_set(**...)` 的关键字参数**。
|
||||
|
||||
★★ 两种格式都得认:
|
||||
|
||||
· **v1.1**:`"Emotion": "刚被夸了,有点得意"` —— 一个字符串
|
||||
· **v1.2**:`"Emotion": {"preset": "喜", "text": "……"}` —— 一个对象
|
||||
|
||||
用户手里可能存着 v1.1 导出的文件。只认新格式的话,他导入时会
|
||||
**在情绪这一步直接抛异常**,而前半截记忆已经写进去了 ——
|
||||
留下一个"记忆进来了、情绪没进来"的半成品,最难查。
|
||||
|
||||
`None` 表示"这一项不要动"(`emotion_set` 的语义:只写传进来的)。
|
||||
"""
|
||||
if isinstance(raw, dict):
|
||||
preset = str(raw.get('preset') or '').strip() or None
|
||||
# 老库里 preset 可能不在五档里(用户手改过文件)—— 夹一下,
|
||||
# 不认识就当没给,免得把界面搞出一个选不中的档位
|
||||
if preset and preset not in PRESETS:
|
||||
preset = None
|
||||
text = raw.get('text')
|
||||
return {'preset': preset, 'text': None if text is None else str(text)}
|
||||
|
||||
if isinstance(raw, str):
|
||||
# v1.1 的单字段:它本来存的就是自由文本 → 全给 text,preset 不动
|
||||
return {'preset': None, 'text': raw}
|
||||
|
||||
return {'preset': None, 'text': None}
|
||||
|
||||
|
||||
def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> list:
|
||||
"""
|
||||
同世界观、**其他**智能体的「id + preset」。
|
||||
|
||||
★ v1.2 起注入的是 **preset(五档)而不是自由文本**(需求 3.5 原文:
|
||||
"开启后注入同世界观其他智能体的「名字 + preset」")。
|
||||
原因:`text` 是那个角色的**内心独白**,读给别的角色听等于扒开他的脑子;
|
||||
preset 是"看得出来他现在什么脸色"——那才是别人该看到的信息粒度。
|
||||
|
||||
[agent_ids] 是绑定了这个世界观的全部智能体 id(由调用方从 agents.json 里挑,
|
||||
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, preset)]。
|
||||
"""
|
||||
init()
|
||||
out = []
|
||||
for aid in agent_ids or []:
|
||||
if not aid or aid == exclude_agent:
|
||||
continue
|
||||
out.append((aid, emotion_state(aid)['preset']))
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Token 统计
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def token_add(agent_id: str, model: str, input_tokens: int, output_tokens: int,
|
||||
cache_hit: int = 0, cache_miss: int = 0) -> None:
|
||||
"""
|
||||
记一次消耗。
|
||||
|
||||
★ 输入 / 输出**分开记**(需求 3.1),而且按**模型**分桶 ——
|
||||
"按模型"是靠每行带 model 名做到的:桶是查询时 group by 出来的,
|
||||
不是提前建好的。这样换模型不会有"桶没建好"的问题。
|
||||
|
||||
★ v1.2 多两个参数:缓存命中 / 未命中。**默认 0** 是有意的 ——
|
||||
`agent_loop.cache_pair()` 归一化之后如果两家都没给,就是 0/0,
|
||||
界面据此不显示那一列(显示假的 0% 是误导)。
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO token_usage (agent_id, model, input, output, cache_hit, cache_miss, created_at) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
(agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0),
|
||||
int(cache_hit or 0), int(cache_miss or 0), now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def token_usage(agent_id: str) -> dict:
|
||||
"""
|
||||
这个智能体的累计用量。
|
||||
|
||||
返回 `{'total': {input, output, cacheHit, cacheMiss},
|
||||
'byModel': [{model, input, output, cacheHit, cacheMiss}]}`
|
||||
|
||||
★ 缓存那两个数是 v1.2 加的;全为 0 时界面**不显示**那一列 ——
|
||||
不是每家提供商都返回缓存信息,显示一个恒为 0 的"命中率"是误导。
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
rows = conn.execute(
|
||||
'SELECT model, SUM(input) AS i, SUM(output) AS o, '
|
||||
'SUM(cache_hit) AS h, SUM(cache_miss) AS m FROM token_usage '
|
||||
'WHERE agent_id = ? GROUP BY model ORDER BY (SUM(input) + SUM(output)) DESC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
by_model = [
|
||||
{
|
||||
'model': r['model'] or '(未知)',
|
||||
'input': int(r['i'] or 0),
|
||||
'output': int(r['o'] or 0),
|
||||
'cacheHit': int(r['h'] or 0),
|
||||
'cacheMiss': int(r['m'] or 0),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
return {
|
||||
'total': {
|
||||
'input': sum(m['input'] for m in by_model),
|
||||
'output': sum(m['output'] for m in by_model),
|
||||
'cacheHit': sum(m['cacheHit'] for m in by_model),
|
||||
'cacheMiss': sum(m['cacheMiss'] for m in by_model),
|
||||
},
|
||||
'byModel': by_model,
|
||||
}
|
||||
|
||||
|
||||
def token_reset(agent_id: str) -> int:
|
||||
"""按智能体清零(需求 3.1 的"管理操作")。返回清掉了几行"""
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('DELETE FROM token_usage WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.commit()
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Skill 绑定
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def skills_of(agent_id: str) -> list:
|
||||
"""这个智能体绑定的自定义 Skill id(**按绑定顺序** —— 注入要按顺序拼)"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT skill_id FROM agent_skills WHERE agent_id = ? ORDER BY ord ASC, skill_id ASC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
return [r['skill_id'] for r in rows]
|
||||
|
||||
|
||||
def bind_skills(agent_id: str, skill_ids: list) -> None:
|
||||
"""整体替换绑定关系(界面上的"勾选"就是一次整体替换,不用做增删接口)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',))
|
||||
for i, sid in enumerate(skill_ids or []):
|
||||
if not sid:
|
||||
continue
|
||||
conn.execute(
|
||||
'INSERT OR REPLACE INTO agent_skills (agent_id, skill_id, ord) VALUES (?, ?, ?)',
|
||||
(agent_id or '', sid, i),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def unbind_agent(agent_id: str) -> None:
|
||||
"""智能体被删掉时的清理(记忆**不删** —— 那是用户的数据,删了他会心疼)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.execute('DELETE FROM emotions WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.commit()
|
||||
@@ -38,6 +38,13 @@ import paths
|
||||
import providers
|
||||
import speech
|
||||
import store
|
||||
import timeouts
|
||||
import agentdb
|
||||
import agent_api
|
||||
import agent_context
|
||||
import context_window
|
||||
import group_chat
|
||||
import rule_engine
|
||||
import tools_runtime
|
||||
import uploads
|
||||
from defaults import PROVIDER_PRESETS
|
||||
@@ -48,6 +55,8 @@ QUIET = False
|
||||
# 安卓上 Lynx 原生 fetch 没有 response.body,只能靠这个通道做"准流式"
|
||||
_RUNS = {}
|
||||
_RUNS_LOCK = threading.Lock()
|
||||
# `send_message` 触发的回复里最多再套几层(防无限套娃,见 /api/session-message)
|
||||
SESSION_MSG_MAX_DEPTH = 2
|
||||
_RUN_TTL_S = 600
|
||||
|
||||
|
||||
@@ -243,8 +252,15 @@ class SseChannel:
|
||||
|
||||
def _ping_loop(self) -> None:
|
||||
while not self.closed:
|
||||
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满 15 秒
|
||||
if self._stop_event.wait(15):
|
||||
# ★ 心跳间隔可调(设置 → 超时 → 心跳间隔)。
|
||||
# 它必须**明显小于**客户端的读超时(sseRead),否则客户端会先
|
||||
# 判定"连接死了"再断开 —— 等用户回答的那种场景会因此白等。
|
||||
try:
|
||||
gap = float(timeouts.get('heartbeat'))
|
||||
except Exception: # noqa: BLE001
|
||||
gap = 15.0
|
||||
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满
|
||||
if self._stop_event.wait(gap):
|
||||
return
|
||||
if self.closed:
|
||||
return
|
||||
@@ -568,7 +584,50 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
'mcp': mcp_client.get_mcp_state(),
|
||||
'mcpConfig': mcp_client.read_mcp_config(),
|
||||
'conversations': store.list_conversations(),
|
||||
'agents': store.list_agents(),
|
||||
# ★ 给每个智能体算好"当前该显示哪张立绘"(需求 2.6 的回退链:
|
||||
# 当前 preset 档 → 平常档 → 旧单一 front → 空 = 内置默认人物)。
|
||||
#
|
||||
# 界面(选择界面、对话界面、编辑界面的预览)直接用这个字段,
|
||||
# 不用各自实现一遍回退链 —— 那种"同一逻辑抄三份"的写法,
|
||||
# 改一处必漏两处,而这个仓库里已经反复出现过。
|
||||
'agents': [
|
||||
{**a, 'portrait': agent_api.portrait_of(
|
||||
a.get('image') or {},
|
||||
(agentdb.emotion_state(a.get('id') or '').get('preset') or '平常'),
|
||||
)}
|
||||
for a in store.list_agents()
|
||||
],
|
||||
# 每个智能体当前的情绪(v1.2 双字段)。
|
||||
# ★ 情绪原来只在提示词里生效 —— AI 用 emotion_set 改了情绪,
|
||||
# 用户完全无感知,这个功能就成了一个看不见的字段。
|
||||
# `preset` 驱动界面(立绘、死亡禁言、成员标签),
|
||||
# `text` 是扮演质感。
|
||||
# **有情绪才带上**:没记过的(默认「平常」+ 空文本)不占位。
|
||||
'emotions': {
|
||||
a.get('id'): st for a in store.list_agents()
|
||||
if (st := agentdb.emotion_state(a.get('id') or ''))
|
||||
and (st.get('text') or st.get('preset') != agentdb.PRESET_DEFAULT)
|
||||
},
|
||||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||||
# 都不大(几个到几十个),一次带给界面省得进页面再拉一次
|
||||
'worldviews': store.list_resource('worldviews'),
|
||||
'modelEntries': store.list_resource('models'),
|
||||
'skills': store.list_resource('skills'),
|
||||
# v1.2 数值状态包。★ **剔掉脚本源码**,只给个数 ——
|
||||
# `/api/state` 是每次刷新都调的,把几 KB 的脚本每次都传一遍
|
||||
# 是纯浪费;列表上也只需要"带不带脚本"这一个信息。
|
||||
# 要看源码去 [规则包编辑],那里单独拉。
|
||||
'rulePacks': [
|
||||
{**{k: v for k, v in p.items() if k != 'scripts'},
|
||||
'scriptCount': len(p.get('scripts') or {})}
|
||||
for p in store.list_resource('rulepacks')
|
||||
],
|
||||
# AI 提的"该整理记忆了"(按智能体存),界面据此显示按钮
|
||||
'memorySuggestions': {
|
||||
a.get('id'): store.peek_summary_suggestion(a.get('id') or '')
|
||||
for a in store.list_agents()
|
||||
if store.peek_summary_suggestion(a.get('id') or '')
|
||||
},
|
||||
'toolNames': tool_names,
|
||||
'suggestedAllow': tools_runtime.suggest_allowlist(tool_names),
|
||||
# 前端用它挑终端里的预设命令(安卓的 getprop / Windows 的 dir 不通用)
|
||||
@@ -583,6 +642,36 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200, {'ok': True, 'settings': store.mask_settings(nxt)})
|
||||
return True
|
||||
|
||||
# ---------------------------------------------------------------- #
|
||||
# 超时(设置 → 超时)
|
||||
#
|
||||
# ★ 清单由内核给,**界面不硬编码这些项目** —— 加一项超时只改 timeouts.py,
|
||||
# 界面自动多出一行(连说明文字都是这里带过去的)。
|
||||
# ★ 写的时候是**整体替换**而不是深合并:默认值在 timeouts.py 里,
|
||||
# "改回默认"等于"从设置文件里删掉这一项",深合并会让它删不掉。
|
||||
# ---------------------------------------------------------------- #
|
||||
if pathname == '/api/timeouts' and method == 'GET':
|
||||
self.send_json(200, {
|
||||
'ok': True,
|
||||
'items': timeouts.catalog(),
|
||||
'values': timeouts.resolved(),
|
||||
})
|
||||
return True
|
||||
|
||||
if pathname == '/api/timeouts' and method in ('PUT', 'POST'):
|
||||
body = self.read_json_body()
|
||||
if body.get('reset'):
|
||||
next_values = timeouts.reset()
|
||||
else:
|
||||
next_values = timeouts.patch(body.get('values') or body)
|
||||
store.write_settings({'timeouts': next_values})
|
||||
self.send_json(200, {
|
||||
'ok': True,
|
||||
'items': timeouts.catalog(),
|
||||
'values': timeouts.resolved(),
|
||||
})
|
||||
return True
|
||||
|
||||
if pathname == '/api/models' and method == 'GET':
|
||||
settings = store.read_settings()
|
||||
try:
|
||||
@@ -665,13 +754,260 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
if pathname == '/api/conversations' and method == 'GET':
|
||||
self.send_json(200, {'conversations': store.list_conversations()})
|
||||
return True
|
||||
|
||||
# ---- AI 主动往会话里发一条消息(send_message 工具)----
|
||||
#
|
||||
# ★★★ 这里最危险的是**死循环**:模型发消息 → 顺手跑回复 →
|
||||
# 回复里又发消息 → ……。所以深度和条数两道闸都在 [SESSION_MSG_*]
|
||||
# 常量那边守着,任何一道超了就直接拒绝并说明原因。
|
||||
if pathname == '/api/session-message' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
conv = str(body.get('conversationId') or '')
|
||||
text = str(body.get('text') or '').strip()
|
||||
role = str(body.get('role') or 'user')
|
||||
want_reply = bool(body.get('reply'))
|
||||
try:
|
||||
depth = int(body.get('depth') or 1)
|
||||
except (TypeError, ValueError):
|
||||
depth = 1
|
||||
|
||||
if not text:
|
||||
self.send_json(400, {'error': 'text 不能为空'})
|
||||
return True
|
||||
if not conv:
|
||||
self.send_json(400, {'error': '缺少 conversationId'})
|
||||
return True
|
||||
|
||||
# 闸①:嵌套太深
|
||||
if depth > SESSION_MSG_MAX_DEPTH:
|
||||
self.send_json(200, {
|
||||
'error': (
|
||||
f'嵌套太深(第 {depth} 层)—— send_message 触发的回复里'
|
||||
f'不能再发消息,最多 {SESSION_MSG_MAX_DEPTH} 层。'
|
||||
'这是防止无限套娃把额度烧光。'
|
||||
),
|
||||
})
|
||||
return True
|
||||
# 闸②:这个会话发得太多了
|
||||
used = store.session_message_count(conv)
|
||||
if used >= store.SESSION_MSG_MAX:
|
||||
self.send_json(200, {
|
||||
'error': (
|
||||
f'这次会话你已经主动发了 {used} 条消息(上限 '
|
||||
f'{store.SESSION_MSG_MAX} 条)。'
|
||||
'别再发了,直接在你这一轮的回答里说。'
|
||||
),
|
||||
})
|
||||
return True
|
||||
|
||||
try:
|
||||
store.append_message(conv, role, text)
|
||||
except KeyError as exc:
|
||||
self.send_json(404, {'error': str(exc)})
|
||||
return True
|
||||
|
||||
if not want_reply:
|
||||
self.send_json(200, {'ok': True, 'sent': True, 'replied': False})
|
||||
return True
|
||||
|
||||
# ★ 要顺手回一轮:**必须放在后台线程**。
|
||||
# 当前这个线程正被 `send_message` 工具占着(模型还在等它的返回值),
|
||||
# 在这里同步跑一轮回复会**死锁**(等自己)。
|
||||
# 而且用 poll 那条路(和安卓端一样),事件进 _RUNS,界面能收到。
|
||||
run_id = 'r%d%s' % (int(time.time() * 1000), uuid.uuid4().hex[:5])
|
||||
with _RUNS_LOCK:
|
||||
_RUNS[run_id] = {'events': [], 'done': False, 'at': time.time()}
|
||||
|
||||
def sink_send(event):
|
||||
with _RUNS_LOCK:
|
||||
run = _RUNS.get(run_id)
|
||||
if run is None:
|
||||
return
|
||||
run['events'].append(event)
|
||||
if event.get('type') in ('done', 'error'):
|
||||
run['done'] = True
|
||||
|
||||
def sink_end():
|
||||
with _RUNS_LOCK:
|
||||
run = _RUNS.get(run_id)
|
||||
if run is not None:
|
||||
run['done'] = True
|
||||
|
||||
worker = threading.Thread(
|
||||
target=self._perform_chat,
|
||||
args=(sink_send, sink_end, store.read_settings(), conv, text, [], {}),
|
||||
kwargs={
|
||||
'should_stop': lambda: False,
|
||||
# ★ 关键:把深度传下去。这一轮回复里模型再调 send_message 时
|
||||
# 拿到的就是 depth+1;超过上限直接被拒。
|
||||
# 不传的话是无限套娃(见 /api/session-message 上面的注释)。
|
||||
'send_depth': depth,
|
||||
},
|
||||
name='self-message-reply',
|
||||
daemon=True,
|
||||
)
|
||||
worker.start()
|
||||
self.send_json(200, {
|
||||
'ok': True, 'sent': True, 'replyStarted': True, 'runId': run_id,
|
||||
})
|
||||
return True
|
||||
|
||||
# ---- 笔记(用户要能查看)----
|
||||
#
|
||||
# ★ 用户的原话:"notes 用户要能查看"。
|
||||
# 以前笔记只有 AI 能读写(走 notes 工具),用户看不到 ——
|
||||
# 而且路径算错落到了 App 外部私有目录,卸载还会被清掉。
|
||||
# 现在存 `<数据目录>/notes`,这几个接口让 App 列出来看。
|
||||
if pathname == '/api/notes' and method == 'GET':
|
||||
self.send_json(200, {'notes': store.list_notes()})
|
||||
return True
|
||||
|
||||
note_name = self._match_id(pathname, '/api/notes/')
|
||||
if note_name is not None:
|
||||
if method == 'GET':
|
||||
note = store.read_note(note_name)
|
||||
if note is None:
|
||||
self.send_json(404, {'error': '笔记不存在'})
|
||||
else:
|
||||
self.send_json(200, note)
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
ok = store.delete_note(note_name)
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# ---- AI 弹过的界面(关掉之后还能再打开)----
|
||||
#
|
||||
# ★ 用户要求:"AI 写的界面可以再点开"。
|
||||
# 每次 show_ui 都把 HTML 存一份到 <data>/screens/,这几个接口
|
||||
# 让 App 列出 / 读取 / 删除它们。
|
||||
if pathname == '/api/screens' and method == 'GET':
|
||||
parsed = urlsplit(self.path)
|
||||
params = dict(
|
||||
pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair
|
||||
)
|
||||
conv = unquote(params.get('conversationId') or '')
|
||||
self.send_json(200, {'screens': store.list_screens(conv)})
|
||||
return True
|
||||
|
||||
screen_id = self._match_id(pathname, '/api/screens/')
|
||||
if screen_id is not None:
|
||||
if method == 'GET':
|
||||
html = store.read_screen(screen_id)
|
||||
if html is None:
|
||||
self.send_json(404, {'error': '界面不存在或已清理'})
|
||||
else:
|
||||
self.send_json(200, {'id': screen_id, 'html': html})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
ok = store.delete_screen(screen_id)
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# ---- AI 界面的数据回流 ----
|
||||
#
|
||||
# ★★★ 这是"AI 自己写进网页里的接口"的落点。
|
||||
#
|
||||
# AI 用 show_ui 弹一个 HTML 界面,界面里可以写:
|
||||
# Doubao.sendToAi("用户选的是方案 B")
|
||||
# 那个值经安卓桥打到这里,**排队等下一次对话**。
|
||||
# 下一轮 run_agent 会把队里的东西作为上下文交给模型 ——
|
||||
# 于是"用户在 AI 自己写的界面里选了什么"真的回到了模型手里。
|
||||
#
|
||||
# ★ 为什么用"排队"而不是"直接起一轮对话":
|
||||
# 用户可能连点几下、或者在界面里选好几项再确认。
|
||||
# 每点一下就跑一轮模型既慢又费 token,而且用户还没说完。
|
||||
# 排队 → 用户下一次说话(或点界面上的提交按钮)时一起带上,
|
||||
# 语义上也更对:**界面是提问的一部分,不是提问本身**。
|
||||
if pathname == '/api/ui-result' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
conv = str(body.get('conversationId') or '')
|
||||
value = str(body.get('value') or '').strip()
|
||||
if not value:
|
||||
self.send_json(400, {'error': 'value 不能为空'})
|
||||
return True
|
||||
if not conv:
|
||||
self.send_json(400, {'error': '缺少 conversationId'})
|
||||
return True
|
||||
n = store.add_pending_ui(conv, value)
|
||||
self.send_json(200, {'ok': True, 'queued': n})
|
||||
return True
|
||||
|
||||
if pathname == '/api/ui-result' and method == 'GET':
|
||||
parsed = urlsplit(self.path)
|
||||
params = dict(
|
||||
pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair
|
||||
)
|
||||
conv = unquote(params.get('conversationId') or '')
|
||||
if not conv:
|
||||
self.send_json(400, {'error': '缺少 conversationId'})
|
||||
return True
|
||||
self.send_json(200, {'pending': store.peek_pending_ui(conv)})
|
||||
return True
|
||||
|
||||
if pathname == '/api/conversations' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
self.send_json(200, {'conversation': store.create_conversation(body.get('title') or '新对话')})
|
||||
kind = str(body.get('type') or 'single')
|
||||
parts = body.get('participants')
|
||||
self.send_json(200, {'conversation': store.create_conversation(
|
||||
body.get('title') or '新对话',
|
||||
# ★ 新会话要**记住它属于谁** —— 会话隔离的依据就是它。
|
||||
# 不传的话所有会话的主人都是空,切换智能体时就没法判断
|
||||
# "这是不是同一个人的对话",只能一直串着(用户报的 bug)。
|
||||
agent_id=(body.get('agentId') or '').strip(),
|
||||
# ★ v1.2 §3.9:群聊是**独立实体**,出现在每个参与者的会话列表里。
|
||||
# 成员列表的第 0 个是主智能体(无人被点名时由它兜底发言)。
|
||||
kind=kind,
|
||||
participants=parts if isinstance(parts, list) else None,
|
||||
)})
|
||||
return True
|
||||
|
||||
# ---- 群聊成员增删(需求 §3.9:"用户手动增删成员无条件")----
|
||||
#
|
||||
# ★ "无条件"是需求原话:不加"只有主智能体能加人""要对方同意"这类
|
||||
# 限制 —— 会话是用户的,他想拉谁就拉谁。
|
||||
# 唯一的例外是主智能体不能移出(移掉就没有兜底发言的人了)。
|
||||
member_id = self._match_id(pathname, '/api/conversations/')
|
||||
if member_id is not None and '/members' in pathname:
|
||||
conv = store.get_conversation(member_id)
|
||||
if not conv:
|
||||
self.send_json(404, {'error': '会话不存在'})
|
||||
return True
|
||||
head, _, tail = pathname.partition('/members')
|
||||
target = tail.strip('/')
|
||||
if method == 'POST' and not target:
|
||||
try:
|
||||
b = self.read_json_body()
|
||||
except ValueError:
|
||||
b = {}
|
||||
target = str(b.get('agentId') or '').strip()
|
||||
if not group_chat.add_member(conv, target):
|
||||
self.send_json(400, {'error': '加不进去(人不存在或已经在里面了)'})
|
||||
return True
|
||||
elif method == 'DELETE' and target:
|
||||
if not group_chat.remove_member(conv, target):
|
||||
self.send_json(400, {'error': '移不出去(主智能体不能被移出)'})
|
||||
return True
|
||||
else:
|
||||
self.send_json(405, {'error': '不支持的操作'})
|
||||
return True
|
||||
# ★ 只存 `participants` —— "成员超过一个就升级成群聊"那条规则
|
||||
# 收在 `group_chat.add_member` 里了。补在这里的话,
|
||||
# 任何别的调用方都会忘,而忘的代价是"拉了人但他从不说话"。
|
||||
updated = store.update_conversation(
|
||||
member_id, {'participants': conv.get('participants') or []}) or conv
|
||||
self.send_json(200, {'conversation': updated})
|
||||
return True
|
||||
|
||||
conv_id = self._match_id(pathname, '/api/conversations/')
|
||||
if conv_id is not None:
|
||||
if method == 'GET':
|
||||
@@ -694,6 +1030,51 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# 标记某条消息为「重要」(v1.2 §4.3)
|
||||
#
|
||||
# 路径:/api/conversations/<convId>/important,body: {content, role?, important?}
|
||||
#
|
||||
# ★ 只有**用户**能打这个标记(需求原话"仅用户可标")——
|
||||
# AI 那边没有对应的工具,它有 `memory_add` 去记该记的东西。
|
||||
# 被标记的消息在**上下文窗口裁剪**时"破格永久携带"。
|
||||
#
|
||||
# ★★ 按**内容**定位而不是下标(踩过):
|
||||
# 界面上那份消息列表和存储里的**不保证一一对应**(本地生成的内容、
|
||||
# 还没落地的流式消息……),按下标"长按第 3 条"会把标记打到第 1 条上,
|
||||
# 而且**静默标错** —— 用户要等哪天发现某句话莫名没被裁掉才知道。
|
||||
# 找不到就报 404,绝不猜一条标上去。
|
||||
if pathname.startswith('/api/conversations/') and pathname.endswith('/important') \
|
||||
and method == 'POST':
|
||||
cid = pathname[len('/api/conversations/'):-len('/important')].strip('/')
|
||||
if cid and '/' not in cid:
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
content = body.get('content')
|
||||
if content is None:
|
||||
self.send_json(400, {'error': '要带上 content(按内容定位那条消息)'})
|
||||
return True
|
||||
want = body.get('important')
|
||||
if want is None:
|
||||
# 不传就取反:界面上是个开关,点一下切一次。
|
||||
# ★ 用**存储里**那条的当前状态取反(不是界面传来的),
|
||||
# 免得界面和服务端状态不一致时越切越乱
|
||||
conv = store.get_conversation(cid) or {}
|
||||
cur = False
|
||||
for m in reversed(conv.get('messages') or []):
|
||||
if str(m.get('content') or '') == str(content):
|
||||
cur = bool(m.get('important'))
|
||||
break
|
||||
want = not cur
|
||||
msg = store.mark_important_by_content(
|
||||
cid, content, str(body.get('role') or ''), bool(want))
|
||||
if msg is None:
|
||||
self.send_json(404, {'error': '没找到这条消息(内容对不上)'})
|
||||
else:
|
||||
self.send_json(200, {'ok': True, 'important': bool(want)})
|
||||
return True
|
||||
|
||||
# 会议模式
|
||||
if pathname == '/api/meetings' and method == 'GET':
|
||||
self.send_json(200, {'meetings': meeting.list_meetings()})
|
||||
@@ -935,9 +1316,24 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(400, {'error': '缺少 name'})
|
||||
return True
|
||||
try:
|
||||
# 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错
|
||||
result = tools_runtime.execute_tool(name, body.get('args') or {},
|
||||
{'security': {'mode': 'open'}})
|
||||
# ★ 手动试运行**不受安全模式限制**(是用户自己在「技能」页点的),
|
||||
# 但仍要能报错。所以 mode 强制 open。
|
||||
#
|
||||
# ★★ 但**不能**只传一个空壳 settings(以前就是 {'security':...}):
|
||||
# 界面工具(show_ui/ask_user/end_conversation)的开关也在 settings 里,
|
||||
# 空壳会让它们**永远被第二道拦截挡住** —— 用户在技能页点"试运行",
|
||||
# 明明开关是开的,却收到"已关闭"。这个错会让人以为是开关没生效。
|
||||
# 所以拿真实设置、只覆盖 security。
|
||||
live = store.read_settings() or {}
|
||||
settings = {**live, 'security': {'mode': 'open', 'allow': []}}
|
||||
tools_runtime.push_context(
|
||||
conversationId=str(body.get('conversationId') or ''),
|
||||
toolName=name,
|
||||
)
|
||||
try:
|
||||
result = tools_runtime.execute_tool(name, body.get('args') or {}, settings)
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
self.send_json(200, result)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.send_json(500, {'ok': False, 'error': str(exc)})
|
||||
@@ -1005,27 +1401,15 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200, {'ok': True})
|
||||
return True
|
||||
|
||||
# 智能体
|
||||
if pathname == '/api/agents' and method == 'GET':
|
||||
self.send_json(200, {'agents': store.list_agents()})
|
||||
# 智能体系统的接口(记忆 / 情绪 / Token / 世界观 / 模型列表 / Skill / 导入导出)
|
||||
#
|
||||
# ★ 全部集中在 agent_api.py 里 —— app.py 已经 1800 行,二十多个新接口
|
||||
# 塞进来会让这个文件彻底没法看。
|
||||
# ★ 老的 /api/agents 那三个路由**删掉了**(原来在下面),由这里统一处理:
|
||||
# 留着就是两份实现,而新那份多了"内置智能体不能删"的保护 ——
|
||||
# 两份并存的话,哪份生效取决于顺序,这种 bug 最难查。
|
||||
if agent_api.handle(self, pathname, method):
|
||||
return True
|
||||
if pathname == '/api/agents' and method == 'POST':
|
||||
body = self.read_json_body()
|
||||
self.send_json(200, {'agent': store.create_agent(body)})
|
||||
return True
|
||||
agent_id = self._match_id(pathname, '/api/agents/')
|
||||
if agent_id is not None:
|
||||
if method in ('PATCH', 'PUT'):
|
||||
body = self.read_json_body()
|
||||
agent = store.update_agent(agent_id, body)
|
||||
if agent:
|
||||
self.send_json(200, {'agent': agent})
|
||||
else:
|
||||
self.send_json(404, {'error': '智能体不存在'})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
self.send_json(200 if store.delete_agent(agent_id) else 404, {'ok': True})
|
||||
return True
|
||||
|
||||
# 附件
|
||||
if pathname == '/api/upload' and method == 'POST':
|
||||
@@ -1174,7 +1558,19 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
)
|
||||
merged_agent = {'systemPrompt': sys_prompt, 'id': '', 'name': '判断器'}
|
||||
else:
|
||||
base = (agent or {}).get('systemPrompt') or cfg.get('systemPrompt') or ''
|
||||
# ★ 会议节点也走**同一套** system prompt 拼装(需求附录 C)。
|
||||
#
|
||||
# 以前这里是自己拼的(`agent.systemPrompt or cfg.systemPrompt`),
|
||||
# 于是同一个智能体在聊天里有记忆/情绪/世界观、在会议节点里没有 ——
|
||||
# "引擎改了另一端必须跟上"这条在这个仓库里踩过好几次,
|
||||
# 所以这次直接复用 agent_context,别再抄一份。
|
||||
#
|
||||
# ★ 节点的额外要求 / 输出要求 / 变量说明仍然**追加在后面**:
|
||||
# 它们是"这一轮的任务约束",比人设更具体,放最后模型才看得重。
|
||||
if agent:
|
||||
base = agent_context.build_system_prompt(store.read_settings(), agent)
|
||||
else:
|
||||
base = cfg.get('systemPrompt') or ''
|
||||
parts = [base] if base.strip() else []
|
||||
if extra:
|
||||
parts.append('【本次任务的额外要求】\n' + extra)
|
||||
@@ -1305,7 +1701,15 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
conversation_id = body.get('conversationId') or 'c_main'
|
||||
text = str(body.get('message') or '').strip()
|
||||
attachments = body.get('attachments') if isinstance(body.get('attachments'), list) else []
|
||||
if not text and not attachments:
|
||||
# ★★ 自动续的那几轮(`autoContinue` / `forceSpeaker`)**本来就没有用户消息** ——
|
||||
# 那是让群里下一个人接着说话,不是用户在打字。
|
||||
#
|
||||
# 不放行的话,每一轮都会被这条校验打回 400,
|
||||
# 用户在界面上看到的是**一屏「出错了:消息为空」**,
|
||||
# 而"两个智能体对话"永远发生不了(真机反馈「还是不能互相对话」,
|
||||
# 现场就是六条这个错误)。
|
||||
auto_continue = bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))
|
||||
if not text and not attachments and not auto_continue:
|
||||
self.send_json(400, {'error': '消息为空'})
|
||||
return
|
||||
|
||||
@@ -1351,16 +1755,17 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
)
|
||||
|
||||
def _perform_chat(self, emit, end, settings, conversation_id, text, attachments, body,
|
||||
should_stop=None) -> None:
|
||||
should_stop=None, send_depth: int = 0) -> None:
|
||||
"""跑一轮对话。SSE 与轮询两条路共用,保证事件序列一致。"""
|
||||
cancelled = should_stop or (lambda: False)
|
||||
try:
|
||||
existing = store.get_conversation(conversation_id) or {}
|
||||
history_source = body.get('history') if isinstance(body.get('history'), list) else \
|
||||
existing.get('messages') or []
|
||||
history = [
|
||||
{'role': m.get('role'), 'content': m.get('content')}
|
||||
for m in history_source
|
||||
# ★ 先只做**过滤**,真正的窗口裁剪放到下面(`agent` 解析之后)——
|
||||
# 因为窗口大小是**按智能体配**的(需求 4.3),这里还不知道是谁。
|
||||
raw_history = [
|
||||
m for m in history_source
|
||||
if isinstance(m, dict) and m.get('role') in ('user', 'assistant')
|
||||
]
|
||||
|
||||
@@ -1386,32 +1791,294 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
has_image = any(p.get('type') == 'image_url' for p in parts)
|
||||
user_content = parts if (has_image or len(parts) > 1) else text
|
||||
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'user',
|
||||
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
|
||||
'attachments': attachment_meta,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
if text:
|
||||
store.auto_title(conversation_id, text)
|
||||
# ★★ 群聊的发言权仲裁(需求 v1.2 §3.9)。
|
||||
#
|
||||
# 单聊时这里是**恒等操作**(`resolve` 原样返回传进去的那个人),
|
||||
# 判断收在 `is_group` 里 —— 只有群聊才真去仲裁。
|
||||
#
|
||||
# 三种来源,优先级从高到低:
|
||||
# ① 用户 @ 的人(用户主权)
|
||||
# ② AI 上一轮 `pass_turn` 移交的人(一轮最多一次)
|
||||
# ③ 主智能体兜底 —— **永不冷场**,没人被点名时也有人接话
|
||||
conv0 = store.get_conversation(conversation_id) or {}
|
||||
if group_chat.is_group(conv0):
|
||||
all_agents = store.list_agents()
|
||||
names = [(x['id'], x.get('name') or '') for x in all_agents]
|
||||
# ★★ 用户这一轮 @ 了谁 —— **只看这一条消息**。
|
||||
#
|
||||
# 这个顺序很容易写错:本函数是「先仲裁、后落库」,
|
||||
# 所以 `raw_history` 里**根本没有本次这条用户消息**。
|
||||
# 拿它去找"最后一条 user",找到的是**上一次**用户说的话。
|
||||
#
|
||||
# 踩过两次:
|
||||
# ① 用户打 `@寐眠 在吗` → 按上一条(没点名)仲裁 → 小黑替寐眠答
|
||||
# ② **自动续轮时又从历史回退** → 把上一轮的 `@寐眠` 又拿来用,
|
||||
# 于是 `talk_to` 明明把话交给了别人,仲裁还是给寐眠 ——
|
||||
# 表现是"下回还是 A 说话"(真机反馈)。
|
||||
#
|
||||
# ★ 续轮(`autoContinue`)**本来就没有新用户消息**,
|
||||
# 那一轮该由 `forced` / `passed` / 轮流来定,
|
||||
# 绝不能去翻历史里的 `@` —— 那是上一件事了。
|
||||
want = group_chat.mention_in(text or '', names)
|
||||
pick = group_chat.resolve(
|
||||
conv0,
|
||||
want=want,
|
||||
# ★★ 从**上一轮**的移交状态取,**不是**从 HTTP body ——
|
||||
# 界面(Kotlin)从来不发 handoffTo 这个字段,
|
||||
# 以前读 body 等于永远拿到空串,② AI 移交那条分支是**死代码**。
|
||||
# 现在 pass_turn 写在 tools_runtime 的轮次状态里,这里读它。
|
||||
passed=str(tools_runtime.handoff_state().get('to') or ''),
|
||||
# ★ 界面点「让他们聊」时指定的人(优先级最高)。
|
||||
# 不这样做的话,"两个 AI 对话"就得指望 AI 自己愿意 pass_turn ——
|
||||
# 实测它并不总会,用户按了也没反应。
|
||||
forced=str(body.get('forceSpeaker') or ''),
|
||||
alive={x['id']: not agentdb.is_dead(x['id']) for x in all_agents},
|
||||
)
|
||||
speaker = store.get_agent(pick.get('speaker'))
|
||||
if speaker:
|
||||
agent, agent_id = speaker, speaker.get('id') or ''
|
||||
# 界面据此显示"这一轮谁在说、为什么是他"
|
||||
emit({'type': 'speaker', 'agentId': agent_id,
|
||||
'reason': pick.get('reason') or '', 'note': pick.get('note') or ''})
|
||||
|
||||
# ★★ 对话上下文窗口(需求 v1.2 §4.3)。
|
||||
#
|
||||
# 只把"最近 N 轮 + 用户标了重要的那几条"送进模型。
|
||||
# 超出的**直接丢弃、不做摘要**(需求原话)—— 沉淀走记忆系统,
|
||||
# 不搞第二套摘要管线(摘要自己也要花一次调用,还会丢信息且不可追溯)。
|
||||
#
|
||||
# ★ 命名:这里叫「上下文窗口」,和记忆侧的「记忆注入窗口」不是一回事。
|
||||
# 后者管"塞多少条记忆",超出部分**还能 memory_search 搜到**;
|
||||
# 这里管"送几轮对话",超出就真的不送了。
|
||||
#
|
||||
# ★ `strip_for_model` 是**新建** dict,不原地改历史 ——
|
||||
# 改一个字,从那儿往后的前缀缓存全废(需求 4.3 的"字节冻结")。
|
||||
win_rounds, win_batch = context_window.resolve(settings, agent)
|
||||
window = context_window.trim(raw_history, win_rounds, win_batch)
|
||||
history = [context_window.strip_for_model(m) for m in window['messages']]
|
||||
if window.get('reason'):
|
||||
print(f'[context] {context_window.describe(window)}', file=sys.stderr)
|
||||
|
||||
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
|
||||
#
|
||||
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
|
||||
# 还在同一个会话里接着聊 —— 历史消息是上一个角色说的,
|
||||
# 而 system prompt 已经换成新角色的了。新角色**会把别人的话
|
||||
# 当成自己说的**(用户的原话:"智能体怎么串味了")。
|
||||
#
|
||||
# 处理:主人不一致就**另起一个会话**,并通知界面换 id。
|
||||
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
|
||||
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
|
||||
owner = (existing.get('agentId') or '').strip()
|
||||
# ★★ **群聊不做这个隔离**:群聊本来就是多智能体的,上面
|
||||
# `group_chat.resolve` 刚把 `agent_id` 定成「本轮的发言人」,
|
||||
# 它不是「会话的主人」。照单聊这样比一下,群里每换一个人说话
|
||||
# 就会另起一个会话 —— 用户 @ 谁,界面就跳到谁的对话去
|
||||
# (真机反馈原话:「群聊一@就跑到别的对话去了」)。
|
||||
# `is_group` 既认 `type` 也认 `participants`,老会话也吃得住。
|
||||
if existing and agent_id and not group_chat.is_group(existing):
|
||||
if not owner:
|
||||
store.set_conversation_agent(conversation_id, agent_id)
|
||||
elif owner != agent_id:
|
||||
conversation_id = store.create_conversation(agent_id=agent_id)['id']
|
||||
existing = store.get_conversation(conversation_id) or {}
|
||||
# 界面据此把当前会话切过去(不然它会往老 id 上继续追加)
|
||||
emit({'type': 'rebased', 'conversationId': conversation_id,
|
||||
'reason': 'agent_changed'})
|
||||
|
||||
# ★★ 死亡的智能体**不能对话**(需求 3.5)。
|
||||
#
|
||||
# 判定放在**发起前**,和 Token 限额同一层:不是在生成时才拦
|
||||
# (那时候已经花了钱),而是根本不让这一轮开始。
|
||||
#
|
||||
# 复活只有两条通道,都不在这里:
|
||||
# · 用户手动改(界面上的情绪区,兜底主权)
|
||||
# · 状态脚本改(定时复活/解药剧情,走沙箱)
|
||||
if agent_id and agentdb.is_dead(agent_id):
|
||||
emit({
|
||||
'type': 'error',
|
||||
'code': 'agent_dead',
|
||||
'message': f'「{(agent or {}).get("name") or "这个智能体"}」已经死亡,无法对话。',
|
||||
'hint': '在「记忆 → 情绪」里把它改回其他状态就能复活。',
|
||||
})
|
||||
return
|
||||
|
||||
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
||||
#
|
||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||
# **已经攒下来的**用量,超了就根本不发这一轮。
|
||||
#
|
||||
# ★ 拦在"写用户消息之前":拦住了还把用户那句话落库的话,
|
||||
# 他会看到自己发的消息挂在那儿、AI 永远不回,以为卡住了。
|
||||
#
|
||||
# ★ 豁免:记忆整理、导出这些**非对话生成**的操作不走这里
|
||||
# (它们有自己的接口),所以不会被限额挡住。
|
||||
try:
|
||||
limit = int(float((agent or {}).get('tokenLimit') or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
if limit > 0 and agent_id:
|
||||
used = sum(agentdb.token_usage(agent_id)['total'].values())
|
||||
if used >= limit:
|
||||
farewell = (settings.get('tokenLimitFarewell') or '我没力气再说话了……').strip()
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'assistant',
|
||||
'content': farewell,
|
||||
'agentId': agent_id,
|
||||
# ★ 标一下"这不是模型生成的":界面据此把它显示成提示样式,
|
||||
# 而且重新生成时不会被当成一条正常的 AI 回复
|
||||
'limitNotice': True,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
emit({
|
||||
'type': 'error',
|
||||
'code': 'token_limit',
|
||||
'message': f'{(agent or {}).get("name") or "这个智能体"}的 Token 额度用完了',
|
||||
'used': used,
|
||||
'limit': limit,
|
||||
'farewell': farewell,
|
||||
'hint': '可以清零重新开始,或者把限额调大 / 改成无限制。',
|
||||
})
|
||||
return
|
||||
|
||||
# ★★ `autoContinue`:这一轮是**界面替 AI 自动续的**,不是用户说的话。
|
||||
#
|
||||
# 群聊里 AI 用 `pass_turn` 把话交给另一个人时,界面会接着再发一次
|
||||
# (不带用户消息)—— 这样两个人就能真的聊起来,而不是
|
||||
# "用户说一句、AI 移交一次、然后就没下文了"。
|
||||
#
|
||||
# ★ 不追加用户消息:追加的话对话里会冒出一堆空消息,
|
||||
# 而且模型会以为用户又说话了。移交状态本来就从
|
||||
# `tools_runtime.handoff_state()` 里读(上一轮留下的),
|
||||
# 所以下一轮的发言人自然是接得上的。
|
||||
# ★ 判据必须和 `_handle_chat` 开头那条校验**完全一致**
|
||||
# (`autoContinue` 或 `forceSpeaker`)—— 两处不一致的话,
|
||||
# 一边放行一边往里塞空用户消息,对话里就会冒出一堆空条目。
|
||||
auto_continue = bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))
|
||||
if not auto_continue:
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'user',
|
||||
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
|
||||
'attachments': attachment_meta,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
if text:
|
||||
store.auto_title(conversation_id, text)
|
||||
|
||||
# ★★ 自动续轮(`autoContinue`)**不能再追加一条空的 user 消息**。
|
||||
#
|
||||
# 以前不管是不是续轮都拼一条 `{'role':'user','content':user_content}`,
|
||||
# 而续轮没有用户输入 → `user_content` 是空串。
|
||||
# 模型看到的是"用户刚发了一条空消息",于是它自己都懵了 ——
|
||||
# 真机上的原话是:「这条又是空的,我这边没收到内容。猜两种可能:…」
|
||||
# (用户报的「talk_to 没有内容呀」)。
|
||||
#
|
||||
# 而 `talk_to` 说的那句话**就在历史里**(落库了),
|
||||
# 不追加空消息它自然就看到了。
|
||||
msgs_for_model = list(history)
|
||||
if not auto_continue:
|
||||
msgs_for_model.append({'role': 'user', 'content': user_content})
|
||||
else:
|
||||
# 续轮补一句**极短的指令**而不是空消息:模型需要知道
|
||||
# "现在轮到你接话",但不该以为用户说了什么。
|
||||
# 这条**不落库**(只进这一轮给模型的 messages),
|
||||
# 所以用户在聊天记录里看不到它。
|
||||
msgs_for_model.append({
|
||||
'role': 'user',
|
||||
'content': '(系统:现在轮到你接着说,不用等用户输入。直接接着上面的内容回应。)',
|
||||
})
|
||||
|
||||
result = agent_loop.run_agent(
|
||||
settings=settings,
|
||||
agent=agent,
|
||||
messages=[*history, {'role': 'user', 'content': user_content}],
|
||||
messages=msgs_for_model,
|
||||
emit=emit,
|
||||
should_stop=cancelled,
|
||||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||
# end_conversation 会明确报错(而不是假装成功)。
|
||||
conversation_id=conversation_id,
|
||||
# ★ 防无限套娃:这一轮的深度传进去,send_message 据此判断能不能再发
|
||||
send_depth=send_depth,
|
||||
)
|
||||
|
||||
# ★ 这一轮的 Token 用量(需求 4.1:对话界面显示"本次对话"的用量)。
|
||||
# 按轮记在消息上,会话级用量是**加起来**算的 —— 这样"重新生成"
|
||||
# 把上一条替换掉时,它的消耗也跟着消失,不会虚高。
|
||||
in_tok, out_tok = agent_loop.usage_pair(result.get('usage'))
|
||||
model_name = (store.provider_info(settings, agent) or {}).get('model') or ''
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'assistant',
|
||||
'content': result.get('content', ''),
|
||||
# 思维链也要落库,否则一刷新「思考过程」就没了
|
||||
'reasoning': result.get('reasoning', '') or '',
|
||||
'agentId': (agent or {}).get('id') or '',
|
||||
'agentId': agent_id,
|
||||
'usage': {'input': in_tok, 'output': out_tok},
|
||||
# ★ 幻觉调用检测(需求 3.7):嘴上说记住了、实际没调工具。
|
||||
# 界面据此显示一个 ⚠ 标记 —— 用户当场看不出来,
|
||||
# 但下次发现它"完全不记得"时就晚了。
|
||||
'hallucination': agent_loop.check_hallucinated_memory(
|
||||
result.get('content') or '',
|
||||
int(result.get('toolCalls') or 0),
|
||||
bool((settings.get('tools') or {}).get('python', True)),
|
||||
),
|
||||
# ★ 工具调用明细要落库 —— 不落的话界面上那些"工具卡片"
|
||||
# 只有流式那一刻能看到,**重启 App 就全没了**
|
||||
# (用户报的「工具怎么重启就不显示了」)。
|
||||
'toolTrace': result.get('toolTrace') or [],
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
|
||||
# ★★ 这一轮 AI 用 `pass_turn` 把话交给了别人吗?交了就**告诉界面**。
|
||||
#
|
||||
# 光靠上面那个 `speaker` 事件不够 —— 它是在**轮前**发的,
|
||||
# 而 `pass_turn` 是**轮中**才调用的。于是最常见的那个剧本:
|
||||
# ① 用户没点名(或点名的人不在场)→ 兜底给主智能体,reason = "host"
|
||||
# ② 主智能体说完话,轮中调 `pass_turn` 让给另一个人
|
||||
# 界面看到的 reason 是 "host",以为没人移交,就**不再续轮** ——
|
||||
# 被让的那个人永远开不了口(用户报的"还是不能互相对话")。
|
||||
#
|
||||
# ★ 判据用 `tools_runtime.handoff_state()`(模块级轮次状态),
|
||||
# 不是线程局部变量 —— 工具跑在 worker 线程上,
|
||||
# 这个坑在 `pass_turn` 上已经踩过一次了。
|
||||
hs = tools_runtime.handoff_state()
|
||||
if hs.get('used') and hs.get('to'):
|
||||
emit({'type': 'handoff', 'to': hs['to'], 'from': agent_id})
|
||||
|
||||
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
|
||||
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
|
||||
if agent_id and (in_tok or out_tok):
|
||||
try:
|
||||
# ★ v1.2:缓存命中 / 未命中一起落库。
|
||||
# `cache_pair` 已经把三家的字段名归一化过
|
||||
# (DeepSeek 两个都给、Claude/OpenAI 只给命中要自己推);
|
||||
# 两家都没给就是 0/0,界面据此**不显示**那一列。
|
||||
hit, miss = agent_loop.cache_pair(result.get('usage'))
|
||||
agentdb.token_add(agent_id, model_name, in_tok, out_tok, hit, miss)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[usage] 记 Token 用量失败:{exc}', file=sys.stderr)
|
||||
|
||||
# ★ 状态每参与一轮减 1(需求 §3.11)。
|
||||
#
|
||||
# 放在**生成之后**:这一轮它确实开口了,才该扣。
|
||||
# 放在之前的话,被额度拦下、被死亡拦下的那些轮次也会扣 ——
|
||||
# 而它根本没说话。
|
||||
#
|
||||
# 过期要播报("中毒已经消退了")—— 那是个用户能感知的变化。
|
||||
if agent_id:
|
||||
try:
|
||||
for ev in rule_engine.tick_statuses(agent_id):
|
||||
emit({
|
||||
'type': 'status',
|
||||
'name': ev.get('name'),
|
||||
'expired': bool(ev.get('expired')),
|
||||
'remaining': ev.get('remaining', 0),
|
||||
})
|
||||
except Exception as exc: # noqa: BLE001 - 状态系统坏了不该让回复发不出去
|
||||
print(f'[rule] 状态递减失败:{exc}', file=sys.stderr)
|
||||
|
||||
conv = store.get_conversation(conversation_id) or {}
|
||||
emit({'type': 'saved', 'conversationId': conversation_id, 'title': conv.get('title')})
|
||||
except Exception as exc: # noqa: BLE001 - 出错也要以 error 事件收尾,前端才知道停了
|
||||
|
||||
@@ -26,6 +26,7 @@ import time
|
||||
import traceback
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 工具定义(与 tools/shell.py、tools/python_run.py 的 TOOL 完全一致,
|
||||
@@ -43,7 +44,10 @@ SHELL_TOOL = {
|
||||
'properties': {
|
||||
'command': {'type': 'string', 'description': '要执行的命令,例如 ls -la 或 python --version'},
|
||||
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → shell 命令」那个值',
|
||||
},
|
||||
},
|
||||
'required': ['command'],
|
||||
},
|
||||
@@ -67,7 +71,10 @@ PYTHON_RUN_TOOL = {
|
||||
'code': {'type': 'string', 'description': '要执行的 Python 代码(action=run 时二选一)'},
|
||||
'file': {'type': 'string', 'description': '要执行的 .py 文件路径(action=run 时二选一)'},
|
||||
'stdin': {'type': 'string', 'description': '传给脚本的标准输入,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 60,最大 600'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → 跑 Python 代码」那个值',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -125,7 +132,8 @@ def shell_run(args: dict) -> dict:
|
||||
if bad in lowered:
|
||||
raise ValueError(f'命令命中黑名单({bad}),已拒绝执行。确实需要请设置 DOUBAO_SHELL_UNSAFE=1')
|
||||
|
||||
timeout = max(1, min(300, int(args.get('timeout') or 30)))
|
||||
# 超时:模型传了就用它的,没传就用设置里的(设置 → 超时 → shell 命令)
|
||||
timeout = timeouts.budget(args, 'shell')
|
||||
cwd = args.get('cwd') or None
|
||||
if cwd and not os.path.isdir(cwd):
|
||||
raise ValueError(f'工作目录不存在:{cwd}')
|
||||
@@ -248,6 +256,17 @@ def run_with_timeout(fn, timeout_s: float):
|
||||
而且 CPython 根本杀不掉一个正在跑的线程。超时后我们只能"放弃等待",
|
||||
被放弃的线程会继续在后台跑完(daemon 线程,不阻塞进程退出)。
|
||||
这个取舍必须让用户知道,所以超时消息里写清楚。
|
||||
|
||||
★★ `timeout_s <= 0` = **不限时**(一直等到它跑完)。
|
||||
|
||||
给"停下来等用户"的那类工具用(`ask_user` / `show_ui` 的 wait 模式)——
|
||||
它们的耗时**完全取决于用户什么时候点**,60 秒的上限只会造成:
|
||||
弹窗还开着、用户 5 分钟后才选,而模型早就收到"工具执行超时"、
|
||||
于是按自己猜的答案往下写了。
|
||||
|
||||
为什么默认仍然是 60 秒:这是"工具里写了死循环"的安全网
|
||||
(不让整个内核跟着卡死)。会等用户的工具属于**设计上就该慢**,
|
||||
由工具自己声明 `WAIT_FOR_USER = True` 来豁免,见 tools_runtime。
|
||||
"""
|
||||
box = {}
|
||||
|
||||
@@ -259,9 +278,13 @@ def run_with_timeout(fn, timeout_s: float):
|
||||
|
||||
thread = threading.Thread(target=worker, name='doubao-python-run', daemon=True)
|
||||
thread.start()
|
||||
thread.join(timeout_s)
|
||||
if thread.is_alive():
|
||||
return None
|
||||
if timeout_s and timeout_s > 0:
|
||||
thread.join(timeout_s)
|
||||
if thread.is_alive():
|
||||
return None
|
||||
else:
|
||||
# 不限时:join() 不带参数就是一直等
|
||||
thread.join()
|
||||
if 'error' in box:
|
||||
raise box['error']
|
||||
return box.get('value')
|
||||
@@ -278,7 +301,7 @@ def python_run(args: dict) -> dict:
|
||||
if not code and not file_path:
|
||||
raise ValueError('code 和 file 至少要给一个')
|
||||
|
||||
timeout = max(1, min(600, int(args.get('timeout') or 60)))
|
||||
timeout = timeouts.budget(args, 'pythonRun')
|
||||
stdin_text = args.get('stdin') or ''
|
||||
|
||||
if file_path:
|
||||
@@ -321,3 +344,13 @@ BUILTIN_TOOLS = {
|
||||
'shell': {'spec': SHELL_TOOL, 'run': shell_run},
|
||||
'python_run': {'spec': PYTHON_RUN_TOOL, 'run': python_run},
|
||||
}
|
||||
|
||||
# 智能体系统的工具(记忆 / 情绪 / 用量)也走**进程内**实现 —— 它们要读写
|
||||
# `agent.db`,而电脑端的文件工具是子进程,根本 import 不到内核模块。
|
||||
#
|
||||
# ★ 合并进这一个字典而不是让 tools_runtime 从两处取:
|
||||
# 发现工具、找入口、判"要不要豁免超时"全都只认 BUILTIN_TOOLS,
|
||||
# 多一个来源就多一处"忘了查"的机会(加进来之后自动全部生效)。
|
||||
from agent_tools import AGENT_TOOLS # noqa: E402
|
||||
|
||||
BUILTIN_TOOLS.update(AGENT_TOOLS)
|
||||
|
||||
230
android/kernel/context_window.py
Normal file
230
android/kernel/context_window.py
Normal file
@@ -0,0 +1,230 @@
|
||||
"""对话上下文窗口(需求 v1.2 §4.3)。
|
||||
|
||||
## 命名纪律
|
||||
|
||||
需求里特别强调了一句,照抄过来:
|
||||
|
||||
> 记忆侧叫「**记忆注入窗口**」,对话侧叫「**上下文窗口**」,文档与 UI 永不混用。
|
||||
|
||||
两个东西确实像但完全不同:
|
||||
|
||||
· 记忆注入窗口(§3.2)—— 每轮往 system prompt 里塞**多少条记忆**,
|
||||
超出部分**降级为可检索**(AI 还能 memory_search 找到)
|
||||
· 对话上下文窗口(§4.3)—— 往模型送**最近多少轮对话**,
|
||||
超出部分**直接丢弃、不做摘要**(沉淀走记忆系统,不搞第二套摘要管线)
|
||||
|
||||
混着叫的话,用户问"我调窗口怎么没用"时你都不知道他调的是哪个。
|
||||
|
||||
## 四条规则
|
||||
|
||||
1. **窗口 = 最近 N 轮 + 重要标记消息**(N 默认 20,按智能体配置)
|
||||
2. **重要标记只有用户能打**(AI 有 memory_add,标记是用户主权)。
|
||||
被标记的消息**破格永久携带**,按**原始时间序**插回去 ——
|
||||
不是塞到最前面:那会打乱因果,模型会看到"先发生的事在后面"。
|
||||
3. **成批对齐裁剪**:不是"超一点就裁一点",而是攒够一批才裁一批。
|
||||
目的是**摊薄前缀缓存失效次数** —— 每轮都裁的话,前缀每轮都变,
|
||||
上下文缓存一次都命中不了,比不裁还贵。
|
||||
4. **字节冻结**:送进去的历史消息**永不原地修改**。
|
||||
改一个字,从那个字往后的前缀缓存全废。
|
||||
|
||||
## 为什么"直接丢弃、不做摘要"
|
||||
|
||||
需求原话。看起来粗暴,但想清楚了:
|
||||
|
||||
· 摘要本身要花一次 LLM 调用(比省下的那点 token 还贵)
|
||||
· 而且摘要会**丢信息且不可追溯** —— 用户翻到三个月前那句话还在界面上,
|
||||
但模型完全不知道,他会以为 AI"忘了"是 bug
|
||||
· 该记住的东西本来就该走 `memory_add` 进记忆系统(那里有检索、有署名、
|
||||
有置顶,是**为长期记忆设计的**)。两套摘要管线只会互相打架。
|
||||
"""
|
||||
import os
|
||||
|
||||
#: 默认窗口(轮)。需求定的 20。
|
||||
DEFAULT_ROUNDS = 20
|
||||
|
||||
#: 默认裁剪批量(轮)。需求定的 5。
|
||||
DEFAULT_BATCH = 5
|
||||
|
||||
#: 窗口上限/下限(用户填什么都不至于把上下文搞爆或搞没)
|
||||
MIN_ROUNDS = 4
|
||||
MAX_ROUNDS = 200
|
||||
|
||||
|
||||
def resolve(settings: dict, agent: dict = None) -> tuple:
|
||||
"""
|
||||
算出这次该用多少:**智能体配置 > 全局设置 > 默认**(返回 `(轮数, 批量)`)。
|
||||
|
||||
★ 和 provider_info / voice_for 一个套路:智能体可以单独配,
|
||||
没配就继承全局。三处规则长得一样,但**不能合并**(数据来源不同)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
settings = settings or {}
|
||||
|
||||
def pick(key, default, lo, hi):
|
||||
for src in (agent.get(key), settings.get(key)):
|
||||
try:
|
||||
v = int(float(src))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if v > 0:
|
||||
return max(lo, min(hi, v))
|
||||
return default
|
||||
|
||||
rounds = pick('contextWindow', DEFAULT_ROUNDS, MIN_ROUNDS, MAX_ROUNDS)
|
||||
batch = pick('contextBatch', DEFAULT_BATCH, 1, 50)
|
||||
return rounds, batch
|
||||
|
||||
|
||||
def split_rounds(messages: list) -> list:
|
||||
"""
|
||||
把消息流切成"轮"。
|
||||
|
||||
★ 一轮 = 从一条 user 到**下一条 user 之前**(含它后面的 assistant 和
|
||||
任何工具痕迹)。不用"user/assistant 配对"来切,是因为:
|
||||
· 工具调用会产生 assistant → tool → assistant 这种多段结构
|
||||
· 界面上用户也可能连发两条
|
||||
按 user 划线对这两种都稳,而且**永远不会切出半轮**(需求要求
|
||||
"按完整轮对齐,不裁半轮")。
|
||||
"""
|
||||
groups = []
|
||||
cur = []
|
||||
for m in messages or []:
|
||||
if not isinstance(m, dict):
|
||||
continue
|
||||
if m.get('role') == 'user' and cur:
|
||||
groups.append(cur)
|
||||
cur = []
|
||||
cur.append(m)
|
||||
if cur:
|
||||
groups.append(cur)
|
||||
return groups
|
||||
|
||||
|
||||
def _indexed_rounds(msgs: list) -> list:
|
||||
"""
|
||||
和 `split_rounds` 一样切轮,但**每条带原始下标** `[(i, msg)]`。
|
||||
|
||||
★ 为什么需要下标:被裁掉的那批里如果有"用户标了重要"的消息,
|
||||
得把它**按原始时间序插回**去 —— 没有下标就只能塞最前面,
|
||||
而那会打乱因果(模型会看到"先发生的事在后面")。
|
||||
"""
|
||||
groups = []
|
||||
cur = []
|
||||
for i, m in enumerate(msgs):
|
||||
if m.get('role') == 'user' and cur:
|
||||
groups.append(cur)
|
||||
cur = []
|
||||
cur.append((i, m))
|
||||
if cur:
|
||||
groups.append(cur)
|
||||
return groups
|
||||
|
||||
|
||||
def trim(messages: list, rounds: int, batch: int = DEFAULT_BATCH) -> dict:
|
||||
"""
|
||||
按窗口裁历史,返回一份**报告**:
|
||||
|
||||
{
|
||||
'messages': 送进模型的那一串(裁过的,或原样),
|
||||
'kept': 保留几条,
|
||||
'dropped': 丢了几条,
|
||||
'reason': '' | 'window' | 'within_batch',
|
||||
'rounds': 总轮数, 'keptRounds': 保留几轮,
|
||||
}
|
||||
|
||||
★ 返回报告而不是只返回列表:调用方要能把这几个数**写给界面**
|
||||
("这次带了 18 轮进来"),也是探针唯一能断言的抓手。
|
||||
"""
|
||||
msgs = [m for m in (messages or []) if isinstance(m, dict)]
|
||||
total = len(msgs)
|
||||
groups = _indexed_rounds(msgs)
|
||||
|
||||
keep_all = {
|
||||
'messages': msgs, 'kept': total, 'dropped': 0, 'reason': '',
|
||||
'rounds': len(groups), 'keptRounds': len(groups),
|
||||
}
|
||||
if rounds <= 0 or len(groups) <= rounds:
|
||||
return keep_all
|
||||
|
||||
extra = len(groups) - rounds
|
||||
# ★ 成批对齐:超出量不到一批就先忍着。
|
||||
# 代价是"实际保留的比窗口多几轮",换来的是**前缀缓存能连续命中**。
|
||||
# 每轮都裁的话前缀每轮都变,缓存一次都命中不了 —— 那比多带几轮贵得多。
|
||||
if extra < batch:
|
||||
out = dict(keep_all)
|
||||
out['reason'] = 'within_batch'
|
||||
out['rounds'] = len(groups)
|
||||
return out
|
||||
|
||||
cut = (extra // batch) * batch
|
||||
kept_idx = [pair for g in groups[cut:] for pair in g]
|
||||
dropped_idx = [pair for g in groups[:cut] for pair in g]
|
||||
|
||||
# ★ 重要标记**破格永久携带**(需求 4.3):从被裁的那批里捞回来
|
||||
important = [pair for pair in dropped_idx if pair[1].get('important')]
|
||||
|
||||
merged = sorted(kept_idx + important, key=lambda p: p[0])
|
||||
out_msgs = [m for _, m in merged]
|
||||
return {
|
||||
'messages': out_msgs,
|
||||
'kept': len(out_msgs),
|
||||
'dropped': total - len(out_msgs),
|
||||
'reason': 'window',
|
||||
'rounds': len(groups),
|
||||
'keptRounds': len(groups) - cut,
|
||||
'rescued': len(important),
|
||||
}
|
||||
|
||||
|
||||
def describe(report: dict) -> str:
|
||||
"""给界面/日志的一行话(不要让它各处自己拼)"""
|
||||
r = report or {}
|
||||
total = r.get('rounds') or 0
|
||||
if not r.get('reason'):
|
||||
return f'{total} 轮全部带上'
|
||||
if r.get('reason') == 'within_batch':
|
||||
return f'{total} 轮(超出窗口但没攒够一批,先不动)'
|
||||
bits = [f'带了最近 {r.get("keptRounds")} 轮(共 {total} 轮)']
|
||||
if r.get('rescued'):
|
||||
bits.append(f'其中 {r["rescued"]} 条是你标了重要的')
|
||||
if r.get('dropped'):
|
||||
bits.append(f'另有 {r["dropped"]} 条较早的没带进来')
|
||||
return ','.join(bits)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 重要标记(需求 4.3:**只有用户能打**)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def is_important(msg: dict) -> bool:
|
||||
return bool((msg or {}).get('important'))
|
||||
|
||||
|
||||
def can_mark(role: str) -> bool:
|
||||
"""
|
||||
谁能打这个标记。**只有界面(用户)** —— AI 没有这个工具(需求原话
|
||||
"AI 有 memory_add,标记是用户主权")。
|
||||
|
||||
★ 这个函数存在的意义是"写下来":将来有人想给 AI 加个 mark_important
|
||||
工具时,会先看到这里写着为什么不行。
|
||||
"""
|
||||
return role == 'user'
|
||||
|
||||
|
||||
def strip_for_model(msg: dict) -> dict:
|
||||
"""
|
||||
把一条消息变成**送进模型的样子**:只留 role / content。
|
||||
|
||||
★★ 顺带就是"字节冻结"的落点:**永远新建一个 dict,绝不原地改** ——
|
||||
原地改(哪怕只是删掉一个 `important` 字段)会让那一条的字节变化,
|
||||
而从它往后的前缀缓存全部失效。需求 4.3 把这条写成"内核纪律"。
|
||||
"""
|
||||
m = msg or {}
|
||||
return {'role': m.get('role'), 'content': m.get('content')}
|
||||
|
||||
|
||||
__all__ = [
|
||||
'DEFAULT_ROUNDS', 'DEFAULT_BATCH', 'MIN_ROUNDS', 'MAX_ROUNDS',
|
||||
'resolve', 'split_rounds', 'trim', 'describe', 'is_important',
|
||||
'can_mark', 'strip_for_model',
|
||||
]
|
||||
@@ -67,8 +67,10 @@ import sys
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
# 单个自定义节点最多跑多久(和会议里的 Python 节点同一套兜底)
|
||||
RUN_TIMEOUT = 10
|
||||
import timeouts
|
||||
|
||||
# ★ 单个自定义节点的超时**不在这里** —— 见 timeouts.py 的 'customNode'
|
||||
# (设置 → 超时 → 自定义节点)。和会议里的 Python 节点是同一套兜底。
|
||||
|
||||
# 引脚类型:exec 是执行引脚,其余是数据引脚
|
||||
PIN_KINDS = ('exec', 'str', 'bool', 'num', 'list')
|
||||
@@ -344,9 +346,10 @@ def run_custom(defn: dict, inputs: dict, variables: dict, node: dict,
|
||||
|
||||
th = threading.Thread(target=work, daemon=True)
|
||||
th.start()
|
||||
th.join(RUN_TIMEOUT)
|
||||
budget = timeouts.get('customNode')
|
||||
th.join(budget)
|
||||
if th.is_alive():
|
||||
return {}, f'超过 {RUN_TIMEOUT} 秒还没跑完(可能有死循环)'
|
||||
return {}, f'超过 {budget:g} 秒还没跑完(可能有死循环,可在设置里调)'
|
||||
return result['outs'], result['err']
|
||||
|
||||
|
||||
|
||||
@@ -15,6 +15,13 @@ DEFAULT_SYSTEM_PROMPT = '\n'.join(
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
'',
|
||||
'关于用户发来的文件(附件):',
|
||||
'6. 附件内容会以 `【文件 名字(大小)本地路径:/绝对/路径】` 的形式给你。',
|
||||
' **那个路径是文件在手机上的真实落盘位置**,可以直接用 shell 或 python 工具打开它 ——',
|
||||
' 不要猜路径,也不要说"我拿不到文件"。',
|
||||
'7. 长文件在对话里只会内联前 20000 个字符,后面会标注"已截断"。',
|
||||
' 需要看全文就按第 6 条给的路径去读,不要凭截断的内容下结论。',
|
||||
]
|
||||
)
|
||||
|
||||
@@ -159,6 +166,29 @@ for _key, _url in PROVIDER_CONSOLE_URLS.items():
|
||||
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
# 记忆注入窗口(条数):每轮最多把多少条记忆放进提示词。
|
||||
#
|
||||
# ★ "记忆无上限"和"每轮全量注入"这两条长期是矛盾的 —— 攒到几百上千条时
|
||||
# 提示词会被记忆撑爆(一千条 × 几十字 ≈ 几万 token),而且**越靠后的
|
||||
# 记忆越贵、反而把最近的对话上下文挤掉**。
|
||||
# 所以给一个窗口:置顶的永远注入,其余取最近的。
|
||||
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
|
||||
# 0 = 不限(退回全量注入)。
|
||||
'memoryWindow': 50,
|
||||
# 背景(立绘 + 背景图)**跟随当前说话者**(v1.2 §6.1,默认开)。
|
||||
#
|
||||
# ★ 群聊里才有区别:关掉时展示区一直用**主智能体**的立绘,
|
||||
# 打开时谁发言就换成谁的 —— 后者能让用户一眼看出"这句是谁说的",
|
||||
# 所以默认开。做成开关是因为**有人就是想要固定的主视觉**。
|
||||
# ★ 单聊时这个开关没有任何效果(说话者永远是同一个人),
|
||||
# 但设置项不隐藏 —— 隐藏的开关比没用的开关更让人困惑。
|
||||
'followSpeaker': True,
|
||||
# 对话上下文窗口(轮,v1.2 §4.3):每轮最多带最近多少轮对话。
|
||||
# 攒够 `contextBatch` 轮才裁一次(摊薄前缀缓存失效),见 context_window。
|
||||
'contextWindow': 20,
|
||||
'contextBatch': 5,
|
||||
# 私聊(幕后对聊)最多几轮,v1.2 §3.9。一轮 = 双方各说一次。
|
||||
'privateChatRounds': 10,
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||
@@ -173,6 +203,12 @@ DEFAULT_SETTINGS = {
|
||||
'toolsDir': '',
|
||||
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
|
||||
'tools': {'python': True, 'mcp': True},
|
||||
# 界面工具:让 AI 主动弹 HTML 界面 / 弹选择框 / 永久结束对话
|
||||
# (show_ui / ask_user / end_conversation)。
|
||||
#
|
||||
# ★ 默认**关**。这三个是"打扰性"能力 —— AI 会主动往用户脸上弹东西、
|
||||
# 甚至把对话封掉,不该装好就默认打开。想用就在「技能」页打开。
|
||||
'uiTools': {'enabled': False},
|
||||
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
||||
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
||||
'speech': {
|
||||
@@ -193,6 +229,13 @@ DEFAULT_SETTINGS = {
|
||||
},
|
||||
# 安全模式:open 全部放行 / restricted 只放 allow 白名单
|
||||
'security': {'mode': 'open', 'allow': []},
|
||||
# 超时。**这里故意是空的** —— 默认值全在 timeouts.py 的 DEFAULT 里,
|
||||
# 只有用户改过的项才会出现在这儿(和默认一样就删掉,见 timeouts.patch)。
|
||||
#
|
||||
# 为什么这么做:以后调整某个默认值时,没动过那一项的用户会跟着新默认走。
|
||||
# 如果把默认值也存进设置文件,老用户会被永久钉在旧的默认上,
|
||||
# 而且"我明明改的是代码里的默认值,怎么没生效"这种问题极难查。
|
||||
'timeouts': {},
|
||||
# Node 版用它指定解释器;Python 内核在进程内执行工具,这个字段只为兼容而保留
|
||||
'pythonBin': '',
|
||||
'nickname': '我',
|
||||
@@ -202,6 +245,114 @@ DEFAULT_SETTINGS = {
|
||||
|
||||
SECRET_KEYS = {'apiKey'}
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 智能体系统(需求 v1.1)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# 内置 Skill:记忆 / 情绪 / 检索 / 用量这几个工具的**使用手册**(需求 3.7)。
|
||||
#
|
||||
# ★ 为什么不把这些写进工具自己的 description:
|
||||
# 工具的 description 只讲"这个工具怎么调",而 Skill 讲的是
|
||||
# "**什么时候该用、用完之后不许干什么**"—— 后者才是模型最容易犯错的地方
|
||||
# (最典型的是"只在嘴上说记住了、根本没调工具")。
|
||||
# 放在 <skills> 段里,每个智能体都能看到;自定义 Skill 按同样的方式追加。
|
||||
BUILTIN_SKILL = '\n'.join([
|
||||
'【记忆】你有自己的记忆库,**跨对话保留**:',
|
||||
'· 用户说了值得长期记住的事(称呼、偏好、重要事实、约定、他的项目),用 memory_add 记下来。',
|
||||
'· 记之前先看上面的记忆清单 —— 已经记过的不要再记一遍,否则清单会越来越乱。',
|
||||
'· 记错了/过时了用 memory_update 改;确实不该留的用 memory_forget 删(只能删你自己写的)。',
|
||||
'· 清单里只有标题,需要正文细节时用 memory_search 检索。',
|
||||
'★★ 绝对不要只在回复里说"我记住了"却不调用 memory_add。',
|
||||
' 说了要记就必须真的调工具;没调就别说这句话 —— 用户会当场发现你在骗他。',
|
||||
'',
|
||||
'【情绪】emotion_set 改的是**你自己**的情绪状态,下次对话还在。',
|
||||
' 情绪要跟着对话内容自然变化;别每轮都改,也别一直用同一个词。',
|
||||
'',
|
||||
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
|
||||
'',
|
||||
# ★★ 群聊的用法(用户反馈「智能体好像不怎么会用」)。
|
||||
#
|
||||
# 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
|
||||
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
|
||||
# 于是对方接到一片空白,两个人永远聊不起来。这段就是纠这个。
|
||||
'【群聊】你可能在一个群里(群里有别人)。',
|
||||
'· 想**主动对某个智能体说一句具体的话**:用 talk_to(agent=他的名字, content=你要说的话)。',
|
||||
' 那句话会真的写进对话,他下一轮看得到、会回应你 —— 这是你和别人**来回聊**的唯一办法。',
|
||||
'· **不要**拿 pass_turn 当"跟他说话":它只交发言权、不带内容,',
|
||||
' 对方接到的是一片空白,只能凭上下文猜(所以那样聊不起来)。',
|
||||
' pass_turn 只在"我没什么可说了,换你"的时候用。',
|
||||
'· 一轮最多一次:talk_to 和 pass_turn 二选一,别两个都调。',
|
||||
'· 单聊里没有"别人",talk_to 会报错 —— 想跟某个人单独聊,让用户去建群或者私聊。',
|
||||
'· 别为了"显得在忙"反复调 talk_to:一轮一次,说人话就行。',
|
||||
])
|
||||
|
||||
# system prompt 的注入模板(需求附录 C,v1.2 修订了段序)。
|
||||
#
|
||||
# ★★ **缓存友好排序**(附录 C 的 v1.2 修订):
|
||||
#
|
||||
# 主流模型的上下文缓存都是**前缀匹配** —— 从第一个 token 开始逐段比对,
|
||||
# 一旦有一处不同,**那之后的所有内容全部失效**(要么重算、要么按未命中计费)。
|
||||
#
|
||||
# 所以段序要按**稳定性**排:最稳的在前、最易变的在最后。
|
||||
#
|
||||
# 稳 → {prompt} 几乎不变(用户很少改人设)
|
||||
# <skills> 很少变
|
||||
# <worldview> 很少变
|
||||
# <memory> 偶尔加几条
|
||||
# ────────────────────────────────────── 上面是长前缀,尽量保持命中
|
||||
# <stats> 数值一变就变
|
||||
# <status> 每轮都可能变(轮数在减)
|
||||
# <emotion> 情绪一变就变
|
||||
# <peer_emotions> 别人的情绪,最不可控
|
||||
# 变 →
|
||||
#
|
||||
# 改之前 emotion 在 memory **前面** —— 情绪一变,后面整段(含最长的 memory)
|
||||
# 缓存全废。挪到最后之后,情绪变化只让最后那两个短段失效。
|
||||
#
|
||||
# 这是这个文件里性价比最高的一处改动:不改任何功能,只改顺序。
|
||||
#
|
||||
# 占位符名字别改 —— agent_context.py 就是按这些名字找段落、空段整段删掉的。
|
||||
DEFAULT_PROMPT_TEMPLATE = '\n'.join([
|
||||
'{prompt}',
|
||||
'',
|
||||
'<skills>',
|
||||
'{skills}',
|
||||
'</skills>',
|
||||
'',
|
||||
'<worldview>',
|
||||
'{worldview}',
|
||||
'</worldview>',
|
||||
'',
|
||||
'<memory>',
|
||||
'{memory}',
|
||||
'</memory>',
|
||||
'',
|
||||
# ---- 以下是易变段,放最后 ----
|
||||
'<stats>',
|
||||
'{stats}',
|
||||
'</stats>',
|
||||
'',
|
||||
'<status>',
|
||||
'{status}',
|
||||
'</status>',
|
||||
'',
|
||||
'<emotion>',
|
||||
'{emotion}',
|
||||
'</emotion>',
|
||||
'',
|
||||
'<peer_emotions>',
|
||||
'{peer_emotions}',
|
||||
'</peer_emotions>',
|
||||
])
|
||||
|
||||
# 记忆注入时的条目模板(附录 C 的 `【标题1】内容1`)。
|
||||
#
|
||||
# ★ 是**全量注入**(标题 + 正文都进去)—— 需求 3.2 的"主动记忆:smartMemory
|
||||
# 全量注入 system prompt"。正文不进的话模型只知道"我记过这件事",
|
||||
# 每次要用都得再检索一次,白花一轮。
|
||||
DEFAULT_MEMORY_LINE = '【{title}】{content}'
|
||||
|
||||
|
||||
# 内置智能体(前端有同名头像,靠 avatar 字段对应)
|
||||
DEFAULT_AGENTS = [
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
接口完全一致,Lynx 前端不用改,只是把 apiBase 指到 http://127.0.0.1:<port>。
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
@@ -17,9 +18,15 @@ import shutil
|
||||
import sys
|
||||
import threading
|
||||
|
||||
# 超时全部收在 timeouts.py 里(用户可在「设置 → 超时」调)。
|
||||
# 它读不到设置时会回落默认值,所以在启动早期 import 也是安全的。
|
||||
import timeouts
|
||||
|
||||
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
||||
BUNDLED_TOOL_FILES = [
|
||||
'_protocol.py',
|
||||
# 界面工具三件套共用的安卓桥 + 上下文读取(被下面三个 import,必须先播种)
|
||||
'_ui_bridge.py',
|
||||
'calc.py',
|
||||
'now.py',
|
||||
'weather.py',
|
||||
@@ -27,6 +34,21 @@ BUNDLED_TOOL_FILES = [
|
||||
'web_fetch.py',
|
||||
'shell.py',
|
||||
'python_run.py',
|
||||
# AI 主动弹界面 / 弹选择框 / 永久结束对话(默认关,见 settings.uiTools)
|
||||
'show_ui.py',
|
||||
'ask_user.py',
|
||||
'end_conversation.py',
|
||||
# AI 主动往当前会话里发一条消息(带防死循环的闸,见 app.py /api/session-message)
|
||||
'send_message.py',
|
||||
# 操作手机:读通知 / 开 App / 调音量
|
||||
'notifications.py',
|
||||
'apps.py',
|
||||
'volume.py',
|
||||
# ★ web_search.py 以前漏在清单外(对拍脚本抓出来的)。
|
||||
# 它其实**照样会被播种**(构建脚本遍历整个 tools/ 目录,
|
||||
# _seed_tools 又用那份源码整体补齐),所以功能上没缺 ——
|
||||
# 但清单是"内置工具一览"的文档,和现实不一致就会误导下一个人。
|
||||
'web_search.py',
|
||||
'_mcp_python_example.py',
|
||||
]
|
||||
|
||||
@@ -135,7 +157,10 @@ SHELL_TOOL_SPEC = {
|
||||
'properties': {
|
||||
'command': {'type': 'string', 'description': '要执行的命令'},
|
||||
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → Termux 命令」那个值',
|
||||
},
|
||||
},
|
||||
'required': ['command'],
|
||||
},
|
||||
@@ -210,7 +235,7 @@ def shell_run(args: dict) -> dict:
|
||||
if not command or _android is None:
|
||||
return fallback_shell(args)
|
||||
|
||||
timeout = max(1, min(300, int(args.get('timeout', 30) or 30)))
|
||||
timeout = timeouts.budget(args, 'termux')
|
||||
hit = _try_termux(command, str(args.get('cwd') or ''), timeout)
|
||||
if hit is not None:
|
||||
return {
|
||||
@@ -257,37 +282,130 @@ def _module_source(name: str):
|
||||
return None
|
||||
|
||||
|
||||
def _src_hash(text: str) -> str:
|
||||
"""源码指纹前 16 位(够用,还短)"""
|
||||
return hashlib.sha256(text.encode('utf-8')).hexdigest()[:16]
|
||||
|
||||
|
||||
def _seed_tools(tools_dir: str) -> int:
|
||||
"""
|
||||
首次运行把内置工具写到手机上的可写目录。
|
||||
之后用户就能自己改、自己加(设置里的"工具目录"指向这里)。
|
||||
把内置工具写到手机上的可写目录。之后用户就能自己改、自己加
|
||||
(设置里的"工具目录"指向这里)。
|
||||
|
||||
源码来源优先级:
|
||||
1) bundled_tool_sources(构建时嵌进来的 base64 源码)—— 安卓上唯一可靠的来源,
|
||||
因为 Chaquopy 只留 .pyc,loader.get_source() 拿不到源码
|
||||
2) 直接从模块读源码 —— 电脑上跑时用这条
|
||||
|
||||
## ★★★ 升级时会重新播种(这是修的一个真 bug)
|
||||
|
||||
以前这里是 `if os.path.exists(dest): continue` —— **只写不存在的文件**。
|
||||
后果:**每一次发版更新的内置工具,在老设备上一律不生效**。
|
||||
|
||||
这个 bug 的表现极具误导性:代码明明改了、APK 明明是新编的、
|
||||
`app.imy` 里也确实有新的 .pyc,但设备上跑的还是几个月前那份 ——
|
||||
因为内核加载的是**落盘的那份旧源码**。
|
||||
实测踩到:v2.0.37 加了 `show_ui` 的 `wait` 参数,设备上报的 spec 里
|
||||
根本没有这个参数,我一度以为是构建没生效。
|
||||
|
||||
## 怎么判断该不该覆盖 —— 这是这一版真正修对的地方
|
||||
|
||||
先看第一版(错的):只看一个本地指纹文件 `.doubao-seed.json`。
|
||||
|
||||
· 指纹对得上 → 我们写的 → 可以覆盖
|
||||
· 对不上 → 用户改过 → 不覆盖
|
||||
|
||||
**但老设备上那个指纹文件是空的**(第一版播种逻辑从来没写过它),
|
||||
于是所有文件都被判成"用户改过",**升级永远不生效**。
|
||||
实测 v2.0.37 给 show_ui 加了 `wait` 参数,真机上死活拿不到 ——
|
||||
12 个没改过的文件"内容相同"跳过,唯一改过的 show_ui 被判成用户改的。
|
||||
|
||||
第二版(现在):加一份**构建时累积的"历史版本哈希登记表"**
|
||||
(`tools/.shipped-hashes.json`,打包时嵌进 `bundled_tool_sources.shipped()`)。
|
||||
判断顺序:
|
||||
|
||||
1. 内容和我们这一版一样 → 什么都不做
|
||||
2. 内容**在历史登记表里** → 是我们以前发的某个版本 → **安全覆盖**
|
||||
3. 内容等于我们本地指纹记的 → 是我们写的 → **安全覆盖**
|
||||
4. 都不是 → 用户改过 → **绝不覆盖**
|
||||
|
||||
第 2 条是关键:它让"老设备上那份我们几个月前发的旧源码"能被认出来。
|
||||
没有它就只能靠"指纹文件",而老设备上那个是空的。
|
||||
"""
|
||||
os.makedirs(tools_dir, exist_ok=True)
|
||||
wanted = {name: _module_source(name[:-3]) for name in BUNDLED_TOOL_FILES}
|
||||
|
||||
shipped: dict = {}
|
||||
try:
|
||||
import bundled_tool_sources # type: ignore[import-not-found]
|
||||
|
||||
for name, source in bundled_tool_sources.sources().items():
|
||||
wanted[name] = source
|
||||
# ★ 历史版本哈希表:靠它认出"盘上这份是我们以前发的"
|
||||
try:
|
||||
shipped = bundled_tool_sources.shipped()
|
||||
except Exception: # noqa: BLE001 - 老版本生成的文件里没有这个函数
|
||||
shipped = {}
|
||||
except Exception: # noqa: BLE001 - 电脑上没有这个生成文件,正常
|
||||
pass
|
||||
|
||||
# 读上次写下的指纹
|
||||
stamp_path = os.path.join(tools_dir, '.doubao-seed.json')
|
||||
seeded: dict = {}
|
||||
try:
|
||||
with open(stamp_path, encoding='utf-8') as fh:
|
||||
loaded = json.load(fh)
|
||||
if isinstance(loaded, dict):
|
||||
seeded = loaded
|
||||
except Exception: # noqa: BLE001 - 没有/坏了都当第一版处理
|
||||
seeded = {}
|
||||
|
||||
copied = 0
|
||||
skipped_user = 0
|
||||
for filename, source in wanted.items():
|
||||
if not source:
|
||||
continue
|
||||
dest = os.path.join(tools_dir, filename)
|
||||
new_hash = _src_hash(source)
|
||||
|
||||
if os.path.exists(dest):
|
||||
continue
|
||||
with open(dest, 'w', encoding='utf-8') as fh:
|
||||
fh.write(source)
|
||||
copied += 1
|
||||
try:
|
||||
with open(dest, encoding='utf-8') as fh:
|
||||
current = fh.read()
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
cur_hash = _src_hash(current)
|
||||
if cur_hash == new_hash:
|
||||
# 已经是这一版了。**顺手把指纹补上** ——
|
||||
# 老设备上指纹是空的,不补的话下次还会走"用户改过"那条。
|
||||
seeded[filename] = cur_hash
|
||||
continue
|
||||
# 是我们以前发的某个版本?→ 可以覆盖
|
||||
ours_history = cur_hash in (shipped.get(filename) or [])
|
||||
ours_stamp = seeded.get(filename) == cur_hash
|
||||
if not ours_history and not ours_stamp:
|
||||
# 用户自己改过 —— 不覆盖。留个日志方便排查
|
||||
skipped_user += 1
|
||||
print(f'[tools] {filename} 被用户改过,保留不覆盖', file=sys.stderr, flush=True)
|
||||
continue
|
||||
# 没改过,且我们的版本变了 → 覆盖
|
||||
try:
|
||||
with open(dest, 'w', encoding='utf-8') as fh:
|
||||
fh.write(source)
|
||||
seeded[filename] = new_hash
|
||||
copied += 1
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[tools] 写 {filename} 失败:{exc}', file=sys.stderr, flush=True)
|
||||
|
||||
if copied or skipped_user:
|
||||
print(f'[tools] 播种:更新 {copied} 个,保留用户改过的 {skipped_user} 个',
|
||||
file=sys.stderr, flush=True)
|
||||
|
||||
try:
|
||||
with open(stamp_path, 'w', encoding='utf-8') as fh:
|
||||
json.dump(seeded, fh, ensure_ascii=False, indent=2)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return copied
|
||||
|
||||
|
||||
|
||||
252
android/kernel/group_chat.py
Normal file
252
android/kernel/group_chat.py
Normal file
@@ -0,0 +1,252 @@
|
||||
"""群聊的发言权仲裁(需求 v1.2 §3.9)。
|
||||
|
||||
## 点名制
|
||||
|
||||
需求原话:
|
||||
|
||||
> **发言权仲裁:点名制**。被 @ 者发言;AI 可通过 `pass_turn` 指定下一位
|
||||
> 发言者,**一轮最多一次移交**;无人被点名时由主智能体(会话发起者)兜底,
|
||||
> **永不冷场**。
|
||||
|
||||
翻译成优先级(从高到低):
|
||||
|
||||
① 用户 @ 的人 用户主权,最高
|
||||
② AI 上一轮 pass_turn 的人 一轮最多一次
|
||||
③ 主智能体(participants[0])兜底,永不冷场
|
||||
|
||||
## 死亡的人不能接
|
||||
|
||||
> 死亡智能体被点名时移交无效,换下一个人接。
|
||||
|
||||
这条单独写出来,是因为"移交无效"有三种可能的处置:
|
||||
报错、随机选一个、回主智能体 —— 需求选了第三种。
|
||||
**回主智能体**也对:它会接着把话头圆下去,用户不会看到"没人应"。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
仲裁是**纯逻辑**(给一群人和几个标记,返回谁说话),没有 IO。
|
||||
放在 `app.py` 的对话循环里就没法逐条测 —— 而它的分支(点名/移交/
|
||||
兜底/死亡/不在场)有五种,正是最该测的那种。
|
||||
"""
|
||||
|
||||
#: 一轮最多移交一次。需求明文,所以做成一个常量而不是散在代码里的布尔。
|
||||
MAX_HANDOFF_PER_ROUND = 1
|
||||
|
||||
import store # noqa: E402 —— 加成员时要查世界观(只读,不参与仲裁)
|
||||
|
||||
|
||||
def member_ids(conv: dict) -> list:
|
||||
"""群聊的成员 id 列表(顺序就是加入顺序,**第 0 个是主智能体**)"""
|
||||
conv = conv or {}
|
||||
ids = conv.get('participants')
|
||||
if not isinstance(ids, list):
|
||||
return []
|
||||
return [str(x) for x in ids if str(x or '').strip()]
|
||||
|
||||
|
||||
def is_group(conv: dict) -> bool:
|
||||
return (conv or {}).get('type') == 'group'
|
||||
|
||||
|
||||
def host_id(conv: dict) -> str:
|
||||
"""
|
||||
⚠️ **不再用于"决定谁发言"** —— 用户明确要求「群聊去掉主人设定」。
|
||||
|
||||
它现在只剩一个用途:`remove_member` 里判断"不能把最后一个人踢走"。
|
||||
决定发言的那条路走 [rotate_next](轮流),不再有"老大"。
|
||||
"""
|
||||
ids = member_ids(conv)
|
||||
return ids[0] if ids else (conv or {}).get('agentId') or ''
|
||||
|
||||
|
||||
def rotate_next(conv: dict, ids: list = None) -> str:
|
||||
"""
|
||||
没人被点名时该谁说 —— **按成员顺序轮**,不设主人。
|
||||
|
||||
★★ 用户原话:「群聊去掉主人设定」。
|
||||
|
||||
原来兜底永远是"会话发起者"(成员列表第一个)——
|
||||
那等于群里有个老大:其他人不 @ 就不开口,@ 了才有台词。
|
||||
现在看**最近一条 AI 消息是谁说的**,下一个人接上,谁都不欠谁。
|
||||
|
||||
★ 找不到上一条(新群、或者老消息没有 agentId)就从第一个开始。
|
||||
"""
|
||||
ids = list(ids if ids is not None else member_ids(conv))
|
||||
if not ids:
|
||||
return ''
|
||||
last = ''
|
||||
for m in reversed((conv or {}).get('messages') or []):
|
||||
if m.get('role') != 'assistant':
|
||||
continue
|
||||
aid = str(m.get('agentId') or '')
|
||||
if aid in ids:
|
||||
last = aid
|
||||
break
|
||||
if not last:
|
||||
return ids[0]
|
||||
return ids[(ids.index(last) + 1) % len(ids)]
|
||||
|
||||
|
||||
def mention_in(text: str, names: list) -> str:
|
||||
"""
|
||||
从用户输入里找出被 @ 的人(返回 id,没有就空串)。
|
||||
|
||||
★ 按**名字**匹配而不是 id:界面上的"成员快捷条"插进去的就是 `@玄辰`
|
||||
(用户看到的是名字)。重名时取**最长的那个**匹配 ——
|
||||
有"玄辰"和"玄辰二号"时,输入 `@玄辰二号` 不该命中"玄辰"。
|
||||
"""
|
||||
t = str(text or '')
|
||||
hit = ''
|
||||
best = ''
|
||||
for aid, name in (names or []):
|
||||
n = str(name or '').strip()
|
||||
if not n or f'@{n}' not in t:
|
||||
continue
|
||||
if len(n) > len(best):
|
||||
best, hit = n, aid
|
||||
return hit
|
||||
|
||||
|
||||
def resolve(conv: dict, want: str = '', passed: str = '',
|
||||
alive: dict = None, handoffs: int = 0, forced: str = '') -> dict:
|
||||
"""
|
||||
决定这一轮谁发言。
|
||||
|
||||
[want] 用户 @ 出来的人(`mention_in` 的结果)
|
||||
[passed] AI 上一轮 `pass_turn` 指定的人
|
||||
[alive] `{agent_id: bool}`,缺省视为活着
|
||||
[handoffs] 这一轮已经移交过几次(用于"一轮最多一次")
|
||||
[forced] 界面点「让他们聊」时**指定**的发言者,优先级最高
|
||||
|
||||
返回 `{'speaker': id, 'reason': 'mention'|'handoff'|'rotate'|'handoff_denied'|'forced', 'note': ''}`。
|
||||
|
||||
★★ 为什么要有 [forced](真机反馈「还是不能互相对话」):
|
||||
下面三条路都要求**用户点名**或者**AI 自己愿意移交**。
|
||||
实测下来 AI 并不总会调 `pass_turn` —— 它更愿意自己把话说完,
|
||||
于是"两个智能体对话"这件事就永远发生不了。
|
||||
用户要的是一个**明确能按下去的入口**:点「让他们聊」,
|
||||
界面就一轮一轮地把发言权在两个人之间递过去,不需要 AI 配合。
|
||||
这是唯一能保证"一定聊得起来"的做法。
|
||||
"""
|
||||
conv = conv or {}
|
||||
alive = alive or {}
|
||||
ids = member_ids(conv)
|
||||
# ★ 兜底**不再是主人**,是轮流(用户要求「群聊去掉主人设定」)
|
||||
nxt = rotate_next(conv, ids)
|
||||
|
||||
def ok(aid: str) -> bool:
|
||||
return bool(aid) and aid in ids and alive.get(aid, True)
|
||||
|
||||
# ① 用户 @ 的人 —— **压过 forced**。
|
||||
#
|
||||
# ★★ 顺序不能反(真机反馈:「@ 的时候立即切换」「对话时没上下文」)。
|
||||
# 现场是这样的:用户点了「让他们聊」,那几轮还在跑;
|
||||
# 这时用户打了一句 `@寐眠 别` —— 界面那一轮仍然带着 `forceSpeaker`
|
||||
# (正轮到小黑),于是**小黑替寐眠答了**。
|
||||
# 用户看到的是"我明明 @ 了他,回答的却是别人",感受上就是"没上下文"。
|
||||
#
|
||||
# 用户的手是最后发言权:他一旦点名,自动对聊必须让位。
|
||||
# (界面那边也会在用户发消息时把自动对聊直接掐掉,这里是第二道。)
|
||||
if want:
|
||||
if ok(want):
|
||||
return {'speaker': want, 'reason': 'mention', 'note': ''}
|
||||
# 被 @ 的人死了或不在场:回主智能体,而不是报错
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': '被点的人不在场或已死亡,换下一个人接'}
|
||||
|
||||
# ② 界面指定的(「让他们聊」)—— 用户没点名时才轮到它
|
||||
#
|
||||
# 它只出现在界面的自动续轮里;用户手打消息时不会带上。
|
||||
if forced:
|
||||
if ok(forced):
|
||||
return {'speaker': forced, 'reason': 'forced', 'note': ''}
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': '指定的人不在场或已死亡,换下一个人接'}
|
||||
|
||||
# ③ AI 的移交(一轮最多一次)
|
||||
if passed:
|
||||
if handoffs >= MAX_HANDOFF_PER_ROUND:
|
||||
return {'speaker': nxt, 'reason': 'handoff_denied',
|
||||
'note': '这一轮已经移交过了,不再移交'}
|
||||
if ok(passed):
|
||||
return {'speaker': passed, 'reason': 'handoff', 'note': ''}
|
||||
# ★ 死亡的人被点名时**移交无效**,换下一个人接(需求明文)
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': f'「{passed}」已死亡或不在场,移交无效,换下一个人接'}
|
||||
|
||||
# ③ 兜底:永不冷场
|
||||
return {'speaker': nxt, 'reason': 'rotate', 'note': ''}
|
||||
|
||||
|
||||
def add_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
加一个成员(用户手动增删基本无条件 —— 用户主权)。
|
||||
|
||||
★ 加完**自动升级成 group**:成员超过一个时 `type` 必须是 `group`,
|
||||
不然成员列表里有人、仲裁逻辑还按单聊跑 ——
|
||||
表现是"我把人拉进来了,但他从来不说话"。
|
||||
这条收在这里而不是让调用方自己补,是因为"忘记补"的代价不对称:
|
||||
补错了只是类型不对,忘补了就是功能整个不生效。
|
||||
|
||||
★ 单聊要拉人 → 那个会话**就地转成群聊**,而不是偷偷往
|
||||
`participants` 里塞一个 id 却把 `type` 留着。
|
||||
|
||||
★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
理由不是洁癖:群聊的上下文里有 `<worldview>` 段,视野不同的两个人
|
||||
看到的是两套设定 —— 同一个群里会出现"这是哪、我们是谁"对不上的情况,
|
||||
而且记忆空间也是按世界观分的(共享记忆会串)。
|
||||
判定以**群主**(`agentId`)的世界观为准;空对空(都没绑)也算同。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
if not aid:
|
||||
return False
|
||||
ids = member_ids(c)
|
||||
if aid in ids:
|
||||
return False
|
||||
|
||||
# ★ 世界观一致才让进
|
||||
target = store.get_agent(aid) or {}
|
||||
if target:
|
||||
mine = (store.get_agent(str(c.get('agentId') or '')) or {}).get('worldviewId') or ''
|
||||
if (target.get('worldviewId') or '') != mine:
|
||||
return False
|
||||
|
||||
ids.append(aid)
|
||||
c['participants'] = ids
|
||||
if len(ids) > 1 and (c.get('type') or 'single') != 'group':
|
||||
c['type'] = 'group'
|
||||
return True
|
||||
|
||||
|
||||
def remove_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
移出一个成员。**主智能体不能被移出**(需求说发言权兜底靠它 ——
|
||||
移掉的话这个群聊就没有兜底了,会冷场)。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
ids = member_ids(c)
|
||||
if aid not in ids or aid == host_id(c):
|
||||
return False
|
||||
ids.remove(aid)
|
||||
c['participants'] = ids
|
||||
return True
|
||||
|
||||
|
||||
def promote(conv: dict, agent_id: str) -> None:
|
||||
"""把单聊转成群聊(拉第二个人进来时用)"""
|
||||
c = conv or {}
|
||||
if c.get('type') != 'group':
|
||||
first = (c.get('agentId') or '').strip()
|
||||
c['type'] = 'group'
|
||||
c['participants'] = [x for x in [first] if x]
|
||||
add_member(c, agent_id)
|
||||
|
||||
|
||||
def describe(conv: dict) -> str:
|
||||
"""给界面/日志的一行话(不要各处自己拼)"""
|
||||
c = conv or {}
|
||||
n = len(member_ids(c))
|
||||
kind = {'group': '群聊', 'private': '私聊记录'}.get(c.get('type') or '', '单聊')
|
||||
return f'{kind}({n} 人)' if n > 1 else kind
|
||||
@@ -29,10 +29,37 @@ import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
PROTOCOL_VERSION = '2024-11-05'
|
||||
CLIENT_INFO = {'name': 'doubao-kernel-py', 'version': '0.1.0'}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 超时
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ★ 这三个超时**不写死在这里** —— 它们在 timeouts.py 里,用户可以在
|
||||
# 「设置 → 超时 → MCP」那一组里调。
|
||||
#
|
||||
# ★ 为什么是函数而不是默认参数值:Python 的默认参数**只在函数定义时求值一次**,
|
||||
# 写成 `def request(self, message, timeout=timeouts.get('mcpRequest'))`
|
||||
# 会把第一次读到的值永久钉住 —— 用户在设置里改完发现没生效,
|
||||
# 而且这种 bug 光看代码看不出来(写法看起来很合理)。
|
||||
# 所以默认值一律写 None,真正取值在这里做。
|
||||
|
||||
def _span_timeout(value, key: str, fallback: float) -> float:
|
||||
if value:
|
||||
return float(value)
|
||||
try:
|
||||
return float(timeouts.get(key))
|
||||
except Exception: # noqa: BLE001 - 设置读不出来也不能让 MCP 用不了
|
||||
return fallback
|
||||
|
||||
|
||||
def _req_timeout(value) -> float:
|
||||
"""单次请求的超时"""
|
||||
return _span_timeout(value, 'mcpRequest', 60.0)
|
||||
|
||||
_clients: dict = {} # serverName -> {'spec','client','tools','error'}
|
||||
_lock = threading.RLock()
|
||||
|
||||
@@ -204,7 +231,8 @@ class _HttpTransport:
|
||||
self.session_id = sid
|
||||
return resp
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
resp = self._post(message, timeout)
|
||||
try:
|
||||
status = getattr(resp, 'status', 200)
|
||||
@@ -575,7 +603,8 @@ class _StdioTransport:
|
||||
self._closed = True
|
||||
self._cv.notify_all()
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
with self._cv:
|
||||
if self._closed:
|
||||
raise McpError('MCP 服务进程已退出')
|
||||
@@ -704,7 +733,8 @@ class _InprocTransport:
|
||||
self._closed = True
|
||||
self._cv.notify_all()
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
req_id = message.get('id')
|
||||
with self._cv:
|
||||
if self._closed:
|
||||
@@ -805,7 +835,8 @@ class McpClient:
|
||||
raise McpError(f'{method} 失败:{detail}')
|
||||
return response.get('result')
|
||||
|
||||
def connect(self, timeout: float = 180) -> 'McpClient':
|
||||
def connect(self, timeout: float = None) -> 'McpClient':
|
||||
timeout = _span_timeout(timeout, 'mcpConnect', 180.0)
|
||||
# initialize 允许失败:inproc 的最小实现可能只认 tools/list、tools/call
|
||||
self._request(
|
||||
'initialize',
|
||||
@@ -818,11 +849,12 @@ class McpClient:
|
||||
tolerate_error=True,
|
||||
)
|
||||
self.transport.notify({'jsonrpc': '2.0', 'method': 'notifications/initialized', 'params': {}})
|
||||
listed = self._request('tools/list', {}, 60) or {}
|
||||
listed = self._request('tools/list', {}, _req_timeout(None)) or {}
|
||||
self.tools = listed.get('tools') or []
|
||||
return self
|
||||
|
||||
def call_tool(self, name: str, arguments: dict, timeout: float = 120) -> dict:
|
||||
def call_tool(self, name: str, arguments: dict, timeout: float = None) -> dict:
|
||||
timeout = _span_timeout(timeout, 'mcpTool', 120.0)
|
||||
result = self._request('tools/call', {'name': name, 'arguments': arguments or {}}, timeout)
|
||||
return result or {}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
@@ -58,7 +59,7 @@ NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while', 'valu
|
||||
# return "结果"
|
||||
#
|
||||
# ctx 提供:
|
||||
# ctx.input 上游传进来的内容(数据线优先,没有就用 exec 上游的输出)
|
||||
# ctx.input 上游**数据线**传进来的内容(exec 线不传数据,永远不)
|
||||
# ctx.vars 变量表(**只读快照**,改它不会影响会议)
|
||||
# ctx.set_var(名, 值) 写变量(会真的写进会议变量表)
|
||||
# ctx.log(内容) 记一条说明,会出现在结果界面的这一步里
|
||||
@@ -74,7 +75,8 @@ NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while', 'valu
|
||||
# 但**必须**做两件事:超时(死循环不能把 App 卡死)和异常兜底
|
||||
# (报错要显示在哪一步,而不是整场会议崩掉)。
|
||||
|
||||
PY_TIMEOUT = 10 # 单个 Python 节点最多跑多少秒
|
||||
# ★ 单个 Python 节点的超时**不在这里** —— 见 timeouts.py 的 'meetingNode'
|
||||
# (设置 → 超时 → 会议节点)。以前写死 10 秒,跑个稍重的计算就会被判死循环。
|
||||
PY_MAX_OUTPUT = 20000 # 输出最多留多少字符
|
||||
|
||||
|
||||
@@ -131,9 +133,10 @@ def run_py_node(code: str, input_text: str, variables: dict,
|
||||
|
||||
th = threading.Thread(target=work, daemon=True)
|
||||
th.start()
|
||||
th.join(PY_TIMEOUT)
|
||||
budget = timeouts.get('meetingNode')
|
||||
th.join(budget)
|
||||
if th.is_alive():
|
||||
return (result['out'] or '')[:PY_MAX_OUTPUT], f'超过 {PY_TIMEOUT} 秒还没跑完(可能有死循环)'
|
||||
return (result['out'] or '')[:PY_MAX_OUTPUT], f'超过 {budget:g} 秒还没跑完(可能有死循环,可在设置里调)'
|
||||
|
||||
for k, v in writes.items():
|
||||
variables[k] = v
|
||||
@@ -158,6 +161,10 @@ CAST_KINDS = (
|
||||
('str', '转成文本'),
|
||||
('bool', '转成真假'),
|
||||
('num', '转成数字'),
|
||||
# ★ 补上 list:`_cast_to()` 一直允许 list(它按 PIN_TYPES 校验),
|
||||
# 界面上的转换节点也一直能选 list —— 只有这份清单少写了一项。
|
||||
# (对拍脚本 scripts/verify-nodekit.py 抓出来的)
|
||||
('list', '转成列表'),
|
||||
)
|
||||
|
||||
# (键, 名字, 输入类型, 输出类型, 要几个输入)
|
||||
@@ -211,8 +218,12 @@ OPS = (
|
||||
('div', '除 ÷', 'num', 'num', 2),
|
||||
('mod', '取余 %', 'num', 'num', 2),
|
||||
('concat', '拼接', 'str', 'str', 2),
|
||||
('eq', '等于 =', 'str', 'bool', 2),
|
||||
('ne', '不等于 ≠', 'str', 'bool', 2),
|
||||
('eq', '等于 =(数字)', 'num', 'bool', 2),
|
||||
('ne', '不等于 ≠(数字)', 'num', 'bool', 2),
|
||||
# ★ 文本相等单独一份:数字相等和文本相等**不是一回事** ——
|
||||
# "01" 和 "1" 作为文本不等,作为数字相等;拼写比较也不能先转成数字。
|
||||
('streq', '文本等于 ==', 'str', 'bool', 2),
|
||||
('strne', '文本不等于 !=', 'str', 'bool', 2),
|
||||
('gt', '大于 >', 'num', 'bool', 2),
|
||||
('lt', '小于 <', 'num', 'bool', 2),
|
||||
('gte', '大于等于 ≥', 'num', 'bool', 2),
|
||||
@@ -343,8 +354,17 @@ def apply_op(op_key: str, a, b=None):
|
||||
|
||||
if op_key == 'concat':
|
||||
return str(a) + str(b), ''
|
||||
if op_key in ('eq', 'ne'):
|
||||
# 文本相等:直接比字符串,不经过 as_num。
|
||||
# 两者不能混:01 和 1 作为文本不等、作为数字相等。
|
||||
if op_key in ('streq', 'strne'):
|
||||
same = str(a) == str(b)
|
||||
return cast_value(same if op_key == 'streq' else not same, 'bool'), ''
|
||||
if op_key in ('eq', 'ne'):
|
||||
x1, e3 = as_num(a)
|
||||
y1, e4 = as_num(b)
|
||||
if e3 or e4:
|
||||
return 'false', (e3 or e4)
|
||||
same = (x1 == y1)
|
||||
return cast_value(same if op_key == 'eq' else not same, 'bool'), ''
|
||||
|
||||
x, e1 = as_num(a)
|
||||
@@ -803,8 +823,10 @@ def _sanitize_nodes(nodes: list) -> list:
|
||||
NODE_DATA_IN = {
|
||||
'agent': ('str',),
|
||||
'judge': ('str',),
|
||||
# 写变量是汇:什么都能存(存进去的都是文本,读的时候按变量类型解释)
|
||||
'var': ('str', 'bool', 'num'),
|
||||
# 写变量是汇:什么都能存(存进去的都是文本,读的时候按变量类型解释)。
|
||||
# ★ 必须含 list —— 之前漏了,列表变量根本写不进去
|
||||
# (加 list 类型时没同步这张表,用户报"写变量的输入也没改")。
|
||||
'var': ('str', 'bool', 'num', 'list'),
|
||||
'while': ('bool',),
|
||||
# 最终输出只是展示,什么类型都能接(展示方式按类型不同)
|
||||
# Python 节点:上游给什么都要能收(它就是拿来处理任意内容的)
|
||||
@@ -812,13 +834,16 @@ NODE_DATA_IN = {
|
||||
# 自定义节点:真正收什么由它声明的引脚决定(见 _data_in_type),
|
||||
# 这里给宽松值,免得还没加载到定义时就把线丢了
|
||||
'custom': ('str', 'bool', 'num', 'list'),
|
||||
# 分支节点:只收一个真假
|
||||
'branch': ('bool', 'str'),
|
||||
# 分支节点:条件收得宽一点(变量/上游多半给的是 true / 1 这类文本)。
|
||||
# ★ num 也要收 —— 界面那边允许,引擎这边不收的话线会被丢掉。
|
||||
'branch': ('bool', 'str', 'num'),
|
||||
'end': ('str', 'bool', 'num', 'list'),
|
||||
# 转换:什么都收,出口由 castTo 决定
|
||||
'cast': ('str', 'bool', 'num'),
|
||||
# 运算:入口类型由运算本身决定(见 _data_in_type)
|
||||
'op': ('str', 'bool', 'num'),
|
||||
# 转换:什么都收,出口由 castTo 决定。
|
||||
# ★ 含 list —— 不然"把列表转成文本"这种最基本的转换做不了。
|
||||
'cast': ('str', 'bool', 'num', 'list'),
|
||||
# 运算:入口类型由运算本身决定(见 _data_in_type)。
|
||||
# 这里给宽松值当兜底:
|
||||
'op': ('str', 'bool', 'num', 'list'),
|
||||
}
|
||||
|
||||
NODE_DATA_OUT = {
|
||||
@@ -867,12 +892,20 @@ def _data_in_type(node_id: str):
|
||||
node = _LAST_BY_ID.get(node_id)
|
||||
if not node:
|
||||
return None
|
||||
# ★ 自定义节点:按声明的 input 引脚类型。
|
||||
#
|
||||
# 这里是"这个节点收哪些类型"的**并集** —— 引擎的类型检查是按**节点**做的
|
||||
# (一条边上没有"接到哪个引脚"的信息),所以多入口只能放宽成并集。
|
||||
# 界面那一侧知道用户在拖哪根线,做的是**按引脚**的精确校验,
|
||||
# 所以严格程度并不会丢:接错了当场就连不上。
|
||||
if node['type'] == 'var':
|
||||
vname = str(node.get('varName') or '').strip()
|
||||
vt = _LAST_VAR_TYPE.get(vname)
|
||||
# ★ 列表变量:入口是 str(要追加的那一项文本),**不是 list**。
|
||||
#
|
||||
# 写变量对列表的动作是"追加一项",不是整体替换 ——
|
||||
# 要求整个列表的话,用户得先拼一个 JSON 数组才能加一项,太别扭。
|
||||
#
|
||||
# ★★ 这条规则必须和界面 inputPins 里那条**一模一样**。
|
||||
# 我只改了界面没改引擎,结果界面上连得上、一保存就被丢掉,
|
||||
# 用户看到的还是"连不上"。改这种规则要两边一起改。
|
||||
if vt == 'list':
|
||||
return ('str',)
|
||||
return (vt,) if vt in PIN_TYPES else ('str',)
|
||||
if node['type'] == 'custom':
|
||||
d = _LAST_CUSTOM.get(str(node.get('customKey') or ''))
|
||||
if d:
|
||||
@@ -884,15 +917,6 @@ def _data_in_type(node_id: str):
|
||||
if node['type'] == 'op':
|
||||
spec = _OPS_BY_KEY.get(str(node.get('op') or 'add'))
|
||||
return (spec[2],) if spec else ('num',)
|
||||
# ★ 写变量是**汇**:什么类型都能存。
|
||||
#
|
||||
# 这里原来按**变量登记表**卡类型(变量声明成 num 就只收 num)。
|
||||
# 后果:智能体输出的是 str → 类型不符 → 引擎保存时把数据线丢掉。
|
||||
# 界面上明明连上了,一保存就没了 —— 用户的原话是"是链接不了",
|
||||
# 而且完全不知道为什么(界面上连的那一下是成功的)。
|
||||
#
|
||||
# 变量的类型只该决定**读出去**能接到哪(readvar 的出口类型),
|
||||
# 不该限制**存进来**的东西:存进去的都是文本,读的时候再按类型解释。
|
||||
return NODE_DATA_IN.get(node['type'])
|
||||
def _data_out_type(node_id: str):
|
||||
"""
|
||||
@@ -1006,7 +1030,16 @@ def _sanitize_edges(edges: list, nodes: list) -> list:
|
||||
if want is None or give is None or give not in want:
|
||||
continue
|
||||
|
||||
out.append({'from': src, 'to': dst, 'branch': str(e.get('branch') or ''), 'kind': kind})
|
||||
# ★ 引脚信息要**原样留着**:一个节点有两个同类型入口(运算的 A/B)时,
|
||||
# 光靠 from/to 分不清线接的是哪个 —— 表现就是"两条线都落在 A 上,
|
||||
# B 永远收不到"。老的边没这个字段,留空时按顺序兜底。
|
||||
out.append({
|
||||
'from': src, 'to': dst,
|
||||
'branch': str(e.get('branch') or ''),
|
||||
'kind': kind,
|
||||
'toPin': str(e.get('toPin') or ''),
|
||||
'fromPin': str(e.get('fromPin') or ''),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
@@ -1036,8 +1069,14 @@ def _outgoing(edges: list, node_id: str) -> list:
|
||||
# - 读变量这种"纯节点"(Get)**没有 exec 引脚**,它的值是被需要的人
|
||||
# **拉取**的,自己不在执行链上 —— 这正是"读变量只有输出"的真正原因。
|
||||
#
|
||||
# 兼容:老会议里没有 kind 字段的边,当成 exec 处理,并且"没有数据入边时
|
||||
# 就用 exec 上游的输出"当输入 —— 这样以前那种"一根线连到底"的图行为不变。
|
||||
# ★★ exec **不传数据** —— 这是**写死**的规则,没有例外、没有兼容回退。
|
||||
#
|
||||
# 一开始为了迁就"一根线连到底"的老图,做过"没有数据入边时就用 exec 上游的
|
||||
# 输出"的回退。那是错的:它让 exec 线看起来能传值,于是**整张图的类型就不
|
||||
# 再有意义** —— 用户没法从图上判断一个值到底从哪来,界面画的颜色和形状
|
||||
# 也都在骗人。宁可让空值显式地空着(节点上会报原因),也不要猜。
|
||||
#
|
||||
# 兼容:老会议里没有 kind 字段的边,当成 exec 处理。
|
||||
|
||||
EXEC = 'exec'
|
||||
DATA = 'data'
|
||||
@@ -1560,24 +1599,16 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
value = (node.get('varValue') or '').strip()
|
||||
note = ''
|
||||
if not value:
|
||||
# ★★ exec **绝不传数据** —— 这条是**写死**的,没有例外。
|
||||
#
|
||||
# 这里以前有个"没连数据线就用 exec 上游的输出"的回退。
|
||||
# 那是错的,而且错得很危险:它让"exec 线"看起来能传值,
|
||||
# 于是整个类型系统就不可信了 —— 用户没法从图上判断
|
||||
# 一个值到底从哪来。蓝图里 exec 就是**只排顺序**。
|
||||
#
|
||||
# 没连数据线就是**空**,节点上会明确报出来
|
||||
# (见下面 _exec_in 那段 warn 的逻辑)。
|
||||
value = incoming
|
||||
# ★ **没连数据线时,退一步用 exec 上游的输出。**
|
||||
#
|
||||
# "exec 不传递数据"这条规则是对的,但对**写变量**太苛刻:
|
||||
# 用户的心智模型就是"这根线连过来了,所以把刚才产生的东西存进去"。
|
||||
# 逼他们必须再拉一根数据线,结果就是反复踩同一个坑
|
||||
# (这个问题被反馈了三次)。
|
||||
#
|
||||
# 所以做一个**有交代的例外**:没数据线就用 exec 上游的输出,
|
||||
# 并且在节点上明确写出来"用了上游的输出" ——
|
||||
# 不是悄悄猜,用户一眼能看到引擎替他做了什么。
|
||||
if not _data_in(edges, node_id):
|
||||
ups = [outputs.get(e.get('from'))
|
||||
for e in _exec_in(edges, node_id)]
|
||||
ups = [t for t in ups if t]
|
||||
if ups:
|
||||
value = ups[-1]
|
||||
note = '(没连数据线,用了 exec 上游的输出)'
|
||||
# ★ **按变量类型决定动作**。
|
||||
#
|
||||
# 列表 → 默认**追加**:列表的用处就是攒东西,"写变量"这个动作
|
||||
@@ -1657,17 +1688,9 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
continue
|
||||
ins[pin['name']] = _collect_pin_input(
|
||||
node_id, edges, pin, d, outputs, variables, by_id)
|
||||
# 没连任何入口时,退一步用 exec 上游的输出喂给**第一个**入口 ——
|
||||
# 和写变量、最终输出一个道理:用户的心智是"线连过来了",
|
||||
# 逼他必须再拉一根数据线只会让他看到空值还不知道为什么。
|
||||
if not any(str(v).strip() for v in ins.values()):
|
||||
data_pins = [p for p in (d.get('inputs') or []) if p['type'] != 'exec']
|
||||
if data_pins and not _data_in(edges, node_id):
|
||||
ups = [outputs.get(e.get('from'))
|
||||
for e in _exec_in(edges, node_id)]
|
||||
ups = [t for t in ups if t]
|
||||
if ups:
|
||||
ins[data_pins[0]['name']] = ups[-1]
|
||||
# ★ exec 不传数据(写死的规则,没有例外)——
|
||||
# 这里以前也有个"没连入口就用 exec 上游的输出"的回退,已删。
|
||||
# 自定义节点的入口收不到值就是空的,节点上会报出来。
|
||||
logs = []
|
||||
outs, err = _cn.run_custom(d, ins, variables, node, logs)
|
||||
if err:
|
||||
@@ -1797,16 +1820,11 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
# 展示方式不同。所以每个 end 节点都把自己那份结果和类型记下来。
|
||||
value = (node.get('text') or '').strip()
|
||||
if not value:
|
||||
# ★ exec 不传数据(写死的规则,没有例外)——
|
||||
# 只连了 exec 线时这里就是空的。以前有个"用 exec 上游
|
||||
# 输出"的回退,已删:它让 exec 看起来能传值,
|
||||
# 整张图的类型就不再有意义了。
|
||||
value = incoming
|
||||
# 和"写变量"同样的道理:只连了 exec 线时,用上游的输出。
|
||||
# 用户的心智模型是"这根线连过来了,所以把刚才产生的东西显示出来",
|
||||
# 逼他必须再拉一根数据线,只会让他看到一片空白还不知道为什么。
|
||||
if not _data_in(edges, node_id):
|
||||
ups = [outputs.get(e.get('from'))
|
||||
for e in _exec_in(edges, node_id)]
|
||||
ups = [t for t in ups if t]
|
||||
if ups:
|
||||
value = ups[-1]
|
||||
outputs[node_id] = value
|
||||
# 类型:**优先看来源节点的实际出口类型**,不要信边上的 kind。
|
||||
#
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
运行期路径与平台判断。
|
||||
|
||||
为什么单独一个模块:
|
||||
@@ -70,10 +70,41 @@ class Paths:
|
||||
# 数据目录下的固定文件(文件名与 Node 版保持一致,方便两边互相读)
|
||||
self.uploads_dir = os.path.join(self.data_dir, 'uploads')
|
||||
self.tmp_dir = os.path.join(self.data_dir, 'tmp')
|
||||
# ★ AI 弹出来的那些 HTML 界面存这儿 —— 用户关掉之后还要能再打开
|
||||
# (用户明确要求:"AI 写的界面可以再点开")
|
||||
self.screens_dir = os.path.join(self.data_dir, 'screens')
|
||||
# ★ notes 工具的笔记存这儿("notes 用户要能查看")。
|
||||
#
|
||||
# 以前 notes.py 自己算路径:`工具文件/../data/notes` ——
|
||||
# 在安卓上会落到 **App 的外部私有目录**
|
||||
# (`/storage/emulated/0/Android/data/<包名>/files/data/notes`)。
|
||||
# 那个地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏),
|
||||
# 而且**卸载 App 就一起删了**。
|
||||
# 放到 data_dir 下和别的数据一起,持久、位置统一、也能通过接口读出来给界面看。
|
||||
self.notes_dir = os.path.join(self.data_dir, 'notes')
|
||||
self.settings_file = os.path.join(self.data_dir, 'settings.json')
|
||||
self.conversations_file = os.path.join(self.data_dir, 'conversations.json')
|
||||
self.agents_file = os.path.join(self.data_dir, 'agents.json')
|
||||
self.mcp_file = os.path.join(self.data_dir, 'mcp.servers.json')
|
||||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||||
#
|
||||
# ★ 和 agents.json 一样是 JSON、一人一个文件:它们的量级也是"几个到几十个",
|
||||
# 而且要人肉可读(用户会想直接看自己建的世界观写成什么样)。
|
||||
# 会**持续增长**的那些(记忆 / 情绪 / Token 统计)在 agent.db 里,
|
||||
# 分界线见 agentdb.py 的文件头。
|
||||
self.worldviews_file = os.path.join(self.data_dir, 'worldviews.json')
|
||||
self.models_file = os.path.join(self.data_dir, 'models.json')
|
||||
self.skills_file = os.path.join(self.data_dir, 'skills.json')
|
||||
# 数值状态包(需求附录 D):定义 + 对应的 Python 脚本源码。
|
||||
# 量级小、而且用户会想看自己写了什么 → 还是 JSON
|
||||
self.rulepacks_file = os.path.join(self.data_dir, 'rulepacks.json')
|
||||
# 规则脚本**落盘**的位置:脚本要作为文件被 exec 起来,
|
||||
# 所以从包里解出来之后得写到磁盘上(不能只存在 JSON 里)
|
||||
self.rule_scripts_dir = os.path.join(self.data_dir, 'rule-scripts')
|
||||
# 智能体系统的 SQLite(记忆 / 情绪 / Token / 绑定关系)
|
||||
self.agent_db_file = os.path.join(self.data_dir, 'agent.db')
|
||||
# 智能体包解出来的图片等资源(导入 zip 时落到这儿)
|
||||
self.agent_assets_dir = os.path.join(self.data_dir, 'agent-assets')
|
||||
|
||||
@staticmethod
|
||||
def _resolve_web_core(explicit: str | None) -> str:
|
||||
@@ -90,7 +121,8 @@ class Paths:
|
||||
return os.path.abspath(candidates[-1])
|
||||
|
||||
def ensure_dirs(self) -> None:
|
||||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir):
|
||||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir,
|
||||
self.notes_dir, self.agent_assets_dir, self.rule_scripts_dir):
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||||
|
||||
249
android/kernel/private_chat.py
Normal file
249
android/kernel/private_chat.py
Normal file
@@ -0,0 +1,249 @@
|
||||
"""私聊:两个智能体在后台自主对聊(需求 v1.2 §3.9 形态 B)。
|
||||
|
||||
## 需求原文
|
||||
|
||||
> **形态 B · 私聊(幕后制)**:两个智能体在后台自主对聊,用户不在场。
|
||||
>
|
||||
> - **安全网**:默认最多 10 轮交替发言(可配),到顶强制收尾;
|
||||
> 一方 Token 触顶则另一方单方面收尾后立即结束,**不撑独角戏**。
|
||||
> - 结束后生成摘要写入共享记忆(复用总结管线),完整记录可翻看。
|
||||
> - Token 消耗按各自发言分别计入各智能体统计、分别受各自限额约束。
|
||||
|
||||
## 三个必须想清楚的点
|
||||
|
||||
**① "安全网"防的是什么**
|
||||
|
||||
两个 AI 互相对话最大的风险是**停不下来**:A 说一句、B 接一句、A 再
|
||||
接回来……它们没有"该结束了"的内在信号(用户不在场,没人喊停)。
|
||||
所以轮数上限不是优化,是**防失控**。
|
||||
|
||||
**② "不撑独角戏"**
|
||||
|
||||
一方 Token 触顶时,**不能**让另一方继续自言自语。
|
||||
需求的做法是:另一方**单方面收尾**(说一句告别/结语)然后立刻结束。
|
||||
独白读起来很怪,而且白花钱。
|
||||
|
||||
**③ 每轮的"用户"是谁**
|
||||
|
||||
对 A 来说,B 说的话就是**用户消息**;对 B 来说反过来。
|
||||
这是私聊能跑起来的关键 —— 两个 AI 都在"跟对方聊天",
|
||||
而不是"在同一个上下文里各写各的"。
|
||||
"""
|
||||
|
||||
import agent_loop
|
||||
import agentdb
|
||||
import store
|
||||
|
||||
#: 默认最多几轮(**一轮 = A 说一次 + B 说一次**)。需求定的 10。
|
||||
DEFAULT_MAX_ROUNDS = 10
|
||||
|
||||
#: 上限的硬顶:用户可以在设置里调,但不该调到能刷爆账单的规模。
|
||||
#: 一轮两次 LLM 调用,100 轮就是 200 次 —— 那不是"聊天",是失控。
|
||||
MAX_ROUNDS_CAP = 60
|
||||
|
||||
|
||||
def resolve_rounds(settings: dict, body: dict = None) -> int:
|
||||
"""
|
||||
这次私聊最多几轮:**调用方指定 > 全局设置 > 默认**,并且夹在硬顶内。
|
||||
|
||||
★ 需求说"默认最多 10 轮(**可配**)"—— 可配的入口是
|
||||
`settings.privateChatRounds`,不是每次调用随便传(那样界面就没法
|
||||
给用户一个稳定的默认值了)。[body] 只给"这一次特殊"用。
|
||||
"""
|
||||
for src in ((body or {}).get('maxRounds'), (settings or {}).get('privateChatRounds')):
|
||||
try:
|
||||
v = int(float(src))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if v > 0:
|
||||
return max(1, min(MAX_ROUNDS_CAP, v))
|
||||
return DEFAULT_MAX_ROUNDS
|
||||
|
||||
|
||||
def _used(agent: dict) -> int:
|
||||
u = agentdb.token_usage((agent or {}).get('id') or '')
|
||||
return int(u['total']['input']) + int(u['total']['output'])
|
||||
|
||||
|
||||
def limit_hit(agent: dict) -> bool:
|
||||
"""
|
||||
这个智能体的额度用完了吗(0 = 无限制)。
|
||||
|
||||
★ 和 `/api/chat` 那道检查**同一个判据**:用掉的总量 >= 上限。
|
||||
两处不一致的话,会出现"私聊里还能说、回到对话里被拦"这种精神分裂。
|
||||
"""
|
||||
agent = agent or {}
|
||||
try:
|
||||
limit = int(float(agent.get('tokenLimit') or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
return limit > 0 and _used(agent) >= limit
|
||||
|
||||
|
||||
def _history_for(speaker_id: str, turns: list) -> list:
|
||||
"""
|
||||
把"到目前为止的对话"翻译成**这个说话者视角**的消息列表。
|
||||
|
||||
对方说的 → `user`(它在跟我说话)
|
||||
我说的 → `assistant`(我说的)
|
||||
|
||||
★ 这是私聊能跑起来的关键:两个 AI 各自都是"在跟对方聊天",
|
||||
而不是"在同一个上下文里各写各的"。
|
||||
"""
|
||||
out = []
|
||||
for t in turns:
|
||||
if not t.get('content'):
|
||||
continue
|
||||
mine = t.get('agentId') == speaker_id
|
||||
out.append({'role': 'assistant' if mine else 'user', 'content': t['content']})
|
||||
return out
|
||||
|
||||
|
||||
def run_pair(settings: dict, first: dict, second: dict, max_rounds: int = 0,
|
||||
opener: str = '', emit=None) -> dict:
|
||||
"""
|
||||
让两个智能体在后台对聊。
|
||||
|
||||
[first] 先开口的那个(也是这个会话的"主")
|
||||
[opener] 给先开口者的由头(比如"用户把你俩拉到了一起")。
|
||||
|
||||
返回:
|
||||
{
|
||||
'ok': True,
|
||||
'conversationId': ...,
|
||||
'turns': [{'agentId','name','content'}],
|
||||
'rounds': 实际说了几轮,
|
||||
'endReason': 'rounds' | 'limit' | 'error',
|
||||
'endedBy': 谁触顶了(endReason=limit 时),
|
||||
'summary': 摘要(有的话),
|
||||
}
|
||||
"""
|
||||
settings = settings or {}
|
||||
first, second = first or {}, second or {}
|
||||
if not (first.get('id') and second.get('id')):
|
||||
return {'ok': False, 'error': '需要两个智能体'}
|
||||
rounds_cap = max_rounds or resolve_rounds(settings)
|
||||
say = emit or (lambda ev: None)
|
||||
|
||||
conv = store.create_conversation(
|
||||
title=f'{(first.get("name") or "?")} 与 {(second.get("name") or "?")} 的私聊',
|
||||
agent_id=first.get('id') or '',
|
||||
# ★ `private` 是独立类型:它出现在**两个参与者的**会话列表里,
|
||||
# 而界面上只读翻看(用户不在场,不该能插话)
|
||||
kind='private',
|
||||
participants=[first.get('id') or '', second.get('id') or ''],
|
||||
)
|
||||
cid = conv['id']
|
||||
turns = []
|
||||
end_reason = 'rounds'
|
||||
ended_by = ''
|
||||
|
||||
def _record(speaker: dict, text: str) -> None:
|
||||
turns.append({'agentId': speaker.get('id') or '',
|
||||
'name': speaker.get('name') or '', 'content': text})
|
||||
store.append_messages(cid, [{
|
||||
'role': 'assistant',
|
||||
'content': text,
|
||||
'agentId': speaker.get('id') or '',
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
|
||||
for i in range(rounds_cap):
|
||||
for who in (first, second):
|
||||
if limit_hit(who):
|
||||
# ★★ 一方触顶 → 另一方**单方面收尾**后立即结束(需求明文)。
|
||||
# 不收尾直接断的话,对话会停在一句没头没尾的话上;
|
||||
# 让另一个人继续说的话,就成了"独角戏"(需求明确说不要)。
|
||||
other = second if who.get('id') == first.get('id') else first
|
||||
if not limit_hit(other):
|
||||
try:
|
||||
_closing = _speak(settings, other, turns, cid, rounds_cap, i,
|
||||
hint='对方的额度用完了,这次对话到此为止 —— '
|
||||
'你说一句收尾的话,不要再问问题。')
|
||||
if _closing:
|
||||
_record(other, _closing)
|
||||
except Exception as exc: # noqa: BLE001 - 收尾失败也要结束
|
||||
say({'type': 'private_error', 'message': str(exc)})
|
||||
end_reason, ended_by = 'limit', who.get('name') or ''
|
||||
break
|
||||
if not turns and who.get('id') == first.get('id'):
|
||||
# 给先开口者一个由头(不然它不知道"跟谁、为什么")
|
||||
turns_seed = opener or f'你和「{second.get("name") or "对方"}」被单独留在了一间屋子里。'
|
||||
else:
|
||||
turns_seed = ''
|
||||
try:
|
||||
text = _speak(settings, who, turns, cid, rounds_cap, i, hint=turns_seed)
|
||||
except Exception as exc: # noqa: BLE001 - 一次生成失败不该让整场私聊崩
|
||||
say({'type': 'private_error', 'message': str(exc)})
|
||||
end_reason = 'error'
|
||||
break
|
||||
if not text:
|
||||
# 模型返回空 —— 当作"它不想说了",正常收尾而不是报错
|
||||
end_reason = 'rounds'
|
||||
break
|
||||
_record(who, text)
|
||||
say({'type': 'private_turn', 'agentId': who.get('id') or '',
|
||||
'name': who.get('name') or '', 'content': text})
|
||||
if end_reason in ('limit', 'error'):
|
||||
break
|
||||
|
||||
out = {
|
||||
'ok': True, 'conversationId': cid, 'turns': turns,
|
||||
'rounds': len(turns), 'endReason': end_reason, 'endedBy': ended_by,
|
||||
}
|
||||
# ★ 结束后生成摘要写入共享记忆(需求:复用总结管线)
|
||||
try:
|
||||
summary = summarize_to_memory(first, second, turns)
|
||||
if summary:
|
||||
out['summary'] = summary
|
||||
except Exception as exc: # noqa: BLE001 - 摘要失败不影响"私聊已经结束"这件事
|
||||
say({'type': 'private_error', 'message': f'摘要失败:{exc}'})
|
||||
store.update_conversation(cid, {'title': conv['title']})
|
||||
return out
|
||||
|
||||
|
||||
def _speak(settings: dict, speaker: dict, turns: list, cid: str,
|
||||
cap: int, round_index: int, hint: str = '') -> str:
|
||||
"""让一个智能体说一句。返回正文(空串 = 它没说话)"""
|
||||
history = _history_for(speaker.get('id') or '', turns)
|
||||
if hint:
|
||||
history = history + [{'role': 'user', 'content': hint}]
|
||||
if not history:
|
||||
history = [{'role': 'user', 'content': '开始吧。'}]
|
||||
result = agent_loop.run_agent(
|
||||
settings=settings,
|
||||
messages=history,
|
||||
agent=speaker,
|
||||
emit=lambda ev: None,
|
||||
conversation_id=cid,
|
||||
# ★ 私聊是**幕后**行为,不能再往里递归拉起别的对话 ——
|
||||
# 加一层深度限制,免得 A 拉 B、B 拉 C 无限套下去
|
||||
send_depth=1,
|
||||
)
|
||||
return str((result or {}).get('content') or '').strip()
|
||||
|
||||
|
||||
def summarize_to_memory(first: dict, second: dict, turns: list) -> str:
|
||||
"""
|
||||
把这场私聊的摘要写进**共享记忆**(需求:复用总结管线)。
|
||||
|
||||
★ 写到哪:两人的**共享空间**(同世界观 → `world:<id>`),
|
||||
这样以后两人聊天时都"记得"这次私聊发生过。
|
||||
没有共同世界观的话**不写** —— 硬塞进某一个人的私有空间,
|
||||
等于替他记了一件他没参与的事。
|
||||
"""
|
||||
if not turns:
|
||||
return ''
|
||||
a, b = first or {}, second or {}
|
||||
wid = (a.get('worldviewId') or '').strip()
|
||||
if not wid or wid != (b.get('worldviewId') or '').strip():
|
||||
return ''
|
||||
body = '\n'.join(f'{(t.get("name") or "?")}:{t.get("content") or ""}' for t in turns)
|
||||
# 摘要是**规则化**的,不再花一次 LLM 调用 —— 私聊本身已经烧了
|
||||
# 2×N 次调用了,为了压两句话再烧一次不划算(需求说的"复用总结管线"
|
||||
# 指的是同一套**写入记忆**的通道,不是非要再调一次模型)
|
||||
title = f'和{(b.get("name") or "对方")}的一次私下交谈'
|
||||
content = f'({len(turns)} 句)' + body[:400]
|
||||
return agentdb.memory_add(
|
||||
agentdb.world_scope(wid), title, content, author_agent=a.get('id') or '',
|
||||
) and title
|
||||
@@ -20,11 +20,20 @@ import urllib.request
|
||||
from typing import Callable, Iterator, Optional
|
||||
|
||||
from defaults import PROVIDER_PRESETS
|
||||
import timeouts
|
||||
|
||||
# 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数
|
||||
REASONING_MODEL_RE = re.compile(r'^(o1|o3|o4|gpt-5|gpt-6)', re.IGNORECASE)
|
||||
|
||||
DEFAULT_TIMEOUT_MS = 180000
|
||||
# ★ 模型请求的超时**不在这里** —— 它和别的超时一起收在 timeouts.py 里
|
||||
# (设置 → 超时 → 等模型回复)。以前这里是 `DEFAULT_TIMEOUT_MS = 180000`,
|
||||
# 用户改不了;现在每次请求现读,改了立刻生效、不用重启。
|
||||
def model_timeout_s() -> float:
|
||||
"""等模型返回的秒数(读设置,出错时回落 180 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('model'))
|
||||
except Exception: # noqa: BLE001 - 设置读不出来也不能让请求发不出去
|
||||
return 180.0
|
||||
|
||||
|
||||
def join_url(base_url: str, suffix: str) -> str:
|
||||
@@ -109,7 +118,7 @@ def _request(url: str, api_key: str, body: dict | None = None, method: str = 'PO
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
# 不用 urlopen 的 with:流式响应要留给调用方边读边消费
|
||||
return urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000)
|
||||
return urllib.request.urlopen(req, timeout=model_timeout_s())
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
try:
|
||||
@@ -263,7 +272,7 @@ def list_models(*, base_url: str, api_key: str) -> list:
|
||||
url = join_url(base_url, '/models')
|
||||
req = urllib.request.Request(url, headers={'Authorization': f'Bearer {api_key}'}, method='GET')
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000)
|
||||
resp = urllib.request.urlopen(req, timeout=model_timeout_s())
|
||||
except urllib.error.HTTPError as exc:
|
||||
raise UpstreamError(f'上游 {exc.code}') from exc
|
||||
except urllib.error.URLError as exc:
|
||||
|
||||
694
android/kernel/rule_engine.py
Normal file
694
android/kernel/rule_engine.py
Normal file
@@ -0,0 +1,694 @@
|
||||
"""规则引擎:数值系统 + 状态系统(需求 v1.2 §3.10 / §3.11)。
|
||||
|
||||
## 一句话分工
|
||||
|
||||
· **定义**在「数值状态包」里(独立资源,可被多个世界观引用)
|
||||
· **值**按 scope 存(`shared` 决定是每个智能体一份还是全世界观一份)
|
||||
· **注入**走 `<stats>` / `<status>` 两个段(附录 C,排在提示词最后)
|
||||
· **操作**只有 `change_stat`(只申请增量,不许写绝对值)
|
||||
|
||||
## 为什么"只申请增量"这条不能通融
|
||||
|
||||
需求 §3.10 原话:`change_stat(name, delta)` —— 只申请增量,内核流程固定:
|
||||
|
||||
脚本裁决(如有)→ clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
|
||||
如果允许 AI 写绝对值,那"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5 点,我判成加 10 点",而不是"你想设成 100,我判……多少"。
|
||||
而且并发时(群聊里两个智能体同时改同一个 shared 数值)
|
||||
绝对值会互相覆盖,增量不会。
|
||||
|
||||
## 值的 scope
|
||||
|
||||
和记忆**故意用同一套写法**:
|
||||
|
||||
shared=0 → "agent:<uuid>" 好感度各算各的
|
||||
shared=1 → "world:<uuid>" 灵气浓度全世界观一份
|
||||
|
||||
好处是"绑定/解绑世界观只换读写空间、值不迁移"这条自动成立 ——
|
||||
和记忆的行为一致,用户不用学两套心智模型。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_sandbox
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 定义:从规则包同步进来
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 规则包里数值定义的合法字段(多出来的忽略,不报错 —— 兼容将来扩展)
|
||||
_STAT_KEYS = ('name', 'min', 'max', 'shared', 'ranges', 'script')
|
||||
_STATUS_KEYS = ('name', 'kind', 'turns', 'max_stack', 'script')
|
||||
|
||||
|
||||
def _num(v, default=0.0):
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def sync_defs(pack_id: str, info: dict = None) -> dict:
|
||||
"""
|
||||
把一个规则包的 `info.json` 同步进库(**幂等**,重复导入只覆盖定义)。
|
||||
|
||||
★ 只同步**定义**,不动**值**(需求附录 D:"数值的**定义**进包,
|
||||
**当前值**不进包 —— 经历与人设分离,同记忆")。
|
||||
所以重新导入一个包不会把你的好感度清零。
|
||||
|
||||
★ [info] 不传时**从 store 里那个包读**。这是默认路径 ——
|
||||
定义只应该有一处源头(包里的 `info.json`),SQLite 里那两张表是
|
||||
**派生**出来的。两处都能写的话,迟早会出现
|
||||
"包里改了、库里还是旧的",而那种不一致极难查。
|
||||
|
||||
返回 `{'stats': n, 'statuses': m}`。
|
||||
"""
|
||||
if info is None:
|
||||
pack = store.get_resource('rulepacks', pack_id or '') or {}
|
||||
info = pack.get('info') if isinstance(pack.get('info'), dict) else {}
|
||||
info = info or {}
|
||||
sid = (pack_id or '').strip()
|
||||
if not sid:
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
# ★★ 空定义**不动库**。
|
||||
#
|
||||
# "读不到这个包"(id 不对、包刚被删)和"用户真要把定义清空"在这一层
|
||||
# 分不清,而**清空定义是不可逆的**:值还在 `stat_values` 里,
|
||||
# 定义没了它们就成了永远读不到的孤儿。
|
||||
# 真要清空,把那个包删掉就行 —— 那是个明确得多的动作。
|
||||
if not info.get('stats') and not info.get('statuses'):
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
agentdb.init() # ★ 别忘了:这几张表是 v1.2 才加的,惰性建表
|
||||
conn = agentdb._connect()
|
||||
stats = info.get('stats') if isinstance(info.get('stats'), list) else []
|
||||
statuses = info.get('statuses') if isinstance(info.get('statuses'), list) else []
|
||||
|
||||
# 定义表整体替换这个包的(不然删掉的数值会一直留着)
|
||||
conn.execute('DELETE FROM stat_defs WHERE pack_id = ?', (sid,))
|
||||
conn.execute('DELETE FROM status_defs WHERE pack_id = ?', (sid,))
|
||||
|
||||
# ★ 数**实际入库的**,不是输入数组的长度:"你导入了 3 条"和
|
||||
# "3 条里有 1 条没名字被跳过"是两回事,界面拿这个数报给用户。
|
||||
n_stats = 0
|
||||
for i, s in enumerate(stats):
|
||||
s = s or {}
|
||||
name = str(s.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
lo, hi = _num(s.get('min'), 0.0), _num(s.get('max'), 100.0)
|
||||
if hi <= lo:
|
||||
hi = lo + 1
|
||||
ranges = s.get('ranges') if isinstance(s.get('ranges'), list) else []
|
||||
conn.execute(
|
||||
'INSERT INTO stat_defs (pack_id, name, min_value, max_value, shared, ranges, script, ord) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
(sid, name, lo, hi, 1 if s.get('shared') else 0,
|
||||
json.dumps(ranges, ensure_ascii=False), str(s.get('script') or ''), i),
|
||||
)
|
||||
n_stats += 1
|
||||
|
||||
n_status = 0
|
||||
for s in statuses:
|
||||
s = s or {}
|
||||
name = str(s.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
kind = 'persistent' if str(s.get('type') or s.get('kind') or '').lower() == 'persistent' else 'timed'
|
||||
conn.execute(
|
||||
'INSERT INTO status_defs (pack_id, name, kind, turns, max_stack, script) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(sid, name, kind, max(1, int(_num(s.get('turns'), 1))),
|
||||
max(1, int(_num(s.get('max_stack'), 1))), str(s.get('script') or '')),
|
||||
)
|
||||
n_status += 1
|
||||
conn.commit()
|
||||
return {'stats': n_stats, 'statuses': n_status}
|
||||
|
||||
|
||||
def stat_defs(pack_id: str) -> list:
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM stat_defs WHERE pack_id = ? ORDER BY ord ASC, name ASC', (pack_id or '',),
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
try:
|
||||
ranges = json.loads(r['ranges'] or '[]')
|
||||
except (TypeError, ValueError):
|
||||
ranges = []
|
||||
out.append({
|
||||
'name': r['name'], 'min': float(r['min_value']), 'max': float(r['max_value']),
|
||||
'shared': bool(r['shared']), 'ranges': ranges if isinstance(ranges, list) else [],
|
||||
'script': r['script'] or '',
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def status_defs(pack_id: str) -> list:
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM status_defs WHERE pack_id = ? ORDER BY name ASC', (pack_id or '',),
|
||||
).fetchall()
|
||||
return [
|
||||
{'name': r['name'], 'kind': r['kind'] or 'timed', 'turns': int(r['turns'] or 1),
|
||||
'max_stack': int(r['max_stack'] or 1), 'script': r['script'] or ''}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 值:按 scope 读写
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def scope_for(agent: dict, definition: dict) -> str:
|
||||
"""
|
||||
一条数值存在哪个空间(`shared` 决定)。
|
||||
|
||||
★ 和记忆用同一套 scope 写法(`agentdb.scope_of` / `world_scope`)——
|
||||
这样"解绑世界观值留在原地"和记忆的行为一致,用户不用学两套。
|
||||
"""
|
||||
agent = agent or {}
|
||||
if (definition or {}).get('shared'):
|
||||
wid = (agent.get('worldviewId') or '').strip()
|
||||
# 没绑世界观却要读"全世界观共享"的值:退回私有空间。
|
||||
# 不报错是因为"刚解绑"是个正常状态,值还在那儿等着再绑回来。
|
||||
return agentdb.world_scope(wid) if wid else agentdb.agent_scope(agent.get('id') or '')
|
||||
return agentdb.agent_scope(agent.get('id') or '')
|
||||
|
||||
|
||||
def value_of(agent: dict, definition: dict) -> float:
|
||||
"""
|
||||
读一条数值的当前值。没写过就取**定义里的初始值** ——
|
||||
用 min 还是 max?
|
||||
|
||||
★ 取 `min`。因为在"好感度 0~100"这种语义里 min 是中性起点;
|
||||
取 max 的话新角色一上来就满好感,明显不对。
|
||||
真想要别的起点,包作者把 min 设成他要的值就行。
|
||||
"""
|
||||
scope = scope_for(agent, definition)
|
||||
agentdb.init()
|
||||
row = agentdb._connect().execute(
|
||||
'SELECT value FROM stat_values WHERE scope = ? AND name = ?',
|
||||
(scope, (definition or {}).get('name') or ''),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return _num((definition or {}).get('min'), 0.0)
|
||||
return float(row['value'])
|
||||
|
||||
|
||||
def set_value(agent: dict, definition: dict, value: float) -> float:
|
||||
"""直接写值(**只给内核用**:脚本裁决和 clamp 之后的落库走这里)"""
|
||||
scope = scope_for(agent, definition)
|
||||
v = _num(value)
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute(
|
||||
'INSERT INTO stat_values (scope, name, value) VALUES (?, ?, ?) '
|
||||
'ON CONFLICT(scope, name) DO UPDATE SET value = excluded.value',
|
||||
(scope, (definition or {}).get('name') or '', v),
|
||||
)
|
||||
conn.commit()
|
||||
return v
|
||||
|
||||
|
||||
def clamp(definition: dict, value: float) -> float:
|
||||
d = definition or {}
|
||||
return max(_num(d.get('min'), 0.0), min(_num(d.get('max'), 100.0), _num(value)))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 区间表:命中哪段注入哪段(需求 §3.10 "声明式区间表")
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def range_text(definition: dict, value: float) -> str:
|
||||
"""
|
||||
命中区间的 text(没命中任何区间就返回空串 = 裸值)。
|
||||
|
||||
★ 区间是**左闭右开** `[min, max)`,除了最后一段是闭的。
|
||||
半开区间是刻意的:0~20 和 20~40 两段,20 该算后一段 ——
|
||||
如果两边都闭,20 会同时命中两段,取哪段就成了未定义行为。
|
||||
"""
|
||||
ranges = (definition or {}).get('ranges')
|
||||
if not isinstance(ranges, list):
|
||||
return ''
|
||||
v = _num(value)
|
||||
total = len(ranges)
|
||||
for i, r in enumerate(ranges):
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
lo = _num(r.get('min'))
|
||||
hi = _num(r.get('max'), lo)
|
||||
last = i == total - 1
|
||||
if (lo <= v < hi) or (last and lo <= v <= hi):
|
||||
return str(r.get('text') or '').strip()
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注入:<stats> / <status>
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 上一轮的变化量(渲染 `450→500` 那个箭头用)。
|
||||
#:
|
||||
#: ★ 放内存、不放库:需求说箭头"**仅保留一轮**",用完就该没了。
|
||||
#: 放库还要额外写一次清理逻辑,而进程重启丢掉它也无所谓 ——
|
||||
#: 箭头只是个提示,不是数据。
|
||||
_pending_delta = {}
|
||||
|
||||
|
||||
def note_delta(scope: str, name: str, delta: float) -> None:
|
||||
"""记下这次变化了多少,下一轮渲染时显示成箭头"""
|
||||
if delta:
|
||||
_pending_delta[(scope, name)] = float(delta)
|
||||
|
||||
|
||||
def take_delta(scope: str, name: str) -> float:
|
||||
"""取出并**清掉**(所以只显示一轮)"""
|
||||
return _pending_delta.pop((scope, name), 0.0)
|
||||
|
||||
|
||||
def stats_section(agent: dict, pack_id: str) -> str:
|
||||
"""
|
||||
渲染 `<stats>` 段(附录 C 的格式):
|
||||
|
||||
[世界·九州] 声望: 450→500/1000 —— 名震九州:世人皆知你之名
|
||||
[自身] 好感度: 45/100 —— 友善:你对用户态度友善,但保持分寸
|
||||
|
||||
来源前缀(`[世界·xx]` / `[自身]`)+ 当前值 + 变化箭头(仅一轮)+
|
||||
命中区间文本(未命中就是裸值)。
|
||||
"""
|
||||
defs = stat_defs(pack_id)
|
||||
if not defs:
|
||||
return ''
|
||||
agent = agent or {}
|
||||
wname = ''
|
||||
wid = (agent.get('worldviewId') or '').strip()
|
||||
if wid:
|
||||
wname = ((store.get_resource('worldviews', wid) or {}).get('name') or '').strip()
|
||||
|
||||
lines = []
|
||||
for d in defs:
|
||||
scope = scope_for(agent, d)
|
||||
v = value_of(agent, d)
|
||||
delta = take_delta(scope, d['name'])
|
||||
src = f'[世界·{wname}]' if d.get('shared') and wname else '[自身]'
|
||||
# 值那一段:有变化时显示 `旧→新`
|
||||
if delta:
|
||||
old = clamp(d, v - delta)
|
||||
val = f'{_fmt(old)}→{_fmt(v)}/{_fmt(d["max"])}'
|
||||
else:
|
||||
val = f'{_fmt(v)}/{_fmt(d["max"])}'
|
||||
text = range_text(d, v)
|
||||
lines.append(f'{src} {d["name"]}: {val}' + (f' —— {text}' if text else ''))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def _fmt(v: float) -> str:
|
||||
"""数值显示:整数就不带小数点(45.0 → 45),免得看着别扭"""
|
||||
f = float(v)
|
||||
return str(int(f)) if f == int(f) else f'{f:g}'
|
||||
|
||||
|
||||
def status_section(agent: dict) -> str:
|
||||
"""
|
||||
渲染 `<status>` 段(附录 C 的格式):
|
||||
|
||||
中毒(剩 3 轮):你感到眩晕,言语变得迟缓
|
||||
|
||||
状态名(剩余轮数)+ 状态提示词(脚本可改写)。
|
||||
持久状态不显示轮数(它不过期)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
rows = list_statuses(agent.get('id') or '')
|
||||
if not rows:
|
||||
return ''
|
||||
lines = []
|
||||
for r in rows:
|
||||
head = r['name']
|
||||
if r.get('kind') != 'persistent' and r.get('remaining', 0) > 0:
|
||||
head += f'(剩 {r["remaining"]} 轮)'
|
||||
if r.get('stacks', 1) > 1:
|
||||
head += f'×{r["stacks"]}'
|
||||
hint = (r.get('hint') or '').strip()
|
||||
lines.append(head + (f':{hint}' if hint else ''))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 状态实例
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def list_statuses(agent_id: str) -> list:
|
||||
"""这个智能体身上生效中的状态(带定义里的 kind)"""
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM status_instances WHERE agent_id = ? ORDER BY granted_at ASC, name ASC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
out.append({
|
||||
'name': r['name'], 'remaining': int(r['remaining'] or 0),
|
||||
'stacks': int(r['stacks'] or 1), 'hint': r['hint'] or '',
|
||||
'grantedAt': r['granted_at'] or '', 'kind': _kind_of(r['name']),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _kind_of(name: str) -> str:
|
||||
"""查一个状态名是持久还是定时(实例表里不存 kind —— 那是定义的事)"""
|
||||
agentdb.init()
|
||||
row = agentdb._connect().execute(
|
||||
'SELECT kind FROM status_defs WHERE name = ? LIMIT 1', (name or '',),
|
||||
).fetchone()
|
||||
return (row['kind'] if row else 'timed') or 'timed'
|
||||
|
||||
|
||||
def put_status(agent_id: str, name: str, remaining: int, stacks: int, hint: str) -> None:
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute(
|
||||
'INSERT INTO status_instances (agent_id, name, remaining, stacks, hint, granted_at) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?) '
|
||||
'ON CONFLICT(agent_id, name) DO UPDATE SET remaining = excluded.remaining, '
|
||||
'stacks = excluded.stacks, hint = excluded.hint',
|
||||
(agent_id or '', name or '', int(remaining), int(stacks), hint or '', agentdb.now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def drop_status(agent_id: str, name: str) -> None:
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute('DELETE FROM status_instances WHERE agent_id = ? AND name = ?',
|
||||
(agent_id or '', name or ''))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def tick_statuses(agent_id: str) -> list:
|
||||
"""
|
||||
"该智能体每参与一轮后减 1"(需求 §3.11)。
|
||||
|
||||
返回 `[{'name':…, 'expired':True/False}]` —— 调用方据此播报
|
||||
"中毒已经消退了"这类消息。
|
||||
|
||||
★ persistent 的是 `remaining = -1`,不参与递减(它不过期)。
|
||||
"""
|
||||
out = []
|
||||
for r in list_statuses(agent_id):
|
||||
if r.get('kind') == 'persistent':
|
||||
continue
|
||||
left = int(r.get('remaining') or 0) - 1
|
||||
if left <= 0:
|
||||
drop_status(agent_id, r['name'])
|
||||
out.append({'name': r['name'], 'expired': True})
|
||||
else:
|
||||
put_status(agent_id, r['name'], left, r.get('stacks') or 1, r.get('hint') or '')
|
||||
out.append({'name': r['name'], 'expired': False, 'remaining': left})
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 脚本执行(需求 §3.10 数值裁决 / §3.11 状态脚本)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 三个入口(需求附录 E 的签名):
|
||||
#
|
||||
# on_stat_change(name, value, delta) -> 生效增量(可放大/缩小/归零否决)
|
||||
# on_turn(self_agent, stats_api) 每轮执行(状态脚本)
|
||||
# on_grant(status_name, source_agent) -> bool(赋予判定,跑在**目标方**)
|
||||
#
|
||||
# 全部走 rule_sandbox 的受限沙箱 + 硬超时。
|
||||
#
|
||||
# ★★ 异常 = 本次操作**归零** + UI 提示,**不中断对话**(需求附录 E)。
|
||||
# 规则脚本是用户自己写的,写错了是常态;一次脚本错误把整轮对话搞崩,
|
||||
# 用户会以为整个 App 坏了 —— 而其实只是他那行 `1/0` 写错了。
|
||||
|
||||
|
||||
def _timeout_s() -> float:
|
||||
import timeouts
|
||||
|
||||
return float(timeouts.get('customNode') or 10)
|
||||
|
||||
|
||||
def script_source(pack_id: str, filename: str) -> str:
|
||||
"""从规则包里取一段脚本源码(空串 = 这个包没带这段脚本)"""
|
||||
if not (filename or '').strip():
|
||||
return ''
|
||||
pack = store.get_resource('rulepacks', pack_id or '') or {}
|
||||
scripts = pack.get('scripts')
|
||||
if not isinstance(scripts, dict):
|
||||
return ''
|
||||
return str(scripts.get(filename) or '')
|
||||
|
||||
|
||||
def run_script(source: str, entry: str, *args) -> tuple:
|
||||
"""
|
||||
跑一段规则脚本,返回 `(结果, 错误说明)`。
|
||||
|
||||
★ **不抛异常**:需求说异常要"归零 + 提示、不中断对话",
|
||||
所以错误在这里就被接住、转成一段人话,由调用方决定怎么显示。
|
||||
抛出去的话,一次脚本报错会顺着调用栈炸到对话主循环。
|
||||
|
||||
★ 超时用 `run_with_timeout`(线程 + join)—— 注意它的说明:
|
||||
超时后线程**杀不掉**,只能放弃等待。所以这里给的默认值不大
|
||||
(`timeouts.customNode`),而且脚本本来就该是"算一下"级别的活。
|
||||
"""
|
||||
if not (source or '').strip():
|
||||
return None, ''
|
||||
|
||||
import builtin_tools
|
||||
|
||||
holder = {}
|
||||
|
||||
def _work():
|
||||
try:
|
||||
ns = rule_sandbox.load(source, '<rule script>', {})
|
||||
holder['value'] = rule_sandbox.call(ns, entry, *args)
|
||||
holder['error'] = ''
|
||||
except rule_sandbox.ScriptRejected as exc:
|
||||
holder['error'] = f'脚本没通过安全检查:{exc}'
|
||||
except KeyError:
|
||||
holder['error'] = f'脚本里没有 `{entry}` 函数'
|
||||
except SyntaxError as exc:
|
||||
holder['error'] = f'脚本第 {exc.lineno} 行有语法错误:{exc.msg}'
|
||||
except Exception as exc: # noqa: BLE001 - 用户脚本什么都能抛
|
||||
holder['error'] = f'脚本报错:{exc.__class__.__name__}: {exc}'
|
||||
|
||||
# 注意:run_with_timeout 返回 None 表示"超时/放弃等待",见它的说明
|
||||
builtin_tools.run_with_timeout(_work, _timeout_s())
|
||||
if holder.get('error'):
|
||||
return None, holder['error']
|
||||
if 'value' not in holder:
|
||||
return None, '脚本超时(已放弃等待,它可能还在后台跑)'
|
||||
return holder['value'], ''
|
||||
|
||||
|
||||
def _stat_api(agent: dict, pack_id: str, narration: list, hints: dict) -> dict:
|
||||
"""
|
||||
给状态脚本的**受限 API**(需求 §3.11 的三项权限 + 旁白)。
|
||||
|
||||
★ 通过**参数**注入,不是做成模块级函数:那样脚本能摸到别的东西,
|
||||
两个脚本也会互相污染。
|
||||
★ 这里没有 `emotion_set` 的死亡检查 —— 需求 §3.11 明说状态脚本是
|
||||
"唯一能让 AI 侧解除死亡的通道"(定时复活 / 解药剧情)。
|
||||
禁止自愈那条只约束 AI 直接调 `emotion_set` 工具。
|
||||
"""
|
||||
def _change_stat(name, delta):
|
||||
r = change(agent, pack_id, str(name or ''), _num(delta))
|
||||
if not r.get('ok'):
|
||||
raise ValueError(r.get('error') or '改数值失败')
|
||||
return r.get('applied', 0)
|
||||
|
||||
def _emotion_set(preset, text=''):
|
||||
import agentdb
|
||||
|
||||
p = str(preset or '').strip()
|
||||
if p not in agentdb.PRESETS:
|
||||
raise ValueError(f'preset 只能是:{"、".join(agentdb.PRESETS)}')
|
||||
agentdb.emotion_set(agent.get('id') or '', preset=p, text=str(text or ''))
|
||||
return True
|
||||
|
||||
def _set_hint(status_name, text):
|
||||
hints[str(status_name or '').strip()] = str(text or '')
|
||||
|
||||
def _narrate(text):
|
||||
t = str(text or '').strip()
|
||||
if t:
|
||||
narration.append(t)
|
||||
|
||||
return {
|
||||
'change_stat': _change_stat,
|
||||
'emotion_set': _emotion_set,
|
||||
'set_hint': _set_hint,
|
||||
'narrate': _narrate,
|
||||
}
|
||||
|
||||
|
||||
def run_turn_scripts(agent: dict, pack_id: str) -> dict:
|
||||
"""
|
||||
每轮**生成回复之前**跑一遍生效状态的脚本(需求 §3.11)。
|
||||
|
||||
顺序是固定的:**状态脚本执行 → 重拼 prompt → 生成**(附录 E)。
|
||||
所以调用点必须在 `build_system_prompt` **之前**,否则脚本这一轮的
|
||||
改动要等下一轮才生效 —— 表现是"中毒了但 AI 这轮还生龙活虎"。
|
||||
|
||||
返回 `{'narration': [...], 'errors': [...], 'changed': [...]}`:
|
||||
· `narration` 是脚本返回的旁白,内核作为系统消息注入下一轮
|
||||
· `errors` 给界面提示(**不中断对话**)
|
||||
"""
|
||||
agent = agent or {}
|
||||
aid = agent.get('id') or ''
|
||||
if not aid:
|
||||
return {'narration': [], 'errors': [], 'changed': []}
|
||||
|
||||
narration, errors = [], []
|
||||
for inst in list_statuses(aid):
|
||||
src = script_source(pack_id, _script_file_of(pack_id, inst['name']))
|
||||
if not src:
|
||||
continue
|
||||
hints = {}
|
||||
api = _stat_api(agent, pack_id, narration, hints)
|
||||
_, err = run_script(src, 'on_turn', dict(agent), api)
|
||||
if err:
|
||||
errors.append(f'状态「{inst["name"]}」的脚本:{err}')
|
||||
continue
|
||||
# 脚本可能改了提示词(需求 §3.11 的权限之一)
|
||||
for sname, text in hints.items():
|
||||
for s in list_statuses(aid):
|
||||
if s['name'] == sname:
|
||||
put_status(aid, sname, s['remaining'], s['stacks'], text)
|
||||
return {'narration': narration, 'errors': errors, 'changed': []}
|
||||
|
||||
|
||||
def _script_file_of(pack_id: str, status_name: str) -> str:
|
||||
"""状态定义里配的脚本文件名"""
|
||||
for d in status_defs(pack_id):
|
||||
if d['name'] == status_name:
|
||||
return d.get('script') or ''
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# change_stat:流程固定(需求 §3.10)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def change(agent: dict, pack_id: str, name: str, delta: float,
|
||||
source_agent: dict = None) -> dict:
|
||||
"""
|
||||
`change_stat(name, delta)` 的**完整流程**,顺序固定:
|
||||
|
||||
脚本裁决(如有)→ clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
|
||||
★ 为什么"只申请增量、不许写绝对值"这条不能通融:
|
||||
允许写绝对值的话"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5 点,我判成加 10 点",而不是"你想设成 100,我判……多少"。
|
||||
而且群聊里两个智能体同时改同一个 shared 数值时,**绝对值会互相覆盖,
|
||||
增量不会**。
|
||||
|
||||
返回 `{'ok':..., 'applied':…, 'before':…, 'after':…, 'narration':…, 'error':…}`
|
||||
"""
|
||||
d = next((x for x in stat_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
return {'ok': False, 'error': f'这个世界观里没有叫「{name}」的数值'}
|
||||
before = value_of(agent, d)
|
||||
want = _num(delta)
|
||||
|
||||
# ① 脚本裁决(可选)
|
||||
narration = []
|
||||
src = script_source(pack_id, d.get('script') or '')
|
||||
if src:
|
||||
out, err = run_script(src, 'on_stat_change', name, before, want)
|
||||
if err:
|
||||
# ★ 异常 = 本次增量**归零**(不是"按原值放行")——
|
||||
# 脚本坏了的时候,宁可这一次不生效,也不能让它失控地改数值
|
||||
return {'ok': False, 'error': err, 'applied': 0, 'before': before, 'after': before}
|
||||
if isinstance(out, (int, float)):
|
||||
want = float(out)
|
||||
elif isinstance(out, (list, tuple)) and out:
|
||||
# 也允许 (增量, 旁白) 这种写法
|
||||
want = _num(out[0])
|
||||
if len(out) > 1 and str(out[1] or '').strip():
|
||||
narration.append(str(out[1]).strip())
|
||||
elif out is None:
|
||||
want = 0.0 # 显式返回 None = 否决
|
||||
|
||||
# ② clamp ③ 写库
|
||||
after = clamp(d, before + want)
|
||||
applied = after - before
|
||||
if applied:
|
||||
set_value(agent, d, after)
|
||||
note_delta(scope_for(agent, d), name, applied)
|
||||
return {
|
||||
'ok': True, 'applied': applied, 'before': before, 'after': after,
|
||||
'narration': narration,
|
||||
'text': range_text(d, after),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# grant_status:赋予流程(需求 §3.11)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def grant(source: dict, pack_id: str, target: dict, status_name: str,
|
||||
turns: int = 0) -> dict:
|
||||
"""
|
||||
A 给 B 挂一个状态。
|
||||
|
||||
流程(需求 §3.11):
|
||||
1. **同世界观**才能赋(不要求同会话在场 —— 否则私聊里没法互相赋予)
|
||||
2. 调 **B 侧的** `on_grant(status_name, source_agent) -> bool`
|
||||
3. 接受 → 实例化到 B;拒绝 → A 收到「被抵抗」回执(**A 必须知道结果**)
|
||||
4. 同名重复赋予默认**刷新轮数**;定义配了 max_stack 才叠层
|
||||
|
||||
跨世界观一律拒绝(第 1 条就挡了)。
|
||||
"""
|
||||
source, target = source or {}, target or {}
|
||||
name = (status_name or '').strip()
|
||||
if not name:
|
||||
return {'ok': False, 'error': '没写状态名'}
|
||||
if not (target.get('id') or ''):
|
||||
return {'ok': False, 'error': '找不到目标智能体'}
|
||||
|
||||
sw = (source.get('worldviewId') or '').strip()
|
||||
tw = (target.get('worldviewId') or '').strip()
|
||||
if not sw or sw != tw:
|
||||
# ★ 跨世界观一律拒绝(需求原话)。也包含"自己没绑世界观"的情况 ——
|
||||
# 那种情况下没有共享的规则体系,赋予本身就没有依据。
|
||||
return {'ok': False, 'error': '你们不在同一个世界观里,赋予无效'}
|
||||
|
||||
d = next((x for x in status_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
return {'ok': False, 'error': f'这个世界观没有叫「{name}」的状态'}
|
||||
|
||||
# ② B 侧的判定脚本
|
||||
src = script_source(pack_id, d.get('script') or '')
|
||||
if src:
|
||||
out, err = run_script(src, 'on_grant', name, source.get('name') or source.get('id') or '')
|
||||
if err:
|
||||
return {'ok': False, 'error': f'对方的判定脚本出错了:{err}'}
|
||||
if out is False:
|
||||
# ★ 拒绝要给 A 一个**明确回执**(需求原话"A 必须知道结果")
|
||||
return {'ok': False, 'resisted': True, 'error': f'「{target.get("name") or "对方"}」抵抗了这个状态'}
|
||||
|
||||
# ④ 叠加规则
|
||||
cur = next((s for s in list_statuses(target['id']) if s['name'] == name), None)
|
||||
if d['kind'] == 'persistent':
|
||||
remaining = -1
|
||||
else:
|
||||
remaining = max(1, int(turns or d.get('turns') or 1))
|
||||
if cur:
|
||||
stacks = min(int(d.get('max_stack') or 1), int(cur.get('stacks') or 1) + 1)
|
||||
if d['kind'] != 'persistent':
|
||||
# 同名重复赋予默认**刷新**轮数(不是累加)
|
||||
remaining = max(remaining, int(cur.get('remaining') or 0))
|
||||
else:
|
||||
stacks = 1
|
||||
hint = cur.get('hint') if cur else ''
|
||||
put_status(target['id'], name, remaining, stacks, hint or '')
|
||||
return {'ok': True, 'name': name, 'remaining': remaining, 'stacks': stacks,
|
||||
'refreshed': bool(cur), 'target': target.get('name') or ''}
|
||||
189
android/kernel/rule_sandbox.py
Normal file
189
android/kernel/rule_sandbox.py
Normal file
@@ -0,0 +1,189 @@
|
||||
"""规则脚本的沙箱(v1.2 附录 E)。
|
||||
|
||||
# 这个沙箱能挡住什么,挡不住什么
|
||||
|
||||
**先说结论:它能挡手滑,挡不住有意。** 这不是偷懒,是 Python 的性质 ——
|
||||
只要你允许执行任意 Python 代码,就没有"关得严"的做法。所以这里的定位是
|
||||
**提高门槛 + 明确告知**,而不是给用户一个虚假的安全承诺。
|
||||
|
||||
## 三层防线
|
||||
|
||||
1. **静态扫描**(`scan`):源码里出现 `__双下划线__`、`import`、
|
||||
`open/eval/exec/getattr/...` 直接**拒绝执行**。
|
||||
这一层拦的是"手滑"和"抄来的脚本里夹带了东西" —— 规则脚本是**数值修正器**,
|
||||
正经写它根本用不到这些。
|
||||
2. **受限 builtins**:`exec` 时只喂一个白名单,`__import__` / `open` /
|
||||
`eval` / `compile` / `getattr` / `globals` 全都不在里面。
|
||||
没有 `__import__` 就没有模块系统。
|
||||
3. **硬超时**:复用 `timeouts.py` 的 `customNode` 那一项。
|
||||
|
||||
## 为什么说"挡不住有意"
|
||||
|
||||
Python 的属性访问是**语法**,不经过 builtins:
|
||||
|
||||
().__class__.__bases__[0].__subclasses__()
|
||||
|
||||
这一句能摸到进程里几乎所有类。第 1 层扫 `__` 就是为了堵它 ——
|
||||
但**字符串拼接**能绕过去(`getattr` 被禁了,可 `"__cla"+"ss__"` 拼出来再
|
||||
`__getattribute__` 呢?)。真想绕总能绕。
|
||||
|
||||
**所以导入规则包时的警告必须说实话**(见 `agent_api.py` 的导入流程):
|
||||
|
||||
> 此包包含可执行 Python 脚本,每轮在你的设备上运行。
|
||||
> 它**能读到你设备上的文件**,只导入你信得过的包。
|
||||
|
||||
而不是写"安全沙箱,请放心导入"。
|
||||
|
||||
## 为什么不直接用子进程
|
||||
|
||||
v1.2 讨论时定过"子进程 + 资源限制",查完发现**安卓上起不了 Python 子进程**:
|
||||
内核是 Chaquopy 嵌的 CPython,没有独立的解释器可执行文件
|
||||
(证据:`builtin_tools.python_run` 用的是进程内 `exec`,注释写着
|
||||
"这就是本工具存在的意义")。要起真子进程只能用 Termux 的 `python3`,
|
||||
但那要求用户装了 Termux、还得维护一个常驻 worker 和 IPC 协议。
|
||||
|
||||
**为一个"改个数值"的功能上那套,不值。** 所以退回白名单 + 明确告知。
|
||||
如果以后规则脚本变得重要到值得隔离,再上 Termux worker —— 那时
|
||||
这个模块的**接口不用变**(`run()` 的签名就是边界)。
|
||||
"""
|
||||
import re
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 第 1 层:静态扫描
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 危险模式 → 拒绝的理由(给用户看的话,不要写术语)
|
||||
DANGEROUS = (
|
||||
(re.compile(r'__\w+__'),
|
||||
'用了双下划线属性(这是绕过限制的经典手法)'),
|
||||
(re.compile(r'^\s*(import|from)\s+\w', re.M),
|
||||
'写了 import 语句(规则脚本不需要引入模块)'),
|
||||
(re.compile(r'\b(open|eval|exec|compile|input|breakpoint|help)\s*\('),
|
||||
'调用了不允许的内置函数'),
|
||||
(re.compile(r'\b(__import__|getattr|setattr|delattr|globals|locals|vars|dir|type|object|super)\s*\('),
|
||||
'调用了不允许的内置函数'),
|
||||
(re.compile(r'\b(exit|quit)\s*\('),
|
||||
'调用了退出函数'),
|
||||
)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 第 2 层:受限 builtins
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 只放"算数、拼字符串、处理列表字典"这一类。规则脚本要干的事就这些:
|
||||
# 读一个数值、算个增量、按区间挑一句话。
|
||||
#
|
||||
# ★ 不放:__import__ / open / eval / exec / compile / getattr / setattr /
|
||||
# globals / locals / vars / dir / type / object / super / input / help
|
||||
# —— 每一个都是逃逸链上的一环。
|
||||
SAFE_BUILTINS = {
|
||||
# 类型与构造
|
||||
'bool': bool, 'int': int, 'float': float, 'str': str,
|
||||
'list': list, 'dict': dict, 'tuple': tuple, 'set': set,
|
||||
'frozenset': frozenset, 'complex': complex, 'bytes': bytes,
|
||||
# 计算与序列
|
||||
'abs': abs, 'divmod': divmod, 'max': max, 'min': min, 'pow': pow,
|
||||
'round': round, 'sum': sum, 'len': len, 'sorted': sorted,
|
||||
'reversed': reversed, 'enumerate': enumerate, 'zip': zip,
|
||||
'range': range, 'any': any, 'all': all, 'map': map, 'filter': filter,
|
||||
# 字符串
|
||||
'format': format, 'repr': repr, 'ascii': ascii, 'chr': chr, 'ord': ord,
|
||||
'hex': hex, 'oct': oct, 'bin': bin,
|
||||
# 判断
|
||||
'isinstance': isinstance, 'issubclass': issubclass, 'callable': callable,
|
||||
# 常量
|
||||
'True': True, 'False': False, 'None': None,
|
||||
# 异常(脚本要能 try/except,不然一个除零就炸整轮对话)
|
||||
'Exception': Exception, 'ValueError': ValueError, 'TypeError': TypeError,
|
||||
'KeyError': KeyError, 'IndexError': IndexError, 'ZeroDivisionError': ZeroDivisionError,
|
||||
'AttributeError': AttributeError, 'ArithmeticError': ArithmeticError,
|
||||
'RuntimeError': RuntimeError,
|
||||
}
|
||||
|
||||
|
||||
class ScriptRejected(Exception):
|
||||
"""脚本没通过静态扫描 —— 带上给用户看的原因"""
|
||||
|
||||
|
||||
def scan(source: str) -> str:
|
||||
"""
|
||||
静态扫描。返回**拒绝原因**(空串 = 通过)。
|
||||
|
||||
★ 这层拦的是"手滑"和"抄来的脚本夹带了东西",不是"有意攻击"。
|
||||
真要有意,Python 语法层面总有办法绕(见模块 docstring)。
|
||||
"""
|
||||
text = source or ''
|
||||
if len(text) > 200_000:
|
||||
return '脚本太长了(上限 200KB)'
|
||||
for pattern, why in DANGEROUS:
|
||||
m = pattern.search(text)
|
||||
if m:
|
||||
line = text[:m.start()].count('\n') + 1
|
||||
return f'第 {line} 行:{why}(`{m.group(0).strip()}`)'
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 第 3 层:执行
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def build_globals(apis: dict, source_name: str = '<rule>') -> dict:
|
||||
"""
|
||||
给 `exec` 用的命名空间。
|
||||
|
||||
[apis] 是**注入给脚本的能力**(需求 3.11 的三项 + 状态提示词改写)——
|
||||
通过**参数**传进去,而不是做成模块级函数:那样脚本能 `import` 到别的东西,
|
||||
也会让两个脚本互相污染。
|
||||
"""
|
||||
return {
|
||||
'__builtins__': dict(SAFE_BUILTINS),
|
||||
'__name__': 'rule_script',
|
||||
'__file__': source_name,
|
||||
'__doc__': None,
|
||||
'__package__': None,
|
||||
**apis,
|
||||
}
|
||||
|
||||
|
||||
def load(source: str, source_name: str = '<rule>', apis: dict = None) -> dict:
|
||||
"""
|
||||
扫描 → 编译 → 执行模块体,返回那个命名空间(里面应该有入口函数)。
|
||||
|
||||
抛 [ScriptRejected] 表示没通过扫描;语法错误直接抛 SyntaxError
|
||||
(调用方接住,转成"你的脚本第 N 行有语法错误")。
|
||||
"""
|
||||
why = scan(source)
|
||||
if why:
|
||||
raise ScriptRejected(why)
|
||||
ns = build_globals(apis or {}, source_name)
|
||||
code = compile(source or '', source_name, 'exec')
|
||||
exec(code, ns) # noqa: S102 - 见模块 docstring:这是提高门槛,不是真沙箱
|
||||
return ns
|
||||
|
||||
|
||||
def call(ns: dict, entry: str, *args, **kwargs):
|
||||
"""
|
||||
调脚本里的入口函数。
|
||||
|
||||
没定义那个函数时抛 `KeyError`,调用方转成
|
||||
"脚本里没有 `on_turn` 函数"这种能给用户看的话。
|
||||
"""
|
||||
fn = ns.get(entry)
|
||||
if not callable(fn):
|
||||
raise KeyError(entry)
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 给界面看的说明(导入警告用)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: ★ 导入规则包时**原样显示**给用户的话。
|
||||
#: 故意不说"安全沙箱"——它挡得住手滑,挡不住有意(见模块 docstring)。
|
||||
IMPORT_WARNING = (
|
||||
'此包包含可执行 Python 脚本,会**每轮在你的设备上运行**。\n\n'
|
||||
'脚本被限制了模块引入和文件读写(只能用几个安全的计算函数),'
|
||||
'但这**不是**真正的沙箱 —— 精心构造的脚本仍然可能读到设备上的文件,'
|
||||
'也可能占用大量内存或算力拖慢手机。\n\n'
|
||||
'只导入你信得过的来源。'
|
||||
)
|
||||
@@ -28,8 +28,28 @@ import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
DEFAULT_TIMEOUT_TTS = 60
|
||||
DEFAULT_TIMEOUT_STT = 120
|
||||
import timeouts
|
||||
|
||||
# ★ 语音的超时也收在 timeouts.py 里(设置 → 超时 → 语音合成 / 语音识别)。
|
||||
# 以前这里是 `DEFAULT_TIMEOUT_TTS = 60` / `DEFAULT_TIMEOUT_STT = 120` 两个常量,
|
||||
# 网络慢或者回复长的时候用户只能忍着。现在是函数 —— 每次现读,改完立刻生效。
|
||||
|
||||
|
||||
def tts_timeout() -> float:
|
||||
"""语音合成等多久(出错回落 60 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('tts'))
|
||||
except Exception: # noqa: BLE001
|
||||
return 60.0
|
||||
|
||||
|
||||
def stt_timeout() -> float:
|
||||
"""语音识别等多久(出错回落 120 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('stt'))
|
||||
except Exception: # noqa: BLE001
|
||||
return 120.0
|
||||
|
||||
|
||||
# 允许用环境变量覆盖:自测时把火山接口指到本地 mock,就能验证"我们到底发了什么"
|
||||
# (鉴权头那个分号、body 的层级,光看代码容易自我说服,实测才算数)
|
||||
@@ -267,7 +287,7 @@ def _synthesize_volc_v3(text: str, speech: dict, speed: float) -> dict:
|
||||
req.add_header('X-Control-Require-Usage-Tokens-Return', '*')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||||
with urllib.request.urlopen(req, timeout=tts_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
@@ -342,7 +362,7 @@ def _synthesize_volc(text: str, speech: dict, speed: float) -> dict:
|
||||
'operation': 'query',
|
||||
},
|
||||
}
|
||||
result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, DEFAULT_TIMEOUT_TTS)
|
||||
result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, tts_timeout())
|
||||
|
||||
code = result.get('code')
|
||||
if code != 3000:
|
||||
@@ -374,7 +394,7 @@ def _synthesize_openai(text: str, settings: dict, speech: dict, speed: float) ->
|
||||
req.add_header('Authorization', f'Bearer {api_key}')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||||
with urllib.request.urlopen(req, timeout=tts_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
ctype = resp.headers.get('Content-Type') or 'audio/mpeg'
|
||||
except urllib.error.HTTPError as exc:
|
||||
@@ -429,7 +449,7 @@ def transcribe(audio: bytes, filename: str, content_type: str, settings: dict) -
|
||||
req.add_header('Authorization', f'Bearer {api_key}')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_STT) as resp:
|
||||
with urllib.request.urlopen(req, timeout=stt_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
@@ -564,7 +584,7 @@ def _stream_volc_v3(text: str, speech: dict, speed: float):
|
||||
|
||||
mime = VOLC_MIME.get(fmt, 'audio/L16')
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS)
|
||||
resp = urllib.request.urlopen(req, timeout=tts_timeout())
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
try:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
352
android/kernel/timeouts.py
Normal file
352
android/kernel/timeouts.py
Normal file
@@ -0,0 +1,352 @@
|
||||
"""**所有超时的唯一一份定义**,以及读取它们的入口。
|
||||
|
||||
## 为什么要收成一份
|
||||
|
||||
改造前,15 个超时散在 10 个文件里,全是模块级常量,谁也说不清一共有几个:
|
||||
|
||||
tools_runtime.py TOOL_TIMEOUT_S = 60 工具执行
|
||||
builtin_tools.py shell 工具 30 / python 60 命令执行(还各自夹了上限)
|
||||
doubao_entry.py termux 命令 30
|
||||
providers.py DEFAULT_TIMEOUT_MS = 180000 模型请求
|
||||
speech.py TTS 60 / STT 120
|
||||
mcp_client.py 请求 60 / 连接 180 / 工具 120
|
||||
meeting.py PY_TIMEOUT = 10 会议里的 Python 节点
|
||||
custom_nodes.py RUN_TIMEOUT = 10
|
||||
tools/ask_user.py TIMEOUT_S = 0 / MAX 3600
|
||||
tools/show_ui.py MIN 5 / MAX 3600
|
||||
KernelClient.kt connect 5s / read 120s
|
||||
|
||||
后果和"节点定义写 6 遍"是同一类:**想调一个超时要先找到它在哪**,
|
||||
而且改了一处不知道还有没有别处也在卡同一个东西。
|
||||
|
||||
## 用户要"全部可调",所以这里同时是**界面数据的来源**
|
||||
|
||||
界面不硬编码这些项目 —— 它读 `GET /api/timeouts`,那个接口返回的就是 [SPECS]。
|
||||
所以**加一项超时只改这个文件**(加 [DEFAULT] 一条 + [SPECS] 一条),
|
||||
内核各处 `timeouts.get('名字')`,界面自动多出一行。
|
||||
|
||||
## 边界
|
||||
|
||||
每项都带 `min` / `max`,取值时**一律夹进去**([get] 里做的)。
|
||||
不是"相信用户不会填错":填 0 会让 curl 永远不超时、填 999999 会让内核线程
|
||||
挂到天荒地老。夹取是这一层唯一该做的"业务判断",所以放在这里而不是各调用点。
|
||||
|
||||
`min = 0` 表示这一项**允许"不限时"**(只有"等用户"这类才该允许)。
|
||||
"""
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 默认值
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 这里只放**数字**。每一项都必须能在 SPECS 里找到同名条目 ——
|
||||
# `scripts/verify-timeouts.py` 会检查两边对得上(少一条就报错)。
|
||||
|
||||
DEFAULT = {
|
||||
# ---- 智能体切换动画(需求 2.3)----
|
||||
'agentAnim.frontOut': 0.3,
|
||||
'agentAnim.gap': 0.5,
|
||||
'agentAnim.frame': 0.4,
|
||||
'agentAnim.frontIn': 0.3,
|
||||
# ---- 对话 ----
|
||||
'model': 180, # 等模型返回
|
||||
'sseRead': 120, # 客户端读 SSE 的间隔上限(内核只负责告诉客户端)
|
||||
'heartbeat': 15, # SSE 心跳间隔
|
||||
'kernelLocal': 10, # 客户端调内核本地接口(安卓侧用)
|
||||
|
||||
# ---- 工具 ----
|
||||
'tool': 60, # 任意 Python 工具执行
|
||||
'shell': 30, # 安卓 shell 命令(builtin)
|
||||
'pythonRun': 60, # 跑一段 Python 代码(builtin)
|
||||
'termux': 30, # 内置 Termux 里跑命令
|
||||
'meetingNode': 10, # 会议里的 Python / 自定义节点
|
||||
'customNode': 10, # 自定义节点(nodes/ 里的)
|
||||
|
||||
# ---- 界面(等用户)----
|
||||
'askUser': 0, # ask_user 等用户选,0 = 不限时
|
||||
'waitUi': 0, # show_ui 的 wait 模式等用户,0 = 不限时
|
||||
'filePicker': 120, # AI 让你选文件时等你多久
|
||||
|
||||
# ---- 语音 ----
|
||||
'tts': 60,
|
||||
'stt': 120,
|
||||
|
||||
# ---- MCP ----
|
||||
'mcpRequest': 60,
|
||||
'mcpConnect': 180,
|
||||
'mcpTool': 120,
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 每一项的说明(界面直接用这些文字)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# group 决定界面上分到哪一组;unit 目前全是"秒"(毫秒的东西一律在调用点换算)。
|
||||
|
||||
SPECS = [
|
||||
# ---------------- 智能体切换动画(需求 2.3)----------------
|
||||
#
|
||||
# ★ 这几项严格说**不是超时**,但它们和超时是同一类东西:
|
||||
# 一个"全局可调的时间数值"。需求 2.3 原话是"所有时长与缓动数值收进全局配置"。
|
||||
#
|
||||
# 为什么不单独造一套(settings 里加个 agentAnim 对象 + 再写一个配置界面):
|
||||
# 那就是**第二份要同步的东西** —— 加一项要改两处、界面要写两遍,
|
||||
# 而这个仓库里"同一逻辑抄成两份、改的时候只改一份"已经反复出现过。
|
||||
# 复用它唯一的代价是分组标题要写清楚(界面上这一组的说明就是这么写的)。
|
||||
{
|
||||
'key': 'agentAnim.frontOut', 'group': '动画', 'label': '角色图出场',
|
||||
'default': 0.3, 'min': 0.05, 'max': 3, 'unit': '秒',
|
||||
'desc': '切换智能体时,**旧**角色图淡出 + 侧移的时长(需求定的 0.3s)。',
|
||||
},
|
||||
{
|
||||
'key': 'agentAnim.gap', 'group': '动画', 'label': '中间留白',
|
||||
'default': 0.5, 'min': 0, 'max': 5, 'unit': '秒', 'zero': '不停顿',
|
||||
'desc': '两个阶段之间的停顿(需求定的 0.5s)。调成 0 就是"出场完立刻换框",'
|
||||
'整个切换会从 1.5 秒缩到 1.0 秒 —— 嫌切换慢就改这个。',
|
||||
},
|
||||
{
|
||||
'key': 'agentAnim.frame', 'group': '动画', 'label': '边框背景切换',
|
||||
'default': 0.4, 'min': 0.05, 'max': 4, 'unit': '秒',
|
||||
'desc': '背景图 / 主体边框 / 介绍框滑出滑入的**总**时长(需求定的 0.4s,'
|
||||
'实际拆成滑出一半、滑入一半)。',
|
||||
},
|
||||
{
|
||||
'key': 'agentAnim.frontIn', 'group': '动画', 'label': '角色图入场',
|
||||
'default': 0.3, 'min': 0.05, 'max': 3, 'unit': '秒',
|
||||
'desc': '**新**角色图淡入 + 侧移到位的时长(需求定的 0.3s)。',
|
||||
},
|
||||
|
||||
# ---------------- 对话 ----------------
|
||||
{
|
||||
'key': 'model', 'group': '对话', 'label': '等模型回复',
|
||||
'default': 180, 'min': 10, 'max': 1800, 'unit': '秒',
|
||||
'desc': '发出去到开始收到第一个字的最长等待。深度思考的模型(R1 这类)'
|
||||
'经常要想一分钟以上,调小了会频繁断在半路;本地小模型可以调大。',
|
||||
},
|
||||
{
|
||||
'key': 'sseRead', 'group': '对话', 'label': '连接空闲上限',
|
||||
'default': 120, 'min': 20, 'max': 3600, 'unit': '秒',
|
||||
'desc': '手机上"多久没收到任何数据就断开"。内核每【心跳间隔】秒发一次心跳,'
|
||||
'所以这个值必须比心跳间隔大不少 —— 内核发的就是心跳间隔那项。'
|
||||
'弱网/代理会悄悄掐长连接,可以把两个都调小一点,断得早反而好重连。',
|
||||
},
|
||||
{
|
||||
'key': 'heartbeat', 'group': '对话', 'label': '心跳间隔',
|
||||
'default': 15, 'min': 5, 'max': 300, 'unit': '秒',
|
||||
'desc': '对话过程中内核每隔这么久发一个空包,证明连接还活着。'
|
||||
'调大了在弱网下容易被中间设备当成死连接掐掉;调小了费电。',
|
||||
},
|
||||
{
|
||||
'key': 'kernelLocal', 'group': '对话', 'label': '本地接口请求',
|
||||
'default': 10, 'min': 3, 'max': 300, 'unit': '秒',
|
||||
'desc': '界面调内核的普通接口(读会话、存设置、拉笔记)等多久。'
|
||||
'只有老设备 + 会话特别长时才会顶到这个值。',
|
||||
},
|
||||
|
||||
# ---------------- 工具 ----------------
|
||||
{
|
||||
'key': 'tool', 'group': '工具', 'label': '工具执行',
|
||||
'default': 60, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': '任意一个 Python 工具最多跑多久。这是"工具里写了死循环"的安全网。\n'
|
||||
'填 0 = 不限时。注意:会停下来等你的工具(AI 提问、AI 界面等待)'
|
||||
'本来就不受这一项限制 —— 它们的时长取决于你什么时候点。',
|
||||
},
|
||||
{
|
||||
'key': 'shell', 'group': '工具', 'label': 'shell 命令',
|
||||
'default': 30, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 调用内置 shell 工具跑一条命令的最长时间。'
|
||||
'装包(pkg install / pip install)这类会超过 30 秒,那时可以让 AI 自己传更长的值。',
|
||||
},
|
||||
{
|
||||
'key': 'pythonRun', 'group': '工具', 'label': '跑 Python 代码',
|
||||
'default': 60, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 写一段 Python 交给内核执行的最长时间。算得久(循环、大文件)就调大。',
|
||||
},
|
||||
{
|
||||
'key': 'termux', 'group': '工具', 'label': 'Termux 命令',
|
||||
'default': 30, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': '在内置 Termux 环境里跑命令的最长时间。',
|
||||
},
|
||||
{
|
||||
'key': 'meetingNode', 'group': '工具', 'label': '会议节点',
|
||||
'default': 10, 'min': 1, 'max': 600, 'unit': '秒',
|
||||
'desc': '会议里一个 Python 节点 / 自定义节点最多跑多久。'
|
||||
'这是防死循环的 —— 调太大会让整个会议卡住,建议别超过 60。',
|
||||
},
|
||||
{
|
||||
'key': 'customNode', 'group': '工具', 'label': '自定义节点',
|
||||
'default': 10, 'min': 1, 'max': 600, 'unit': '秒',
|
||||
'desc': 'nodes/ 目录里自己写的节点,执行一次的最长时间。',
|
||||
},
|
||||
|
||||
# ---------------- 界面 ----------------
|
||||
{
|
||||
'key': 'askUser', 'group': '界面', 'label': 'AI 提问等多久',
|
||||
'default': 0, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': 'AI 弹选择框问你时,等多久算"你没空"。**默认 0 = 一直等**。\n'
|
||||
'不建议改:设成有限值后,你去忙一会儿回来,AI 已经按它自己猜的答案'
|
||||
'往下写了,而它并不知道自己在猜。',
|
||||
},
|
||||
{
|
||||
'key': 'waitUi', 'group': '界面', 'label': 'AI 界面等多久',
|
||||
'default': 0, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': 'AI 弹的界面在 wait 模式下等你点按钮的时长。**默认 0 = 一直等**。',
|
||||
},
|
||||
{
|
||||
'key': 'filePicker', 'group': '界面', 'label': '选文件等多久',
|
||||
'default': 120, 'min': 10, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 让你挑一个文件时,等你挑完的时长。'
|
||||
'去相册里翻一张老照片可能不止两分钟,可以调大。',
|
||||
},
|
||||
|
||||
# ---------------- 语音 ----------------
|
||||
{
|
||||
'key': 'tts', 'group': '语音', 'label': '语音合成',
|
||||
'default': 60, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '把回复转成语音的最长等待。长回复、网络慢时要更久。',
|
||||
},
|
||||
{
|
||||
'key': 'stt', 'group': '语音', 'label': '语音识别',
|
||||
'default': 120, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '把录音转成文字的最长等待。录音越长越久。',
|
||||
},
|
||||
|
||||
# ---------------- MCP ----------------
|
||||
{
|
||||
'key': 'mcpRequest', 'group': 'MCP', 'label': '单次请求',
|
||||
'default': 60, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '和 MCP 服务说话时,单次请求等多久。',
|
||||
},
|
||||
{
|
||||
'key': 'mcpConnect', 'group': 'MCP', 'label': '连接',
|
||||
'default': 180, 'min': 5, 'max': 900, 'unit': '秒',
|
||||
'desc': '启动 MCP 服务(npx / uvx 第一次要下载)的最长等待。'
|
||||
'第一次装包经常要几分钟,这也是默认给到 180 秒的原因。',
|
||||
},
|
||||
{
|
||||
'key': 'mcpTool', 'group': 'MCP', 'label': '调用工具',
|
||||
'default': 120, 'min': 5, 'max': 900, 'unit': '秒',
|
||||
'desc': '调用 MCP 服务里某个工具的最长等待。',
|
||||
},
|
||||
]
|
||||
|
||||
BY_KEY = {s['key']: s for s in SPECS}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 读取
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _stored() -> dict:
|
||||
"""用户改过的那部分(没改过就是空的)"""
|
||||
try:
|
||||
import store # 局部导入:store 依赖 paths,放顶部会把导入顺序弄难读
|
||||
raw = (store.read_settings() or {}).get('timeouts')
|
||||
except Exception: # noqa: BLE001 - 设置读不出来时一律用默认值,别让业务挂掉
|
||||
return {}
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def coerce(key: str, raw) -> float:
|
||||
"""
|
||||
把用户填的东西变成一个合法的秒数。
|
||||
|
||||
★ 容错是必须的:界面上是输入框,用户可能填 "60秒"、空串、负数、
|
||||
或者一个巨大的数。任何一种都不该让调用它的地方炸掉。
|
||||
"""
|
||||
spec = BY_KEY.get(key)
|
||||
if spec is None:
|
||||
raise KeyError(f'没有这个超时项:{key}')
|
||||
value = spec['default']
|
||||
if raw is not None and raw != '':
|
||||
try:
|
||||
value = float(str(raw).strip().rstrip('秒sS'))
|
||||
except (TypeError, ValueError):
|
||||
value = spec['default']
|
||||
lo, hi = spec['min'], spec['max']
|
||||
if value < lo:
|
||||
value = lo
|
||||
if value > hi:
|
||||
value = hi
|
||||
return value
|
||||
|
||||
|
||||
def get(key: str) -> float:
|
||||
"""读一项当前的超时(秒)。0 = 不限时(只有允许的项才会是 0)。"""
|
||||
return coerce(key, _stored().get(key))
|
||||
|
||||
|
||||
def ms(key: str) -> int:
|
||||
"""要毫秒的地方用这个(别在每个调用点自己写 * 1000)"""
|
||||
return int(get(key) * 1000)
|
||||
|
||||
|
||||
def resolved() -> dict:
|
||||
"""当前生效的全部值(默认 + 用户改的),给界面和诊断用"""
|
||||
stored = _stored()
|
||||
return {s['key']: coerce(s['key'], stored.get(s['key'])) for s in SPECS}
|
||||
|
||||
|
||||
def catalog() -> list:
|
||||
"""
|
||||
给界面的清单:每一项的说明 + 默认值 + 边界 + 现在是多少。
|
||||
|
||||
★ 界面**不硬编码**这些项目,它读这个。加一项超时只改本文件。
|
||||
"""
|
||||
stored = _stored()
|
||||
out = []
|
||||
for s in SPECS:
|
||||
item = dict(s)
|
||||
item['value'] = coerce(s['key'], stored.get(s['key']))
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def patch(values: dict) -> dict:
|
||||
"""
|
||||
算出"要存下来的那部分"(只含和默认值不同的项)。
|
||||
|
||||
★ 只存"和默认值不同的":这样以后改了默认值,没动过的项会跟着新默认走
|
||||
(如果一律存下来,老用户会被永久钉在旧默认上)。
|
||||
和默认一样就**删掉**这个键,不是存一个相同的值。
|
||||
"""
|
||||
current = dict(_stored())
|
||||
if not isinstance(values, dict):
|
||||
return resolved()
|
||||
for key, raw in values.items():
|
||||
if key not in BY_KEY:
|
||||
continue
|
||||
value = coerce(key, raw)
|
||||
if abs(value - float(BY_KEY[key]['default'])) < 1e-9:
|
||||
current.pop(key, None)
|
||||
else:
|
||||
# 存成 int 更好看(都是整秒),带小数的也不丢
|
||||
current[key] = int(value) if float(value).is_integer() else value
|
||||
return current
|
||||
|
||||
|
||||
def reset() -> dict:
|
||||
"""全部恢复默认"""
|
||||
return {}
|
||||
|
||||
|
||||
def budget(args: dict, key: str) -> int:
|
||||
"""
|
||||
算一次工具执行的超时:**工具参数优先,否则用设置里的值**,一律夹在该项边界内。
|
||||
|
||||
给 shell / python_run / termux 这几个"模型自己可以传 timeout"的工具用:
|
||||
|
||||
· 模型传了就用它的(它知道自己要跑多久:装个包当然比 ls 久)
|
||||
· 没传就用设置里的默认值(用户可能在设置里统一调大了)
|
||||
· 不管谁给的都夹在 [min, max] 里 —— 模型传 999999 也不能真的等那么久
|
||||
"""
|
||||
spec = BY_KEY.get(key)
|
||||
if spec is None:
|
||||
raise KeyError(f'没有这个超时项:{key}')
|
||||
raw = (args or {}).get('timeout')
|
||||
if raw in (None, ''):
|
||||
return int(get(key))
|
||||
try:
|
||||
value = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return int(get(key))
|
||||
return int(max(spec['min'], min(spec['max'], value)))
|
||||
@@ -24,6 +24,7 @@ import threading
|
||||
|
||||
import mcp_client
|
||||
import paths
|
||||
import timeouts
|
||||
from builtin_tools import BUILTIN_TOOLS, run_with_timeout
|
||||
|
||||
# 文件工具的缓存:path -> {'mtime':..., 'spec':..., 'error':...}
|
||||
@@ -32,9 +33,196 @@ _cache_lock = threading.Lock()
|
||||
# 已经 import 过的模块名(重载时要先从 sys.modules 里摘掉)
|
||||
_loaded_modules: dict = {}
|
||||
|
||||
TOOL_TIMEOUT_S = 60
|
||||
# ★ 工具的默认执行超时**不在这里** —— 它和别的 15 个超时一起收在
|
||||
# `timeouts.py` 里,用户可以在「设置 → 超时」里调。这里以前写死 `TOOL_TIMEOUT_S = 60`,
|
||||
# 现在一律 `timeouts.get('tool')`。
|
||||
BUILTIN_FILE_LABEL = '<内置>'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 会"停下来等用户"的工具:执行超时对它们不适用
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★★ 这个坑很隐蔽,记下来:
|
||||
#
|
||||
# 用户要求"AI 询问界面不要限时",我把弹窗那侧改成了无限等(`AiSurface.ask`),
|
||||
# 实测弹窗确实 135 秒还在 —— **但工具调用在 60 秒时就被内核判超时了**,
|
||||
# 模型收到的是"工具执行超时(60s)",用户五分钟后点的那个选项**根本回不到
|
||||
# 模型手里**。表现就是"弹窗还在、但 AI 已经自己往下写了"。
|
||||
#
|
||||
# 所以"不限时"必须**三处一起改**才算数:
|
||||
# ① 界面侧等多久(AiSurface)
|
||||
# ② 内核侧给工具多少时间(这里)
|
||||
# ③ 工具自己声明的 timeout(tools/ask_user.py、tools/show_ui.py)
|
||||
#
|
||||
# 判定方式:工具模块里声明 `WAIT_FOR_USER = True`。
|
||||
# 放在工具文件里而不是在这个列表里硬编码 —— 加新工具时不会漏(写工具的人
|
||||
# 自己知道它会不会等用户)。
|
||||
def _waits_for_user(name: str, spec: dict, module) -> bool:
|
||||
"""这个工具会不会停下来等用户交互"""
|
||||
if spec.get('_builtin'):
|
||||
return bool((BUILTIN_TOOLS.get(name) or {}).get('WAIT_FOR_USER'))
|
||||
return bool(getattr(module, 'WAIT_FOR_USER', False))
|
||||
|
||||
|
||||
def _with_default_timeouts(name: str, spec: dict, module, payload: dict) -> dict:
|
||||
"""
|
||||
把设置里的默认超时**注入**给声明了要的工具。
|
||||
|
||||
## 工具是这么声明的
|
||||
|
||||
# tools/ask_user.py
|
||||
TIMEOUT_KEYS = {'timeout': 'askUser'}
|
||||
|
||||
意思是:"我这个 `timeout` 参数如果模型没给,就用设置里 `askUser` 那一项的值。"
|
||||
|
||||
## 为什么要走这条路,而不是让工具自己 import timeouts
|
||||
|
||||
因为工具**不一定跑在内核进程里**:安卓端是进程内 import(能读),
|
||||
电脑端是 `python tool.py` 起子进程(读不到内核的模块)。而工具是要跨端复用的,
|
||||
所以不能让它们依赖内核的模块。
|
||||
|
||||
内核在**调用前**把值塞进参数里,工具照常从自己的参数读 —— 两端行为一致,
|
||||
工具本身也不用知道"设置"这回事(单独跑、自测时用自己文件里的兜底默认值)。
|
||||
"""
|
||||
keys = getattr(module, 'TIMEOUT_KEYS', None)
|
||||
if not isinstance(keys, dict) or not keys:
|
||||
return payload
|
||||
out = dict(payload)
|
||||
for arg_name, key in keys.items():
|
||||
# 模型给了就不覆盖(模型知道自己要等多久);给 0 也当"没给",
|
||||
# 因为 0 是"不限时"的合法值,但默认参数里它和"没填"是同一个意思
|
||||
if out.get(arg_name) in (None, '', 0, '0'):
|
||||
try:
|
||||
out[arg_name] = timeouts.get(key)
|
||||
except Exception: # noqa: BLE001 - 设置读不出来就用工具自己的兜底
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 界面工具的开关
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# 这些工具由 AI 主动驱动界面 / 主动说话,属于"会打扰用户"的能力,
|
||||
# 所以**默认关**,用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。
|
||||
#
|
||||
# ★ send_message 也在里面:它会让 AI **主动往对话里塞消息**(用户没说话它也说),
|
||||
# 同样是打扰性能力。而且它带"顺手跑一轮回复"的选项,能让模型连锁调用自己 ——
|
||||
# 默认开着的风险比前三个还大。
|
||||
UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation', 'send_message')
|
||||
|
||||
# 开关在 settings 里的位置。用嵌套 dict 而不是散落的顶层键,
|
||||
# 以后加界面工具不必再动 settings 的形状。
|
||||
UI_TOOL_SETTINGS_KEY = 'uiTools'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 当前调用上下文(线程局部)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 为什么需要它:工具要拿到"当前是哪次对话"才能结束对话,但工具签名是
|
||||
# run(args) —— 只有模型给的参数,没有对话信息。
|
||||
#
|
||||
# 已有先例是往 settings 里塞 `nodeTools`(会议节点工具),但那是**工具定义**,
|
||||
# 不是**运行时上下文**;上下文每轮都在变,塞进 settings 会和"设置"的语义混在一起。
|
||||
#
|
||||
# 所以单独开一个 thread-local:agent_loop 在执行工具前 push,
|
||||
# 执行完 pop。HTTP 是每请求一线程,thread-local 天然隔离,不会串。
|
||||
_ctx = threading.local()
|
||||
|
||||
|
||||
def push_context(**kw) -> None:
|
||||
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)。
|
||||
|
||||
★ 这是**替换**语义:把整份上下文换成新的。
|
||||
"""
|
||||
_ctx.value = dict(kw)
|
||||
|
||||
|
||||
def update_context(**kw) -> None:
|
||||
"""
|
||||
在**当前上下文里补几个键**(已有的不动)。
|
||||
|
||||
★★ 和 `push_context` 的区别很要紧,踩过一次:
|
||||
|
||||
· `push_context` 是**替换** —— 给"进入一次工具调用"用的
|
||||
· 工具内部想加个标记(比如 `pass_turn` 记"这一轮移交过了")时
|
||||
如果用 `push_context`,会把 `agentId` / `conversationId` 一起冲掉,
|
||||
接着同一个工具里的 `_me()` 就炸了(表现是"拿不到当前智能体",
|
||||
而报错的地方离真正的原因隔着好几步)
|
||||
"""
|
||||
cur = dict(getattr(_ctx, 'value', None) or {})
|
||||
cur.update(kw)
|
||||
_ctx.value = cur
|
||||
|
||||
|
||||
def clear_context() -> None:
|
||||
_ctx.value = None
|
||||
|
||||
|
||||
def current_context() -> dict:
|
||||
"""当前工具调用的上下文;不在调用中时返回空 dict"""
|
||||
return dict(getattr(_ctx, 'value', None) or {})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 轮次级状态(发言权移交)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★★ 为什么**不能**用工具上下文(`update_context`)来记这个 —— 踩过:
|
||||
#
|
||||
# 工具跑在 **worker 线程**里(`builtin_tools.run_with_timeout` 起线程),
|
||||
# 而 `_ctx` 是 `threading.local()`。工具在里面写 `update_context(...)`,
|
||||
# 写的是**那个 worker 线程**的副本;线程一结束、`finally` 里把值置 None,
|
||||
# 标记就没了。而主线程每次调用前又 `push_context(...)`(替换语义)——
|
||||
# 于是"这一轮已经移交过"**永远是 False**,`pass_turn` 可以一轮交无限次。
|
||||
#
|
||||
# ★ 更麻烦的是:探针当时是**直接调 `agent_tools.pass_turn`**(主线程),
|
||||
# 标记留在主线程里没被清 → 探针**假通过**。真机上才会露馅。
|
||||
# 所以这里的修复必须配一条**走真实路径**的探针(见 probe-group-chat)。
|
||||
#
|
||||
# 轮次级状态放**模块级**,和线程无关,`agent_loop` 每轮开头重置一次。
|
||||
_handoff = {'to': '', 'used': False}
|
||||
|
||||
|
||||
def begin_round() -> None:
|
||||
"""一轮对话开始时调用(agent_loop 在生成前调)"""
|
||||
_handoff['to'] = ''
|
||||
_handoff['used'] = False
|
||||
|
||||
|
||||
def note_handoff(agent_id: str) -> None:
|
||||
"""`pass_turn` 记下"这一轮移交给了谁" """
|
||||
_handoff['to'] = str(agent_id or '')
|
||||
_handoff['used'] = True
|
||||
|
||||
|
||||
def handoff_state() -> dict:
|
||||
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`)"""
|
||||
return dict(_handoff)
|
||||
|
||||
|
||||
def ui_tools_enabled(settings: dict) -> bool:
|
||||
"""
|
||||
界面工具开了没有。
|
||||
|
||||
★ 默认 **False**:这三个工具会让 AI 主动弹界面/弹窗、甚至结束对话,
|
||||
对用户是"打扰性"能力,不该装好就默认打开。
|
||||
"""
|
||||
box = (settings or {}).get(UI_TOOL_SETTINGS_KEY)
|
||||
if isinstance(box, dict):
|
||||
return box.get('enabled') is True
|
||||
if isinstance(box, bool):
|
||||
return box
|
||||
return False
|
||||
|
||||
|
||||
def filter_ui_tools(specs: list, settings: dict) -> list:
|
||||
"""开关关着时,把界面工具从工具表里摘掉(模型根本看不到,也就不会调)。"""
|
||||
if ui_tools_enabled(settings):
|
||||
return specs
|
||||
return [s for s in specs if s.get('name') not in UI_TOOLS]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 目录与文件
|
||||
@@ -235,15 +423,43 @@ def run_python_tool(name: str, args: dict) -> dict:
|
||||
runner = getattr(module, 'run')
|
||||
|
||||
payload = args if isinstance(args, dict) else {}
|
||||
# ★ 设置里的默认超时注入给声明了 TIMEOUT_KEYS 的工具(ask_user / show_ui)
|
||||
payload = _with_default_timeouts(name, spec, module, payload)
|
||||
# ★★★ **先抓住当前线程的上下文**,因为 run_with_timeout 会在**另一个线程**里
|
||||
# 跑工具,而 threading.local() 是**不跨线程继承**的 —— 不搬过去的话,
|
||||
# 工作线程里 current_context() 永远是空的。
|
||||
#
|
||||
# 这个坑的表现特别隐蔽:工具照常执行(参数都对),只有"当前是哪次对话"
|
||||
# 拿不到,于是 end_conversation 报"拿不到当前对话 id"。我一开始以为是
|
||||
# app.py 没传 conversationId,查了一圈才发现是线程的问题。
|
||||
ctx = current_context()
|
||||
|
||||
def _invoke():
|
||||
if ctx:
|
||||
_ctx.value = dict(ctx)
|
||||
try:
|
||||
return runner(payload)
|
||||
finally:
|
||||
if ctx:
|
||||
_ctx.value = None
|
||||
|
||||
try:
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
|
||||
outcome = run_with_timeout(lambda: runner(payload), TOOL_TIMEOUT_S)
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死。
|
||||
# ★ 会等用户的工具(ask_user / show_ui 的 wait 模式)**不限时** ——
|
||||
# 它们的耗时取决于用户什么时候点,给上限等于"用户想久了 AI 就自己编"。
|
||||
# 见 _waits_for_user 的注释。
|
||||
# ★ 预算是**设置里可调**的(设置 → 超时 → 工具执行),不是写死的 60。
|
||||
if _waits_for_user(name, spec, module):
|
||||
budget = 0
|
||||
else:
|
||||
budget = timeouts.get('tool')
|
||||
outcome = run_with_timeout(_invoke, budget)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
||||
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
|
||||
return {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
if outcome is None:
|
||||
return {'ok': False, 'error': f'工具执行超时({TOOL_TIMEOUT_S}s)'}
|
||||
return {'ok': False, 'error': f'工具执行超时({budget:g}s,可在设置里调)'}
|
||||
result = outcome
|
||||
# 工具可以像 _protocol 那样返回 {"ok":..,"result":..},也可以直接返回业务结果
|
||||
if isinstance(result, dict) and 'ok' in result:
|
||||
@@ -381,6 +597,8 @@ def build_tool_defs(settings: dict) -> list:
|
||||
defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp'])
|
||||
# 会议里的 Python 节点工具并进来(受限模式也走同一个白名单)
|
||||
defs = defs + node_tool_defs(settings)
|
||||
# 界面工具(AI 弹界面 / 弹窗 / 结束对话)开关关着时对模型隐藏
|
||||
defs = filter_ui_tools(defs, settings)
|
||||
return apply_security(defs, settings)
|
||||
|
||||
|
||||
@@ -393,6 +611,15 @@ def execute_tool(name: str, args: dict, settings: dict) -> dict:
|
||||
allow = ((settings or {}).get('security') or {}).get('allow') or []
|
||||
if name not in allow:
|
||||
return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'}
|
||||
# ★ 界面工具的第二道拦截:开关关着时,即使模型硬编名字也不执行。
|
||||
# (第一道是 build_tool_defs 里根本不把它给模型看。)
|
||||
# 两道都要有 —— 只藏不给看的话,用户把工具关掉之后模型仍可能
|
||||
# 从历史消息里学会这个名字再调一次。
|
||||
if name in UI_TOOLS and not ui_tools_enabled(settings):
|
||||
return {
|
||||
'ok': False,
|
||||
'error': f'界面工具「{name}」已关闭。请在「技能」页打开"AI 界面能力"后再用。',
|
||||
}
|
||||
# 会议节点工具优先(它是这次会议里用户刚写的东西,不会有重名歧义)
|
||||
if name in node_tool_names(settings):
|
||||
return run_node_tool(name, args, settings)
|
||||
|
||||
@@ -16,6 +16,7 @@ import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
import paths
|
||||
from store import _rand36, _ts36, now_iso # 复用同一套 id/时间风格
|
||||
@@ -62,6 +63,51 @@ def _safe_name(name: str) -> str:
|
||||
return cleaned[-60:]
|
||||
|
||||
|
||||
def _stamp() -> str:
|
||||
"""
|
||||
落盘文件名用的时间戳:**人能读**的本地时间,格式 `20260101-120000`。
|
||||
|
||||
★ 以前这里用的是 `_ts36()`(base36 的毫秒数,形如 `m5k8xk2`)。
|
||||
它唯一的优点是不会重名,缺点是**看见文件名完全不知道是什么时候的东西** ——
|
||||
排查问题时只能一个个 `ls -la`。
|
||||
|
||||
用户明确反馈过这一点(bug 报告问题 5):"私有目录下一堆时间戳名/哈希名
|
||||
临时件,无统一约定"。所以换成可读格式。
|
||||
|
||||
★ 秒级精度会撞名(同一秒传两个同名文件)。落盘前用 [_unique_path] 消歧,
|
||||
不靠时间戳本身保证唯一。
|
||||
"""
|
||||
return datetime.now().strftime('%Y%m%d-%H%M%S')
|
||||
|
||||
|
||||
def uploads_dir() -> str:
|
||||
"""
|
||||
附件的固定落地目录(绝对路径)。**只有这一个入口,别在别处拼路径。**
|
||||
|
||||
存在的意义是给"AI 拿到附件后想去 shell 里处理它"一个稳定约定 ——
|
||||
`attachment_payload` 会把 `path` 明明白白写进给模型的内容里,
|
||||
模型不必去猜文件在哪(bug 报告问题 5 的核心诉求)。
|
||||
"""
|
||||
return os.path.join(paths.get().uploads_dir, '').rstrip(os.sep)
|
||||
|
||||
|
||||
def _unique_path(directory: str, stamp: str, safe_name: str) -> str:
|
||||
"""
|
||||
`{目录}/{时间戳}_{安全文件名}`;重名时在扩展名前加 `-1`、`-2`…
|
||||
|
||||
★ 一定要保留扩展名:`report.pdf` 变成 `report-1.pdf` 而不是 `report.pdf-1` ——
|
||||
一堆工具(含我们自己的 `is_image()` / `mime_of()`)都按扩展名判断类型。
|
||||
"""
|
||||
base, ext = os.path.splitext(safe_name)
|
||||
for i in range(0, 1000):
|
||||
suffix = '' if i == 0 else f'-{i}'
|
||||
candidate = os.path.join(directory, f'{stamp}_{base}{suffix}{ext}')
|
||||
if not os.path.exists(candidate):
|
||||
return candidate
|
||||
# 极端情况:同秒同名超过 1000 个,交给随机后缀
|
||||
return os.path.join(directory, f'{stamp}_{base}-{_rand36(4)}{ext}')
|
||||
|
||||
|
||||
def _ext_of(name: str) -> str:
|
||||
return os.path.splitext(str(name or ''))[1].lower()
|
||||
|
||||
@@ -86,7 +132,8 @@ def _meta(file_path: str, name: str, copy: bool = True) -> dict:
|
||||
stored_path = file_path
|
||||
url = ''
|
||||
if copy and size <= COPY_LIMIT:
|
||||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||
os.makedirs(uploads_dir(), exist_ok=True)
|
||||
target = _unique_path(uploads_dir(), _stamp(), _safe_name(name))
|
||||
with open(file_path, 'rb') as src, open(target, 'wb') as dst:
|
||||
while True:
|
||||
chunk = src.read(256 * 1024)
|
||||
@@ -118,8 +165,8 @@ def save_upload(name: str, base64_data: str) -> dict:
|
||||
raise ValueError(f'base64 解码失败:{exc}') from exc
|
||||
if len(buffer) > COPY_LIMIT:
|
||||
raise ValueError(f'文件超过 {COPY_LIMIT // 1024 // 1024}MB')
|
||||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
os.makedirs(uploads_dir(), exist_ok=True)
|
||||
target = _unique_path(uploads_dir(), _stamp(), _safe_name(name))
|
||||
with open(target, 'wb') as fh:
|
||||
fh.write(buffer)
|
||||
return {
|
||||
@@ -158,21 +205,32 @@ def attachment_payload(attachment: dict) -> dict:
|
||||
"""
|
||||
把附件转成模型能吃的形式:图片走视觉格式(data URL),文本类内联正文。
|
||||
返回 {text, images:[{url}]},与 Node 版 attachmentPayload 一致。
|
||||
|
||||
★★★ **每一条分支都会把落盘的绝对路径写进 text。**
|
||||
|
||||
这一条是用户明确提的(bug 报告问题 5):附件进了上下文,但没人告诉
|
||||
模型文件落在哪,模型想去 shell / python 里处理它只能靠猜,猜错就是
|
||||
FileNotFoundError。之前只有"二进制"那一条给了路径,文本和图片都没给 ——
|
||||
而**恰恰是文本最需要**:超过 20000 字符会被截断,被截掉的那部分
|
||||
只能靠模型自己去读原文件。
|
||||
|
||||
格式统一成 `本地路径:<绝对路径>`,模型一眼能捞出来。
|
||||
"""
|
||||
out = {'text': '', 'images': []}
|
||||
item = attachment or {}
|
||||
file_path = item.get('path') or ''
|
||||
name = item.get('name') or '未知'
|
||||
if not file_path or not os.path.isfile(file_path):
|
||||
out['text'] = f"【附件 {item.get('name') or '未知'} 已丢失】"
|
||||
out['text'] = f"【附件 {name} 已丢失】"
|
||||
return out
|
||||
size = os.path.getsize(file_path)
|
||||
if is_image(item.get('name')) and size <= VISION_LIMIT:
|
||||
if is_image(name) and size <= VISION_LIMIT:
|
||||
with open(file_path, 'rb') as fh:
|
||||
b64 = base64.b64encode(fh.read()).decode('ascii')
|
||||
out['images'].append({'url': f"data:{item.get('mime')};base64,{b64}"})
|
||||
out['text'] = f"【图片 {item.get('name')}】"
|
||||
out['text'] = f"【图片 {name}({size} 字节)本地路径:{file_path}】"
|
||||
return out
|
||||
if is_text(item.get('name')) or size < 64 * 1024:
|
||||
if is_text(name) or size < 64 * 1024:
|
||||
body = ''
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8', errors='replace') as fh:
|
||||
@@ -181,7 +239,10 @@ def attachment_payload(attachment: dict) -> dict:
|
||||
print(f'[uploads] 读取 {file_path} 失败:{exc}', file=sys.stderr)
|
||||
if body:
|
||||
clipped = f'{body[:20000]}\n…(已截断,共 {len(body)} 字符)' if len(body) > 20000 else body
|
||||
out['text'] = f"【文件 {item.get('name')}({size} 字节)】\n```\n{clipped}\n```"
|
||||
out['text'] = (
|
||||
f"【文件 {name}({size} 字节)本地路径:{file_path}】\n"
|
||||
f'```\n{clipped}\n```'
|
||||
)
|
||||
return out
|
||||
out['text'] = f"【附件 {item.get('name')}({size} 字节,二进制)本地路径:{file_path}】"
|
||||
out['text'] = f"【附件 {name}({size} 字节,二进制)本地路径:{file_path}】"
|
||||
return out
|
||||
|
||||
77
android/nodekit/build.gradle.kts
Normal file
77
android/nodekit/build.gradle.kts
Normal file
@@ -0,0 +1,77 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
/*
|
||||
* ★ 刻意**不挂** `org.jetbrains.kotlin.plugin.compose`。
|
||||
*
|
||||
* 这个库里没有任何 `@Composable` 函数 —— 唯一用到 Compose 的地方是
|
||||
* [com.doubao.nodekit.NodeShapes],而它只用 `Path` / `Rect` / `CornerRadius`
|
||||
* 这些**普通值类型**(画形状是渲染方的事,库只负责给出路径)。
|
||||
*
|
||||
* 挂了那个插件就必须把 compose runtime 也塞进 classpath,
|
||||
* 否则报 "The Compose Compiler requires the Compose Runtime to be on the
|
||||
* class path" —— 一个纯规则库不该被拖进运行时依赖。
|
||||
*/
|
||||
}
|
||||
|
||||
/**
|
||||
* 会议节点定义库。
|
||||
*
|
||||
* ## 为什么是独立 module 而不是 app 里的一个包
|
||||
*
|
||||
* 这套"节点形式"(有哪些节点、每个节点什么引脚、什么颜色、什么形状、
|
||||
* 卡片多高、连线从哪儿出去)以前**全散在 MeetingsScreen.kt 的 8485 行里**,
|
||||
* 而且全是 `private`,同一个概念在 6 个地方各写一遍。
|
||||
*
|
||||
* 抽成独立 module 的目的是让"不能复用"变成**编译期就做不到**:
|
||||
* · 库看不到 app 的 `MeetingNode` / `CustomNodeDef`,只能收自己定义的
|
||||
* [com.doubao.nodekit.NodeView] —— 于是"节点定义"和"节点数据"被迫分开
|
||||
* · 库看不到 `isDark()` / `Doubao.Blue` / `AppViewModel` —— 于是主题色
|
||||
* 只能靠**参数**传进来,不会偷偷依赖界面状态
|
||||
* · 别的地方(积木编辑器、以后别的项目)能直接依赖它
|
||||
*
|
||||
* ## 刻意不依赖 Compose
|
||||
*
|
||||
* 库里的定义、引脚表、算子表、几何计算**一行 Compose 都没有**,
|
||||
* 只依赖标准库。原因:
|
||||
* · 这些是"规则",规则不该长在渲染框架上
|
||||
* · 不依赖 Compose 才能被**单元测试**直接跑(JVM 上不需要起 Android)
|
||||
* · 颜色用 `Int`(ARGB)存,渲染方自己 `Color(int)` 转
|
||||
*
|
||||
* 唯一带 Compose 的是 [com.doubao.nodekit.NodeShapes](形状的 Path),
|
||||
* 它单独一个文件,不用形状的人不受影响。
|
||||
*/
|
||||
android {
|
||||
namespace = "com.doubao.nodekit"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
// ★ 不开 compose:库里没有 @Composable,见文件头的 plugins 注释
|
||||
compose = false
|
||||
}
|
||||
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// 形状用到 Compose 的 Path / Rect / CornerRadius(都是普通值类型,不是 @Composable)。
|
||||
// 版本跟 app 的 compose-bom 走 —— 这里用 implementation 而不是锁死版本,
|
||||
// 免得和 app 的 compose 版本打架
|
||||
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||
implementation("androidx.compose.ui:ui-graphics")
|
||||
}
|
||||
216
android/nodekit/src/main/java/com/doubao/nodekit/Catalog.kt
Normal file
216
android/nodekit/src/main/java/com/doubao/nodekit/Catalog.kt
Normal file
@@ -0,0 +1,216 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/**
|
||||
* 节点类型。
|
||||
*
|
||||
* ## ★★ 这就是"节点形式"的清单,以前它被抄了 6 遍
|
||||
*
|
||||
* 1. `android/kernel/meeting.py:46` `NODE_TYPES`(13 种,权威)
|
||||
* 2. `android/kernel/app.py:1054` `/api/meeting/meta` 的 `nodeTypes`(12 种,漏 custom)
|
||||
* 3. `server/src/meeting.mjs:26` `NODE_TYPES`(6 种,落后)
|
||||
* 4. `MeetingsScreen.kt:7025` `nodeColor()` 的 when
|
||||
* 5. `MeetingsScreen.kt:3695` `inputPins()` 的 when
|
||||
* 6. `MeetingsScreen.kt:3893` `outputPins()` 的 when
|
||||
*
|
||||
* 结果是"加一种节点要改 6 个地方",漏一个的表现是**界面上少一个颜色分支**
|
||||
* 或者**引脚画不出来**,而且不报错。
|
||||
*
|
||||
* 现在 Kotlin 这边只有 [NodeCatalog] 这一份。引擎那边是 Python,跨语言没法
|
||||
* 共享代码,所以用 `scripts/verify-nodekit.py` **守门对拍**(这是这个仓库里
|
||||
* 跨语言一致性的标准做法)。
|
||||
*/
|
||||
object NodeKind {
|
||||
const val START = "start"
|
||||
const val AGENT = "agent"
|
||||
const val JUDGE = "judge"
|
||||
const val END = "end"
|
||||
const val VAR = "var"
|
||||
const val READVAR = "readvar"
|
||||
const val WHILE = "while"
|
||||
const val VALUE = "value"
|
||||
const val CAST = "cast"
|
||||
const val OP = "op"
|
||||
const val PY = "py"
|
||||
const val CUSTOM = "custom"
|
||||
const val BRANCH = "branch"
|
||||
|
||||
/** 全部内置类型。顺序 = 「加节点」面板里的顺序 */
|
||||
val ALL: List<String> = listOf(
|
||||
START, AGENT, JUDGE, BRANCH, WHILE, END,
|
||||
VAR, READVAR, VALUE, CAST, OP, PY, CUSTOM,
|
||||
)
|
||||
|
||||
/**
|
||||
* 用户能手动加的类型。
|
||||
*
|
||||
* ★ `custom` 不在里面:它不是"加一个节点",而是"先在 `nodes/` 目录里
|
||||
* 放一个 .py 声明",走的是另一条路(见 NodeManager)。
|
||||
*
|
||||
* ★ 注释里别写 `nodes/` 加通配符那种路径 —— Kotlin 的块注释**可以嵌套**,
|
||||
* 里面出现一个斜杠加星号就把整个注释吃掉了,报的错还是"缺少 }"
|
||||
* (我在这里踩过,找了半天)。
|
||||
*/
|
||||
val ADDABLE: List<String> = ALL.filter { it != CUSTOM }
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点在画布上的**形状**。
|
||||
*
|
||||
* ## 形状即语法
|
||||
*
|
||||
* 这条原则在积木编辑器里是落地的(帽形 / C 型 / 六边形),但在**会议画布上
|
||||
* 一直是"全是圆角矩形"** —— 唯一的类型区分是标题栏的颜色。用户看不出
|
||||
* "这个节点是起点还是终点、是判断还是动作",只能靠读标题。
|
||||
*
|
||||
* 现在每种类型声明自己的形状,画布上有两处用到它:
|
||||
* · 「加节点」面板里每个类型前面有一个形状缩略图(选之前就看出是什么)
|
||||
* · 节点卡片标题栏左边有一个小徽标(在图上也能认出来)
|
||||
*
|
||||
* 形状的含义(这条得和积木编辑器保持一致,别自成一套):
|
||||
*
|
||||
* Hat 帽形 事件入口 —— 整张图从这里开始,没有输入
|
||||
* Diamond 菱形 分支判断 —— 一进两出,走哪条看条件
|
||||
* Loop 六边形 循环 —— 条件成立就回去
|
||||
* Capsule 胶囊 纯数据节点 —— 没有 exec,不在执行链上,值是被"拉"的
|
||||
* Terminal 圆角粗边 终点 —— 交出结果,没有输出
|
||||
* Rect 圆角矩形 普通动作 —— 一进一出
|
||||
*/
|
||||
enum class NodeShape {
|
||||
Hat, Diamond, Loop, Capsule, Terminal, Rect,
|
||||
}
|
||||
|
||||
/**
|
||||
* 一种节点类型的全部元数据。
|
||||
*
|
||||
* [color] 是 `Int`(ARGB)而不是 Compose 的 `Color`:库不依赖 Compose,
|
||||
* 渲染方自己 `Color(spec.color)` 转一下。
|
||||
*/
|
||||
data class NodeSpec(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val desc: String,
|
||||
/** 标题栏颜色 */
|
||||
val color: Int,
|
||||
val shape: NodeShape,
|
||||
/** 卡片上没写标题时显示什么 */
|
||||
val defaultTitle: String,
|
||||
/**
|
||||
* 纯节点:没有 exec 引脚,不在执行链上。
|
||||
*
|
||||
* ★ 这不是"有没有数据引脚",而是"**会不会被执行到**" ——
|
||||
* 读变量 / 值 / 运算 / 转换都是纯节点,它们的值是被下游
|
||||
* 节点运行时**拉取**的。这就是"读变量为什么只有输出、没有 exec 入"的答案。
|
||||
*/
|
||||
val pure: Boolean = false,
|
||||
/** 有循环体(可以往里拖节点)*/
|
||||
val container: Boolean = false,
|
||||
) {
|
||||
/** 是不是"多条 exec 出口"的节点(判断 / 分支 / while) */
|
||||
val branching: Boolean
|
||||
get() = key == NodeKind.JUDGE || key == NodeKind.BRANCH || key == NodeKind.WHILE
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点目录:**唯一一份**节点类型表。
|
||||
*
|
||||
* 加一种节点时,改这里的 `ALL` 加一条 —— 颜色、形状、默认标题、引脚
|
||||
* ([NodeSpecs])、配置面板(使用方)都从这一条走。
|
||||
*/
|
||||
object NodeCatalog {
|
||||
/**
|
||||
* 颜色。
|
||||
*
|
||||
* ★ 取值有个原则:**同一族的东西同色系**(变量/运算都是青,值/转换都是紫),
|
||||
* 用户靠颜色记"这类节点干什么"。但判断(橙黄)和分支(橙红)特意
|
||||
* 分开了 —— 它们长得像、用途完全不同(判断按规则算、分支直接收真假)。
|
||||
*/
|
||||
private const val GREEN = 0xFF34A853.toInt()
|
||||
private const val ORANGE = 0xFFF29900.toInt()
|
||||
private const val ORANGE_RED = 0xFFE8710A.toInt()
|
||||
private const val PURPLE = 0xFF7B61FF.toInt()
|
||||
private const val LIGHT_PURPLE = 0xFF9C6ADE.toInt()
|
||||
private const val DEEP_PURPLE = 0xFF7E57C2.toInt()
|
||||
private const val TEAL = 0xFF00A0A0.toInt()
|
||||
private const val DEEP_TEAL = 0xFF00897B.toInt()
|
||||
private const val SLATE = 0xFF37474F.toInt()
|
||||
private const val MAGENTA = 0xFFAD1457.toInt()
|
||||
private const val RED = 0xFFD93025.toInt()
|
||||
|
||||
/** 普通智能体节点的颜色。和 App 主题的 `Doubao.Blue` 是同一个值 */
|
||||
const val DEFAULT_COLOR = 0xFF2B7BFF.toInt()
|
||||
|
||||
val ALL: List<NodeSpec> = listOf(
|
||||
NodeSpec(
|
||||
NodeKind.START, "开始事件", "整张图从这里开始(exec 起点)",
|
||||
GREEN, NodeShape.Hat, "初始输入",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.AGENT, "智能体", "一个智能体处理一轮",
|
||||
DEFAULT_COLOR, NodeShape.Rect, "智能体",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.JUDGE, "判断", "按条件分 true / false 两条路",
|
||||
ORANGE, NodeShape.Diamond, "判断",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.BRANCH, "分支", "收一个真假,走真/假两条 exec(和判断的区别:判断按规则算,分支直接收)",
|
||||
ORANGE_RED, NodeShape.Diamond, "分支",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.WHILE, "while 循环", "条件为真就跑循环体,像 C 的 while",
|
||||
RED, NodeShape.Loop, "while 循环", container = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.END, "最终输出", "汇总结果",
|
||||
PURPLE, NodeShape.Terminal, "最终输出",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.VAR, "写变量", "把内容存进一个变量,后面任何节点都能读",
|
||||
TEAL, NodeShape.Rect, "写变量",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.READVAR, "读变量", "纯节点:取变量当前值(只出数据,没有 exec)",
|
||||
TEAL, NodeShape.Capsule, "读变量", pure = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.VALUE, "值", "纯节点:一个写死的值,接到智能体的数据输入",
|
||||
LIGHT_PURPLE, NodeShape.Capsule, "值", pure = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.CAST, "转换", "纯节点:str / bool / num / list 互转",
|
||||
DEEP_PURPLE, NodeShape.Capsule, "转换", pure = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.OP, "运算", "纯节点:+ − × ÷ % 拼接 取反 比较 逻辑",
|
||||
DEEP_TEAL, NodeShape.Capsule, "运算", pure = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.PY, "Python", "写一段 Python(run(ctx)),也可以给智能体当工具调",
|
||||
SLATE, NodeShape.Rect, "Python",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.CUSTOM, "自定义", "用户自己在 nodes/ 里写的节点",
|
||||
MAGENTA, NodeShape.Rect, "自定义",
|
||||
),
|
||||
)
|
||||
|
||||
private val BY_KEY: Map<String, NodeSpec> = ALL.associateBy { it.key }
|
||||
|
||||
/** 查一种类型。查不到给一个"安全默认"(老数据里可能有已经删掉/改名的类型) */
|
||||
fun of(key: String): NodeSpec =
|
||||
BY_KEY[key] ?: NodeSpec(
|
||||
key, if (key.isBlank()) "节点" else key, "", DEFAULT_COLOR,
|
||||
NodeShape.Rect, if (key.isBlank()) "节点" else key,
|
||||
)
|
||||
|
||||
fun color(key: String): Int = of(key).color
|
||||
|
||||
fun label(key: String): String = of(key).label
|
||||
|
||||
fun shape(key: String): NodeShape = of(key).shape
|
||||
|
||||
/** 卡片上的标题(用户没自己写时) */
|
||||
fun defaultTitle(key: String): String = of(key).defaultTitle
|
||||
|
||||
fun isPure(key: String): Boolean = of(key).pure
|
||||
}
|
||||
169
android/nodekit/src/main/java/com/doubao/nodekit/Geometry.kt
Normal file
169
android/nodekit/src/main/java/com/doubao/nodekit/Geometry.kt
Normal file
@@ -0,0 +1,169 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
|
||||
/**
|
||||
* 节点的几何:卡片多高、第 n 个引脚在哪儿、一条线该从哪个点出发。
|
||||
*
|
||||
* ## 为什么这套尺寸值得单独拎出来
|
||||
*
|
||||
* 因为它**同时被四个地方用**,任何一处不一致就出鬼:
|
||||
*
|
||||
* 1. 卡片布局(`NodeCard` 的实际高度)
|
||||
* 2. 引脚绘制(Canvas 上的圆点位置)
|
||||
* 3. 连线绘制与命中(贝塞尔曲线的端点)
|
||||
* 4. 拖拽吸附 / 端口命中范围
|
||||
*
|
||||
* 以前这四处的常量都在 `MeetingsScreen.kt` 里各写一遍,而且已经出现了
|
||||
* **两个再也用不到的死常量**(`NODE_H = 88f`、`CANVAS_W/H`)—— 高度改成
|
||||
* 由 [height] 算了以后没人删它们,看代码的人会以为高度还是 88。
|
||||
*
|
||||
* ## 尺寸是"UE 蓝图式"的:标题栏 + 引脚行 + 内容区
|
||||
*
|
||||
* ┌────────────┐ ← WIDTH = 116
|
||||
* │ 标题栏 │ ← HEADER_H = 24
|
||||
* ├──●───────●─┤ ← 一行引脚 PIN_ROW_H = 21(引脚垂直居中在这行里)
|
||||
* ├──●───────●─┤
|
||||
* │ 内容预览 │ ← BODY_H = 34
|
||||
* └────────────┘
|
||||
*
|
||||
* 卡片高度**跟着引脚数走**:判断节点两行出线、智能体进出各两种,就高一些。
|
||||
*/
|
||||
object NodeGeometry {
|
||||
|
||||
/** 卡片宽度。定这个值的坑:内容区的说明文字两行 24 + 底部 14,留点余量 */
|
||||
const val WIDTH = 116f
|
||||
|
||||
/** 顶部彩色标题栏的高度 */
|
||||
const val HEADER_H = 24f
|
||||
|
||||
/** 一行引脚占的高度 */
|
||||
const val PIN_ROW_H = 21f
|
||||
|
||||
/** 引脚下面的内容区(预览文字 + 路数) */
|
||||
const val BODY_H = 34f
|
||||
|
||||
/** 引脚画多大 */
|
||||
const val PORT_R = 5.5f
|
||||
|
||||
/** 引脚的命中半径。比画出来的大一圈 —— 手指没那么准 */
|
||||
const val PORT_HIT = 19f
|
||||
|
||||
/** 画布右下留多少空白(节点能拖到多远)*/
|
||||
const val MARGIN = 900f
|
||||
|
||||
/**
|
||||
* 节点卡片的高度。
|
||||
*
|
||||
* ★ 高度只看**引脚个数**,类型不影响 —— 所以查不到变量类型时
|
||||
* (名字不对但行数还是 1)也画得对。
|
||||
*/
|
||||
fun height(view: NodeView): Float {
|
||||
val rows = maxOf(
|
||||
NodeSpecs.inputPins(view).size,
|
||||
NodeSpecs.outputPins(view).size,
|
||||
1,
|
||||
)
|
||||
return HEADER_H + rows * PIN_ROW_H + BODY_H
|
||||
}
|
||||
|
||||
/**
|
||||
* 第 [index] 个引脚的坐标。
|
||||
*
|
||||
* 在标题栏下面第 index 行、垂直居中;输入贴左边、输出贴右边 ——
|
||||
* 和蓝图一致,连线从节点边缘出发 / 接入。
|
||||
*/
|
||||
fun pinPos(nodeX: Float, nodeY: Float, index: Int, isOutput: Boolean): Offset {
|
||||
val y = nodeY + HEADER_H + PIN_ROW_H * index + PIN_ROW_H / 2f
|
||||
val x = if (isOutput) nodeX + WIDTH else nodeX
|
||||
return Offset(x, y)
|
||||
}
|
||||
|
||||
/** 按 (种类, 分支) 找输出引脚的序号;找不到就退回第一条(老数据容错) */
|
||||
fun outPinIndex(view: NodeView, kind: String, branch: String): Int {
|
||||
val pins = NodeSpecs.outputPins(view)
|
||||
val exact = pins.indexOfFirst {
|
||||
it.kind == kind && (it.kind != PinKind.EXEC || it.key == branch)
|
||||
}
|
||||
if (exact >= 0) return exact
|
||||
val byBranch = pins.indexOfFirst { it.kind == PinKind.EXEC && it.key == branch }
|
||||
return if (byBranch >= 0) byBranch else 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 输入端口的位置。
|
||||
*
|
||||
* data 线接"值/输入"那条;exec 线接"▶"那条。
|
||||
* 找不到对应种类时退回第一条 —— 老会议里没有 kind 字段,边一律当 exec,
|
||||
* 而老图的节点只有一条入线,退回第一条正好对上。
|
||||
*/
|
||||
fun portIn(
|
||||
view: NodeView,
|
||||
nodeX: Float,
|
||||
nodeY: Float,
|
||||
kind: String,
|
||||
/** 边上记的引脚 key。有就**按 key 精确定位** ——
|
||||
* 运算的 A/B 都是 num,不靠它分不开(表现就是两条线都落在 A 上、B 收不到) */
|
||||
pinKey: String = "",
|
||||
): Offset {
|
||||
val pins = NodeSpecs.inputPins(view)
|
||||
if (pinKey.isNotBlank()) {
|
||||
val byKey = pins.indexOfFirst { it.key == pinKey }
|
||||
if (byKey >= 0) return pinPos(nodeX, nodeY, byKey, isOutput = false)
|
||||
}
|
||||
// ★ 按"这个入口能不能接 kind"来找,不是 kind 相等 ——
|
||||
// while 的条件入口能接 bool 和 str,两种情况都得能定位到同一条引脚。
|
||||
val index = pins.indexOfFirst { it.accepts_(kind) }
|
||||
return pinPos(nodeX, nodeY, if (index >= 0) index else 0, isOutput = false)
|
||||
}
|
||||
|
||||
/** 输出端口的位置 */
|
||||
fun portOut(
|
||||
view: NodeView,
|
||||
nodeX: Float,
|
||||
nodeY: Float,
|
||||
kind: String,
|
||||
branch: String,
|
||||
/** 边上记的引脚 key(同 [portIn];只有自定义节点有多个同名类型的数据出口时才用得上) */
|
||||
pinKey: String = "",
|
||||
): Offset {
|
||||
val pins = NodeSpecs.outputPins(view)
|
||||
if (pinKey.isNotBlank()) {
|
||||
val byKey = pins.indexOfFirst { it.key == pinKey }
|
||||
if (byKey >= 0) return pinPos(nodeX, nodeY, byKey, isOutput = true)
|
||||
}
|
||||
return pinPos(nodeX, nodeY, outPinIndex(view, kind, branch), isOutput = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 画布要多大(所有节点都要装得下,再留一圈边)。
|
||||
*
|
||||
* [sizes] 是每个节点的 (x, y, 高度)。
|
||||
*/
|
||||
fun canvasSize(sizes: List<Triple<Float, Float, Float>>): Pair<Float, Float> {
|
||||
var maxX = 0f
|
||||
var maxY = 0f
|
||||
for ((x, y, h) in sizes) {
|
||||
if (x + WIDTH > maxX) maxX = x + WIDTH
|
||||
if (y + h > maxY) maxY = y + h
|
||||
}
|
||||
return Pair(maxX + MARGIN, maxY + MARGIN)
|
||||
}
|
||||
|
||||
/**
|
||||
* 平移量的夹取:内容比视口小的时候不允许拖出空白。
|
||||
*
|
||||
* ★ `minOf(0f, ...)` 是必须的:内容比视口小时的合法范围是
|
||||
* `[viewW - contentW, 0]`,而那个上界是**负数**;
|
||||
* 直接用 `coerceIn(viewW - contentW, 0f)` 反而对。
|
||||
* 写反了的表现是"小图能拖到天上去"。
|
||||
*/
|
||||
fun clampPan(
|
||||
x: Float, y: Float,
|
||||
viewW: Float, viewH: Float,
|
||||
contentW: Float, contentH: Float,
|
||||
): Pair<Float, Float> = Pair(
|
||||
x.coerceIn(minOf(0f, viewW - contentW), 0f),
|
||||
y.coerceIn(minOf(0f, viewH - contentH), 0f),
|
||||
)
|
||||
}
|
||||
138
android/nodekit/src/main/java/com/doubao/nodekit/NodeShapes.kt
Normal file
138
android/nodekit/src/main/java/com/doubao/nodekit/NodeShapes.kt
Normal file
@@ -0,0 +1,138 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.geometry.RoundRect
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.PathOperation
|
||||
|
||||
/**
|
||||
* 形状的画法。
|
||||
*
|
||||
* ## 形状即语法(这次是真的落在会议画布上了)
|
||||
*
|
||||
* 积木编辑器里形状一直是语法(帽形 = 事件、C 型 = 容器、六边形 = 真假值)。
|
||||
* 但**会议画布上所有节点都是圆角矩形** —— 用户只能靠标题栏颜色和文字认节点。
|
||||
* 颜色有 13 种,记不住;形状只有 6 种,一眼能认。
|
||||
*
|
||||
* 所以 [NodeShape] 是 [NodeCatalog] 里每种节点的一个字段,这里负责把它画出来。
|
||||
* 用到的两处:
|
||||
*
|
||||
* 1. 「加节点」面板里每个类型前面的**缩略图** —— 选之前就看出这是起点还是判断
|
||||
* 2. 节点卡片标题栏左边的**小徽标** —— 在密密麻麻的图上也能认出来
|
||||
*
|
||||
* ## 为什么形状是"圆角矩形 + 局部变形"而不是纯菱形/纯六边形
|
||||
*
|
||||
* 因为节点卡片里要装东西:标题栏 24 + 引脚行 21×N + 内容 34。
|
||||
* 画成真正的菱形,四个角全是空的,引脚反而没地方放(引脚必须贴在左右边缘上,
|
||||
* 那是连线出发的位置,不能为了形状把线挪走)。
|
||||
*
|
||||
* 所以每种形状都只在**边缘**做变化,中间那块留给内容和引脚:
|
||||
*
|
||||
* Hat 顶部凸一个圆顶 ("这是起点")
|
||||
* Diamond 四角斜切 ("这里分叉")
|
||||
* Loop 左右两端收成尖 ("会回到这里")
|
||||
* Capsule 左右全圆(胶囊) ("它不执行,只提供值")
|
||||
* Terminal 上边两角斜切 ("到这里结束")
|
||||
* Rect 普通圆角矩形 ("普通动作")
|
||||
*/
|
||||
object NodeShapes {
|
||||
|
||||
/** 普通圆角半径 */
|
||||
const val RADIUS = 8f
|
||||
|
||||
/** 斜切量占短边的比例 */
|
||||
private const val CHAMFER = 0.22f
|
||||
|
||||
/**
|
||||
* 画一个形状。
|
||||
*
|
||||
* [w] / [h] 是外接矩形;画出来的东西**不会超出**这个矩形
|
||||
* (除了 [NodeShape.Hat] 的圆顶 —— 它也会被压在里面,只是主体下移)。
|
||||
*/
|
||||
fun path(shape: NodeShape, w: Float, h: Float): Path {
|
||||
if (w <= 0f || h <= 0f) return Path()
|
||||
val cut = minOf(w, h) * CHAMFER
|
||||
return when (shape) {
|
||||
NodeShape.Rect -> roundRectPath(w, h, RADIUS)
|
||||
|
||||
NodeShape.Capsule -> roundRectPath(w, h, minOf(w, h) / 2f)
|
||||
|
||||
// 帽形:下面一个圆角矩形,上面扣一个圆顶(两者求并集)
|
||||
NodeShape.Hat -> {
|
||||
val dome = h * 0.22f
|
||||
val body = roundRectPath(w, h - dome, RADIUS)
|
||||
body.translate(Offset(0f, dome))
|
||||
val cap = Path().apply {
|
||||
addOval(Rect(w * 0.16f, 0f, w * 0.84f, dome * 2f))
|
||||
}
|
||||
// ★ op 会改第一个参数(base)本身,所以先算 base 再传
|
||||
Path().apply {
|
||||
op(body, cap, PathOperation.Union)
|
||||
}
|
||||
}
|
||||
|
||||
// 菱形(其实是四角斜切的矩形,见类注释)
|
||||
NodeShape.Diamond -> polyPath(
|
||||
listOf(
|
||||
Offset(cut, 0f), Offset(w - cut, 0f),
|
||||
Offset(w, cut), Offset(w, h - cut),
|
||||
Offset(w - cut, h), Offset(cut, h),
|
||||
Offset(0f, h - cut), Offset(0f, cut),
|
||||
),
|
||||
)
|
||||
|
||||
// 循环:左右两端收成尖(六边形),"从这里会绕回去"
|
||||
NodeShape.Loop -> polyPath(
|
||||
listOf(
|
||||
Offset(0f, h / 2f),
|
||||
Offset(cut * 1.4f, 0f), Offset(w - cut * 1.4f, 0f),
|
||||
Offset(w, h / 2f),
|
||||
Offset(w - cut * 1.4f, h), Offset(cut * 1.4f, h),
|
||||
),
|
||||
)
|
||||
|
||||
// 终点:上边两角斜切,底部保持圆角("往下收口")
|
||||
NodeShape.Terminal -> polyPath(
|
||||
listOf(
|
||||
Offset(cut, 0f), Offset(w - cut, 0f),
|
||||
Offset(w, cut), Offset(w, h - RADIUS),
|
||||
Offset(w - RADIUS, h), Offset(RADIUS, h),
|
||||
Offset(0f, h - RADIUS), Offset(0f, cut),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩略图路径(加节点面板里用的小图标)。
|
||||
*
|
||||
* 画在 [size] × [size] 的方框里。**方框比形状本身大一圈**,
|
||||
* 这样描边不会贴边被裁掉。
|
||||
*/
|
||||
fun thumbPath(shape: NodeShape, size: Float): Path {
|
||||
val pad = size * 0.10f
|
||||
val inner = size - pad * 2
|
||||
val p = path(shape, inner, inner * 0.82f)
|
||||
p.translate(Offset(pad, pad))
|
||||
return p
|
||||
}
|
||||
|
||||
private fun roundRectPath(w: Float, h: Float, radius: Float): Path = Path().apply {
|
||||
addRoundRect(
|
||||
RoundRect(
|
||||
rect = Rect(0f, 0f, w, h),
|
||||
cornerRadius = CornerRadius(radius, radius),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** 顶点列表 → 闭合多边形。斜切处是硬边(小图标上看不出来,也没必要圆) */
|
||||
private fun polyPath(pts: List<Offset>): Path = Path().apply {
|
||||
if (pts.isEmpty()) return@apply
|
||||
moveTo(pts[0].x, pts[0].y)
|
||||
for (i in 1 until pts.size) lineTo(pts[i].x, pts[i].y)
|
||||
close()
|
||||
}
|
||||
}
|
||||
132
android/nodekit/src/main/java/com/doubao/nodekit/Ops.kt
Normal file
132
android/nodekit/src/main/java/com/doubao/nodekit/Ops.kt
Normal file
@@ -0,0 +1,132 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/**
|
||||
* 一个算子。
|
||||
*
|
||||
* [arity] 是要几个输入引脚(1 = 单目,比如"取反""逻辑非")。
|
||||
*/
|
||||
data class Op(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val inType: String,
|
||||
val outType: String,
|
||||
val arity: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* 算子表(`op` 节点的下拉项)。
|
||||
*
|
||||
* ## ★★ 以前这张表被拆成三份,散在两个文件里
|
||||
*
|
||||
* `MeetingsScreen.kt:3615` `OPS_UI` —— 只有 (键, 名字)
|
||||
* `MeetingsScreen.kt:3643` `opSpec` —— 只有 (入类型, 出类型, 元数)
|
||||
* `android/kernel/meeting.py:207` `OPS` —— 权威的完整表
|
||||
*
|
||||
* 于是加一个算子要改三个地方,而且"名字在 A、类型在 B"这种拆法必然出现
|
||||
* **A 加了 B 忘了** —— 历史上真的发生过:单目运算 `neg` / `not` 引擎里有、
|
||||
* 界面上选不到(原来有个 `scripts/verify-ops.py` 专门抓这个,现在并进
|
||||
* `scripts/verify-nodekit.py` 了 —— 那个脚本会拿这张表和引擎逐项对拍)。
|
||||
*
|
||||
* 现在这里是**唯一一份**,而且每一项都是**原子**的(不会只加一半)。
|
||||
* 守门脚本 `scripts/verify-nodekit.py` 会拿它和 `meeting.py` 的 `OPS` 逐项对拍。
|
||||
*
|
||||
* ★ 顺序就是界面上的显示顺序 —— 分组的空行靠注释表达,别在中间插项,
|
||||
* 要加就加在对应分组的末尾。
|
||||
*/
|
||||
object Ops {
|
||||
/** 和引擎 `meeting.py` 的 `OPS` 一一对应,顺序也一样 */
|
||||
val ALL: List<Op> = listOf(
|
||||
Op("add", "加 +", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("sub", "减 −", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("mul", "乘 ×", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("div", "除 ÷", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("mod", "取余 %", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("concat", "拼接", PinKind.STR, PinKind.STR, 2),
|
||||
Op("eq", "等于 =(数字)", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("ne", "不等于 ≠(数字)", PinKind.NUM, PinKind.BOOL, 2),
|
||||
// ★ 文本相等单独一份:数字相等和文本相等**不是一回事** ——
|
||||
// "01" 和 "1" 作为文本不等、作为数字相等
|
||||
Op("streq", "文本等于 ==", PinKind.STR, PinKind.BOOL, 2),
|
||||
Op("strne", "文本不等于 !=", PinKind.STR, PinKind.BOOL, 2),
|
||||
Op("gt", "大于 >", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("lt", "小于 <", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("gte", "大于等于 ≥", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("lte", "小于等于 ≤", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("neg", "取反(负号)", PinKind.NUM, PinKind.NUM, 1),
|
||||
Op("not", "逻辑非 !", PinKind.BOOL, PinKind.BOOL, 1),
|
||||
// ---- 逻辑运算:两边都是真假,结果也是真假 ----
|
||||
Op("and", "与 and", PinKind.BOOL, PinKind.BOOL, 2),
|
||||
Op("or", "或 or", PinKind.BOOL, PinKind.BOOL, 2),
|
||||
Op("xor", "异或 xor", PinKind.BOOL, PinKind.BOOL, 2),
|
||||
// ---- 位运算:整数才有的操作,结果为数字 ----
|
||||
Op("shl", "左移 <<", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("shr", "右移 >>", PinKind.NUM, PinKind.NUM, 2),
|
||||
// ---- 列表 ----
|
||||
Op("append", "追加到列表", PinKind.LIST, PinKind.LIST, 2),
|
||||
Op("clear", "清空列表", PinKind.LIST, PinKind.LIST, 1),
|
||||
)
|
||||
|
||||
private val BY_KEY: Map<String, Op> = ALL.associateBy { it.key }
|
||||
|
||||
/**
|
||||
* 查一个算子。
|
||||
*
|
||||
* ★ 查不到时**退回加法**(和以前的 `else -> Triple("num","num",2)` 行为一致)——
|
||||
* 老会议里可能有已经删掉的算子名,那时卡片还得画得出来。
|
||||
*/
|
||||
fun of(key: String): Op = BY_KEY[key] ?: BY_KEY.getValue("add")
|
||||
|
||||
/** 显示名。查不到就原样显示那个键(用户至少知道存的是什么) */
|
||||
fun label(key: String): String = BY_KEY[key]?.label ?: key
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换节点的目标类型。
|
||||
*
|
||||
* ★ 含 `list` —— 不然"把列表转成文本"这种最基本的转换做不了。
|
||||
*
|
||||
* ★★ 注意引擎那边的 `CAST_KINDS` **只列了 str / bool / num 三项**(而且全仓库
|
||||
* 没有任何地方读它,是一份死数据)。真正的类型校验在 `_cast_to()` 里,
|
||||
* 用的是 `PIN_TYPES`(**含 list**)。也就是说:引擎行为支持 list,
|
||||
* 只是那份清单没跟上。这里按**行为**写(4 项),那一份也已经补齐。
|
||||
*/
|
||||
object CastKinds {
|
||||
val ALL: List<String> = listOf(PinKind.STR, PinKind.BOOL, PinKind.NUM, PinKind.LIST)
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断节点的条件种类。
|
||||
*
|
||||
* ★★ 这份**必须和引擎的 `JUDGE_KINDS` 逐字一致** —— 判断条件不是"界面自己
|
||||
* 存的字符串",而是引擎按它分派的(`meeting.py` 里有一大段
|
||||
* `if kind == ...`)。界面上多一项,用户选了会在运行时报
|
||||
* "不认识的判断条件";少一项,那个能力就等于没有。
|
||||
*
|
||||
* `ai`(让模型判断)是最后一项,也是最贵的一项 —— 它会真的去调一次模型,
|
||||
* 所以放在最后、措辞上也别鼓励用户首选(能算的就别问模型)。
|
||||
*/
|
||||
object JudgeKinds {
|
||||
val ALL: List<Pair<String, String>> = listOf(
|
||||
"contains" to "包含关键词",
|
||||
"not_contains" to "不包含关键词",
|
||||
"longer_than" to "字数多于",
|
||||
"shorter_than" to "字数少于",
|
||||
"empty" to "为空",
|
||||
"not_empty" to "不为空",
|
||||
"ai" to "让模型判断",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 写变量节点遇到**列表**变量时的两种模式。
|
||||
*
|
||||
* 这是最容易搞混的一处:
|
||||
* · `append` 往里**加一项**(默认)—— "把每个结果都攒起来"要的就是它
|
||||
* · `replace` 整个**换掉**
|
||||
*/
|
||||
object ListModes {
|
||||
val ALL: List<Pair<String, String>> = listOf(
|
||||
"append" to "追加一项",
|
||||
"replace" to "整个覆盖",
|
||||
)
|
||||
}
|
||||
147
android/nodekit/src/main/java/com/doubao/nodekit/Pins.kt
Normal file
147
android/nodekit/src/main/java/com/doubao/nodekit/Pins.kt
Normal file
@@ -0,0 +1,147 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/*
|
||||
* 引脚:类型、定义、以及"算引脚需要知道哪些节点信息"。
|
||||
*
|
||||
* ## 这一层存在的理由
|
||||
*
|
||||
* 引脚类型这件事以前在仓库里有 **5 份**:
|
||||
*
|
||||
* android/kernel/meeting.py PIN_TYPES = ('str','bool','num','list')
|
||||
* server/src/meeting.mjs PIN_TYPES = ['str','bool','num'] ← 缺 list
|
||||
* android/kernel/custom_nodes.py PIN_KINDS = ('exec','str','bool','num','list')
|
||||
* ui/NodeDecl.kt PIN_TYPES_FOR_DECL = [...]
|
||||
* ui/MeetingsScreen.kt ANY_DATA = ["str","bool","num","list"]
|
||||
*
|
||||
* 内容还不一样(Node 那份没有 list,于是"列表变量"在 Web 端根本连不上)。
|
||||
* 现在这里是**唯一一份**,其余地方一律引用它。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 引脚类型。
|
||||
*
|
||||
* 和引擎的 `PIN_TYPES`(`android/kernel/meeting.py`)**必须一字不差** ——
|
||||
* `scripts/verify-nodekit.py` 会去比对,对不上就报错。
|
||||
*/
|
||||
object PinKind {
|
||||
/** 执行引脚:只排顺序、不传数据 */
|
||||
const val EXEC = "exec"
|
||||
const val STR = "str"
|
||||
const val BOOL = "bool"
|
||||
const val NUM = "num"
|
||||
const val LIST = "list"
|
||||
|
||||
/**
|
||||
* 老会议里的 `data` 类型 —— 当 `str` 处理。
|
||||
*
|
||||
* ★ 不能删:第一版会议数据里边上写的就是 `data`,删了老图全部接线失效。
|
||||
*/
|
||||
const val LEGACY_DATA = "data"
|
||||
|
||||
/** 数据引脚的类型(不含 exec)。就是引擎的 `PIN_TYPES`。 */
|
||||
val DATA: List<String> = listOf(STR, BOOL, NUM, LIST)
|
||||
|
||||
/** 什么数据类型都能接的引脚(`accepts = ANY`) */
|
||||
val ANY: List<String> = DATA
|
||||
|
||||
/** 声明一个引脚时能选的类型(含 exec)。自定义节点的声明界面用。 */
|
||||
val DECLARABLE: List<String> = listOf(EXEC, STR, BOOL, NUM, LIST)
|
||||
|
||||
fun label(kind: String): String = when (kind) {
|
||||
EXEC -> "执行"
|
||||
STR -> "文本"
|
||||
BOOL -> "真假"
|
||||
NUM -> "数字"
|
||||
LIST -> "列表"
|
||||
LEGACY_DATA -> "文本"
|
||||
else -> kind
|
||||
}
|
||||
|
||||
/** `文本 str` 这种带英文的写法(选择器里用,用户要能对上引擎里的名字) */
|
||||
fun labelWithKey(kind: String): String = "${label(kind)} $kind"
|
||||
|
||||
/** 显示名字时把老类型归一到新名字 */
|
||||
fun normalize(kind: String): String =
|
||||
if (kind == LEGACY_DATA) STR else kind
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个引脚。
|
||||
*
|
||||
* [accepts] 是"这个入口能接哪些类型",空表示只接自己这种 [kind]。
|
||||
* 为什么要它:`while` 的条件入口只收 `bool` 的话,用户没法把变量(文本)接上去,
|
||||
* 于是给成 `bool + str + num` —— 判断真假由引擎的 `truthy()` 负责。
|
||||
*
|
||||
* [branch] 是 exec 出口的分支名。判断节点的 true/false、while 的 body/done、
|
||||
* 自定义节点的多路出口都是同一套机制:连线时把分支名写进边里,引擎才知道走哪条。
|
||||
*/
|
||||
data class PinSpec(
|
||||
val kind: String,
|
||||
val key: String,
|
||||
val label: String,
|
||||
val accepts: List<String> = emptyList(),
|
||||
val branch: String = "",
|
||||
) {
|
||||
/** 能不能接下 [fromKind] 这条线 */
|
||||
fun accepts_(fromKind: String): Boolean =
|
||||
(if (accepts.isEmpty()) listOf(kind) else accepts).contains(fromKind)
|
||||
|
||||
/** 是不是"什么都能接"的宽入口 */
|
||||
val isAny: Boolean
|
||||
get() = kind != PinKind.EXEC && accepts.containsAll(PinKind.ANY)
|
||||
}
|
||||
|
||||
/** 自定义节点声明里的一个引脚(从内核的 `nodes/` 目录下的 .py 读来的) */
|
||||
data class PinDecl(val name: String, val type: String)
|
||||
|
||||
/**
|
||||
* 一个自定义节点声明的**引脚部分**。
|
||||
*
|
||||
* ★ 只搬引脚,不搬"这个节点叫什么、在哪个文件里" ——
|
||||
* 库只关心"怎么画引脚",别的一概不管(那是使用方的事)。
|
||||
*/
|
||||
data class CustomNodePins(
|
||||
val inputs: List<PinDecl> = emptyList(),
|
||||
val outputs: List<PinDecl> = emptyList(),
|
||||
) {
|
||||
val dataInputs: List<PinDecl> get() = inputs.filter { it.type != PinKind.EXEC }
|
||||
val execOutputs: List<PinDecl> get() = outputs.filter { it.type == PinKind.EXEC }
|
||||
val dataOutputs: List<PinDecl> get() = outputs.filter { it.type != PinKind.EXEC }
|
||||
}
|
||||
|
||||
/**
|
||||
* 算引脚需要的**全部**节点信息。
|
||||
*
|
||||
* ## 为什么不让库直接用使用方的节点类
|
||||
*
|
||||
* 因为那样库就"反向依赖"了使用方 —— 这是库最容易腐化的地方:
|
||||
* 一开始只是读两个字段,后来慢慢开始读 `status`、读 `output`、读主题色,
|
||||
* 最后库和 app 长在一起,换个人根本拿不走。
|
||||
*
|
||||
* 所以库只认这个小结构,使用方自己写一行转换:
|
||||
*
|
||||
* fun MeetingNode.view(varTypes: Map<String, String>) = NodeView(
|
||||
* type = type, op = op, varName = varName, valueType = valueType,
|
||||
* castTo = castTo, customKey = customKey, varTypes = varTypes,
|
||||
* )
|
||||
*
|
||||
* ★ 字段全给默认值,这样"只想画个 value 节点"的人不用写一堆空参数。
|
||||
*/
|
||||
data class NodeView(
|
||||
/** 节点类型,见 [NodeKind] */
|
||||
val type: String,
|
||||
/** 运算节点的算子(`add` / `concat` / …),见 [Ops] */
|
||||
val op: String = "add",
|
||||
/** 写变量 / 读变量引用的变量名 */
|
||||
val varName: String = "",
|
||||
/** 值节点的类型:`str` / `bool` / `num` / `list` */
|
||||
val valueType: String = PinKind.STR,
|
||||
/** 转换节点要转成什么类型 */
|
||||
val castTo: String = PinKind.STR,
|
||||
/** 自定义节点对应哪份声明([custom] 里的 key) */
|
||||
val customKey: String = "",
|
||||
/** 自定义节点的引脚声明(内核里读来的),没有就退回一个宽松默认 */
|
||||
val custom: CustomNodePins? = null,
|
||||
/** 变量登记表:变量名 → 类型。写/读变量的引脚类型按它查 */
|
||||
val varTypes: Map<String, String> = emptyMap(),
|
||||
)
|
||||
230
android/nodekit/src/main/java/com/doubao/nodekit/Specs.kt
Normal file
230
android/nodekit/src/main/java/com/doubao/nodekit/Specs.kt
Normal file
@@ -0,0 +1,230 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/*
|
||||
* 引脚表:每种节点有哪些输入 / 输出引脚。
|
||||
*
|
||||
* ## 从哪搬来的
|
||||
*
|
||||
* 逐字搬自 `MeetingsScreen.kt` 的 `inputPins()`(原 3695 行)和
|
||||
* `outputPins()`(原 3893 行)。搬的时候**没改任何规则** —— 这两张表是
|
||||
* 界面和引擎之间最容易出错的地方,历史上的坑(写变量的 list 入口、
|
||||
* 读变量的 num 出口)全在这里,重写一遍只会把老坑再踩一遍。
|
||||
*
|
||||
* 改的只有两件事:
|
||||
* 1. `node.type` 之类改成 `view.type`(库不认使用方的节点类)
|
||||
* 2. 自定义节点的引脚从 `CustomNodeDef` 改成 [CustomNodePins](只取引脚部分)
|
||||
*
|
||||
* ## ★ 和引擎的关系
|
||||
*
|
||||
* 引擎那边是 `meeting.py` 的 `NODE_DATA_IN` / `NODE_DATA_OUT` 两张字典
|
||||
* **加上** `_data_in_type()` / `_data_out_type()` 两个特判函数。
|
||||
* 界面这边只有一个 when。两边靠 `scripts/verify-nodekit.py` 对拍。
|
||||
*/
|
||||
|
||||
object NodeSpecs {
|
||||
|
||||
/**
|
||||
* 输入引脚(从上到下)。
|
||||
*
|
||||
* ★ **纯节点**(读变量 / 值)没有 exec 入:它们是蓝图里的 Get / 常量,
|
||||
* 不在执行链上,值是被需要的节点运行时拉取的 —— 这就是"读变量只有输出"的真正原因。
|
||||
* ★ 开始事件也没有 exec 入:它是整张图的起点。
|
||||
*/
|
||||
fun inputPins(view: NodeView): List<PinSpec> = when (view.type) {
|
||||
|
||||
NodeKind.CUSTOM -> {
|
||||
val d = view.custom
|
||||
if (d == null) {
|
||||
// 定义还没加载到:给一个宽松默认(不收 exec、一个文本入口),
|
||||
// 免得卡片画不出引脚、用户以为节点坏了
|
||||
listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输入", accepts = PinKind.ANY),
|
||||
)
|
||||
} else {
|
||||
buildList {
|
||||
// 自己声明的 exec 入口(没有就不画 —— 纯数据节点)
|
||||
d.inputs.filter { it.type == PinKind.EXEC }
|
||||
.forEach { add(PinSpec(PinKind.EXEC, "", "▶")) }
|
||||
d.dataInputs.forEach { p ->
|
||||
add(PinSpec(p.type, p.name, p.name, accepts = listOf(p.type)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 分支:收一个真假,走真/假两条 exec
|
||||
NodeKind.BRANCH -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
// 条件收得宽一点:变量和上游多半给的是 "true"/"1" 这类文本
|
||||
PinSpec(PinKind.BOOL, "", "条件", accepts = listOf(PinKind.BOOL, PinKind.STR, PinKind.NUM)),
|
||||
)
|
||||
|
||||
NodeKind.START, NodeKind.READVAR, NodeKind.VALUE -> emptyList()
|
||||
|
||||
// Python 节点:执行节点 —— 上游什么都要能收(它就是拿来处理任意内容的)
|
||||
NodeKind.PY -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输入", accepts = PinKind.ANY),
|
||||
)
|
||||
|
||||
// 转换:什么都收(出口类型在配置面板里选)
|
||||
NodeKind.CAST -> listOf(PinSpec(PinKind.STR, "", "值", accepts = PinKind.ANY))
|
||||
|
||||
// 运算:入口类型由算子决定(加法要数字、拼接要文本),单目只有一个入口
|
||||
NodeKind.OP -> {
|
||||
val key = view.op.ifBlank { "add" }
|
||||
val spec = Ops.of(key)
|
||||
if (spec.arity == 1) {
|
||||
listOf(PinSpec(spec.inType, "a", if (spec.inType == PinKind.NUM) "数" else "值"))
|
||||
} else if (key == "append") {
|
||||
// ★ 追加的第二个入口是"要加进去的东西",**什么类型都行** ——
|
||||
// 往里塞一句话、一个数字、一个真假都对。
|
||||
listOf(
|
||||
PinSpec(PinKind.LIST, "a", "列表"),
|
||||
PinSpec(PinKind.STR, "b", "加什么", accepts = PinKind.ANY),
|
||||
)
|
||||
} else {
|
||||
listOf(
|
||||
PinSpec(spec.inType, "a", "A"),
|
||||
PinSpec(spec.inType, "b", "B"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
NodeKind.WHILE -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
// 条件:bool 最自然,但变量是字符串,所以两种都收(见 PinSpec 注释)
|
||||
PinSpec(PinKind.BOOL, "", "条件", accepts = listOf(PinKind.BOOL, PinKind.STR, PinKind.NUM)),
|
||||
)
|
||||
|
||||
NodeKind.JUDGE -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "值"),
|
||||
)
|
||||
|
||||
// 写变量:入口类型**按变量登记表**,而且**严格**(和读变量的出口对称)。
|
||||
//
|
||||
// 之前写成"不卡类型"是治错了病:让用户难受的不是"卡得严",
|
||||
// 是"接不上还不说为什么"。所以现在:
|
||||
// · 类型跟着变量走(颜色也变,一眼知道这个入口要什么)
|
||||
// · 不匹配就接不上,但**当场弹出说明**告诉他加转换节点
|
||||
NodeKind.VAR -> {
|
||||
val declType = view.varTypes[view.varName] ?: PinKind.STR
|
||||
// ★ 列表变量:入口是 **str**(追加的是"一项内容",不是整个列表)。
|
||||
// 入口写成 list 的话,用户得先拼一个 JSON 数组才能往里加一项 —— 太别扭了。
|
||||
val vt = if (declType == PinKind.LIST) PinKind.STR else declType
|
||||
val vtLabel = if (declType == PinKind.LIST) "追加的文本" else PinKind.label(vt)
|
||||
listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(vt, "", vtLabel, accepts = listOf(vt)),
|
||||
)
|
||||
}
|
||||
|
||||
// ★ end(最终输出)**什么类型都收** —— 引擎那边 NODE_DATA_IN['end']
|
||||
// 就是四种全要。这里写死 str 的话,数字/列表接到最终输出会被界面拒掉。
|
||||
NodeKind.END -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "值", accepts = PinKind.ANY),
|
||||
)
|
||||
|
||||
else -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输入"),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出引脚(从上到下)。
|
||||
*
|
||||
* ★ 判断节点有**两条 exec 出线**(真/假)—— 相当于蓝图里的 Branch。
|
||||
* ★ while 有**两条 exec 出线**(循环体/结束)—— 相当于蓝图里的 While Loop。
|
||||
* ★ 写变量**没有数据出线**(存进去的值不从它往下传),但有 exec 出线。
|
||||
* ★ 纯节点(读变量 / 值 / 运算 / 转换)**只有数据出线**,没有任何 exec 引脚。
|
||||
*/
|
||||
fun outputPins(view: NodeView): List<PinSpec> = when (view.type) {
|
||||
|
||||
NodeKind.CUSTOM -> {
|
||||
val d = view.custom
|
||||
if (d == null) {
|
||||
listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输出"),
|
||||
)
|
||||
} else {
|
||||
buildList {
|
||||
// 多个 exec 出口 = N 路分支,每条一个引脚(名字就是分支名)
|
||||
d.execOutputs.forEach {
|
||||
add(PinSpec(PinKind.EXEC, it.name, it.name, branch = it.name))
|
||||
}
|
||||
d.dataOutputs.forEachIndexed { i, p ->
|
||||
add(
|
||||
PinSpec(
|
||||
p.type,
|
||||
p.name,
|
||||
p.name + if (i > 0) "(接不了线)" else "",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 分支:真 / 假两条 exec 出口
|
||||
NodeKind.BRANCH -> listOf(
|
||||
PinSpec(PinKind.EXEC, "true", "真 ▶"),
|
||||
PinSpec(PinKind.EXEC, "false", "假 ▶"),
|
||||
)
|
||||
|
||||
NodeKind.END -> emptyList()
|
||||
|
||||
// ★ 读变量的出口类型**必须按变量登记表**,不能写死 str。
|
||||
//
|
||||
// 写死 str 的后果:一个 num 变量 → 读变量 → 运算 的线**接不上**
|
||||
// (运算的 num 入口只收 num,而读变量声称自己给 str)。
|
||||
// 引擎那边 _data_out_type 本来就是对的做法,界面这份是漏了
|
||||
// —— 用户报的"运算为啥不给数字类型连"就是这个。
|
||||
NodeKind.READVAR -> listOf(
|
||||
PinSpec(view.varTypes[view.varName] ?: PinKind.STR, "", "值"),
|
||||
)
|
||||
|
||||
// Python 节点:执行节点,交出文本
|
||||
NodeKind.PY -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输出"),
|
||||
)
|
||||
|
||||
// 转换:出口类型就是它要转成的那个类型
|
||||
NodeKind.CAST -> listOf(PinSpec(view.castTo.ifBlank { PinKind.STR }, "", "值"))
|
||||
|
||||
// 运算:出口类型由算子决定(加法出数字、比较出真假)
|
||||
NodeKind.OP -> listOf(PinSpec(Ops.of(view.op.ifBlank { "add" }).outType, "", "结果"))
|
||||
|
||||
// 值节点的类型由它自己选 —— 这决定了它能接到哪去
|
||||
NodeKind.VALUE -> listOf(
|
||||
PinSpec(view.valueType.ifBlank { PinKind.STR }, "", "值"),
|
||||
)
|
||||
|
||||
NodeKind.JUDGE -> listOf(
|
||||
PinSpec(PinKind.EXEC, "true", "真 ▶"),
|
||||
PinSpec(PinKind.EXEC, "false", "假 ▶"),
|
||||
)
|
||||
|
||||
NodeKind.WHILE -> listOf(
|
||||
PinSpec(PinKind.EXEC, "body", "循环体 ▶"),
|
||||
PinSpec(PinKind.EXEC, "done", "结束 ▶"),
|
||||
)
|
||||
|
||||
NodeKind.VAR -> listOf(PinSpec(PinKind.EXEC, "", "▶"))
|
||||
|
||||
NodeKind.START -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输出"),
|
||||
)
|
||||
|
||||
else -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输出"),
|
||||
)
|
||||
}
|
||||
}
|
||||
85
android/nodekit/src/main/java/com/doubao/nodekit/Styles.kt
Normal file
85
android/nodekit/src/main/java/com/doubao/nodekit/Styles.kt
Normal file
@@ -0,0 +1,85 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/**
|
||||
* 引脚 / 连线的配色。
|
||||
*
|
||||
* ★ 全部是 `Int`(ARGB)。库不依赖 Compose,渲染方自己转:
|
||||
*
|
||||
* Color(NodeStyles.pinColor(pin.kind))
|
||||
*
|
||||
* ## 为什么颜色要集中在这
|
||||
*
|
||||
* 以前这几个颜色常量散在 `MeetingsScreen.kt` 里,同一个绿写了 6 遍
|
||||
* (`0xFF34A853` 出现在 nodeColor、pinColor、画连线、结果界面…),
|
||||
* 而且**语义相同的两个值写法不同**:
|
||||
*
|
||||
* pinColor("exec") = 0xFFECEFF1 EXEC_COLOR = 0xFFE8EAED ← 两个"白"
|
||||
* nodeColor("start") = 0xFF34A853 画线时的"真"分支 = 0xFF34A853
|
||||
*
|
||||
* 改一个忘一个的表现是"同一个意思两种颜色",肉眼很难发现。
|
||||
*/
|
||||
object NodeStyles {
|
||||
|
||||
/** 执行引脚:白。它不传值,所以是"无色"的 —— 和彩色数据引脚形成对比 */
|
||||
const val EXEC_FILL = 0xFFECEFF1.toInt()
|
||||
|
||||
/** 执行引脚的描边(描在白引脚外面,浅色背景下才看得见) */
|
||||
const val EXEC_BORDER = 0xFF5F6368.toInt()
|
||||
|
||||
/** 能接任何类型的引脚:紫。**一眼看出"这个入口不挑"** */
|
||||
const val ANY_FILL = 0xFF9C27B0.toInt()
|
||||
|
||||
/** 认不出的类型:灰 */
|
||||
const val UNKNOWN_FILL = 0xFF9AA0A6.toInt()
|
||||
|
||||
/** 数据引脚按类型上色 */
|
||||
fun pinColor(kind: String): Int = when (kind) {
|
||||
PinKind.EXEC -> EXEC_FILL
|
||||
PinKind.STR -> 0xFF34A853.toInt()
|
||||
PinKind.NUM -> 0xFF1A73E8.toInt()
|
||||
PinKind.BOOL -> 0xFFE53935.toInt()
|
||||
PinKind.LIST -> 0xFFF9A825.toInt()
|
||||
// 老会议里没有 kind 字段的数据线,一律当文本
|
||||
PinKind.LEGACY_DATA -> 0xFF34A853.toInt()
|
||||
else -> UNKNOWN_FILL
|
||||
}
|
||||
|
||||
/**
|
||||
* 按**引脚**算颜色(而不是只看 kind):收全部类型的引脚是紫的。
|
||||
*
|
||||
* ★ 为什么不能只看 kind:`end` / `py` / `cast` 的入口 kind 是 `str`,
|
||||
* 但它们**什么都收** —— 画成绿色的话用户以为只能连文本进来。
|
||||
*/
|
||||
fun pinColorOf(pin: PinSpec): Int =
|
||||
if (pin.isAny) ANY_FILL else pinColor(pin.kind)
|
||||
|
||||
/** 引脚的描边色 */
|
||||
fun pinBorder(kind: String): Int =
|
||||
if (kind == PinKind.EXEC) EXEC_BORDER else pinColor(kind)
|
||||
|
||||
fun pinBorderOf(pin: PinSpec): Int =
|
||||
if (pin.kind == PinKind.EXEC) EXEC_BORDER else pinColorOf(pin)
|
||||
|
||||
/**
|
||||
* 一条 exec 出线的颜色。
|
||||
*
|
||||
* ★ 真/假分支用绿/红是**刻意**的:这两条线在画布上并排走,
|
||||
* 颜色一样的话用户根本分不清哪条是"条件成立"。
|
||||
* 其他 exec 出口(body/done/自定义分支)用统一的描边色。
|
||||
*/
|
||||
fun execWireColor(key: String): Int = when (key) {
|
||||
"true" -> 0xFF34A853.toInt()
|
||||
"false" -> 0xFFEA4335.toInt()
|
||||
"body" -> 0xFF4C97FF.toInt()
|
||||
"done" -> 0xFF5F6368.toInt()
|
||||
else -> EXEC_BORDER
|
||||
}
|
||||
|
||||
/** 一条连线的颜色(数据线按类型,exec 线按分支) */
|
||||
fun wireColor(pin: PinSpec): Int =
|
||||
if (pin.kind == PinKind.EXEC) execWireColor(pin.key) else pinColorOf(pin)
|
||||
|
||||
/** 运行状态:正在跑 / 出错 / 正常。使用方拿它给卡片描边 */
|
||||
const val RUNNING = 0xFF1A73E8.toInt()
|
||||
const val ERROR = 0xFFD93025.toInt()
|
||||
}
|
||||
@@ -16,3 +16,5 @@ dependencyResolutionManagement {
|
||||
|
||||
rootProject.name = "DoubaoLynxClone"
|
||||
include(":app")
|
||||
// 会议节点定义库(节点类型 / 引脚 / 算子 / 几何 / 形状)—— 见 nodekit/,文档 docs/节点库.md
|
||||
include(":nodekit")
|
||||
|
||||
254
android/termux-dpkg/README.md
Normal file
254
android/termux-dpkg/README.md
Normal file
@@ -0,0 +1,254 @@
|
||||
# 自编 dpkg —— 让内置 Termux 和真 Termux 能共存
|
||||
|
||||
这个目录里的东西,是为了把 **dpkg + apt 替成我们自己编的**,
|
||||
从而解决一个从根上无解的冲突。
|
||||
|
||||
---
|
||||
|
||||
## 要解决什么问题
|
||||
|
||||
内置 Termux 的二进制全部来自 Termux 官方仓库,它们是拿
|
||||
`--sysconfdir=$PREFIX/etc` 编的,而 `$PREFIX` 在**编译期**就固化成了
|
||||
|
||||
```
|
||||
/data/data/com.termux/files/usr
|
||||
```
|
||||
|
||||
于是在装了真 Termux 的手机上,我们的 `pkg install` 必死:
|
||||
|
||||
```
|
||||
dpkg: error: error opening configuration directory
|
||||
'/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
|
||||
E: Sub-process /data/user/0/com.doubao.lynxclone/files/usr/bin/dpkg returned an error code (2)
|
||||
```
|
||||
|
||||
**为什么绕不过去**(这些都实测过,不是推测):
|
||||
|
||||
| 试过的办法 | 为什么不行 |
|
||||
|---|---|
|
||||
| `--admindir` / `--instdir` / `--root` | 配置目录是**编译期常量**,跟 admindir 无关 |
|
||||
| `DPKG_ROOT` 等环境变量 | 上游没有这种变量(`strings dpkg \| grep '^DPKG_'` 里没有) |
|
||||
| `LD_PRELOAD=libtermux-exec.so` | 它只拦 `execve`,不碰 `opendir` |
|
||||
| 在 prefix 里造软链 | 软链只对**相对我们前缀**的路径有效;dpkg 走的是根下的绝对路径 |
|
||||
| 在 `/data/data` 下建 `com.termux` 软链 | `/data/data` 是 `drwxrwx--x system`,我们建不了 |
|
||||
| `unshare -m` + `mount --bind` | 应用没有 `CAP_SYS_ADMIN`,`Operation not permitted` |
|
||||
| 直接改二进制里的路径串 | 21 字节 → 40 字节,长度不等,改了就崩(`scripts/verify-elf-patch.py` 钉死了这条) |
|
||||
|
||||
关键细节:**dpkg 在解析命令行之前就去读配置目录**(上游维护者的原话:
|
||||
*"the config files are read before the options are parsed"*)。
|
||||
配置目录 `ENOENT` 是静默跳过,`EACCES` 直接致命退出 —— 真 Termux 的
|
||||
`/data/data/com.termux` 是 `0700`、属于另一个 UID,我们连穿都穿不进去。
|
||||
|
||||
所以唯一干净的出路是:**自己编一个**,把那一处换成运行时解析。
|
||||
|
||||
---
|
||||
|
||||
## 自编版改了什么
|
||||
|
||||
一共九处补丁,都在 `patches/doubao/`(由 `make-doubao-patches.py` 生成):
|
||||
|
||||
### 1. 配置目录改成运行时解析(核心)
|
||||
|
||||
上游 `lib/dpkg/options.c` 里只有**两处**用到编译期常量 `CONFIGDIR`。
|
||||
自编版换成一个函数,从 `/proc/self/exe` 反推前缀:
|
||||
|
||||
```
|
||||
/proc/self/exe = /data/user/0/<包名>/files/usr/bin/dpkg
|
||||
~~~~ 去掉 /bin/dpkg
|
||||
/data/user/0/<包名>/files/usr
|
||||
→ 配置目录 = <prefix>/etc/dpkg
|
||||
```
|
||||
|
||||
同一个二进制在任何包名下都指向**自己所在的前缀**,不需要为每个包名编一份。
|
||||
还留了 `DOUBAO_DPKG_PREFIX` 环境变量做显式覆盖(测试用)。
|
||||
|
||||
### 2. 架构名用 Termux 的写法
|
||||
|
||||
这条是**实测撞出来的**:Termux 仓库里包的 `Architecture` 字段是
|
||||
`x86_64` / `aarch64` / `arm` / `i686`(就是 GNU CPU 名),
|
||||
而 Debian 那边是 `amd64` / `arm64`。
|
||||
|
||||
用错名字的后果很大:dpkg 会把数据库里**每一个包**都判成
|
||||
|
||||
```
|
||||
'x86_64' is not a valid architecture name in 'Architecture' field:
|
||||
character '_' not allowed (only letters, digits and characters '-')
|
||||
```
|
||||
|
||||
而且 `x86_64` 带下划线,上游的架构名校验(C 侧 `lib/dpkg/arch.c`
|
||||
和 Perl 侧 `scripts/Dpkg/Arch.pm`)**两处都不让过**,所以两边都要放开。
|
||||
|
||||
`dpkg-architecture` 那边还绕了一下:上游的 `data/ostable` 里**根本没有
|
||||
`android` 这个操作系统**,所以 `*-linux-android` 这种三元组永远解析不出来,
|
||||
configure 会报 `cannot determine host dpkg architecture`。
|
||||
自编版在 `m4/dpkg-arch.m4` 里直接从 `$host_cpu` 取值。
|
||||
|
||||
> 顺带一个坑:`--host=x86_64-linux-android` 会被 `config.sub`
|
||||
> 规范化成 `x86_64-pc-linux-android`,所以 `$host_os` 是
|
||||
> **`linux-android`**,不是 `android`。匹配要写 `*android*`。
|
||||
|
||||
### 3. 修好 PATH 和 `LD_LIBRARY_PATH`
|
||||
|
||||
apt 派生 dpkg 时会**清洗环境**,塞给它一个指向**另一个 App 前缀**的 PATH
|
||||
(实录:`PATH=[/data/data/com.termux/files/usr/bin]`)。dpkg 于是报:
|
||||
|
||||
```
|
||||
dpkg: warning: 'sh' not found in PATH or not executable
|
||||
dpkg: error: 5 expected programs not found in PATH or not executable
|
||||
```
|
||||
|
||||
自编版在 `dpkg_options_load()` 之后(也就是任何 `checkpath()` 之前)
|
||||
按自己的前缀把 PATH / `LD_LIBRARY_PATH` 补上。
|
||||
|
||||
### 4. 改写维护脚本里的前缀
|
||||
|
||||
Termux 包的维护脚本整篇都是 Termux 前缀:
|
||||
|
||||
```sh
|
||||
#!/data/data/com.termux/files/usr/bin/sh
|
||||
mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_${a}_key"
|
||||
```
|
||||
|
||||
- 第一行由**内核**解析,落在另一个 App 的私有目录 → EACCES,
|
||||
而 dpkg 会把它显示成"脚本没有执行权限",**指错方向**
|
||||
- 后面那些是**根下的绝对路径**,我们的沙箱软链拦不住
|
||||
|
||||
脚本是纯文本,所以自编版在 exec 之前把 `DOUBAO_OLD_PREFIX` 换成自己的前缀。
|
||||
三条执行路径(`vmaintscript_installed` / `maintscript_new` /
|
||||
`maintscript_fallback`)都要挂上 —— 只挂一处的话 `--configure` 那条路
|
||||
(走的正是 `vmaintscript_installed`)不会有任何效果。
|
||||
|
||||
改完之后的实录:
|
||||
|
||||
```
|
||||
Setting up openssh (10.6p1-2) ...
|
||||
Generating public/private rsa key pair.
|
||||
Generating public/private ecdsa key pair.
|
||||
Generating public/private ed25519 key pair.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 怎么构建
|
||||
|
||||
```bash
|
||||
# 1. 下源码(依赖库 + termux-packages + dpkg)
|
||||
bash fetch-sources.sh /root/tb
|
||||
|
||||
# 2. 编依赖(libmd / zlib / bzip2 / liblzma / libzstd,给两个架构都来一遍)
|
||||
bash build-deps.sh x86_64
|
||||
bash build-deps.sh arm64
|
||||
|
||||
# 3. 编 dpkg
|
||||
bash build-dpkg.sh x86_64
|
||||
bash build-dpkg.sh arm64
|
||||
|
||||
# 4. 校验(每一条都对应一个真踩过的坑)
|
||||
python3 verify-dpkg.py x86_64
|
||||
python3 verify-dpkg.py arm64
|
||||
|
||||
# 5. 打包成 jniLibs 里的 .so
|
||||
bash make-jnilibs.sh /root/tb ../app/src/main/jniLibs
|
||||
```
|
||||
|
||||
需要的环境变量(都有默认值):
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| `ANDROID_NDK` | `/root/tb/android-ndk-r27c` | NDK 根目录 |
|
||||
| `TERMUX_DPKG_WORK` | `/root/tb` | 工作目录 |
|
||||
| `TERMUX_DPKG_SRC` | `$WORK/src/dpkg` | dpkg 源码(**必须 git checkout**) |
|
||||
| `DOUBAO_PREFIX` | `com.doubao.lynxclone` 的前缀 | 编译进二进制的兜底前缀 |
|
||||
|
||||
改了 `make-doubao-patches.py` 之后要重新生成补丁:
|
||||
|
||||
```bash
|
||||
python3 make-doubao-patches.py /root/tb/src/dpkg patches/doubao
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 几个构建上的坑
|
||||
|
||||
**dpkg 源码必须是 git checkout。** 它的 `build-aux/get-version` 要用 git
|
||||
(或发行 tarball)定版本号,`git archive` 出来的树会让 `autogen` 报
|
||||
`cannot get project version`。构建脚本用 `git worktree` 解决(共享 `.git`,
|
||||
树是干净的,还能随手删掉重来)。
|
||||
|
||||
**补丁不要手写。** hunk 头(`@@ -55,6 +55,22 @@`)的行号必须和源码逐字对上,
|
||||
手数极容易错 —— 我错过两次:一次少一行 `malformed patch`,
|
||||
一次多一行把紧跟的 `DPKG_OS_TYPE` 吃掉了,而 **patch 两种都不报错**,
|
||||
只是行为诡异。所以补丁一律用 `diff -u` 从"改好的文件"生成。
|
||||
|
||||
**依赖库全部静态链进去。** 只有 `libmd` 是硬依赖(`readelf -d` 显示
|
||||
Termux 的 dpkg 只 NEEDED `libmd.so` + `libc.so`,zlib/bz2/lzma/zstd 都是
|
||||
可选),全静态链进去就不依赖运行时环境。
|
||||
|
||||
**RUNPATH 要烧进 ELF。** dpkg 会 exec 出 `dpkg-query` / `dpkg-deb`
|
||||
这些辅助程序,那些进程不一定继承到 `LD_LIBRARY_PATH`:
|
||||
|
||||
```
|
||||
-Wl,-rpath,$PREFIX/lib -Wl,--enable-new-dtags
|
||||
```
|
||||
|
||||
**xz 的 configure 会在 CFLAGS 上做 `-Werror` 试编译**,而
|
||||
`-D__ANDROID_API__=24` 会触发它的告警,于是它误判 CFLAGS 有问题直接退出。
|
||||
加 `SKIP_WERROR_CHECK=yes` 跳过。
|
||||
|
||||
**`dpkg-realpath` 是 shell 脚本不是 ELF**,strip 会失败,忽略即可。
|
||||
|
||||
---
|
||||
|
||||
## 怎么打进 APK
|
||||
|
||||
`make-jnilibs.sh` 把六个程序打成一个 **tar 包**,改名成
|
||||
`lib/<abi>/libdoubao-dpkg.so`。
|
||||
|
||||
为什么不放 `assets/`:Android 安装 APK 时只对 `lib/<abi>/*.so`
|
||||
免压缩解包,别的路径会被压缩、还得自己再解一遍。
|
||||
这也跟这个仓库里 `libtermux-bootstrap.so` 的做法一致。
|
||||
|
||||
Kotlin 侧的解包在 `TermuxInstaller.installOwnDpkg()`,是手写的 ustar 读取
|
||||
(只认普通文件、拒绝带斜杠的名字),为了这点事不值得引一个 tar 库。
|
||||
|
||||
装好之后 **`bin/dpkg.real` + wrapper 那一套就不需要了** ——
|
||||
wrapper 本来就是在绕"配置目录编译死"这个我们已经从根上修掉的问题。
|
||||
|
||||
---
|
||||
|
||||
## 校验脚本守什么
|
||||
|
||||
`verify-dpkg.py` 守的每一条都对应一个踩过的坑:
|
||||
|
||||
1. 六个程序齐全、架构正确
|
||||
2. 二进制里的 `com.termux` 字符串**只允许**是重写函数自己要匹配的模式 ——
|
||||
出现别的(尤其是配置目录)就说明补丁没生效,装上必然 EACCES
|
||||
3. 有 `/proc/self/exe`(运行时前缀的前提)
|
||||
4. 不能出现 `amd64` / `arm64`(Termux 用 GNU CPU 名)
|
||||
5. 源码里架构名校验放开了下划线
|
||||
6. RUNPATH 指向前缀 `lib`
|
||||
7. 不依赖 `libmd.so`(已静态链入)
|
||||
|
||||
---
|
||||
|
||||
## 实测结果(Android 14 x86_64 模拟器,**真 Termux 同时装着**)
|
||||
|
||||
真 Termux 的目录权限一直是 `drwx------ u0_a109`,我们全程读不到它。
|
||||
|
||||
```
|
||||
$ pkg install -y openssh
|
||||
...
|
||||
Setting up openssh (10.6p1-2) ...
|
||||
Generating public/private rsa key pair.
|
||||
Generating public/private ecdsa key pair.
|
||||
Generating public/private ed25519 key pair.
|
||||
|
||||
$ dpkg -l | grep -c '^i[^i]' # 未配置项
|
||||
0
|
||||
$ ssh -V
|
||||
OpenSSH_10.6p1, OpenSSL 3.4.1 11 Feb 2025
|
||||
```
|
||||
|
||||
另外验证过的:`nmap`、`git 2.56.0` 全新安装(含 `lua54` / `libpcap` /
|
||||
`openssh` 这些带 postinst 的依赖链)全部 `未配置 = 0`。
|
||||
126
android/termux-dpkg/build-deps.sh
Normal file
126
android/termux-dpkg/build-deps.sh
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/bin/bash
|
||||
# 为 Android 交叉编译 dpkg 需要的静态库
|
||||
#
|
||||
# 用法: build-deps.sh <arch> arch = x86_64 | arm64
|
||||
#
|
||||
# 需要的环境变量(都有默认值,默认是开发机上的位置):
|
||||
# ANDROID_NDK NDK 根目录
|
||||
# TERMUX_DPKG_WORK 工作目录(下载源码、解包、编译中间产物都放这里)
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-deps.sh x86_64|arm64}"
|
||||
|
||||
NDK="${ANDROID_NDK:-/root/tb/android-ndk-r27c}"
|
||||
WORK="${TERMUX_DPKG_WORK:-/root/tb}"
|
||||
SRC="$WORK/dl"
|
||||
OUT="$WORK/out/$ARCH"
|
||||
API="${ANDROID_API:-24}"
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ;;
|
||||
*) echo "未知 arch: $ARCH(支持 x86_64 / arm64)"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
export LDFLAGS=""
|
||||
|
||||
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; echo " 设一下 ANDROID_NDK"; exit 1; }
|
||||
echo "### arch=$ARCH CC=$CC"
|
||||
"$CC" --version | head -1
|
||||
|
||||
mkdir -p "$OUT/lib" "$OUT/include" "$WORK/work"
|
||||
cd "$WORK/work"
|
||||
|
||||
# 每个库都单独判断,编过就跳过,方便断点续编
|
||||
need() { [ ! -f "$OUT/lib/$1" ]; }
|
||||
|
||||
########################################
|
||||
# libmd 1.3.0 —— dpkg 唯一必需的第三方库
|
||||
########################################
|
||||
if need libmd.a; then
|
||||
echo "=== libmd ==="
|
||||
rm -rf libmd-1.3.0 && tar xf "$SRC/libmd.tar.xz"
|
||||
cd libmd-1.3.0
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static >/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
"$STRIP" --strip-unneeded "$OUT/lib/libmd.a" 2>/dev/null || true
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libmd.a" ] && echo " ✓ libmd" || echo " ✗ libmd 失败"
|
||||
|
||||
########################################
|
||||
# zlib
|
||||
########################################
|
||||
if need libz.a; then
|
||||
echo "=== zlib ==="
|
||||
rm -rf zlib-1.3.2 && tar xf "$SRC/zlib.tar.gz"
|
||||
cd zlib-1.3.2
|
||||
CHOST="$TRIPLE" ./configure --static --prefix="$OUT" >/dev/null 2>&1
|
||||
make -j"$(nproc)" libz.a >/dev/null 2>&1
|
||||
cp libz.a "$OUT/lib/" && cp zlib.h zconf.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libz.a" ] && echo " ✓ zlib" || echo " ✗ zlib 失败"
|
||||
|
||||
########################################
|
||||
# bzip2 1.0.8
|
||||
########################################
|
||||
if need libbz2.a; then
|
||||
echo "=== bzip2 ==="
|
||||
rm -rf bzip2-1.0.8 && tar xf "$SRC/bzip2.tar.gz"
|
||||
cd bzip2-1.0.8
|
||||
make -j"$(nproc)" libbz2.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
|
||||
CFLAGS="$CFLAGS -D_FILE_OFFSET_BITS=64" >/dev/null 2>&1
|
||||
cp libbz2.a "$OUT/lib/" && cp bzlib.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libbz2.a" ] && echo " ✓ bzip2" || echo " ✗ bzip2 失败"
|
||||
|
||||
########################################
|
||||
# liblzma (xz)
|
||||
########################################
|
||||
if need liblzma.a; then
|
||||
echo "=== liblzma ==="
|
||||
rm -rf xz-5.8.4 && tar xf "$SRC/xz.tar.xz"
|
||||
cd xz-5.8.4
|
||||
# SKIP_WERROR_CHECK: xz 的 configure 会用 -Werror 试编译,而
|
||||
# -D__ANDROID_API__=24 会触发它的告警,导致它误判 CFLAGS 有问题
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static \
|
||||
--disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo \
|
||||
--disable-scripts --disable-doc --disable-nls \
|
||||
SKIP_WERROR_CHECK=yes \
|
||||
>/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/liblzma.a" ] && echo " ✓ liblzma" || echo " ✗ liblzma 失败"
|
||||
|
||||
########################################
|
||||
# libzstd
|
||||
########################################
|
||||
if need libzstd.a; then
|
||||
echo "=== libzstd ==="
|
||||
rm -rf zstd-1.5.7 && tar xf "$SRC/zstd.tar.gz"
|
||||
cd zstd-1.5.7/lib
|
||||
make -j"$(nproc)" libzstd.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
|
||||
CFLAGS="$CFLAGS" >/dev/null 2>&1
|
||||
cp libzstd.a "$OUT/lib/"
|
||||
cp zstd.h zstd_errors.h zdict.h "$OUT/include/" 2>/dev/null || true
|
||||
cd ../..
|
||||
fi
|
||||
[ -f "$OUT/lib/libzstd.a" ] && echo " ✓ libzstd" || echo " ✗ libzstd 失败"
|
||||
|
||||
echo
|
||||
echo "=== $ARCH 产物 ==="
|
||||
ls -la "$OUT/lib/"*.a
|
||||
149
android/termux-dpkg/build-dpkg.sh
Normal file
149
android/termux-dpkg/build-dpkg.sh
Normal file
@@ -0,0 +1,149 @@
|
||||
#!/bin/bash
|
||||
# 为 Android 交叉编译 dpkg(用 Termux 的补丁 + 我们自己的运行时前缀补丁)
|
||||
#
|
||||
# 用法: build-dpkg.sh <arch> arch = x86_64 | arm64
|
||||
#
|
||||
# 环境变量(都有默认值):
|
||||
# ANDROID_NDK NDK 根目录
|
||||
# TERMUX_DPKG_WORK 工作目录
|
||||
# TERMUX_DPKG_SRC dpkg 源码目录(必须是 git checkout)
|
||||
# DOUBAO_PREFIX 编译进二进制的兜底前缀(运行时会被 /proc/self/exe 覆盖)
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-dpkg.sh x86_64|arm64}"
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
NDK="${ANDROID_NDK:-/root/tb/android-ndk-r27c}"
|
||||
WORK="${TERMUX_DPKG_WORK:-/root/tb}"
|
||||
SRC="${TERMUX_DPKG_SRC:-$WORK/src/dpkg}"
|
||||
DEPS="$WORK/out/$ARCH"
|
||||
OUT="$WORK/out/$ARCH"
|
||||
API="${ANDROID_API:-24}"
|
||||
PREFIX="${DOUBAO_PREFIX:-/data/data/com.doubao.lynxclone/files/usr}"
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ;;
|
||||
*) echo "未知 arch: $ARCH(支持 x86_64 / arm64)"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
export CPPFLAGS="-I$DEPS/include"
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
# RUNPATH:dpkg 会 exec 出 dpkg-query / dpkg-deb 等辅助程序,那些进程不一定
|
||||
# 继承到 LD_LIBRARY_PATH,所以把库搜索路径烧进 ELF 里,不依赖环境变量。
|
||||
export LDFLAGS="-L$DEPS/lib -static-libgcc -Wl,-rpath,$PREFIX/lib -Wl,--enable-new-dtags"
|
||||
export LIBS="-lmd -lz -lbz2 -llzma -lzstd"
|
||||
|
||||
BUILD="$WORK/build/dpkg-$ARCH"
|
||||
mkdir -p "$WORK/build" "$BUILD"
|
||||
|
||||
echo "########## 0. 检查前提 ##########"
|
||||
[ -d "$SRC/.git" ] || { echo "!! $SRC 不是 git checkout(dpkg 的 get-version 要求)"; exit 1; }
|
||||
[ -f "$DEPS/lib/libmd.a" ] || { echo "!! 先跑 build-deps.sh $ARCH"; exit 1; }
|
||||
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; exit 1; }
|
||||
echo " src=$SRC"
|
||||
echo " 前缀=$PREFIX"
|
||||
|
||||
echo "########## 1. 准备源码树 ##########"
|
||||
# 不能把源码复制出来就完事 —— dpkg 的 build-aux/get-version 需要一个真正的
|
||||
# git checkout(或发行 tarball)才能定出版本号。用 git worktree:共享 .git,
|
||||
# 树是干净的,而且可以随时删掉重来。
|
||||
cd "$SRC"
|
||||
git worktree remove --force "$BUILD" 2>/dev/null || true
|
||||
rm -rf "$BUILD"
|
||||
git worktree add --detach --force "$BUILD" HEAD >/dev/null 2>&1 || {
|
||||
echo "git worktree 失败"; exit 1; }
|
||||
cd "$BUILD"
|
||||
echo " worktree 就绪: $(pwd)"
|
||||
|
||||
apply() { # apply <补丁文件> [必需]
|
||||
local p="$1" must="${2:-}"
|
||||
local n; n=$(basename "$p")
|
||||
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
|
||||
echo " ✓ $n"
|
||||
else
|
||||
echo " ✗ $n"
|
||||
patch -p1 -N -l -i "$p" 2>&1 | head -15
|
||||
[ -n "$must" ] && exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
echo "########## 2. Termux 上游补丁 ##########"
|
||||
for p in "$HERE"/patches/termux/*.patch; do apply "$p"; done
|
||||
|
||||
echo "########## 3. 我们自己的补丁 ##########"
|
||||
for p in "$HERE"/patches/doubao/*.patch; do apply "$p" required; done
|
||||
|
||||
echo "########## 4. autogen ##########"
|
||||
# dpkg 的构建脚本叫 autogen(没后缀,也没可执行位)
|
||||
if [ ! -x configure ] || [ ! -f Makefile.in ]; then
|
||||
NOCONFIGURE=1 sh ./autogen > "$BUILD/autogen.log" 2>&1 || {
|
||||
echo "autogen 失败,尾部:"; tail -30 "$BUILD/autogen.log"; exit 1; }
|
||||
fi
|
||||
echo " configure 就绪"
|
||||
|
||||
echo "########## 5. configure ##########"
|
||||
# PERL: 宿主机 perl 版本可能低于 dpkg 要求的 5.32.1。perl 只用于构建期脚本
|
||||
# (dpkg-architecture 之类),跟我们真正要的 C 程序无关,所以直接告诉它
|
||||
# perl 在哪,跳过版本探测。
|
||||
#
|
||||
# --bindir / --libdir 指到 Termux 前缀:dpkg 会用 BINDIR 去找它的辅助程序
|
||||
# (dpkg -l 实际是转给 dpkg-query 执行),用 LIBDIR 去找 libdpkg 的数据。
|
||||
./configure \
|
||||
--host="$TRIPLE" \
|
||||
--build="$(uname -m)-pc-linux-gnu" \
|
||||
--prefix="$PREFIX" \
|
||||
--bindir="$PREFIX/bin" \
|
||||
--libdir="$PREFIX/lib" \
|
||||
--sysconfdir="$PREFIX/etc" \
|
||||
--localstatedir="$PREFIX/var" \
|
||||
--disable-shared \
|
||||
--disable-dselect \
|
||||
--disable-start-stop-daemon \
|
||||
--disable-update-alternatives \
|
||||
--disable-largefile \
|
||||
--disable-nls \
|
||||
--without-selinux \
|
||||
--without-libselinux \
|
||||
--without-systemd \
|
||||
PERL="${PERL:-$(command -v perl)}" \
|
||||
ac_cv_lib_selinux_setexecfilecon=no \
|
||||
dpkg_cv_c99_snprintf=yes \
|
||||
DPKG_PAGER=pager \
|
||||
> "$BUILD/configure.log" 2>&1 || {
|
||||
echo "configure 失败,尾部:"; tail -40 "$BUILD/configure.log"; exit 1; }
|
||||
echo " ✓ configure 通过"
|
||||
|
||||
echo "########## 6. make ##########"
|
||||
make -j"$(nproc)" > "$BUILD/make.log" 2>&1 || {
|
||||
echo "make 失败,错误摘要:"
|
||||
grep -nE 'error:|Error [0-9]' "$BUILD/make.log" | head -30
|
||||
exit 1; }
|
||||
echo " ✓ make 通过"
|
||||
|
||||
echo "########## 7. 收集产物 ##########"
|
||||
mkdir -p "$OUT/dpkg-bin"
|
||||
for b in dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger; do
|
||||
f=""
|
||||
for cand in "src/dpkg/main/.libs/$b" "src/dpkg/deb/.libs/$b" \
|
||||
"src/dpkg/split/.libs/$b" "src/dpkg/query/.libs/$b" \
|
||||
"src/dpkg/divert/.libs/$b" "src/dpkg/trigger/.libs/$b" \
|
||||
"src/.libs/$b" "src/main/.libs/$b" "utils/.libs/$b" \
|
||||
"src/$b" "src/main/$b" "utils/$b"; do
|
||||
[ -f "$cand" ] && { f="$cand"; break; }
|
||||
done
|
||||
if [ -z "$f" ]; then echo " ? 找不到 $b"; continue; fi
|
||||
cp "$f" "$OUT/dpkg-bin/$b"
|
||||
"$STRIP" "$OUT/dpkg-bin/$b" 2>/dev/null || echo " ! strip 失败: $b"
|
||||
done
|
||||
|
||||
echo
|
||||
ls -la "$OUT/dpkg-bin/"
|
||||
echo
|
||||
echo "产物在 $OUT/dpkg-bin/"
|
||||
29
android/termux-dpkg/extract-termux-patches.sh
Normal file
29
android/termux-dpkg/extract-termux-patches.sh
Normal file
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# 从 termux-packages 里把 dpkg 的上游补丁抽到本仓库。
|
||||
#
|
||||
# 为什么要把它们拷进仓库:build-dpkg.sh 依赖这批补丁才能让 dpkg 在 Android 上
|
||||
# 跑起来(Android 不支持硬链接、应用没有 chown 权限、不允许 root 检查……)。
|
||||
# 直接引用 termux-packages 的 checkout 会让构建依赖一个会随时变化的 master,
|
||||
# 所以拷一份固定下来。
|
||||
#
|
||||
# 用法: extract-termux-patches.sh [termux-packages 路径]
|
||||
set -eu
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
TP="${1:-${TERMUX_DPKG_WORK:-/root/tb}/termux-packages}"
|
||||
SRCDIR="$TP/packages/dpkg"
|
||||
DST="$HERE/patches/termux"
|
||||
|
||||
[ -d "$SRCDIR" ] || { echo "!! 找不到 $SRCDIR"; echo " 先跑 fetch-sources.sh"; exit 1; }
|
||||
|
||||
mkdir -p "$DST"
|
||||
cd "$SRCDIR"
|
||||
for f in *.patch; do
|
||||
[ -f "$f" ] || continue
|
||||
cp "$f" "$DST/termux-$f"
|
||||
printf ' %s\n' "termux-$f"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "已拷到 $DST:"
|
||||
ls -la "$DST"
|
||||
76
android/termux-dpkg/fetch-sources.sh
Normal file
76
android/termux-dpkg/fetch-sources.sh
Normal file
@@ -0,0 +1,76 @@
|
||||
#!/bin/bash
|
||||
# 下载构建 dpkg 需要的全部源码。
|
||||
#
|
||||
# 用法: fetch-sources.sh [工作目录]
|
||||
#
|
||||
# 说明几个源的选择:
|
||||
# - GitHub 在部分网络下连不上,但 codeload.github.com 通常可以,
|
||||
# 所以 termux-packages 走 codeload 的 tarball 接口。
|
||||
# - dpkg 源码必须在 git 仓库里(build-aux/get-version 依赖它来判断版本号),
|
||||
# 所以从 salsa.debian.org 克隆。
|
||||
# - 依赖库都从 Debian 镜像取 orig.tar,避免各上游站点可达性不一致。
|
||||
set -eu
|
||||
|
||||
WORK="${1:-${TERMUX_DPKG_WORK:-/root/tb}}"
|
||||
DL="$WORK/dl"
|
||||
SRC="$WORK/src"
|
||||
mkdir -p "$DL" "$SRC"
|
||||
|
||||
# -4:WSL 里 packages.termux.dev 会解析出 IPv6,而那条路不通,curl 会卡住
|
||||
CURL="curl -4 -fsSL --retry 3 --retry-delay 3"
|
||||
|
||||
get() { # get <文件名> <url...> 依次尝试,成功即止
|
||||
local name="$1"; shift
|
||||
if [ -s "$DL/$name" ]; then echo " 已有 $name"; return 0; fi
|
||||
local u
|
||||
for u in "$@"; do
|
||||
if $CURL -o "$DL/$name" "$u" 2>/dev/null; then
|
||||
printf ' ✓ %-22s %s 字节\n' "$name" "$(stat -c%s "$DL/$name")"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
printf ' ✗ %-22s 全部源都失败\n' "$name"
|
||||
return 1
|
||||
}
|
||||
|
||||
TUNA=https://mirrors.tuna.tsinghua.edu.cn/debian/pool/main
|
||||
DEB=https://deb.debian.org/debian/pool/main
|
||||
|
||||
echo "=== 依赖库源码 ==="
|
||||
get libmd.tar.xz "$DEB/libm/libmd/libmd_1.3.0.orig.tar.xz" \
|
||||
"$TUNA/libm/libmd/libmd_1.3.0.orig.tar.xz"
|
||||
get zlib.tar.gz "https://zlib.net/zlib-1.3.2.tar.gz" \
|
||||
"$TUNA/z/zlib/zlib_1.3.2.orig.tar.gz"
|
||||
get bzip2.tar.gz "https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz" \
|
||||
"$TUNA/b/bzip2/bzip2_1.0.8.orig.tar.gz"
|
||||
get xz.tar.xz "https://tukaani.org/xz/xz-5.8.4.tar.xz" \
|
||||
"$TUNA/x/xz-utils/xz-utils_5.8.4.orig.tar.xz"
|
||||
get zstd.tar.gz "https://codeload.github.com/facebook/zstd/tar.gz/refs/tags/v1.5.7"
|
||||
|
||||
echo
|
||||
echo "=== Termux 的 dpkg 补丁(从 termux-packages 抽) ==="
|
||||
TP="$WORK/termux-packages"
|
||||
if [ ! -d "$TP/packages/dpkg" ]; then
|
||||
echo " 拉 termux-packages…"
|
||||
$CURL -o "$DL/tp.tar.gz" \
|
||||
"https://codeload.github.com/termux/termux-packages/tar.gz/refs/heads/master"
|
||||
rm -rf "$TP"
|
||||
tar xzf "$DL/tp.tar.gz" -C "$WORK"
|
||||
mv "$WORK/termux-packages-master" "$TP"
|
||||
fi
|
||||
echo " termux-packages: $TP"
|
||||
ls "$TP/packages/dpkg/" | head -20
|
||||
|
||||
echo
|
||||
echo "=== dpkg 源码(必须 git checkout) ==="
|
||||
if [ ! -d "$SRC/dpkg/.git" ]; then
|
||||
echo " 克隆 dpkg 1.22.6…"
|
||||
timeout 900 git clone --depth 1 --branch 1.22.6 \
|
||||
https://salsa.debian.org/dpkg-team/dpkg.git "$SRC/dpkg"
|
||||
fi
|
||||
echo " dpkg: $(cd "$SRC/dpkg" && git log --oneline -1)"
|
||||
|
||||
echo
|
||||
echo "全部就绪。接下来:"
|
||||
echo " bash build-deps.sh x86_64 # 或 arm64"
|
||||
echo " bash build-dpkg.sh x86_64"
|
||||
659
android/termux-dpkg/make-doubao-patches.py
Normal file
659
android/termux-dpkg/make-doubao-patches.py
Normal file
@@ -0,0 +1,659 @@
|
||||
#!/usr/bin/env python3
|
||||
"""生成"我们自己"的 dpkg 补丁。
|
||||
|
||||
为什么要单独一个脚本生成补丁,而不是把补丁直接写死在仓库里:
|
||||
|
||||
补丁的 hunk 头(`@@ -55,6 +55,22 @@`)里的行号必须和 dpkg 源码逐字对上,
|
||||
手写极容易数错——我就在这上面栽过两次,一次少写一行导致 `malformed patch`,
|
||||
一次多写一行把紧跟的 `DPKG_OS_TYPE` 吃掉了,而 patch 两个都不报错、
|
||||
只是行为诡异。
|
||||
|
||||
所以这里的做法是:从 git 取出原始文件,用 Python 做结构化的文本替换,
|
||||
再用 `diff -u` 生成补丁。diff 产出的 hunk 头永远是对的。
|
||||
|
||||
用法:
|
||||
python3 make-doubao-patches.py <dpkg源码目录> [输出目录]
|
||||
|
||||
需要 dpkg 源码是一个 git checkout(dpkg 自己的 build-aux/get-version 也要求如此)。
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
|
||||
SRC = os.path.abspath(sys.argv[1])
|
||||
OUT = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)), "patches", "doubao")
|
||||
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
|
||||
def git_show(rel):
|
||||
r = subprocess.run(["git", "show", "HEAD:" + rel], cwd=SRC,
|
||||
capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
raise SystemExit(f"git show HEAD:{rel} 失败:{r.stderr.strip()}")
|
||||
return r.stdout
|
||||
|
||||
|
||||
def write_patch(rel, old, new, name):
|
||||
"""old -> new 的补丁,路径写成 a/<rel> b/<rel>,供 patch -p1 使用。"""
|
||||
a = os.path.join(tempfile.mkdtemp(), "a")
|
||||
b = os.path.join(tempfile.mkdtemp(), "b")
|
||||
open(a, "w").write(old)
|
||||
open(b, "w").write(new)
|
||||
r = subprocess.run(["diff", "-u", a, b], capture_output=True, text=True)
|
||||
body = r.stdout.replace(a, "a/" + rel, 1).replace(b, "b/" + rel, 1)
|
||||
path = os.path.join(OUT, name)
|
||||
open(path, "w").write(body)
|
||||
print(f" → {name} ({len(body.splitlines())} 行)")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. 头文件
|
||||
# ======================================================================
|
||||
HEADER = '''/*
|
||||
* doubao-prefix.h - resolve the installation prefix at runtime
|
||||
*
|
||||
* Copyright (C) 2026 doubao-clone
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 2 of the License, or
|
||||
* (at your option) any later version.
|
||||
*/
|
||||
|
||||
#ifndef DOUBAO_PREFIX_H
|
||||
#define DOUBAO_PREFIX_H
|
||||
|
||||
#include <dpkg/dpkg.h>
|
||||
|
||||
DPKG_BEGIN_DECLS
|
||||
|
||||
/**
|
||||
* Return the prefix this dpkg was installed under.
|
||||
*
|
||||
* The prefix is derived from the path of the running executable, because
|
||||
* Android hands every application its own private data directory and the
|
||||
* same binary has to work under any of them. Falls back to the compile-time
|
||||
* DOUBAO_DEFAULT_PREFIX when the executable path cannot be determined.
|
||||
*/
|
||||
const char *doubao_prefix(void);
|
||||
|
||||
/**
|
||||
* Return the configuration directory ($prefix/etc/dpkg).
|
||||
*/
|
||||
const char *doubao_config_dir(void);
|
||||
|
||||
/**
|
||||
* Prepend our own bin directories to PATH and point LD_LIBRARY_PATH at our
|
||||
* own lib directory.
|
||||
*
|
||||
* Needed because apt sanitises the environment before it execs dpkg, and the
|
||||
* PATH it hands over names the *other* application's prefix; dpkg would then
|
||||
* fail its own sanity check with "expected programs not found in PATH".
|
||||
*/
|
||||
void doubao_fix_environment(void);
|
||||
|
||||
/**
|
||||
* Rewrite a maintainer script's interpreter line so it points at this
|
||||
* installation instead of the application it was built for.
|
||||
*/
|
||||
void doubao_fix_script_shebang(const char *path);
|
||||
|
||||
DPKG_END_DECLS
|
||||
|
||||
#endif /* DOUBAO_PREFIX_H */
|
||||
'''
|
||||
|
||||
# ======================================================================
|
||||
# 2. 实现
|
||||
# ======================================================================
|
||||
IMPL = r'''/*
|
||||
* doubao-prefix.c - resolve the installation prefix at runtime
|
||||
*
|
||||
* Copyright (C) 2026 doubao-clone
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 2 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Upstream dpkg bakes its configuration directory in at configure time
|
||||
* (-DCONFIGDIR), and Termux builds it as $PREFIX/etc/dpkg where $PREFIX is a
|
||||
* fixed absolute path chosen by the Termux application. Android gives every
|
||||
* application its own private data directory, so a dpkg built for
|
||||
* com.termux will always look inside /data/data/com.termux -- a directory
|
||||
* another application is not allowed to traverse. The resulting EACCES makes
|
||||
* dpkg abort before it has even parsed its command line, which is why the two
|
||||
* applications cannot coexist.
|
||||
*
|
||||
* We instead derive the prefix from the path of the running executable, which
|
||||
* is exactly where this binary happens to live. That also lets us repair
|
||||
* PATH, LD_LIBRARY_PATH and the interpreter lines of maintainer scripts,
|
||||
* all of which upstream assumes are already correct.
|
||||
*/
|
||||
|
||||
#include <config.h>
|
||||
#include <compat.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <dpkg/i18n.h>
|
||||
#include <dpkg/debug.h>
|
||||
#include <dpkg/dpkg.h>
|
||||
#include <dpkg/doubao-prefix.h>
|
||||
|
||||
/* How many distinct strings we keep alive so returned pointers stay valid. */
|
||||
#define DOUBAO_CACHE_SLOTS 4
|
||||
|
||||
static char prefix_buf[PATH_MAX];
|
||||
static const char *prefix_cached;
|
||||
static char config_buf[PATH_MAX];
|
||||
|
||||
static void
|
||||
doubao_prefix_resolve(void)
|
||||
{
|
||||
char self[PATH_MAX];
|
||||
const char *override;
|
||||
char *slash;
|
||||
ssize_t n;
|
||||
|
||||
if (prefix_cached != NULL)
|
||||
return;
|
||||
|
||||
prefix_cached = DOUBAO_DEFAULT_PREFIX;
|
||||
|
||||
override = getenv("DOUBAO_DPKG_PREFIX");
|
||||
if (override != NULL) {
|
||||
if (*override != '\0' && strlen(override) < sizeof(prefix_buf)) {
|
||||
strcpy(prefix_buf, override);
|
||||
prefix_cached = prefix_buf;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
n = readlink("/proc/self/exe", self, sizeof(self) - 1);
|
||||
if (n <= 0 || (size_t)n >= sizeof(self) - 1)
|
||||
return;
|
||||
self[n] = '\0';
|
||||
|
||||
/* .../bin/dpkg -> .../bin -> ... */
|
||||
slash = strrchr(self, '/');
|
||||
if (slash == NULL)
|
||||
return;
|
||||
*slash = '\0';
|
||||
|
||||
slash = strrchr(self, '/');
|
||||
if (slash == NULL)
|
||||
return;
|
||||
*slash = '\0';
|
||||
|
||||
if (strlen(self) < sizeof(prefix_buf)) {
|
||||
strcpy(prefix_buf, self);
|
||||
prefix_cached = prefix_buf;
|
||||
}
|
||||
}
|
||||
|
||||
const char *
|
||||
doubao_prefix(void)
|
||||
{
|
||||
doubao_prefix_resolve();
|
||||
return prefix_cached;
|
||||
}
|
||||
|
||||
const char *
|
||||
doubao_config_dir(void)
|
||||
{
|
||||
const char *prefix = doubao_prefix();
|
||||
|
||||
if (snprintf(config_buf, sizeof(config_buf), "%s/etc/dpkg", prefix)
|
||||
>= (int)sizeof(config_buf))
|
||||
return CONFIGDIR;
|
||||
|
||||
return config_buf;
|
||||
}
|
||||
|
||||
/*
|
||||
* Prepend our own bin directories to PATH and make sure the loader can find
|
||||
* our shared libraries, so that dpkg and the maintainer scripts it runs work
|
||||
* no matter what environment our parent handed us.
|
||||
*/
|
||||
void
|
||||
doubao_fix_environment(void)
|
||||
{
|
||||
static bool done = false;
|
||||
static char pathbuf[4 * PATH_MAX];
|
||||
static char libbuf[PATH_MAX + 64];
|
||||
|
||||
const char *prefix, *old;
|
||||
size_t len;
|
||||
|
||||
if (done)
|
||||
return;
|
||||
done = true;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
|
||||
old = getenv("PATH");
|
||||
/* Only prepend when our prefix is not already the first entry, so that
|
||||
* a re-exec does not keep growing PATH. */
|
||||
len = strlen(prefix);
|
||||
if (old == NULL || strncmp(old, prefix, len) != 0 ||
|
||||
strncmp(old + len, "/bin:", 5) != 0) {
|
||||
if (snprintf(pathbuf, sizeof(pathbuf), "%s/bin:%s/bin/applets:%s",
|
||||
prefix, prefix, old != NULL ? old : "/system/bin")
|
||||
< (int)sizeof(pathbuf))
|
||||
setenv("PATH", pathbuf, 1);
|
||||
}
|
||||
|
||||
if (snprintf(libbuf, sizeof(libbuf), "%s/lib",
|
||||
prefix) < (int)sizeof(libbuf))
|
||||
setenv("LD_LIBRARY_PATH", libbuf, 1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Maintainer scripts inside a Termux package are written in terms of the
|
||||
* Termux prefix:
|
||||
*
|
||||
* #!/data/data/com.termux/files/usr/bin/sh
|
||||
* mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
* KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_rsa_key"
|
||||
*
|
||||
* Neither form works for us. The interpreter line is resolved by the kernel
|
||||
* and lands in another application's private directory (EACCES, which dpkg
|
||||
* then reports as though the script itself were not executable), and the
|
||||
* absolute paths are absolute -- our sandbox symlinks live under our own
|
||||
* prefix and cannot intercept a path that starts at "/".
|
||||
*
|
||||
* The scripts are plain text, so rewrite both before executing them. This is
|
||||
* a local edit of the dpkg database rather than a change to the package, so
|
||||
* it also covers packages installed long after this code was written.
|
||||
*/
|
||||
#define DOUBAO_OLD_PREFIX "/data/data/com.termux/files/usr"
|
||||
|
||||
static void
|
||||
doubao_rewrite_script(const char *path)
|
||||
{
|
||||
char *buf;
|
||||
char *out;
|
||||
const char *prefix;
|
||||
size_t oldlen = sizeof(DOUBAO_OLD_PREFIX) - 1;
|
||||
size_t newlen, len, cap;
|
||||
size_t i, o;
|
||||
int fd;
|
||||
ssize_t n;
|
||||
struct stat st;
|
||||
|
||||
if (path == NULL)
|
||||
return;
|
||||
|
||||
fd = open(path, O_RDONLY);
|
||||
if (fd < 0)
|
||||
return;
|
||||
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
|
||||
st.st_size > 1024 * 1024) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
len = (size_t)st.st_size;
|
||||
buf = malloc(len + 1);
|
||||
if (buf == NULL) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
n = read(fd, buf, len);
|
||||
close(fd);
|
||||
if (n <= 0) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
buf[n] = '\0';
|
||||
len = (size_t)n;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
newlen = strlen(prefix);
|
||||
|
||||
/* 先看有没有要换的东西,没有就别写盘 */
|
||||
for (i = 0; i + oldlen <= len; i++) {
|
||||
if (memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0)
|
||||
break;
|
||||
}
|
||||
if (i + oldlen > len) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
|
||||
/* 每一步替换都会变长(我们的前缀比 Termux 的长),所以要放大缓冲 */
|
||||
cap = len + 64;
|
||||
out = malloc(cap);
|
||||
if (out == NULL) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
|
||||
for (i = 0, o = 0; i < len; ) {
|
||||
if (i + oldlen <= len &&
|
||||
memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0) {
|
||||
if (o + newlen + (len - i) + 2 > cap) {
|
||||
cap = (o + newlen + (len - i) + 2) * 2;
|
||||
out = realloc(out, cap);
|
||||
if (out == NULL) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
}
|
||||
memcpy(out + o, prefix, newlen);
|
||||
o += newlen;
|
||||
i += oldlen;
|
||||
} else {
|
||||
out[o++] = buf[i++];
|
||||
}
|
||||
}
|
||||
out[o] = '\0';
|
||||
free(buf);
|
||||
|
||||
fd = open(path, O_WRONLY | O_TRUNC);
|
||||
if (fd < 0) {
|
||||
free(out);
|
||||
return;
|
||||
}
|
||||
if (write(fd, out, o) != (ssize_t)o) {
|
||||
close(fd);
|
||||
free(out);
|
||||
ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
}
|
||||
close(fd);
|
||||
free(out);
|
||||
|
||||
debug(dbg_scripts, "rewrote prefix in maintainer script '%s'", path);
|
||||
}
|
||||
|
||||
/*
|
||||
* 把维护脚本的 shebang 换成本安装自己的 shell。
|
||||
*
|
||||
* 保留原来用的是哪个 shell(`sh` 还是 `bash`)—— 换错解释器会毁掉脚本,
|
||||
* 这一条真踩过:把 `bin/pip`(Python 脚本)的 shebang 改成 bash,
|
||||
* 于是报 `bin/pip: line 2: import: command not found`。
|
||||
* 规则是"只换路径,不动解释器"。
|
||||
*/
|
||||
void
|
||||
doubao_fix_script_shebang(const char *path)
|
||||
{
|
||||
static const char old_shebang[] = "#!/data/data/com.termux/files/usr/";
|
||||
/* Android 上 /data/user/0/<pkg> 和 /data/data/<pkg> 是同一个目录的两种
|
||||
* 写法,包里两种都出现过,所以两个都要认。 */
|
||||
static const char old_shebang_alt[] = "#!/data/user/0/com.termux/files/usr/";
|
||||
|
||||
char buf[PATH_MAX + 256];
|
||||
const char *prefix;
|
||||
char *nl;
|
||||
int fd;
|
||||
ssize_t n;
|
||||
ssize_t skip = -1;
|
||||
size_t head, rest, total;
|
||||
char *fixed;
|
||||
|
||||
if (path == NULL)
|
||||
return;
|
||||
|
||||
/* 先把正文里的绝对路径改掉(`#!/...` 那行也会一起被改到) */
|
||||
doubao_rewrite_script(path);
|
||||
|
||||
fd = open(path, O_RDONLY);
|
||||
if (fd < 0)
|
||||
return;
|
||||
|
||||
n = read(fd, buf, sizeof(buf) - 1);
|
||||
close(fd);
|
||||
if (n <= 0)
|
||||
return;
|
||||
buf[n] = '\0';
|
||||
|
||||
if (strncmp(buf, old_shebang, sizeof(old_shebang) - 1) == 0)
|
||||
skip = (ssize_t)(sizeof(old_shebang) - 1);
|
||||
else if (strncmp(buf, old_shebang_alt, sizeof(old_shebang_alt) - 1) == 0)
|
||||
skip = (ssize_t)(sizeof(old_shebang_alt) - 1);
|
||||
|
||||
if (skip < 0)
|
||||
return;
|
||||
|
||||
nl = strchr(buf, '\n');
|
||||
if (nl == NULL)
|
||||
return;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
head = 2 + strlen(prefix) + 1; /* "#!/" + prefix + "/" */
|
||||
rest = (size_t)n - (size_t)skip; /* 旧前缀之后的一直到文件尾 */
|
||||
total = head + rest;
|
||||
if (total + 1 > sizeof(buf))
|
||||
return;
|
||||
|
||||
fixed = malloc(total + 1);
|
||||
if (fixed == NULL)
|
||||
return;
|
||||
|
||||
fixed[0] = '#';
|
||||
fixed[1] = '!';
|
||||
memcpy(fixed + 2, prefix, strlen(prefix));
|
||||
fixed[2 + strlen(prefix)] = '/';
|
||||
memcpy(fixed + head, buf + skip, rest);
|
||||
fixed[total] = '\0';
|
||||
|
||||
fd = open(path, O_WRONLY | O_TRUNC);
|
||||
if (fd < 0) {
|
||||
free(fixed);
|
||||
return;
|
||||
}
|
||||
if (write(fd, fixed, total) != (ssize_t)total)
|
||||
ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
close(fd);
|
||||
free(fixed);
|
||||
|
||||
debug(dbg_scripts, "rewrote interpreter line of '%s'", path);
|
||||
}
|
||||
'''
|
||||
|
||||
write_patch("lib/dpkg/doubao-prefix.h", "", HEADER, "doubao-prefix-h.patch")
|
||||
write_patch("lib/dpkg/doubao-prefix.c", "", IMPL, "doubao-prefix-c.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 3. Makefile.am:加入源文件 + 定义兜底前缀
|
||||
# ======================================================================
|
||||
ma = git_show("lib/dpkg/Makefile.am")
|
||||
out, added_src, added_def = [], False, False
|
||||
for ln in ma.split("\n"):
|
||||
out.append(ln)
|
||||
if not added_src and ln.strip() == "utils.c \\":
|
||||
out.append("\tdoubao-prefix.c \\")
|
||||
added_src = True
|
||||
if not added_def and ln.strip().startswith("-DDEFAULT_TEXT_DOMAIN="):
|
||||
# 兜底前缀:正常由 /proc/self/exe 推导,这行只是推导失败时的退路
|
||||
out.append("\t-DDOUBAO_DEFAULT_PREFIX=\\\"$(prefix)\\\" \\")
|
||||
added_def = True
|
||||
assert added_src and added_def, "Makefile.am 结构变了,插入点找不到"
|
||||
new_ma = "\n".join(out)
|
||||
if "\tdpkg.h \\" in new_ma:
|
||||
new_ma = new_ma.replace("\tdpkg.h \\", "\tdpkg.h \\\n\tdoubao-prefix.h \\", 1)
|
||||
write_patch("lib/dpkg/Makefile.am", ma, new_ma, "doubao-prefix-makefile.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 4. options.c:配置目录改为运行时解析
|
||||
# ======================================================================
|
||||
oc = git_show("lib/dpkg/options.c")
|
||||
new_oc = oc.replace("#include <dpkg/options.h>\n",
|
||||
"#include <dpkg/options.h>\n#include <dpkg/doubao-prefix.h>\n", 1)
|
||||
assert new_oc != oc, "options.c 里插入 include 失败"
|
||||
new_oc = new_oc.replace('dirname = str_fmt("%s/%s.cfg.d", CONFIGDIR, prog);',
|
||||
'dirname = str_fmt("%s/%s.cfg.d", doubao_config_dir(), prog);', 1)
|
||||
new_oc = new_oc.replace('file = str_fmt("%s/%s.cfg", CONFIGDIR, prog);',
|
||||
'file = str_fmt("%s/%s.cfg", doubao_config_dir(), prog);', 1)
|
||||
assert "CONFIGDIR" not in new_oc, "options.c 里还有 CONFIGDIR 残留"
|
||||
write_patch("lib/dpkg/options.c", oc, new_oc, "doubao-prefix-options.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 5. main.c:启动时修好 PATH
|
||||
# ======================================================================
|
||||
mc = git_show("src/main/main.c")
|
||||
new_mc = mc.replace(
|
||||
" dpkg_options_load(DPKG, cmdinfos);\n",
|
||||
" dpkg_options_load(DPKG, cmdinfos);\n"
|
||||
"\n"
|
||||
" /* Another Android application may have handed us a PATH that points at\n"
|
||||
" * its own prefix; repair ours before anything looks a program up. */\n"
|
||||
" doubao_fix_environment();\n", 1)
|
||||
assert new_mc != mc, "main.c 里插入 doubao_fix_environment 失败"
|
||||
assert '#include "main.h"' in new_mc, "main.c 里找不到 main.h"
|
||||
new_mc = new_mc.replace('#include "main.h"',
|
||||
'#include "main.h"\n\n#include <dpkg/doubao-prefix.h>', 1)
|
||||
write_patch("src/main/main.c", mc, new_mc, "doubao-prefix-main.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 6. script.c:三条执行路径都修 shebang
|
||||
# ======================================================================
|
||||
sc = git_show("src/main/script.c")
|
||||
FIX = """ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
* the Termux prefix; on Android that path belongs to another
|
||||
* application and the kernel refuses to exec it. Point it at us. */
|
||||
doubao_fix_script_shebang(%s);
|
||||
|
||||
"""
|
||||
targets = [
|
||||
(" if (stat(scriptpath, &stab)) {\n command_destroy(&cmd);\n", "scriptpath"),
|
||||
(" if (stat(cidir, &stab)) {\n command_destroy(&cmd);\n", "cidir"),
|
||||
(" if (stat(oldscriptpath, &stab)) {\n", "oldscriptpath"),
|
||||
]
|
||||
new_sc, total = sc, 0
|
||||
for needle, arg in targets:
|
||||
cnt = new_sc.count(needle)
|
||||
assert cnt > 0, f"script.c 里找不到 {arg} 的 stat 块"
|
||||
new_sc = new_sc.replace(needle, (FIX % arg) + needle)
|
||||
total += cnt
|
||||
print(f" script.c {arg}: {cnt} 处")
|
||||
assert total >= 3, f"script.c 只修了 {total} 处,至少该有 3 处"
|
||||
new_sc = new_sc.replace('#include "main.h"',
|
||||
'#include "main.h"\n\n#include <dpkg/doubao-prefix.h>', 1)
|
||||
write_patch("src/main/script.c", sc, new_sc, "doubao-prefix-script.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 7. 架构名:Termux 用的是 GNU CPU 名(x86_64 / aarch64 / arm / i686)
|
||||
# ======================================================================
|
||||
am = git_show("m4/dpkg-arch.m4")
|
||||
OLD_ARCH = """AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
_DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
], [
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
])# DPKG_ARCHITECTURE"""
|
||||
|
||||
NEW_ARCH = """AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
dnl Termux/Android: data/cputable, data/ostable and data/tupletable only
|
||||
dnl describe the Debian and GNU worlds -- ostable has no "android" entry at
|
||||
dnl all -- so the generic lookup below can never resolve a *-linux-android
|
||||
dnl host triple and configure dies with "cannot determine host dpkg
|
||||
dnl architecture".
|
||||
dnl
|
||||
dnl Termux names its architectures after the GNU CPU name (the repository
|
||||
dnl serves x86_64, aarch64, arm and i686), and the package database shipped
|
||||
dnl in our bootstrap was written with exactly those names, so we have to
|
||||
dnl report the same thing or dpkg would reject every installed package.
|
||||
dnl
|
||||
dnl Note the host OS arrives as "linux-android", not "android": config.sub
|
||||
dnl normalises --host=x86_64-linux-android into x86_64-pc-linux-android.
|
||||
AS_CASE([$host_os],
|
||||
[*android*], [
|
||||
AS_CASE([$host_cpu],
|
||||
[x86_64|aarch64|i686|arm], [dpkg_arch=$host_cpu],
|
||||
[armv7*], [dpkg_arch=arm],
|
||||
[AC_MSG_ERROR([unsupported Android CPU: $host_cpu])])
|
||||
cpu_type=$host_cpu
|
||||
os_type=android
|
||||
have_dpkg_arch=yes
|
||||
])
|
||||
AS_IF([test "x$have_dpkg_arch" = "xyes"], [
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
], [
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
_DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
], [
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
])# DPKG_ARCHITECTURE"""
|
||||
|
||||
assert OLD_ARCH in am, "m4/dpkg-arch.m4 里找不到 DPKG_ARCHITECTURE 宏体"
|
||||
write_patch("m4/dpkg-arch.m4", am, am.replace(OLD_ARCH, NEW_ARCH, 1),
|
||||
"doubao-android-arch.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 8. 架构名校验:x86_64 / aarch64 带下划线,两边都要放开
|
||||
# ======================================================================
|
||||
ac = git_show("lib/dpkg/arch.c")
|
||||
OLD_VAL = """\tif (!c_isalnum(*p))
|
||||
\t\treturn _("must start with an alphanumeric");
|
||||
\twhile (*++p != '\\0')
|
||||
\t\tif (!c_isalnum(*p) && *p != '-')
|
||||
\t\t\tbreak;
|
||||
\tif (*p == '\\0')
|
||||
\t\treturn NULL;
|
||||
|
||||
\tsnprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
\t "letters, digits and characters '%s')"),
|
||||
\t *p, "-");
|
||||
\treturn buf;"""
|
||||
NEW_VAL = """\t/* Termux/Android: Termux names its architectures after the GNU CPU
|
||||
\t * name, and two of the four it serves -- x86_64 and aarch64 -- carry an
|
||||
\t * underscore. Without this every package in the bootstrap database
|
||||
\t * would be reported as having an invalid Architecture. */
|
||||
\tif (!c_isalnum(*p))
|
||||
\t\treturn _("must start with an alphanumeric");
|
||||
\twhile (*++p != '\\0')
|
||||
\t\tif (!c_isalnum(*p) && *p != '-' && *p != '_')
|
||||
\t\t\tbreak;
|
||||
\tif (*p == '\\0')
|
||||
\t\treturn NULL;
|
||||
|
||||
\tsnprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
\t "letters, digits and characters '%s')"),
|
||||
\t *p, "-_");
|
||||
\treturn buf;"""
|
||||
assert OLD_VAL in ac, "lib/dpkg/arch.c 里找不到 dpkg_arch_name_is_illegal 函数体"
|
||||
write_patch("lib/dpkg/arch.c", ac, ac.replace(OLD_VAL, NEW_VAL, 1),
|
||||
"doubao-arch-name.patch")
|
||||
|
||||
ap = git_show("scripts/Dpkg/Arch.pm")
|
||||
OLD_RE = " my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9-]*/;"
|
||||
NEW_RE = (" # Termux/Android: allow underscores, because Termux names\n"
|
||||
" # architectures after the GNU CPU name and x86_64 / aarch64\n"
|
||||
" # both contain one.\n"
|
||||
" my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9_-]*/;")
|
||||
assert OLD_RE in ap, "scripts/Dpkg/Arch.pm 里找不到架构名正则"
|
||||
write_patch("scripts/Dpkg/Arch.pm", ap, ap.replace(OLD_RE, NEW_RE, 1),
|
||||
"doubao-debarch-name.patch")
|
||||
|
||||
print("\n全部生成到 " + OUT)
|
||||
53
android/termux-dpkg/make-jnilibs.sh
Normal file
53
android/termux-dpkg/make-jnilibs.sh
Normal file
@@ -0,0 +1,53 @@
|
||||
#!/bin/bash
|
||||
# 把编好的 dpkg 打包成 jniLibs 里的 libdoubao-dpkg.so。
|
||||
#
|
||||
# 为什么打成 tar 再改名成 .so:
|
||||
# Android 安装 APK 时只对 lib/<abi>/*.so 免压缩解包,别的路径(assets/)
|
||||
# 会被压缩、还得自己解压一遍。打成 tar 塞进 .so 里,安装完直接读就行,
|
||||
# 也跟这个仓库里 libtermux-bootstrap.so 的做法一致。
|
||||
#
|
||||
# 用法: make-jnilibs.sh <工作目录> <输出 jniLibs 目录>
|
||||
set -eu
|
||||
|
||||
WORK="${1:-${TERMUX_DPKG_WORK:-/root/tb}}"
|
||||
JNI="${2:?用法: make-jnilibs.sh <工作目录> <jniLibs 目录>}"
|
||||
|
||||
PROGRAMS="dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger"
|
||||
|
||||
# APK 的 abi 目录名跟我们的 arch 名不一样
|
||||
declare -A ABI=( [x86_64]=x86_64 [arm64]=arm64-v8a )
|
||||
|
||||
for arch in x86_64 arm64; do
|
||||
src="$WORK/out/$arch/dpkg-bin"
|
||||
abi="${ABI[$arch]}"
|
||||
dst="$JNI/$abi"
|
||||
|
||||
[ -d "$src" ] || { echo "!! 没有 $src,先跑 build-dpkg.sh $arch"; exit 1; }
|
||||
mkdir -p "$dst"
|
||||
|
||||
stage="$(mktemp -d)"
|
||||
for p in $PROGRAMS; do
|
||||
[ -f "$src/$p" ] || { echo "!! 缺 $src/$p"; exit 1; }
|
||||
cp "$src/$p" "$stage/$p"
|
||||
chmod 755 "$stage/$p"
|
||||
done
|
||||
|
||||
# tar 用固定的 uid/gid/mtime,保证同样输入产出同样字节(可复现)
|
||||
tar --create --file "$dst/libdoubao-dpkg.so" \
|
||||
--directory "$stage" \
|
||||
--owner=0 --group=0 --numeric-owner \
|
||||
--mtime='2026-01-01 00:00:00 UTC' \
|
||||
--sort=name \
|
||||
$PROGRAMS
|
||||
|
||||
rm -rf "$stage"
|
||||
printf ' %-10s -> %-46s %s 字节\n' "$arch" "jniLibs/$abi/libdoubao-dpkg.so" \
|
||||
"$(stat -c%s "$dst/libdoubao-dpkg.so")"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "内容确认:"
|
||||
for arch in x86_64 arm64; do
|
||||
echo "--- ${ABI[$arch]} ---"
|
||||
tar -tvf "$JNI/${ABI[$arch]}/libdoubao-dpkg.so"
|
||||
done
|
||||
48
android/termux-dpkg/patches/doubao/doubao-android-arch.patch
Normal file
48
android/termux-dpkg/patches/doubao/doubao-android-arch.patch
Normal file
@@ -0,0 +1,48 @@
|
||||
--- a/m4/dpkg-arch.m4 2026-10-14 12:41:34.709430018 +0800
|
||||
+++ b/m4/dpkg-arch.m4 2026-10-14 12:41:34.709459828 +0800
|
||||
@@ -55,12 +55,40 @@
|
||||
AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
- AC_MSG_CHECKING([dpkg architecture name])
|
||||
- _DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
- AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
- AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
- ], [
|
||||
+ dnl Termux/Android: data/cputable, data/ostable and data/tupletable only
|
||||
+ dnl describe the Debian and GNU worlds -- ostable has no "android" entry at
|
||||
+ dnl all -- so the generic lookup below can never resolve a *-linux-android
|
||||
+ dnl host triple and configure dies with "cannot determine host dpkg
|
||||
+ dnl architecture".
|
||||
+ dnl
|
||||
+ dnl Termux names its architectures after the GNU CPU name (the repository
|
||||
+ dnl serves x86_64, aarch64, arm and i686), and the package database shipped
|
||||
+ dnl in our bootstrap was written with exactly those names, so we have to
|
||||
+ dnl report the same thing or dpkg would reject every installed package.
|
||||
+ dnl
|
||||
+ dnl Note the host OS arrives as "linux-android", not "android": config.sub
|
||||
+ dnl normalises --host=x86_64-linux-android into x86_64-pc-linux-android.
|
||||
+ AS_CASE([$host_os],
|
||||
+ [*android*], [
|
||||
+ AS_CASE([$host_cpu],
|
||||
+ [x86_64|aarch64|i686|arm], [dpkg_arch=$host_cpu],
|
||||
+ [armv7*], [dpkg_arch=arm],
|
||||
+ [AC_MSG_ERROR([unsupported Android CPU: $host_cpu])])
|
||||
+ cpu_type=$host_cpu
|
||||
+ os_type=android
|
||||
+ have_dpkg_arch=yes
|
||||
+ ])
|
||||
+ AS_IF([test "x$have_dpkg_arch" = "xyes"], [
|
||||
+ AC_MSG_CHECKING([dpkg architecture name])
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
+ ], [
|
||||
+ AC_MSG_CHECKING([dpkg architecture name])
|
||||
+ _DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
+ AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
+ AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
+ ], [
|
||||
+ AC_MSG_RESULT([$dpkg_arch])
|
||||
+ ])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
26
android/termux-dpkg/patches/doubao/doubao-arch-name.patch
Normal file
26
android/termux-dpkg/patches/doubao/doubao-arch-name.patch
Normal file
@@ -0,0 +1,26 @@
|
||||
--- a/lib/dpkg/arch.c 2026-10-14 12:41:34.729574429 +0800
|
||||
+++ b/lib/dpkg/arch.c 2026-10-14 12:41:34.729607515 +0800
|
||||
@@ -62,17 +62,21 @@
|
||||
internerr("arch name argument is NULL");
|
||||
if (!*p)
|
||||
return _("may not be empty string");
|
||||
+ /* Termux/Android: Termux names its architectures after the GNU CPU
|
||||
+ * name, and two of the four it serves -- x86_64 and aarch64 -- carry an
|
||||
+ * underscore. Without this every package in the bootstrap database
|
||||
+ * would be reported as having an invalid Architecture. */
|
||||
if (!c_isalnum(*p))
|
||||
return _("must start with an alphanumeric");
|
||||
while (*++p != '\0')
|
||||
- if (!c_isalnum(*p) && *p != '-')
|
||||
+ if (!c_isalnum(*p) && *p != '-' && *p != '_')
|
||||
break;
|
||||
if (*p == '\0')
|
||||
return NULL;
|
||||
|
||||
snprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
"letters, digits and characters '%s')"),
|
||||
- *p, "-");
|
||||
+ *p, "-_");
|
||||
return buf;
|
||||
}
|
||||
|
||||
14
android/termux-dpkg/patches/doubao/doubao-debarch-name.patch
Normal file
14
android/termux-dpkg/patches/doubao/doubao-debarch-name.patch
Normal file
@@ -0,0 +1,14 @@
|
||||
--- a/scripts/Dpkg/Arch.pm 2026-10-14 12:41:34.752824615 +0800
|
||||
+++ b/scripts/Dpkg/Arch.pm 2026-10-14 12:41:34.752929467 +0800
|
||||
@@ -612,7 +612,10 @@
|
||||
sub debarch_is_illegal
|
||||
{
|
||||
my ($arch, %opts) = @_;
|
||||
- my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9-]*/;
|
||||
+ # Termux/Android: allow underscores, because Termux names
|
||||
+ # architectures after the GNU CPU name and x86_64 / aarch64
|
||||
+ # both contain one.
|
||||
+ my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9_-]*/;
|
||||
|
||||
if ($opts{positive}) {
|
||||
return $arch !~ m/^$arch_re$/;
|
||||
352
android/termux-dpkg/patches/doubao/doubao-prefix-c.patch
Normal file
352
android/termux-dpkg/patches/doubao/doubao-prefix-c.patch
Normal file
@@ -0,0 +1,352 @@
|
||||
--- a/lib/dpkg/doubao-prefix.c 2026-10-14 12:41:34.595602235 +0800
|
||||
+++ b/lib/dpkg/doubao-prefix.c 2026-10-14 12:41:34.600860227 +0800
|
||||
@@ -0,0 +1,349 @@
|
||||
+/*
|
||||
+ * doubao-prefix.c - resolve the installation prefix at runtime
|
||||
+ *
|
||||
+ * Copyright (C) 2026 doubao-clone
|
||||
+ *
|
||||
+ * This is free software; you can redistribute it and/or modify
|
||||
+ * it under the terms of the GNU General Public License as published by
|
||||
+ * the Free Software Foundation; either version 2 of the License, or
|
||||
+ * (at your option) any later version.
|
||||
+ *
|
||||
+ * Upstream dpkg bakes its configuration directory in at configure time
|
||||
+ * (-DCONFIGDIR), and Termux builds it as $PREFIX/etc/dpkg where $PREFIX is a
|
||||
+ * fixed absolute path chosen by the Termux application. Android gives every
|
||||
+ * application its own private data directory, so a dpkg built for
|
||||
+ * com.termux will always look inside /data/data/com.termux -- a directory
|
||||
+ * another application is not allowed to traverse. The resulting EACCES makes
|
||||
+ * dpkg abort before it has even parsed its command line, which is why the two
|
||||
+ * applications cannot coexist.
|
||||
+ *
|
||||
+ * We instead derive the prefix from the path of the running executable, which
|
||||
+ * is exactly where this binary happens to live. That also lets us repair
|
||||
+ * PATH, LD_LIBRARY_PATH and the interpreter lines of maintainer scripts,
|
||||
+ * all of which upstream assumes are already correct.
|
||||
+ */
|
||||
+
|
||||
+#include <config.h>
|
||||
+#include <compat.h>
|
||||
+
|
||||
+#include <fcntl.h>
|
||||
+#include <limits.h>
|
||||
+#include <stdlib.h>
|
||||
+#include <string.h>
|
||||
+#include <sys/stat.h>
|
||||
+#include <unistd.h>
|
||||
+
|
||||
+#include <dpkg/i18n.h>
|
||||
+#include <dpkg/debug.h>
|
||||
+#include <dpkg/dpkg.h>
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
+
|
||||
+/* How many distinct strings we keep alive so returned pointers stay valid. */
|
||||
+#define DOUBAO_CACHE_SLOTS 4
|
||||
+
|
||||
+static char prefix_buf[PATH_MAX];
|
||||
+static const char *prefix_cached;
|
||||
+static char config_buf[PATH_MAX];
|
||||
+
|
||||
+static void
|
||||
+doubao_prefix_resolve(void)
|
||||
+{
|
||||
+ char self[PATH_MAX];
|
||||
+ const char *override;
|
||||
+ char *slash;
|
||||
+ ssize_t n;
|
||||
+
|
||||
+ if (prefix_cached != NULL)
|
||||
+ return;
|
||||
+
|
||||
+ prefix_cached = DOUBAO_DEFAULT_PREFIX;
|
||||
+
|
||||
+ override = getenv("DOUBAO_DPKG_PREFIX");
|
||||
+ if (override != NULL) {
|
||||
+ if (*override != '\0' && strlen(override) < sizeof(prefix_buf)) {
|
||||
+ strcpy(prefix_buf, override);
|
||||
+ prefix_cached = prefix_buf;
|
||||
+ }
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ n = readlink("/proc/self/exe", self, sizeof(self) - 1);
|
||||
+ if (n <= 0 || (size_t)n >= sizeof(self) - 1)
|
||||
+ return;
|
||||
+ self[n] = '\0';
|
||||
+
|
||||
+ /* .../bin/dpkg -> .../bin -> ... */
|
||||
+ slash = strrchr(self, '/');
|
||||
+ if (slash == NULL)
|
||||
+ return;
|
||||
+ *slash = '\0';
|
||||
+
|
||||
+ slash = strrchr(self, '/');
|
||||
+ if (slash == NULL)
|
||||
+ return;
|
||||
+ *slash = '\0';
|
||||
+
|
||||
+ if (strlen(self) < sizeof(prefix_buf)) {
|
||||
+ strcpy(prefix_buf, self);
|
||||
+ prefix_cached = prefix_buf;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+const char *
|
||||
+doubao_prefix(void)
|
||||
+{
|
||||
+ doubao_prefix_resolve();
|
||||
+ return prefix_cached;
|
||||
+}
|
||||
+
|
||||
+const char *
|
||||
+doubao_config_dir(void)
|
||||
+{
|
||||
+ const char *prefix = doubao_prefix();
|
||||
+
|
||||
+ if (snprintf(config_buf, sizeof(config_buf), "%s/etc/dpkg", prefix)
|
||||
+ >= (int)sizeof(config_buf))
|
||||
+ return CONFIGDIR;
|
||||
+
|
||||
+ return config_buf;
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * Prepend our own bin directories to PATH and make sure the loader can find
|
||||
+ * our shared libraries, so that dpkg and the maintainer scripts it runs work
|
||||
+ * no matter what environment our parent handed us.
|
||||
+ */
|
||||
+void
|
||||
+doubao_fix_environment(void)
|
||||
+{
|
||||
+ static bool done = false;
|
||||
+ static char pathbuf[4 * PATH_MAX];
|
||||
+ static char libbuf[PATH_MAX + 64];
|
||||
+
|
||||
+ const char *prefix, *old;
|
||||
+ size_t len;
|
||||
+
|
||||
+ if (done)
|
||||
+ return;
|
||||
+ done = true;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+
|
||||
+ old = getenv("PATH");
|
||||
+ /* Only prepend when our prefix is not already the first entry, so that
|
||||
+ * a re-exec does not keep growing PATH. */
|
||||
+ len = strlen(prefix);
|
||||
+ if (old == NULL || strncmp(old, prefix, len) != 0 ||
|
||||
+ strncmp(old + len, "/bin:", 5) != 0) {
|
||||
+ if (snprintf(pathbuf, sizeof(pathbuf), "%s/bin:%s/bin/applets:%s",
|
||||
+ prefix, prefix, old != NULL ? old : "/system/bin")
|
||||
+ < (int)sizeof(pathbuf))
|
||||
+ setenv("PATH", pathbuf, 1);
|
||||
+ }
|
||||
+
|
||||
+ if (snprintf(libbuf, sizeof(libbuf), "%s/lib",
|
||||
+ prefix) < (int)sizeof(libbuf))
|
||||
+ setenv("LD_LIBRARY_PATH", libbuf, 1);
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * Maintainer scripts inside a Termux package are written in terms of the
|
||||
+ * Termux prefix:
|
||||
+ *
|
||||
+ * #!/data/data/com.termux/files/usr/bin/sh
|
||||
+ * mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
+ * KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_rsa_key"
|
||||
+ *
|
||||
+ * Neither form works for us. The interpreter line is resolved by the kernel
|
||||
+ * and lands in another application's private directory (EACCES, which dpkg
|
||||
+ * then reports as though the script itself were not executable), and the
|
||||
+ * absolute paths are absolute -- our sandbox symlinks live under our own
|
||||
+ * prefix and cannot intercept a path that starts at "/".
|
||||
+ *
|
||||
+ * The scripts are plain text, so rewrite both before executing them. This is
|
||||
+ * a local edit of the dpkg database rather than a change to the package, so
|
||||
+ * it also covers packages installed long after this code was written.
|
||||
+ */
|
||||
+#define DOUBAO_OLD_PREFIX "/data/data/com.termux/files/usr"
|
||||
+
|
||||
+static void
|
||||
+doubao_rewrite_script(const char *path)
|
||||
+{
|
||||
+ char *buf;
|
||||
+ char *out;
|
||||
+ const char *prefix;
|
||||
+ size_t oldlen = sizeof(DOUBAO_OLD_PREFIX) - 1;
|
||||
+ size_t newlen, len, cap;
|
||||
+ size_t i, o;
|
||||
+ int fd;
|
||||
+ ssize_t n;
|
||||
+ struct stat st;
|
||||
+
|
||||
+ if (path == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ fd = open(path, O_RDONLY);
|
||||
+ if (fd < 0)
|
||||
+ return;
|
||||
+ if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
|
||||
+ st.st_size > 1024 * 1024) {
|
||||
+ close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ len = (size_t)st.st_size;
|
||||
+ buf = malloc(len + 1);
|
||||
+ if (buf == NULL) {
|
||||
+ close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+ n = read(fd, buf, len);
|
||||
+ close(fd);
|
||||
+ if (n <= 0) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+ buf[n] = '\0';
|
||||
+ len = (size_t)n;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+ newlen = strlen(prefix);
|
||||
+
|
||||
+ /* 先看有没有要换的东西,没有就别写盘 */
|
||||
+ for (i = 0; i + oldlen <= len; i++) {
|
||||
+ if (memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0)
|
||||
+ break;
|
||||
+ }
|
||||
+ if (i + oldlen > len) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ /* 每一步替换都会变长(我们的前缀比 Termux 的长),所以要放大缓冲 */
|
||||
+ cap = len + 64;
|
||||
+ out = malloc(cap);
|
||||
+ if (out == NULL) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ for (i = 0, o = 0; i < len; ) {
|
||||
+ if (i + oldlen <= len &&
|
||||
+ memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0) {
|
||||
+ if (o + newlen + (len - i) + 2 > cap) {
|
||||
+ cap = (o + newlen + (len - i) + 2) * 2;
|
||||
+ out = realloc(out, cap);
|
||||
+ if (out == NULL) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+ }
|
||||
+ memcpy(out + o, prefix, newlen);
|
||||
+ o += newlen;
|
||||
+ i += oldlen;
|
||||
+ } else {
|
||||
+ out[o++] = buf[i++];
|
||||
+ }
|
||||
+ }
|
||||
+ out[o] = '\0';
|
||||
+ free(buf);
|
||||
+
|
||||
+ fd = open(path, O_WRONLY | O_TRUNC);
|
||||
+ if (fd < 0) {
|
||||
+ free(out);
|
||||
+ return;
|
||||
+ }
|
||||
+ if (write(fd, out, o) != (ssize_t)o) {
|
||||
+ close(fd);
|
||||
+ free(out);
|
||||
+ ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
+ }
|
||||
+ close(fd);
|
||||
+ free(out);
|
||||
+
|
||||
+ debug(dbg_scripts, "rewrote prefix in maintainer script '%s'", path);
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * 把维护脚本的 shebang 换成本安装自己的 shell。
|
||||
+ *
|
||||
+ * 保留原来用的是哪个 shell(`sh` 还是 `bash`)—— 换错解释器会毁掉脚本,
|
||||
+ * 这一条真踩过:把 `bin/pip`(Python 脚本)的 shebang 改成 bash,
|
||||
+ * 于是报 `bin/pip: line 2: import: command not found`。
|
||||
+ * 规则是"只换路径,不动解释器"。
|
||||
+ */
|
||||
+void
|
||||
+doubao_fix_script_shebang(const char *path)
|
||||
+{
|
||||
+ static const char old_shebang[] = "#!/data/data/com.termux/files/usr/";
|
||||
+ /* Android 上 /data/user/0/<pkg> 和 /data/data/<pkg> 是同一个目录的两种
|
||||
+ * 写法,包里两种都出现过,所以两个都要认。 */
|
||||
+ static const char old_shebang_alt[] = "#!/data/user/0/com.termux/files/usr/";
|
||||
+
|
||||
+ char buf[PATH_MAX + 256];
|
||||
+ const char *prefix;
|
||||
+ char *nl;
|
||||
+ int fd;
|
||||
+ ssize_t n;
|
||||
+ ssize_t skip = -1;
|
||||
+ size_t head, rest, total;
|
||||
+ char *fixed;
|
||||
+
|
||||
+ if (path == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ /* 先把正文里的绝对路径改掉(`#!/...` 那行也会一起被改到) */
|
||||
+ doubao_rewrite_script(path);
|
||||
+
|
||||
+ fd = open(path, O_RDONLY);
|
||||
+ if (fd < 0)
|
||||
+ return;
|
||||
+
|
||||
+ n = read(fd, buf, sizeof(buf) - 1);
|
||||
+ close(fd);
|
||||
+ if (n <= 0)
|
||||
+ return;
|
||||
+ buf[n] = '\0';
|
||||
+
|
||||
+ if (strncmp(buf, old_shebang, sizeof(old_shebang) - 1) == 0)
|
||||
+ skip = (ssize_t)(sizeof(old_shebang) - 1);
|
||||
+ else if (strncmp(buf, old_shebang_alt, sizeof(old_shebang_alt) - 1) == 0)
|
||||
+ skip = (ssize_t)(sizeof(old_shebang_alt) - 1);
|
||||
+
|
||||
+ if (skip < 0)
|
||||
+ return;
|
||||
+
|
||||
+ nl = strchr(buf, '\n');
|
||||
+ if (nl == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+ head = 2 + strlen(prefix) + 1; /* "#!/" + prefix + "/" */
|
||||
+ rest = (size_t)n - (size_t)skip; /* 旧前缀之后的一直到文件尾 */
|
||||
+ total = head + rest;
|
||||
+ if (total + 1 > sizeof(buf))
|
||||
+ return;
|
||||
+
|
||||
+ fixed = malloc(total + 1);
|
||||
+ if (fixed == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ fixed[0] = '#';
|
||||
+ fixed[1] = '!';
|
||||
+ memcpy(fixed + 2, prefix, strlen(prefix));
|
||||
+ fixed[2 + strlen(prefix)] = '/';
|
||||
+ memcpy(fixed + head, buf + skip, rest);
|
||||
+ fixed[total] = '\0';
|
||||
+
|
||||
+ fd = open(path, O_WRONLY | O_TRUNC);
|
||||
+ if (fd < 0) {
|
||||
+ free(fixed);
|
||||
+ return;
|
||||
+ }
|
||||
+ if (write(fd, fixed, total) != (ssize_t)total)
|
||||
+ ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
+ close(fd);
|
||||
+ free(fixed);
|
||||
+
|
||||
+ debug(dbg_scripts, "rewrote interpreter line of '%s'", path);
|
||||
+}
|
||||
55
android/termux-dpkg/patches/doubao/doubao-prefix-h.patch
Normal file
55
android/termux-dpkg/patches/doubao/doubao-prefix-h.patch
Normal file
@@ -0,0 +1,55 @@
|
||||
--- a/lib/dpkg/doubao-prefix.h 2026-10-14 12:41:34.579902172 +0800
|
||||
+++ b/lib/dpkg/doubao-prefix.h 2026-10-14 12:41:34.580926465 +0800
|
||||
@@ -0,0 +1,52 @@
|
||||
+/*
|
||||
+ * doubao-prefix.h - resolve the installation prefix at runtime
|
||||
+ *
|
||||
+ * Copyright (C) 2026 doubao-clone
|
||||
+ *
|
||||
+ * This is free software; you can redistribute it and/or modify
|
||||
+ * it under the terms of the GNU General Public License as published by
|
||||
+ * the Free Software Foundation; either version 2 of the License, or
|
||||
+ * (at your option) any later version.
|
||||
+ */
|
||||
+
|
||||
+#ifndef DOUBAO_PREFIX_H
|
||||
+#define DOUBAO_PREFIX_H
|
||||
+
|
||||
+#include <dpkg/dpkg.h>
|
||||
+
|
||||
+DPKG_BEGIN_DECLS
|
||||
+
|
||||
+/**
|
||||
+ * Return the prefix this dpkg was installed under.
|
||||
+ *
|
||||
+ * The prefix is derived from the path of the running executable, because
|
||||
+ * Android hands every application its own private data directory and the
|
||||
+ * same binary has to work under any of them. Falls back to the compile-time
|
||||
+ * DOUBAO_DEFAULT_PREFIX when the executable path cannot be determined.
|
||||
+ */
|
||||
+const char *doubao_prefix(void);
|
||||
+
|
||||
+/**
|
||||
+ * Return the configuration directory ($prefix/etc/dpkg).
|
||||
+ */
|
||||
+const char *doubao_config_dir(void);
|
||||
+
|
||||
+/**
|
||||
+ * Prepend our own bin directories to PATH and point LD_LIBRARY_PATH at our
|
||||
+ * own lib directory.
|
||||
+ *
|
||||
+ * Needed because apt sanitises the environment before it execs dpkg, and the
|
||||
+ * PATH it hands over names the *other* application's prefix; dpkg would then
|
||||
+ * fail its own sanity check with "expected programs not found in PATH".
|
||||
+ */
|
||||
+void doubao_fix_environment(void);
|
||||
+
|
||||
+/**
|
||||
+ * Rewrite a maintainer script's interpreter line so it points at this
|
||||
+ * installation instead of the application it was built for.
|
||||
+ */
|
||||
+void doubao_fix_script_shebang(const char *path);
|
||||
+
|
||||
+DPKG_END_DECLS
|
||||
+
|
||||
+#endif /* DOUBAO_PREFIX_H */
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user