Compare commits

...

4 Commits

Author SHA1 Message Date
l
ab8296901d v2.0.81 —— 修「群聊删不了人」+ 世界观能挂数值状态包了(附教程)
## 一、群聊删不了人:两处都修了

**① 内核还留着"主智能体不能移出"**

你早就要求「群聊去掉主人设定」,界面上也写了「谁都能移出」——
但内核 `remove_member` 里还留着 `aid == host_id(c)` 的拦截,
于是**第一个进群的人删不掉**(点了没反应)。

现在唯一的拒绝条件是"不能删到一个人不剩";删到剩 1 个会**退回单聊**
(`type` 一起改回去,不然界面还按群聊渲染、仲裁还按群聊跑)。

**② `invite_agent` 的「需确认」被绕过**

它排在"单聊 → 转群聊"那个分支**后面**,所以单聊里拉人时
直接把人拉进来了,配置的"拉起需要确认"完全没生效。现在排到最前面。

**③ 顺便**:删除失败时的提示还是"主智能体不能被移出",
那条规则已经废了,改成如实说「群里没这个人,或者就剩他一个了」。

## 二、世界观能挂数值状态包了(之前整条链路是断的)

规则包挂在**世界观**上(`world.rulePackId`),内核那条链路一直是通的,
但**世界观编辑界面没有这个入口** —— 也就是说:

> 你在「资源 → 规则包」里辛苦写完数值和状态,回来发现**没有任何地方能启用它**。

现在世界观编辑页加了「数值状态包」选择器(列出所有包 + 各自有几条数值/状态/
带不带脚本 + 「不挂」选项)。链路终于闭环:

```
资源 → 规则包(建包)→ 世界观挂上它 → 智能体绑这个世界观 → 有数值了
```

## 三、新增两个文档

- **`docs/Python脚本.md`** —— 六处跑 Python 的地方和它们的权限边界
- **`docs/数值状态系统-教程.md`** —— 手把手跑通「好感度 + 中毒」:
  链路、字段含义、脚本三个入口、常见问题,以及**最快四步清单**

教程里如实标注了一个已知缺口:**AI 只有「加状态」没有「移除状态」**
(`persistent` 状态挂上后界面上没有一键清掉的地方)。

## 四、测试

这次按你说的**用模拟器测**(`emulator-5558`,Android 14 / x86_64),
在真实数据上验证删人:

```
群成员: ['豆包', '文案师']
删第一个人 豆包(以前删不掉的那位)
  HTTP 200  → 剩: ['文案师']  type= single
删最后一个(应被拒绝)
  HTTP 400  移不出去(群里没这个人,或者就剩他一个了)
```

界面上也确认了:点「移出」→ **2 个人在群里 → 1 个人在群里**。

八个探针全绿(`probe-group-chat` 里三条过期断言已按新语义更新)。
2026-10-17 16:25:20 +08:00
l
c09df1d0a2 docs: 新增《Python 脚本》—— 六处跑 Python 的地方和它们的权限边界
这个仓库有六类地方会跑 Python:AI 的 python_run / shell、规则脚本、
会议 Python 节点、自定义节点、内置 Termux。它们的权限和兜底手段完全不同,
混着看会出事(以为规则脚本能读文件、或者以为 python_run 有沙箱)。

文档把每处的:谁能写 / 能做什么 / 兜底手段 / 超时键 / 安全边界 列成表,
并给了规则脚本三个入口的签名和示例、自定义节点的声明格式和三条语义。

结论一句话:只有规则脚本有沙箱,而它挡得住手滑、挡不住有意。
2026-10-17 16:02:28 +08:00
l
31c62fafc2 v2.0.80 —— 群聊里 AI 能看到谁说的 + talk_to 多目标 + 私聊
## 一、智能体能读到群里所有人的发言了

以前送进模型的 `history` 只有 `role` / `content` —— 群里**别人说的话**,
模型根本分不清是谁说的,只能当成自己说过或用户说过。

现在群聊时,送给模型的每条消息前面都标上发言人:

```
[用户] @寐眠 你们聊聊
[小黑] 我哪句是打岔,哪句是问号,哪句是逗号——我记性好
[寐眠] 你打的是「你们」。我知道,你打的时候大概是想把两个都算进去
```

(只在**送给模型的那份**上加,落库的正文和界面显示都还是干净的。)
顺带在 skill 里写清楚:「你能看到群里所有人的发言,别把别人的话当成自己说过。」

## 二、talk_to 一次可以找好几个人

```
talk_to(agents=["小黑", "寐眠"], content="你们都说说")
```

目标会**挨个**回话 —— 移交状态带队列,界面逐个接下去(自动模式直接跑,
手动模式每轮都出「让他说 / 停在这」)。

为了兼容老写法,`agent="名字"` 仍然能用,等价于只找一个人。

## 三、talk_to 加私聊:只有目标知道

```
talk_to(agent="寐眠", content="别告诉小黑", private=true)
```

- 这条消息**只有目标智能体**能看到;
- 内核组装 history 时按「是不是给我的」过滤掉,所以**别的 AI 真的看不到**;
- **你(用户)照样看得到** —— 你是观察者,不能连自己都瞒着。
  skill 里也这么写了:「别以为私聊就可以说见不得人的话」。

## 四、顺手

- 探针里三条**旧断言**过期了(`talk_to` 参数从「agent+content」扩成
  `agents`/`agent`/`content`/`private`;移交状态多了 `queue`)—— 已更新,
  不是放宽标准,是接口真的变了。

## 验证

八个探针全绿;`probe-group-chat` 新增第 21 节共 8 条断言,
覆盖:多目标参数、私聊参数、移交队列、新一轮清队列、
送模型的历史带发言人、别人的私聊被过滤。
2026-10-17 14:46:49 +08:00
l
7498810c70 v2.0.79 —— 修「加人没反应」:那个接口一直是 404
## 根因:路由被自己的解析函数挡住了

你说「加人界面点了没反应,人也没加到」。查下来是**接口根本没通**:

```
POST /api/conversations/<id>/members  →  404 {"error": "未知接口 ..."}
```

不是路由没写 —— 是它用 `_match_id(pathname, '/api/conversations/')` 去解析 id,
而那个函数的规则是**「id 后面不能有斜杠」**:

```python
rest = pathname[len(prefix):]
if not rest or '/' in rest:
    return None          #  ← /api/conversations/<id>/members 的 rest 是 "<id>/members"
```

所以 `member_id` 永远是 `None`,**整个成员分支永远进不去**,落到最后就是 404。
界面拿到失败,表现就是"点了没反应、人也加不上"。

修:这个分支自己解析 id,不碰 `_match_id`。

**实测**(直接打接口,不经界面):
```
群里现有: ['数据分析', '豆包', '代码搭子', '文案师']
要加:     黑化豆包
HTTP 200 -> 现在成员: [... , '黑化豆包']
```

## 顺便修好的两件(上一版没生效的)

- **未绑世界观的智能体可以拉**:它没有设定会串,和谁都合得来。
  上一版我写成"世界观必须相等",于是「黑化豆包」这种没绑的也进不来。
- **被世界观挡下的人会列出来**并说明原因,不再"凭空消失"。

另外界面那个「加人」面板确实会展开(点了变「取消」+「拉谁进来」),
之前看不到候选就是因为上面的接口 404 + 过滤条件太严。

## 验证

八个探针全绿;`probe-group-chat` 新增第 20 节,
专门守「成员增删路由不能用 `_match_id`」—— 别再退回去。
2026-10-17 14:26:42 +08:00
56 changed files with 9396 additions and 301 deletions

3
.gitignore vendored
View File

@@ -87,3 +87,6 @@ Desktop.ini
# 调试时生成的临时探针
.tmp/
.tmp-*
# 豆包网页版参考镜像(第三方资源,仅本地研究/对照用,不入库)
reference/doubao-web-mirror/

View File

@@ -1,4 +1,4 @@
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
@@ -440,6 +440,14 @@ python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calli
`python scripts/audit-ui-tree.py` 会拿它**和源码对拍**:
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
**Python 脚本在哪跑、各有什么权限**:[`docs/Python脚本.md`](docs/Python脚本.md) ——
这个 App 里**六类地方**会跑 Python(AI 的 `python_run` / `shell`、规则脚本、
会议 Python 节点、自定义节点、内置 Termux),它们的权限和沙箱**完全不同**。
一句话结论:
> **只有「规则脚本」有沙箱,而且那个沙箱挡得住手滑、挡不住有意。**
> 其余几处本质就是"在你手机上跑代码",靠超时兜底,不是权限隔离。
**还没做的**:Node 端(Web / exe)的智能体系统仍是旧的那套 ——
按仓库约定"引擎改了另一端必须跟上",这是欠账。

View File

@@ -1,4 +1,4 @@
plugins {
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose")
@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 278
versionName = "2.0.78"
versionCode = 281
versionName = "2.0.81"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份

View File

@@ -273,6 +273,9 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
com.doubao.lynxclone.data.WorldviewItem(
name = name,
setting = text,
// ★ 世界观挂的数值状态包。不传的话这条路**永远存成空** ——
// 界面选了也白选("配了但读出来没有"那个经典坑)。
rulePackId = (extra["rulePackId"] as? String).orEmpty(),
image = (extra["image"] as? com.doubao.lynxclone.data.AgentImage)
?: com.doubao.lynxclone.data.AgentImage(),
),
@@ -1425,6 +1428,23 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
private val handoffToRef = AtomicReference("")
private val handoffFromRef = AtomicReference("")
/**
* 这一轮 AI 把话交给了**一串人**(`talk_to` 多目标)。
*
* ★ 用 `AtomicReference` 的理由同 [handoffDone]:写在 IO 回调线程上、
* `finally` 里马上要读。
*/
private val handoffQueueRef = AtomicReference<List<String>>(emptyList())
/**
* 待接话的人(队列)。
*
* ★★ 用户要求:「talk_to 支持多个目标(目标智能体挨个回话)」。
* 所以一轮跑完如果还有没接过话的人,就摆出"下一个是他",
* 自动模式直接接着跑、手动模式把按钮摆出来等用户点。
*/
private val handoffQueue = ArrayDeque<String>()
/** 已经连续自动续了几轮。防止两个 AI 你一句我一句停不下来(那是烧钱) */
private var autoRounds = 0
@@ -1466,6 +1486,8 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
pendingHandoffTo = ""
pendingHandoffName = ""
pendingHandoffFromName = ""
// ★ 队列也一起清掉:用户说停就是停,别过一会儿又冒出来一个"下一个"
handoffQueue.clear()
handoffDone.set(false)
if (who.isNotBlank()) showHint("停在这里了($who 没接)")
}
@@ -1913,6 +1935,9 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
// 自动模式:不用用户确认,直接接着让他说
if (autoRounds < autoRoundCap) {
autoRounds++
// ★ 把多目标的队列也带上:下一轮跑完 `finally` 会继续消费
handoffQueue.clear()
handoffQueue.addAll(handoffQueueRef.get().filter { it.isNotBlank() })
runChat("", emptyList(), auto = true)
}
} else {
@@ -1922,12 +1947,29 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
pendingHandoffName = state.agents
.firstOrNull { it.id == handoffToRef.get() }?.name.orEmpty()
pendingHandoffFromName = handoffFromRef.get()
// ★ 多目标:剩下的排进队列,`continueHandoff` 之后由
// 这次 `runChat` 的 finally 接着摆出来("挨个回话")
handoffQueue.clear()
handoffQueue.addAll(handoffQueueRef.get().filter { it.isNotBlank() })
}
} else if (canContinue && handoffQueue.isNotEmpty()) {
// ★★ 队列里还有没接过话的人(`talk_to` 多目标)——
// 用户要求「目标智能体挨个回话」,所以接着摆下一个。
val next = handoffQueue.removeFirst()
val nextName = state.agents.firstOrNull { it.id == next }?.name.orEmpty()
if (state.settings.aiTalkAuto) {
runChat("", emptyList(), auto = true, forceSpeaker = next)
} else {
pendingHandoffTo = next
pendingHandoffName = nextName
pendingHandoffFromName = handoffFromRef.get()
}
} else {
// 收尾:清掉自动对聊的计数,免得下次发消息又自己续上
aiTalkLeft = 0
aiTalkTurn = 0
aiTalkPair = emptyList()
handoffQueue.clear()
}
}
}
@@ -1944,6 +1986,8 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
if (event is StreamEvent.Handoff) {
handoffDone.set(true)
handoffToRef.set(event.to)
// 多目标:剩下的那些也记下来,`finally` 里逐个消费
handoffQueueRef.set(event.queue)
handoffFromRef.set(
state.agents.firstOrNull { it.id == event.from }?.name.orEmpty()
)

View File

@@ -75,10 +75,13 @@ fun GroupMembersScreen(
// 世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。
// 内核 `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)
it.worldviewId.orEmpty().isBlank() || 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 }
@@ -86,12 +89,8 @@ fun GroupMembersScreen(
Card {
if (candidates.isEmpty()) {
Hint(
if (blocked > 0) {
"没有可以拉的人了。还有 $blocked 个智能体在世界观上跟这个群不一样," +
"拉进来会串设定 —— 换个群或者先给它们绑同一个世界观。"
} else {
"所有同世界观的智能体都在群里了。"
},
if (blocked > 0) "没有可以拉的人了。"
else "所有能拉的人都在群里了。",
)
} else {
for (a in candidates) {
@@ -115,6 +114,31 @@ fun GroupMembersScreen(
}
Hint("想加几个就加几个 —— 点一个加一个,这排不会收起来。")
}
// ★★ 被世界观挡下的**也列出来**,并说清原因。
//
// 不列的话用户只看到"某些智能体不见了",以为功能坏了 ——
// 他报的「还是加不了人」有一半是这种感觉。
val blockedAgents = vm.state.agents.filter { it.id !in inGroup && it !in sameWorldview }
if (blockedAgents.isNotEmpty()) {
Spacer(Modifier.height(10.dp))
Text(
"这些绑的是别的世界观,拉进来会串设定(两套背景、共享记忆也会混):",
fontSize = 11.sp,
lineHeight = 16.sp,
color = doubaoTextSecondary(),
)
Spacer(Modifier.height(4.dp))
for (a in blockedAgents) {
Text(
"· ${a.name}",
fontSize = 12.sp,
color = doubaoTextSecondary(),
modifier = Modifier.padding(start = 6.dp, top = 2.dp),
)
}
Spacer(Modifier.height(4.dp))
Hint("想拉它们:先去它们的编辑页绑成这个世界观(或者另开一个群)。")
}
}
Spacer(Modifier.height(10.dp))
}

View File

@@ -420,7 +420,13 @@ private fun ResourceEditScreen(
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)
mapOf(
"name" to it.name,
"setting" to it.setting,
// ★ 世界观挂的数值状态包 —— 不读出来的话,一进编辑页
// 选择器就显示"没挂",用户一保存就把原来的关联抹了
"rulePackId" to it.rulePackId,
)
} ?: emptyMap()
"skills" -> vm.state.skills.firstOrNull { it.id == id }?.let {
mapOf("name" to it.name, "content" to it.content)
@@ -475,7 +481,11 @@ private fun ResourceEditScreen(
extra["pricePerK"] = values["pricePerK"]?.toDoubleOrNull() ?: 0.0
extra["noTools"] = values["noTools"] == "1"
}
if (kind.id == "worldviews") extra["image"] = worldImage
if (kind.id == "worldviews") {
extra["image"] = worldImage
// ★ 世界观挂的数值状态包(空 = 不挂)
extra["rulePackId"] = values["rulePackId"].orEmpty()
}
vm.saveResource(kind.id, id, name, text, extra) { saving = false; onDone() }
}
},
@@ -550,6 +560,84 @@ private fun ResourceEditScreen(
}
}
// ★★ 数值状态包:**世界观是它的挂载点**(需求 §3.6)。
//
// 以前这里**没有这个入口** —— 内核那条链路是通的
// (`agent_context.pack_of` 读 `世界观.rulePackId`),
// 但界面上根本挂不上,于是整个数值/状态系统在 App 里是死的:
// 用户在「资源 → 规则包」里辛苦写完,回来发现没有任何地方能启用它。
//
// 只在世界观这一种资源上出现(规则包/Skill/模型没有这个概念)。
if (kind.id == "worldviews") {
SectionLabel("数值状态包")
Column(
Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.clip(RoundedCornerShape(14.dp))
.background(doubaoSurface())
.padding(14.dp),
) {
Text(
"挂上之后,绑这个世界观的智能体就有**数值**(好感度、声望……)" +
"和**状态**(中毒、庇佑……)。不挂就没有 —— 提示词里那两段是空的。",
fontSize = 11.sp,
lineHeight = 16.sp,
color = doubaoTextSecondary(),
)
Spacer(Modifier.height(8.dp))
val pickedPack = values["rulePackId"].orEmpty()
val packs = vm.state.rulePacks
if (packs.isEmpty()) {
Text(
"还没有数值状态包。去「资源 → 规则包」新建一个(有模板)。",
fontSize = 12.sp,
color = doubaoTextSecondary(),
)
} else {
// 一行一个:手机上横向排不下(包名可能很长),
// 而且"选中哪个"要一眼看得出来
Row(
Modifier.fillMaxWidth().clickable { values = values + ("rulePackId" to "") }
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
if (pickedPack.isBlank()) "◉" else "○",
fontSize = 15.sp,
color = if (pickedPack.isBlank()) Doubao.Blue else doubaoTextSecondary(),
)
Spacer(Modifier.width(10.dp))
Text("不挂(没有数值和状态)", fontSize = 13.sp, color = doubaoText())
}
for (p in packs) {
val on = p.id == pickedPack
Row(
Modifier.fillMaxWidth().clickable {
values = values + ("rulePackId" to p.id)
}.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
if (on) "◉" else "○",
fontSize = 15.sp,
color = if (on) Doubao.Blue else doubaoTextSecondary(),
)
Spacer(Modifier.width(10.dp))
Column(Modifier.weight(1f)) {
Text(p.name.ifBlank { "(未命名)" }, fontSize = 13.sp, color = doubaoText())
val bits = mutableListOf<String>()
bits.add("${p.stats.size} 条数值")
bits.add("${p.statuses.size} 条状态")
if (p.hasScripts) bits.add("带脚本")
Text(bits.joinToString(" · "), fontSize = 10.sp, color = doubaoTextSecondary())
}
}
}
}
}
}
/* ---- 世界观的四件套(需求 3.6:沿用智能体那一套)---- */
if (kind.id == "worldviews") {
SectionLabel("外观(四件套)")

View File

@@ -568,6 +568,24 @@ def invite_agent(args: dict) -> dict:
if not my_world or my_world != (target.get('worldviewId') or '').strip():
raise ValueError(f'「{target.get("name")}」和你不在同一个世界观里,拉不进来')
# ★★ 「需确认」必须**排在任何拉人动作之前**。
#
# 以前它排在"单聊 → 转群聊"那个分支的**后面**,于是:
# 用户在单聊里让 AI 拉个人 → 走"转群聊"分支直接拉进来了,
# **配置的"拉起需要确认"完全没生效**。
# 探针里 `c2` 正好被前面删到剩一个(退化成单聊),一拉就中招。
#
# 正确的顺序是:**先问能不能拉,再决定怎么拉。**
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'用户答应之后再调一次这个工具。'),
}
if not group_chat.is_group(conv):
# 单聊拉人 → 转成群聊(需求 §3.9:"当前会话中加入多个智能体")
group_chat.promote(conv, target['id'])
@@ -581,17 +599,6 @@ def invite_agent(args: dict) -> dict:
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'])
@@ -654,39 +661,58 @@ def pass_turn(args: dict) -> dict:
TALK_TO = {
'name': 'talk_to',
'description': (
'在群聊里**主动对另一个智能体说一句话**。\n'
'在群聊里**主动对一个或多个智能体说话**。\n'
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
'★ 想跟群里的谁聊就调它,一来一回可以聊好几轮。\n'
'★ 一次可以找**好几个人**(`agents` 列表),他们会**挨个**回应。\n'
'★ `private=true` 时这条只有**目标**看得到,群里其他智能体看不到 ——\n'
' 用户能看到(他是观察者),但别的 AI 不会知道你们说了什么。\n'
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
'★ 单聊里没有"别人",调了会报错。'
),
'parameters': {
'type': 'object',
'properties': {
'agent': {'type': 'string', 'description': '对方的名字或 id'},
'content': {'type': 'string', 'description': '你要对他说的话'},
'agents': {
'type': 'array',
'items': {'type': 'string'},
'description': '对方的名字列表(只找一个人也可以只写一个)。他们会按顺序挨个回应。',
},
'agent': {
'type': 'string',
'description': '老写法:只找一个人时可以直接写名字(等价于 agents=[名字])。',
},
'content': {'type': 'string', 'description': '你要对他们说的话'},
'private': {
'type': 'boolean',
'description': '私聊模式:只有目标能看到这条,群里其他智能体看不到(默认 false)。',
},
},
'required': ['agent', 'content'],
'required': ['content'],
},
}
def talk_to(args: dict) -> dict:
"""
主动找群里的另一个智能体说话。
主动找群里的一个或多个智能体说话。
★★ 为什么单独一个工具(用户明确要求:「智能体主动调用工具和别的智能体聊」,
「工具定义 / 智能体加上内容」):
★★ 三个能力都是用户点名要的:
`pass_turn` 只交发言权、**不带内容** —— 对方接到的是一片空白。
要"两个智能体真的聊起来",就得让发起方**能说一句具体的话**,
而且那句话要**落进对话**,对方下一轮才看得到。
所以这个工具的参数就是那两样:**跟谁说 + 说什么**。
① **能说具体的话**(`content`)
`pass_turn` 只交发言权、不带内容 —— 对方接到一片空白,聊不起来。
★ 说完之后把发言权交给他(`note_handoff`)—— 界面据此**自动续一轮**,
他会真的开口回应;他也可以反过来再 `talk_to` 回来,于是就能聊下去。
② **一次找多个人**(`agents`)—— 他们**挨个**回话。
发言权排成队列交给 `tools_runtime`,界面逐个接下去。
③ **私聊模式**(`private=true`)—— 这条只有目标看得到,
群里其他人(包括别的 AI)都不知道你们说了什么。
落库时打在消息的 `privateTo` 上;`app.py` 组装 history 时
会按"是不是给我的"过滤掉,所以别的 AI 真的看不到。
★ 说完之后把发言权交出去(`note_handoff`,多目标时排队)——
界面据此逐个让他们回应;他们也可以反过来再 `talk_to` 回来。
"""
import group_chat
import tools_runtime
@@ -705,41 +731,69 @@ def talk_to(args: dict) -> dict:
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
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")}」不在这个群里,先把他拉进来')
# ★ 目标名单:`agents` 列表优先,兼容老的单数 `agent`
raw = args.get('agents')
wanted = []
if isinstance(raw, list):
wanted = [str(x or '').strip() for x in raw]
elif raw:
wanted = [str(raw or '').strip()]
if not wanted:
single = str(args.get('agent') or '').strip()
if single:
wanted = [single]
wanted = [x for x in wanted if x]
if not wanted:
raise ValueError('要跟谁说?写 agent 或 agents')
targets, missing = [], []
for name in wanted:
t = _find_agent(name)
if not t:
missing.append(name)
continue
if t.get('id') == me.get('id'):
continue # 自己跳过(一次找多人时很常见)
if t['id'] not in group_chat.member_ids(conv):
missing.append(f'{t.get("name")}(不在群里)')
continue
if all(t['id'] != x['id'] for x in targets):
targets.append(t)
if not targets:
raise ValueError(f'一个都没找到:{"、".join(missing) or "(空的)"}')
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, [{
is_private = bool(args.get('private'))
msg = {
'role': 'assistant',
'content': content,
'agentId': me.get('id'),
'at': store.now_iso(),
}])
}
if is_private:
# ★ 私聊:只给这几个目标看(`app.py` 组装 history 时按这个过滤)
msg['privateTo'] = [t['id'] for t in targets]
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
store.append_messages(conv_id, [msg])
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'])
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} private={is_private} '
f'targets={[t.get("name") for t in targets]} 内容={content[:20]!r}', file=sys.stderr)
# ★ 发言权:多目标排成队列,界面逐个接着让他们回应
names_out = '、'.join(t.get('name') or '?' for t in targets)
tools_runtime.note_handoff(targets[0]['id'], queue=[t['id'] for t in targets])
return {
'said_to': target.get('name'),
# ★★ **回显说了什么**。不回显的话模型看不到自己的话落在哪儿,
# 会以为"传过去是空的"、然后反复重试 ——
# 真机上就是模型自己在回复里写「这条是空的,我猜是想看我把 talk_to 真跑一遍」
# (用户报的「talk_to 没有内容呀」)。
'said_to': [t.get('name') for t in targets],
'content': content,
'private': is_private,
'note': (
f'已把「{content}」说给「{target.get("name")}」,'
'这句话已经写进对话、他下一轮看得到,接下来由他回应。别再重复调这个工具。'
f'已把「{content}」{"(私下)" if is_private else ""}说给「{names_out}」,'
'这句话已经写进对话,他们会挨个回应。别再重复调这个工具。'
+ (f'(没找到:{"、".join(missing)})' if missing else '')
),
}

View File

@@ -976,8 +976,15 @@ class KernelHandler(BaseHTTPRequestHandler):
# ★ "无条件"是需求原话:不加"只有主智能体能加人""要对方同意"这类
# 限制 —— 会话是用户的,他想拉谁就拉谁。
# 唯一的例外是主智能体不能移出(移掉就没有兜底发言的人了)。
member_id = self._match_id(pathname, '/api/conversations/')
if member_id is not None and '/members' in pathname:
#
# ★★ 这里**绝不能用 `_match_id`**:它要求"id 后面没有斜杠",
# 而这条路是 `/api/conversations/<id>/members` —— `rest` 里带 `/`,
# 它直接返回 None,**整个分支永远进不去**。
# 真机表现就是「点加人没反应、人也加不上」,接口回的是
# **404 未知接口**(看着像路由没写,其实写了、被这个门槛拦住了)。
if pathname.startswith('/api/conversations/') and '/members' in pathname:
head, _, tail = pathname.partition('/members')
member_id = unquote(head[len('/api/conversations/'):].strip('/'))
conv = store.get_conversation(member_id)
if not conv:
self.send_json(404, {'error': '会话不存在'})
@@ -995,7 +1002,10 @@ class KernelHandler(BaseHTTPRequestHandler):
return True
elif method == 'DELETE' and target:
if not group_chat.remove_member(conv, target):
self.send_json(400, {'error': '移不出去(主智能体不能被移出)'})
# ★ 错误信息要**如实**:以前这里写"主智能体不能被移出",
# 而那个规则已经废了(群里没有主人)。真实原因只剩
# "人不在群里"或"就剩他一个了"。
self.send_json(400, {'error': '移不出去(群里没这个人,或者就剩他一个了)'})
return True
else:
self.send_json(405, {'error': '不支持的操作'})
@@ -1861,6 +1871,40 @@ class KernelHandler(BaseHTTPRequestHandler):
if window.get('reason'):
print(f'[context] {context_window.describe(window)}', file=sys.stderr)
# ★★ 群聊:给送进模型的每条消息标上**是谁说的**,并过滤私聊消息。
#
# ① 以前 history 里只有 role/content —— 群里**别人说的话**
# 模型根本分不清是谁,只能当成自己说过/用户说过。
# 用户的原话:「智能体可以读取群聊所有智能体的对话信息」。
# 这里在内容的**前面**加 `[名字] `,只改"送给模型的这份",
# 落库的正文保持干净(界面显示不受影响)。
#
# ② `talk_to` 的私聊模式(`privateTo`):那条消息只有**目标智能体**
# 和**用户**看得到,别人(包括模型)都不该有。所以在送进模型之前
# 就把"不是给我的私聊"剔掉 —— 在窗口裁剪之后剔除,
# 这样裁剪的"轮数"还是按全群算的,不会因为私聊把窗口算歪。
_is_group = group_chat.is_group(existing)
if _is_group:
_name_of = {x['id']: (x.get('name') or '') for x in store.list_agents()}
_filtered = []
for _m in history:
_to = _m.get('privateTo')
if isinstance(_to, list) and _to and agent_id not in _to:
# 这条是别人之间的私聊 —— 你看不到(用户能看到,那是用户的事)
continue
_who = ''
if _m.get('role') == 'assistant':
_who = _name_of.get(str(_m.get('agentId') or ''), '')
elif _m.get('role') == 'user':
_who = '用户'
if _who:
_m = dict(_m)
_content = _m.get('content')
if isinstance(_content, str):
_m['content'] = f'[{_who}] {_content}'
_filtered.append(_m)
history = _filtered
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
#
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
@@ -2045,7 +2089,11 @@ class KernelHandler(BaseHTTPRequestHandler):
# 这个坑在 `pass_turn` 上已经踩过一次了。
hs = tools_runtime.handoff_state()
if hs.get('used') and hs.get('to'):
emit({'type': 'handoff', 'to': hs['to'], 'from': agent_id})
emit({'type': 'handoff', 'to': hs['to'],
# ★ `talk_to` 一次找多个人时,剩下的人在这里 ——
# 界面逐个接下去让他们回应(用户要求"目标智能体挨个回话")
'queue': hs.get('queue') or [],
'from': agent_id})
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
@@ -2139,6 +2187,12 @@ class KernelHandler(BaseHTTPRequestHandler):
if target and os.path.isfile(target):
return self.serve_file(target)
# 新网页版(web/ 目录)的静态资源:/assets/* /js/* 之类。
# 旧 Lynx 宿主页只用 / 和 /static/*,上面几条已经先匹配掉了,这里不会抢路由。
web_file = safe_join(p.web_dir, pathname.lstrip('/'))
if web_file and os.path.isfile(web_file):
return self.serve_file(web_file)
if pathname in ('/main.web.bundle', '/main.lynx.bundle'):
return self.serve_file(os.path.join(p.dist_dir, os.path.basename(pathname)))

View File

@@ -276,8 +276,13 @@ BUILTIN_SKILL = '\n'.join([
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
# 于是对方接到一片空白,两个人永远聊不起来。这段就是纠这个。
'【群聊】你可能在一个群里(群里有别人)。',
'· 你能**看到群里所有人的发言**(送进上下文的每条都有 `[名字]` 前缀,'
'「[用户]」是你对面那个人说的)。别把别人说的话当成自己说过。',
'· 想**主动对某个智能体说一句具体的话**:用 talk_to(agent=他的名字, content=你要说的话)。',
' 那句话会真的写进对话,他下一轮看得到、会回应你 —— 这是你和别人**来回聊**的唯一办法。',
'· 一次想找**好几个人**:talk_to(agents=["甲","乙"], content=...),他们会**挨个**回应。',
'· 想**私下**跟某人说(只有他知道、群里其他 AI 看不到):加 `private=true`。'
' 用户还是看得到(他是观察者)—— 所以别以为私聊就可以说见不得人的话。',
'· **不要**拿 pass_turn 当"跟他说话":它只交发言权、不带内容,',
' 对方接到的是一片空白,只能凭上下文猜(所以那样聊不起来)。',
' pass_turn 只在"我没什么可说了,换你"的时候用。',

View File

@@ -205,11 +205,16 @@ def add_member(conv: dict, agent_id: str) -> bool:
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:
theirs = target.get('worldviewId') or ''
if theirs and theirs != mine:
return False
ids.append(aid)
@@ -221,16 +226,29 @@ def add_member(conv: dict, agent_id: str) -> bool:
def remove_member(conv: dict, agent_id: str) -> bool:
"""
移出一个成员。**主智能体不能被移出**(需求说发言权兜底靠它 ——
移掉的话这个群聊就没有兜底了,会冷场)。
移出一个成员。
★★ **谁都能移出** —— 用户要求「群聊去掉主人设定」之后,
"主智能体不能移出"这条就失去了依据:群里已经没有"主人"这回事了,
没人被 @ 时按顺序轮(`rotate_next`)。
以前这里还留着 `aid == host_id(c)` 的拦截,于是**第一个进群的人删不掉**
—— 界面上「移出」按钮人人都有,点了却没反应(真机反馈"群聊删不了人")。
★ 唯一的拒绝条件:**不能删到一个人都不剩**(空群没法开会话)。
删到剩 1 个是允许的 —— 那时退化成单聊,`type` 要跟着改回去,
不然界面还按群聊渲染、仲裁还按群聊跑,而群里只剩一个人。
"""
c = conv or {}
aid = str(agent_id or '').strip()
ids = member_ids(c)
if aid not in ids or aid == host_id(c):
if aid not in ids or len(ids) <= 1:
return False
ids.remove(aid)
c['participants'] = ids
if len(ids) <= 1:
# 只剩一个人 → 退回单聊,并把对话主人设成他
c['type'] = 'single'
c['agentId'] = ids[0] if ids else ''
return True

View File

@@ -150,6 +150,44 @@ def start_kernel(
return handle
def register_desktop_hooks(bridge_url: str) -> None:
"""
桌面(Electron)版把原生能力委托给主进程:选文件、写剪贴板、在资源管理器里显示。
为什么要绕一道 HTTP:内核是 Electron 起的**子进程**,Python 里没有 Electron 的
dialog/clipboard。安卓侧是 Kotlin 直接调 `app.set_native_hooks(...)`(见 doubao_entry.py),
桌面侧就由主进程开一个只监听 127.0.0.1 的小桥(desktop/main.cjs),Python 通过 HTTP 调它。
这样内核代码两边共用一份,不用为桌面另写一套。
"""
import urllib.request
def _call(path: str, payload: dict | None = None):
data = json.dumps(payload or {}).encode('utf-8')
req = urllib.request.Request(
bridge_url.rstrip('/') + path,
data=data,
headers={'Content-Type': 'application/json; charset=utf-8'},
)
with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310 - 只连本机主进程
return json.loads(resp.read().decode('utf-8') or '{}')
def _clipboard(text: str):
_call('/clipboard', {'text': text})
def _pick_file():
return list(_call('/pick-file').get('paths') or [])
def _reveal(target: str):
# 约定:成功返回 None,失败返回一句人话(app.py 直接把它回给界面)
try:
result = _call('/reveal', {'path': target})
except Exception as exc: # noqa: BLE001 - 桥挂了也要给人话,不能让接口 500
return f'打开文件夹失败:{exc}'
return None if result.get('ok') else str(result.get('error') or '打开文件夹失败')
app.set_native_hooks(clipboard=_clipboard, pick_file=_pick_file, reveal=_reveal)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog='doubao-kernel',
@@ -169,6 +207,8 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument('--dist-dir', default=None, help='Lynx 产物目录(默认 app/dist)')
parser.add_argument('--web-core', default=None, help='@lynx-js/web-core 静态资源目录')
parser.add_argument('--no-mcp-autostart', action='store_true', help='启动时不自动连 MCP 服务器')
parser.add_argument('--desktop-bridge', default=None,
help='桌面版原生能力桥(http://127.0.0.1:<port>),由 Electron 主进程提供')
parser.add_argument('--quiet', action='store_true', help='不打印访问日志和启动横幅')
parser.add_argument('--json', action='store_true', help='启动后打印一行 JSON(含真实端口),便于脚本拉起')
return parser
@@ -191,6 +231,13 @@ def main(argv=None) -> int:
if args.json:
print(json.dumps(handle.as_dict(), ensure_ascii=False), flush=True)
# 桌面版:把选文件/剪贴板/打开文件夹委托给 Electron 主进程(安卓不走这里)
if args.desktop_bridge:
try:
register_desktop_hooks(args.desktop_bridge)
except Exception as exc: # noqa: BLE001 - 桥连不上不该让内核起不来
print(f'[kernel] 桌面能力桥注册失败:{exc}', file=sys.stderr)
stop = threading.Event()
def _on_signal(signum, _frame): # noqa: ANN001 - 信号回调签名固定

View File

@@ -182,24 +182,36 @@ def current_context() -> dict:
# 所以这里的修复必须配一条**走真实路径**的探针(见 probe-group-chat)。
#
# 轮次级状态放**模块级**,和线程无关,`agent_loop` 每轮开头重置一次。
_handoff = {'to': '', 'used': False}
_handoff = {'to': '', 'used': False, 'queue': []}
def begin_round() -> None:
"""一轮对话开始时调用(agent_loop 在生成前调)"""
_handoff['to'] = ''
_handoff['used'] = False
_handoff['queue'] = []
def note_handoff(agent_id: str) -> None:
"""`pass_turn` 记下"这一轮移交给了谁" """
_handoff['to'] = str(agent_id or '')
def note_handoff(agent_id: str, queue: list = None) -> None:
"""
记下"这一轮把话交给了谁"。
[queue] 是**多目标**时的完整名单(`talk_to` 支持一次找好几个人,
他们挨个回话)。`to` 始终是**第一个**,保持老调用方不用改。
"""
ids = [str(x) for x in (queue or []) if str(x or '').strip()]
if not ids and str(agent_id or '').strip():
ids = [str(agent_id)]
_handoff['to'] = ids[0] if ids else str(agent_id or '')
_handoff['used'] = True
# 剩下的排进队列(`to` 已经算第一个了)
_handoff['queue'] = ids[1:]
def handoff_state() -> dict:
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`)"""
return dict(_handoff)
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`,界面要用 `queue`)"""
return {'to': _handoff['to'], 'used': _handoff['used'],
'queue': list(_handoff.get('queue') or [])}
def ui_tools_enabled(settings: dict) -> bool:

View File

@@ -0,0 +1,645 @@
A. HISTORY OF THE SOFTWARE
==========================
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Digital Creations, which became
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
https://www.python.org/psf/) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property.
Zope Corporation was a sponsoring member of the PSF.
All Python releases are Open Source (see https://opensource.org for
the Open Source Definition). Historically, most, but not all, Python
releases have also been GPL-compatible; the table below summarizes
the various releases.
Release Derived Year Owner GPL-
from compatible? (1)
0.9.0 thru 1.2 1991-1995 CWI yes
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI yes (2)
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF yes
2.1.1 2.1+2.0.1 2001 PSF yes
2.1.2 2.1.1 2002 PSF yes
2.1.3 2.1.2 2002 PSF yes
2.2 and above 2.1.1 2001-now PSF yes
Footnotes:
(1) GPL-compatible doesn't mean that we're distributing Python under
the GPL. All Python licenses, unlike the GPL, let you distribute
a modified version without making your changes open source. The
GPL-compatible licenses make it possible to combine Python with
other software that is released under the GPL; the others don't.
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
because its license has a choice of law clause. According to
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
is "not incompatible" with the GPL.
Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
===============================================================
Python software and documentation are licensed under the
Python Software Foundation License Version 2.
Starting with Python 3.8.6, examples, recipes, and other code in
the documentation are dual licensed under the PSF License Version 2
and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses.
The licenses are listed with code falling under that license.
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001-2024 Python Software Foundation; All Rights Reserved"
are retained in Python alone or in any derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization ("Licensee") accessing and otherwise using
this software in source or binary form and its associated
documentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an "AS IS"
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------
1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 ("CNRI"), and the Individual or Organization
("Licensee") accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
1995-2001 Corporation for National Research Initiatives; All Rights
Reserved" are retained in Python 1.6.1 alone or in any derivative
version prepared by Licensee. Alternately, in lieu of CNRI's License
Agreement, Licensee may substitute the following text (omitting the
quotes): "Python 1.6.1 is made available subject to the terms and
conditions in CNRI's License Agreement. This Agreement together with
Python 1.6.1 may be located on the internet using the following
unique, persistent identifier (known as a handle): 1895.22/1013. This
Agreement may also be obtained from a proxy server on the internet
using the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
----------------------------------------------------------------------
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
Additional Conditions for this Windows binary build
---------------------------------------------------
This program is linked with and uses Microsoft Distributable Code,
copyrighted by Microsoft Corporation. The Microsoft Distributable Code
is embedded in each .exe, .dll and .pyd file as a result of running
the code through a linker.
If you further distribute programs that include the Microsoft
Distributable Code, you must comply with the restrictions on
distribution specified by Microsoft. In particular, you must require
distributors and external end users to agree to terms that protect the
Microsoft Distributable Code at least as much as Microsoft's own
requirements for the Distributable Code. See Microsoft's documentation
(included in its developer tools and on its website at microsoft.com)
for specific details.
Redistribution of the Windows binary build of the Python interpreter
complies with this agreement, provided that you do not:
- alter any copyright, trademark or patent notice in Microsoft's
Distributable Code;
- use Microsoft's trademarks in your programs' names or in a way that
suggests your programs come from or are endorsed by Microsoft;
- distribute Microsoft's Distributable Code to run on a platform other
than Microsoft operating systems, run-time technologies or application
platforms; or
- include Microsoft Distributable Code in malicious, deceptive or
unlawful programs.
These restrictions apply only to the Microsoft Distributable Code as
defined above, not to Python itself or any programs running on the
Python interpreter. The redistribution of the Python interpreter and
libraries is governed by the Python Software License included with this
file, or by other licenses as marked.
--------------------------------------------------------------------------
This program, "bzip2", the associated library "libbzip2", and all
documentation, are copyright (C) 1996-2019 Julian R Seward. All
rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Julian Seward, jseward@acm.org
bzip2/libbzip2 version 1.0.8 of 13 July 2019
--------------------------------------------------------------------------
libffi - Copyright (c) 1996-2022 Anthony Green, Red Hat, Inc and others.
See source files for details.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
This software is copyrighted by the Regents of the University of
California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
Corporation and other parties. The following terms apply to all files
associated with the software unless explicitly disclaimed in
individual files.
The authors hereby grant permission to use, copy, modify, distribute,
and license this software and its documentation for any purpose, provided
that existing copyright notices are retained in all copies and that this
notice is included verbatim in any distributions. No written agreement,
license, or royalty fee is required for any of the authorized uses.
Modifications to this software may be copyrighted by their authors
and need not follow the licensing terms described here, provided that
the new terms are clearly indicated on the first page of each file where
they apply.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
GOVERNMENT USE: If you are acquiring this software on behalf of the
U.S. government, the Government shall have only "Restricted Rights"
in the software and related documentation as defined in the Federal
Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
are acquiring the software on behalf of the Department of Defense, the
software shall be classified as "Commercial Computer Software" and the
Government shall have only "Restricted Rights" as defined in Clause
252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the
authors grant the U.S. Government and others acting in its behalf
permission to use and distribute the software in accordance with the
terms specified in this license.
This software is copyrighted by the Regents of the University of
California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
Corporation, Apple Inc. and other parties. The following terms apply to
all files associated with the software unless explicitly disclaimed in
individual files.
The authors hereby grant permission to use, copy, modify, distribute,
and license this software and its documentation for any purpose, provided
that existing copyright notices are retained in all copies and that this
notice is included verbatim in any distributions. No written agreement,
license, or royalty fee is required for any of the authorized uses.
Modifications to this software may be copyrighted by their authors
and need not follow the licensing terms described here, provided that
the new terms are clearly indicated on the first page of each file where
they apply.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
GOVERNMENT USE: If you are acquiring this software on behalf of the
U.S. government, the Government shall have only "Restricted Rights"
in the software and related documentation as defined in the Federal
Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
are acquiring the software on behalf of the Department of Defense, the
software shall be classified as "Commercial Computer Software" and the
Government shall have only "Restricted Rights" as defined in Clause
252.227-7013 (b) (3) of DFARs. Notwithstanding the foregoing, the
authors grant the U.S. Government and others acting in its behalf
permission to use and distribute the software in accordance with the
terms specified in this license.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,5 @@
python313.zip
.
# Uncomment to run site.main() automatically
#import site

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

301
docs/Python脚本.md Normal file
View File

@@ -0,0 +1,301 @@
# Python 脚本
这个 App 里**六类地方**会跑 Python 代码。它们的**权限、限制、超时、谁能写**
完全不同 —— 混在一起看会出事(比如以为规则脚本也能读文件,或者以为
`python_run` 有沙箱)。
结论先放这儿:
> **只有"规则脚本"有沙箱,而且那个沙箱挡得住手滑、挡不住有意。**
> 其余几处(`python_run` / 会议节点 / 自定义节点)本质就是"在你手机上跑代码",
> 靠的是**超时**兜底,不是权限隔离。
---
## 一、总览
| # | 在哪 | 谁写 | 能做什么 | 兜底手段 | 超时键 |
|---|---|---|---|---|---|
| 1 | `python_run` 工具 | AI | 任意 Python,可 `import`、可读写文件 | 只有超时 | `pythonRun`(60s) |
| 2 | `shell` 工具 | AI | 任意命令 | 危险命令黑名单 + 超时 | `shell`(30s) |
| 3 | **规则脚本**(数值/状态) | 用户 | 只能算数/拼字符串,**不能 import、不能读文件** | **白名单沙箱** + 超时 | `customNode`(10s) |
| 4 | 会议画布的 Python 节点 | 用户 | 任意 Python(`run(ctx)`) | 只有超时 | `meetingNode`(10s) |
| 5 | 自定义节点 `.py` | 用户 | 任意 Python(声明 + `run(ctx, node)`) | 只有超时 | `customNode`(10s) |
| 6 | 内置 Termux | 用户 | 真的 bash / python3(独立进程) | Termux 自己的限制 | `termux`(30s) |
超时都能在**设置 → 超时**里改。0 = 不限时(只有 `askUser` / `waitUi` 允许)。
---
## 二、`python_run`:AI 写的代码(进程内执行)
AI 的一个内置工具,参数:
| 参数 | 说明 |
|---|---|
| `action` | `run`(默认)/ `libs`(列出环境里有哪些库) |
| `code` | 直接给源码 |
| `file` | 或者给一个 `.py` 文件路径 |
| `stdin` | 喂给脚本的标准输入 |
| `timeout` | 秒;不传就用设置里的 `pythonRun` |
**怎么执行的**(`kernel/builtin_tools.py` 的 `_exec_source`):
```python
ns = {'__name__': '__main__', '__builtins__': builtins, ...}
exec(compile(source, filename, 'exec'), ns) # 全 builtins,没有沙箱
```
- 用的是**进程内的 CPython**(Chaquopy 嵌的)—— 安卓上起不了 Python 子进程
- `stdout` / `stderr` 用 `redirect_*` 捕获,`sys.exit()` 的 code 当退出码
- 其它异常打印**完整 traceback** 到 stderr(模型据此自我修正)
- `cwd` 临时切过去、跑完恢复
**能干什么**:算数、数据处理(`pandas` 要自己 `pip install`)、调网络
(`requests` / `httpx` / `urllib`)、读写文件。
**注意**:`redirect_stdout` 和 `chdir` 都是**进程级**的(Python 没有线程级实现),
所以并发跑两段 `python_run` 时,另一段的 `print` 也可能被收进本次结果。
本地单人用没问题,别指望它做多用户服务。
---
## 三、`shell`:AI 写的一条命令
参数 `command` / `cwd` / `timeout`。有一份**危险命令黑名单**
(`rm -rf /`、`mkfs`、`dd if=/dev/zero`、frok 炸弹……),
可以用环境变量 `DOUBAO_SHELL_UNSAFE=1` 关掉黑名单。
黑名单是**防手滑**的,不是安全边界 —— 换个写法就绕过去了。
---
## 四、规则脚本(唯一有沙箱的地方)
给**数值系统 / 状态系统**用的脚本。写在「数值状态包」里,每轮在设备上跑。
### 三个入口函数
```python
def on_stat_change(name, value, delta):
"""数值裁决:返回生效的增量。可放大/缩小/归零否决。"""
if name == '声望':
return delta * 2 # 加倍
return delta # 原样
# return None → 否决(这次改动不生效)
# return (增量, "旁白") → 顺带给用户一句话
def on_turn(self_agent, stats_api):
"""每轮执行(状态脚本用)"""
...
def on_grant(status_name, source_agent):
"""别人给你挂状态时跑。返回 False = 抵抗掉。"""
if status_name == '中毒' and self_agent.get('世界') == '仙门':
return False
return True
```
### 注给脚本的能力(`stats_api`)
状态脚本通过 `stats_api` 读写数值(具体字段见 `rule_engine._stat_api`),
用它是**唯一**碰数据的方式 —— 脚本拿不到 store、agentdb 这些东西。
### 沙箱三层(`kernel/rule_sandbox.py`)
| 层 | 做什么 | 拦什么 |
|---|---|---|
| ① 静态扫描 | 源码里有 `__xx__`、`import`、`open/eval/exec/compile/getattr/...` → **直接拒绝** | 手滑、抄来的脚本夹带东西 |
| ② 受限 builtins | `exec` 时只喂白名单(算数、字符串、容器、异常) | 没有 `__import__` 就没有模块系统 |
| ③ 硬超时 | `customNode` 那一项(默认 10s) | 死循环 |
### 这个沙箱挡不住什么(写清楚,不装)
Python 的属性访问是**语法**,不走 builtins:
```python
().__class__.__bases__[0].__subclasses__()
```
第 1 层扫 `__` 就是堵它,但**字符串拼接能绕过去**。真想绕总能绕。
所以导入带脚本的规则包时,界面上的警告是**实话**:
> 此包包含可执行 Python 脚本,会**每轮在你的设备上运行**。
> 脚本被限制了模块引入和文件读写,但这**不是**真正的沙箱 ——
> 精心构造的脚本仍然可能读到设备上的文件。只导入你信得过的来源。
(而不是写"安全沙箱,请放心导入"。)
### 异常怎么处理
**异常 = 本次操作归零 + UI 提示,绝不中断对话。**
脚本是用户自己写的,写错是常态;一次 `1/0` 把整轮对话搞崩,
用户会以为整个 App 坏了。
### 脚本存在哪
- 定义在 `rulepacks.json` 的 `scripts` 字段里(跟着包走,可导出/导入)
- 执行时从 `data/rule-scripts/` 落盘读(脚本要作为文件被 `exec`)
---
## 五、会议画布的 Python 节点
会议(`ui/MeetingsScreen`)里有一种节点,代码框里写:
```python
def run(ctx):
ctx.log('收到:', ctx.input)
ctx.set_var('结果', ctx.input.upper())
return '跑完了'
```
**`ctx` 的 API**(`kernel/meeting.py`):
| 成员 | 说明 |
|---|---|
| `ctx.input` | 上游传进来的文本 |
| `ctx.vars` | 会议变量的**只读快照**(改它不影响会议) |
| `ctx.get_var(name, default='')` | 读变量 |
| `ctx.set_var(name, value)` | 写变量(真的写进会议变量表) |
| `ctx.log(*parts)` | 打印到节点日志(界面上能看到) |
| `ctx.node` | 当前节点的信息 |
- 每次执行都在**全新命名空间**里(节点之间不串变量)
- 必须定义 `run(ctx)`,否则报"代码里没有定义 run 函数"
- 输出截断到 `PY_MAX_OUTPUT`
- 超时 `meetingNode`(默认 10s),超了报"可能有死循环"
**没有沙箱** —— 就是跑代码。默认的 `__builtins__` 是全的。
---
## 六、自定义节点(`nodes/` 里的 `.py`)
放在**数据目录的 `nodes/`** 下(安卓上是 `files/kernel-data/nodes/`)。
文件名按字典序加载(顺序稳定,界面列表不跳),`_` 开头的跳过。
一个文件里写两段:
```python
ToolName = {
'name': '转大写',
'icon': 'text',
'input': [
{'type': 'str', 'name': 'A1', 'value': ''},
{'type': 'bool', 'name': 'B1', 'value': True},
],
'output': [
{'type': 'exec', 'name': 'e1'},
{'type': 'exec', 'name': 'e2'},
{'type': 'str', 'name': 'xx'},
],
}
def run(ctx, node):
ctx.log('收到:', node['input']['A1'])
node['output']['xx'] = '666'
node['output']['e1'] = True # 多个 exec 只能一个 True
node['output']['e2'] = False
return node
```
### 三条语义(**必须在文档和界面上都写清楚**,不然用户一定踩)
1. **`node['input'][名]` 是引擎填的**实际值,不是声明里的 `value`。
声明里的 `value` 只是"这根线没接时用什么"。
2. **多个 `exec` 输出最多只能有一个 `True`** —— 这就是多路分支:
- 恰好一个 True → 走那一条
- 一个都不 True → **停在原地** + 节点上一条警告(不猜、不顺走第一条)
- 超过一个 True → 报错(引擎没法替你选)
非 exec 的输出不受这条限制。
3. **`return` 什么无所谓** —— 引擎读的是 `node['output']`,不看返回值。
声明是"**同时有 `input` 和 `output` 两个键的字典**",变量名随便叫
(`ToolName` / `MyNode` / 中文都行)。
引脚类型:`exec`(执行)、`str`、`bool`、`num`、`list`。只能用标准库。
---
## 七、内置 Termux(真独立进程)
App 里内置了一套 Termux 环境(`files/usr/`),可以跑真的 `bash` / `python3` /
`apt` / `pip`。这是唯一**独立进程**的一处 —— 内核通过它的 CLI 跑命令,
超时键 `termux`(默认 30s)。
软件源已经指向清华 TUNA。第一次启动时会跑一串探针(12 条)验证环境可用。
---
## 八、项目自己的 `scripts/`(开发用,不跑在手机上)
`scripts/` 下有 60 多个 Python 脚本,分三类:
| 类别 | 例子 | 干什么 |
|---|---|---|
| **探针**(`probe-*.py`) | `probe-agent-system.py`、`probe-group-chat.py` | 不开 App、不联网,在电脑上跑内核逻辑逐条断言 |
| **验证**(`verify-*.py`) | `verify-nodekit.py`、`verify-tts-stream.py` | 验证某个子系统的行为或产物 |
| **审计**(`audit-*.py`) | `audit-ui-tree.py`、`audit-ui-entries.py` | 静态检查:文档和代码是否一致、每个界面有没有入口 |
| **工具** | `publish-release.py`、`build-apk.mjs` 配套脚本 | 发版、构建辅助 |
**八个常驻探针**(每次改动都要全绿):
```bash
python scripts/probe-agent-system.py
python scripts/probe-degraded.py
python scripts/probe-rule-sandbox.py
python scripts/probe-rule-engine.py
python scripts/probe-context-window.py
python scripts/probe-group-chat.py
python scripts/audit-ui-tree.py
python scripts/audit-ui-entries.py
```
它们**不需要装机、不需要网络**:把 `DOUBAO_DATA` 指到一个临时目录,
内核的存储层无状态,整条链路在一个进程里跑完。
### 写探针的一条硬纪律:走**生产同一条**调用路径
踩过:第 22 节直接调 `_set_asset`,而卡住真机的是 `handle()` 里的 `body()` ——
探针全绿、真机全挂。
> **探针能绕过的那一层,就是下次会出问题的那一层。**
同理,工具类探针要走 `tools_runtime.execute_tool`(它会把上下文搬到 worker 线程),
直接调 `agent_tools.xxx` 测的是"函数逻辑对不对",不是"它在这个系统里生不生效"。
---
## 九、安全边界(一张表说清)
| 地方 | 能读设备文件 | 能 import | 能联网 | 能起子进程 | 真沙箱 |
|---|---|---|---|---|---|
| `python_run` | ✅ | ✅ | ✅ | ❌(安卓没有) | ❌ |
| `shell` | ✅ | — | ✅ | ✅ | ❌(只有黑名单) |
| **规则脚本** | ❌ | ❌ | ❌ | ❌ | ⚠️ 白名单,**挡手滑不挡有意** |
| 会议 Python 节点 | ✅ | ✅ | ✅ | ❌ | ❌ |
| 自定义节点 | ✅ | ✅ | ✅ | ❌ | ❌ |
| Termux | ✅ | ✅ | ✅ | ✅ | ❌ |
**一句话**:除了规则脚本,其它几处都是"能跑代码"级别的能力 ——
只在你自己的设备上、你自己授权的前提下有意义。别把别人的包直接导进来。
---
## 十、相关文件
| 文件 | 作用 |
|---|---|
| `kernel/builtin_tools.py` | `shell` / `python_run` 两个内置工具 |
| `kernel/rule_sandbox.py` | 规则脚本的三层沙箱 |
| `kernel/rule_engine.py` | 规则脚本的入口调用、数值/状态流程 |
| `kernel/custom_nodes.py` | 自定义节点(声明 + `run`) |
| `kernel/meeting.py` | 会议画布、Python 节点执行 |
| `kernel/timeouts.py` | 所有超时键的默认值和说明 |
| `kernel/paths.py` | `rule-scripts/`、`nodes/` 等目录 |
| `RulePackEditScreen.kt` | 规则包编辑(含脚本框) |
| `NodeBlockEditor.kt` | 会议节点编辑(含 Python 代码框) |
| `scripts/probe-rule-sandbox.py` | 沙箱边界验证 |
| `scripts/probe-rule-engine.py` | 数值/状态系统验证 |

1203
docs/kernel-api-chat.md Normal file

File diff suppressed because it is too large Load Diff

1208
docs/kernel-api-misc.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,337 @@
# 数值状态系统 · 教程
手把手把「好感度」和「中毒」跑起来。看完你会知道:
- 数值/状态**从哪进、挂在哪**
- 一个规则包由什么组成
- 脚本怎么写(三个入口 + 沙箱的限制)
- **怎么确认它真的生效了**
配套参考:[`Python脚本.md`](Python脚本.md)(脚本的权限边界)、
[`智能体系统.md`](智能体系统.md)(需求项 → 文件对照)。
---
## 0. 先理解链路(这一步搞错后面全白做)
```
「世界观 · 技能 · 模型 → 规则包」建包 ← 定义:有哪些数值、哪些状态
↓
「世界观 · 技能 · 模型 → 世界观」挂上这个包 ← ★ 挂载点是**世界观**,不是智能体
↓
智能体绑这个世界观 ← 同一个世界观的智能体共用一个包
↓
它的提示词里就出现了 <stats> / <status>
↓
AI 用 change_stat / grant_status 改值 → 落库 → 下一轮反映新值
```
**为什么挂在世界观上**:数值是"这个世界的规则"(灵气、声望、门派贡献),
不是一个角色的私有物。而且这么设计之后,**共享数值(`shared=1`)天然只能
在一个世界观内共享**,和记忆用的是同一套 scope 写法 —— 用户不用学两套心智模型。
> ⚠️ 最容易卡住的一步:**建完包不挂到世界观**。不挂就没有
> `<stats>` / `<status>` 两段,AI 完全不知道有这回事。
---
## 1. 五分钟跑通一个「好感度」
### 1.1 建包
**抽屉 → 更多功能 → **世界观 · 技能 · 模型** → 顶栏切到「规则包」→ 右上角「新建」**。
建出来的包**自带模板**(好感度 + 中毒),可以直接拿来改。
### 1.2 看它长什么样
点进包 → 进「规则包编辑」全屏页。顶部两行是**名称**和**说明**,
下面是**脚本**区和**定义**区。
一个包的完整内容就是三样:
```jsonc
{
"stats": [
{
"name": "好感度", // ★ 唯一标识,脚本和工具里都用它
"min": 0, // 下限
"max": 100, // 上限
"shared": 0, // 0 = 每个智能体各算各的;1 = 全世界观一份
"ranges": [ // 区间表:命中哪段,就把那段文字注入提示词
{"min": 0, "max": 30, "text": "戒备:你对他还有戒心"},
{"min": 30, "max": 70, "text": "友善:你对他态度友善,但保持分寸"},
{"min": 70, "max": 100, "text": "亲近:你已经把他当自己人了"}
],
"script": "stat.py" // 可选:数值裁决脚本
}
],
"statuses": [
{
"name": "中毒",
"kind": "timed", // timed = 每轮减 1;persistent = 永不过期
"turns": 3, // timed 时持续几轮
"max_stack": 1, // 最多叠几层
"script": "status.py" // 可选:赋予判定 + 每轮行为
}
]
}
```
### 1.3 挂到世界观
**世界观 · 技能 · 模型 → 世界观 → 点开一个世界观 → 往下找「数值状态包」** →
选你刚建的那个包(选「不挂」就关掉)。
保存。
### 1.4 让智能体绑这个世界观
**智能体编辑 → 世界观** → 选同一个。
### 1.5 确认生效
打开那个智能体的对话,问它一句「你现在对我什么感觉」。
如果它的话里带上了 interval 表里的措辞("戒备"/"友善"/"亲近"),
说明 `<stats>` 段注进去了。
**更准的自查**:聊天页顶栏点状态栏 → 进 [状态数值] 页 ——
那里列着所有数值和当前值,**来源会写明来自哪个包**。
---
## 2. 数值怎么变
AI 只能调一个工具:
```
change_stat(name="好感度", delta=5)
```
**注意它只能给增量,不能写绝对值。** 这是刻意的:
- 允许写绝对值的话,"脚本裁决"就没意义了 —— 修正器要的是
"你想加 5,我判成加 10",而不是"你想设成 100,我判……多少"
- 群聊里两个智能体同时改同一个 shared 数值时,**绝对值互相覆盖,增量不会**
### 完整流程(顺序固定)
```
脚本裁决(有脚本时) → clamp 到 [min,max] → 写库 → 下一轮注入反映新值
```
| 环节 | 说明 |
|---|---|
| **脚本裁决** | 脚本返回生效的增量;可放大/缩小;返回 `None` = 否决 |
| **clamp** | 超界的值被钳到 `min`/`max` |
| **写库** | 按 scope 写(`agent:<uuid>` 或 `world:<uuid>`) |
| **下一轮注入** | 提示词里显示新值,**并且带一个 `450→500` 的箭头** |
那个箭头**只显示一轮**(放内存、用完就丢),它只是提示,不是数据。
### 注入的实际样子
```
[世界·九州] 声望: 450→500/1000 —— 名震九州:世人皆知你之名
[自身] 好感度: 45/100 —— 友善:你对他态度友善,但保持分寸
```
`[世界·xx]` / `[自身]` 前缀是自动加的,让模型知道哪些值是全世界的、
哪些是它自己的。
---
## 3. 状态怎么来、怎么没
### 赋予
AI 调:
```
grant_status(target="用户", status="中毒")
```
流程固定四条:
1. **必须同世界观** —— 跨世界观一律拒绝(没有共享规则体系,"赋予"没有依据)
2. 跑**目标方**的 `on_grant` 判定脚本 —— 判定权在被挂的人手里
3. 接受 → 实例化;拒绝 → 发起方收到「被抵抗」的明确回执
4. **同名重复赋予默认刷新轮数**(不是累加);定义里配了 `max_stack` 才叠层
### 消退
`timed` 的状态**每参与一轮减 1**,到 0 删除,并播报「中毒已经消退了」。
`persistent` 的状态**永不过期**(内部记 `remaining = -1`,不参与递减),
要移掉得用 `drop_status`。
---
## 4. 脚本怎么写
脚本是**可选的**。不写脚本,数值照样按增量改、状态照样到期消失 ——
脚本只在你要"额外的判断"时才需要。
### 4.1 数值裁决:`on_stat_change`
包里起个文件(比如 `stat.py`),在「规则包编辑 → 脚本」里新建并写:
```python
def on_stat_change(name, value, delta):
"""
name : 数值名
value : 改之前的值
delta : AI 想加的增量
返回 : 实际生效的增量
"""
if name == '好感度':
# 越熟越难加(边际递减)
if value >= 80:
return delta * 0.3
return delta
return delta
```
返回值有三种写法:
| 返回 | 含义 |
|---|---|
| 一个数字 | 生效的增量(可以跟 `delta` 不一样) |
| `None` | **否决**这次改动 |
| `(增量, "旁白")` | 顺带往这一轮的旁白里加一句 |
### 4.2 每轮行为:`on_turn`
```python
def on_turn(self_agent, stats_api):
"""每轮执行一次(状态脚本用)"""
...
```
### 4.3 赋予判定:`on_grant`
**跑在目标方** —— 被挂状态的人有权抵抗:
```python
def on_grant(status_name, source_agent):
"""返回 False = 抵抗掉这个状态"""
if status_name == '中毒' and self_agent.get('世界') == '仙门':
return False
return True
```
### 4.4 脚本不能做什么(这是硬限制)
规则脚本跑在**白名单沙箱**里:
- ❌ **不能 `import`**(没有模块系统)
- ❌ **不能 `open`**(读不了文件)
- ❌ 不能用 `eval` / `exec` / `getattr` / `__xx__` 这类东西
- ✅ 能算数、拼字符串、处理列表字典、`try/except`
**为什么这么严**:规则脚本是"数值修正器",正经写它根本用不到那些。
静态扫描拦的是"手滑"和"抄来的脚本夹带东西"。
> ⚠️ 但要说实话:**这个沙箱挡得住手滑,挡不住有意。**
> Python 的属性访问是语法,精心构造的代码*可能*绕过。
> 所以导入带脚本的包时,请只导你信得过的来源。
### 4.5 脚本写错了会怎样
**异常 = 本次操作归零 + 界面提示,不会中断对话。**
数字脚本报错时"这一次改动不生效",而不是"按原值放行" ——
宁可这一下不生效,也不能让坏脚本失控地改数值。
---
## 5. 界面上还有哪些地方能看到
| 界面 | 从哪进 | 看什么 |
|---|---|---|
| **[状态数值]** | 聊天页状态栏 / 智能体编辑的「它的状态」/ 群成员页的「状态」 | 所有数值的当前值 + 谁在挂这个包 |
| **规则包编辑** | 世界观 · 技能 · 模型 → 规则包 → 点一个包 | 改定义、写脚本、导出/导入 |
| **规则包列表** | 抽屉 → 更多功能 →「世界观 · 技能 · 模型」→ 切「规则包」 | 包列表,副标题写着有几条数值/状态、带不带脚本 |
**用户可以直接改值**(在 [状态数值] 页里)—— 这是兜底主权:
AI 记错了、脚本判歪了,得有一个人能直接拨回去。
---
## 6. 常见问题
<details>
<summary><b>AI 完全不知道有数值这回事</b></summary>
按顺序查:
1. **世界观挂包了吗** ← 最常见。「世界观 · 技能 · 模型 → 世界观 → 数值状态包」得选上
2. **智能体绑这个世界观了吗**
3. **包里有 `stats` 吗** —— 空包同步时会直接跳过(不动库)
4. 提示词里 `<stats>` 段在**最末尾**,模型如果只读了开头可能没注意 ——
直接问它"你的好感度现在多少"
</details>
<details>
<summary><b>改了值但提示词里还是旧的</b></summary>
数值是**每轮开始**才注入的。改完要**下一条消息**才看得到新值 ——
一次对话只有一次注入。
</details>
<details>
<summary><b>两个智能体的好感度互相串了</b></summary>
检查 `shared`:
- `shared=0` → `agent:<uuid>`,各算各的
- `shared=1` → `world:<uuid>`,整个世界观一份
串了说明定义里写成了 `shared=1`。
</details>
<details>
<summary><b>状态删不掉</b></summary>
分两种情况:
- **`timed`**:每参与一轮减 1,到 0 自己就没了。不想等就把 `turns` 改小。
- **`persistent`**:**永远不会自己过期**(内部记 `remaining = -1`)。
而**目前没有"移除状态"的工具** —— AI 手里只有 `grant_status`(只能加)。
所以 `persistent` 状态一旦挂上,界面上没有一键清掉的地方。
这是个已知缺口(要做的话,加一个 `drop_status` 工具 + 状态数值页的删除按钮就行)。
**绕开的办法**:把那个状态的 `kind` 改成 `timed` 并把 `turns` 设小,
重新保存定义;或者把状态名改掉(旧实例就成了读不到的孤儿,但不会再有影响)。
</details>
<details>
<summary><b>脚本报"用了双下划线属性"/"写了 import"</b></summary>
这是沙箱的静态扫描在拦。规则脚本**不需要**那些东西 ——
把 `import` 删掉,把 `xxx.__yyy__` 换成普通写法。
</details>
<details>
<summary><b>删了数值定义,值去哪了</b></summary>
**值还在库里,但读不到了** —— 定义没了它们就成了孤儿。
所以内核有一条保护:**空定义不同步**(不会因为读不到包就把定义清空)——
要清定义就把整个包删掉,那是个明确得多的动作。
</details>
---
## 7. 最小可用清单
想最快看到效果,记住这四步就够:
1. **世界观 · 技能 · 模型 → 规则包 → 新建**(用模板)
2. **世界观 · 技能 · 模型 → 世界观 → 数值状态包 → 选它**
3. **智能体 → 世界观 → 选同一个**
4. 发一句话,问它"你现在对我什么感觉"
脚本可以先完全不管 —— 没有脚本,数值和状态照样工作。

View File

@@ -0,0 +1,73 @@
/** 从抓下来的 CSS 里提取 light 主题变量 + 关键组件类,汇总成一份参考。 */
import fs from 'node:fs';
import path from 'node:path';
const ROOT = path.resolve(import.meta.dirname, 'doubao-web-mirror');
const OUT = path.join(ROOT, 'styles');
const cssFiles = [];
const walk = (dir) => {
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, ent.name);
if (ent.isDirectory()) walk(p);
else if (ent.name.endsWith('.css')) cssFiles.push(p);
}
};
walk(path.join(ROOT, 'assets'));
console.log('CSS 文件:', cssFiles.length);
let all = '';
for (const f of cssFiles) all += '\n' + fs.readFileSync(f, 'utf8');
console.log('CSS 总长:', (all.length / 1048576).toFixed(2), 'MB');
// 1) light 主题变量块
const lightBlocks = [];
for (const m of all.matchAll(/([^{}]{0,80})\{([^{}]*--dbx-text-primary:#000[^{}]*)\}/g)) {
lightBlocks.push(m[0]);
}
const vars = {};
for (const block of lightBlocks) {
for (const m of block.matchAll(/(--dbx-[a-z0-9-]+):([^;{}]+);/g)) {
const [, k, v] = m;
if (v.includes('var(')) continue;
if (!(k in vars)) vars[k] = v.trim();
}
}
fs.writeFileSync(path.join(OUT, 'dbx-light-vars.json'), JSON.stringify(vars, null, 2), 'utf8');
console.log('light 主题变量:', Object.keys(vars).length, '个 → dbx-light-vars.json');
// 2) 常用工具类定义(按 DOM 里见到的类名精确找)
const wanted = [
'w-sidebar-width', 'text-28', 'text-dbx-text-primary', 'text-dbx-text-secondary',
'bg-dbx-bg-base-web', 'bg-dbx-bg-body-web', 's-font-small', 's-font-base', 's-font-h1',
'rounded-dbx-2xl', 'rounded-dbx-3xl', 'rounded-dbx-4xl', 'rounded-full',
'shadow-dbx-drop-shadow-sm', 'shadow-dbx-drop-shadow-xs',
];
const found = {};
for (const cls of wanted) {
const re = new RegExp('\\.' + cls.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\{[^}]*\\}', 'g');
const hits = [...all.matchAll(re)].map((m) => m[0]);
if (hits.length) found[cls] = hits.slice(0, 2).join(' || ');
}
fs.writeFileSync(path.join(OUT, 'key-classes.css'), Object.entries(found).map(([k, v]) => `/* ${k} */\n${v}`).join('\n\n'), 'utf8');
// 3) 字体相关的 @font-face(只留 family/src/weight)
const fontFaces = [...all.matchAll(/@font-face\{[^}]*\}/g)].map((m) => m[0]);
const fontSummary = new Map();
for (const face of fontFaces) {
const fam = (face.match(/font-family:([^;]+)/) || [])[1];
const src = (face.match(/src:url\(([^)]+)\)/) || [])[1];
const weight = (face.match(/font-weight:([^;]+)/) || [])[1];
if (!fam) continue;
const key = fam.replace(/["']/g, '') + '|' + (weight || '');
if (!fontSummary.has(key)) fontSummary.set(key, { family: fam.replace(/["']/g, ''), weight: weight || '', src: src || '' });
}
fs.writeFileSync(path.join(OUT, 'fonts.json'), JSON.stringify([...fontSummary.values()], null, 2), 'utf8');
console.log('字体:', [...fontSummary.keys()].join(', '));
// 4) 滚动条 / 圆角 / 阴影 token 概览
const radii = [...new Set([...all.matchAll(/--dbx-radius-[a-z0-9]+:([^;}]+)/g)].map((m) => m[1]))];
const shadows = [...new Set([...all.matchAll(/--dbx-drop-shadow-[a-z]+:([^;}]+)/g)].map((m) => m[1]))];
fs.writeFileSync(path.join(OUT, 'tokens.txt'), [
'# 圆角', ...radii, '', '# 阴影', ...shadows, '',
].join('\n'), 'utf8');
console.log('done');

View File

@@ -0,0 +1,154 @@
/**
* 精测豆包网页版布局:有效 CSS 变量、组件尺寸/间距、字体。
* 结果写到 .tmp-scrape/doubao-web-mirror/styles/metrics.json
*/
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const OUT = path.join(HERE, 'doubao-web-mirror');
const EDGE = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
const PORT = 9613;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const child = spawn(EDGE, ['--headless=new', '--no-sandbox', '--disable-gpu', '--disable-crash-reporter', '--no-first-run',
'--disable-extensions', '--hide-scrollbars', `--remote-debugging-port=${PORT}`,
`--user-data-dir=${path.join(os.tmpdir(), 'doubao-scrape-profile')}`, '--window-size=1440,900', 'about:blank'],
{ stdio: 'ignore', windowsHide: true });
async function findPage() {
for (let i = 0; i < 80; i += 1) {
try {
const list = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
const page = list.find((t) => t.type === 'page');
if (page?.webSocketDebuggerUrl) return page;
} catch { /* not up */ }
await sleep(300);
}
throw new Error('CDP 连不上');
}
function connect(wsUrl) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(wsUrl);
let id = 0;
const pending = new Map();
ws.addEventListener('open', () => resolve({
send(method, params = {}) {
const msgId = ++id;
ws.send(JSON.stringify({ id: msgId, method, params }));
return new Promise((res, rej) => pending.set(msgId, { res, rej }));
},
close() { ws.close(); },
}));
ws.addEventListener('error', reject);
ws.addEventListener('message', (ev) => {
const msg = JSON.parse(ev.data);
if (msg.id && pending.has(msg.id)) {
const { res, rej } = pending.get(msg.id);
pending.delete(msg.id);
msg.error ? rej(new Error(JSON.stringify(msg.error))) : res(msg.result);
}
});
});
}
const page = await findPage();
const cdp = await connect(page.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
await cdp.send('Page.navigate', { url: 'https://www.doubao.com/chat/' });
await sleep(15000);
const expr = `(() => {
const pick = (el) => {
if (!el) return null;
const s = getComputedStyle(el); const r = el.getBoundingClientRect();
return {
tag: el.tagName, cls: String(el.className).slice(0, 90),
text: (el.innerText || '').trim().replace(/\\n/g, ' / ').slice(0, 40),
rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)],
bg: s.backgroundColor, color: s.color, fs: s.fontSize, fw: s.fontWeight, lh: s.lineHeight,
ls: s.letterSpacing, br: s.borderRadius, border: s.border, shadow: s.boxShadow, pad: s.padding,
gap: s.gap, display: s.display, align: s.alignItems, justify: s.justifyContent,
};
};
const q = (sel) => document.querySelector(sel);
const byText = (needle, tag) => [...document.querySelectorAll(tag || '*')].reverse()
.find((el) => (el.innerText || '').trim() === needle);
const root = document.documentElement;
const cs = getComputedStyle(root);
const names = ['--dbx-text-primary','--dbx-text-secondary','--dbx-text-tertiary','--dbx-text-disable',
'--dbx-bg-body-web','--dbx-bg-base-web','--dbx-bg-base-1','--dbx-bg-base-2','--dbx-bg-base-3','--dbx-bg-float',
'--dbx-color-blue-100','--dbx-color-blue-400','--dbx-color-blue-500','--dbx-color-blue-600',
'--dbx-line-primary','--dbx-line-secondary','--dbx-border-primary','--dbx-static-white',
'--dbx-neutral-700','--dbx-neutral-1000-8','--dbx-fill-primary-50','--dbx-function-danger','--dbx-function-success',
'--dbx-fill-secondary','--dbx-fill-tertiary','--dbx-fill-quaternary','--dbx-brand-primary','--dbx-brand-blue'];
const vars = {};
for (const n of names) { const v = cs.getPropertyValue(n).trim(); if (v) vars[n] = v; }
const out = { vars, elements: {} };
const aside = q('aside') || q('nav');
out.elements.sidebar = pick(aside ? aside.parentElement : null);
out.elements.sidebarPanel = pick(aside);
out.elements.brand = pick(byText('豆包', 'div') || byText('豆包', 'span'));
const navTexts = ['新工作任务', '新对话', '项目', 'API 服务', '更多'];
out.elements.navItems = {};
for (const t of navTexts) {
const label = [...document.querySelectorAll('div,span')].find((el) => (el.innerText || '').trim() === t);
if (!label) continue;
let row = label;
for (let i = 0; i < 4 && row.parentElement; i += 1) row = row.parentElement;
out.elements.navItems[t] = { label: pick(label), row: pick(row) };
}
out.elements.greeting = pick(byText('有什么我能帮你的吗?', 'div'));
const chips = [...document.querySelectorAll('div')].filter((el) => /一吨100元|一万步|欧元|胃真的/.test(el.innerText || '') );
const chip = chips.filter((el) => { const r = el.getBoundingClientRect(); return r.width > 100 && r.height > 20 && r.height < 80; })
.sort((a, b) => a.getBoundingClientRect().height - b.getBoundingClientRect().height)[0];
out.elements.recommendChip = pick(chip);
out.elements.recommendLabel = pick(byText('为你推荐', 'div') || byText('为你推荐', 'span'));
const ta = q('textarea');
out.elements.textarea = pick(ta);
if (ta) {
let box = ta;
for (let i = 0; i < 6 && box.parentElement; i += 1) box = box.parentElement;
out.elements.inputWrap = pick(box);
// 输入框最外层:找有较大圆角和边框的祖先
let cur = ta; const chain = [];
for (let i = 0; i < 10 && cur; i += 1) { chain.push(pick(cur)); cur = cur.parentElement; }
out.elements.inputChain = chain;
}
// 顶部工具条
const collapseBtn = [...document.querySelectorAll('button,div')].find((el) => el.getBoundingClientRect().x > 280 && el.getBoundingClientRect().x < 330 && el.getBoundingClientRect().y < 80 && el.getBoundingClientRect().y > 0);
out.elements.topCollapseIcon = pick(collapseBtn);
const loginBtn = byText('登录', 'button') || byText('登录', 'div');
out.elements.loginBtn = pick(loginBtn);
// 字体
out.fonts = [];
for (const sheet of document.styleSheets) {
try { for (const rule of sheet.cssRules) if (rule instanceof CSSFontFaceRule) out.fonts.push(rule.cssText.slice(0, 400)); } catch { /* */ }
}
out.bodyFont = getComputedStyle(document.body).fontFamily.slice(0, 120);
out.bodyBg = getComputedStyle(document.body).backgroundColor;
out.mainBg = pick(document.querySelector('main'));
return JSON.stringify(out);
})()`;
const r = await cdp.send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true });
const value = r.result?.value || '{}';
fs.writeFileSync(path.join(OUT, 'styles', 'metrics.json'), value, 'utf8');
try {
const j = JSON.parse(value);
console.log('vars:', Object.keys(j.vars || {}).length, '| navItems:', Object.keys(j.elements?.navItems || {}).length, '| fonts:', (j.fonts || []).length);
console.log(JSON.stringify(j.vars, null, 1));
for (const [k, v] of Object.entries(j.elements || {})) {
if (k === 'navItems' || k === 'inputChain') continue;
console.log(k, JSON.stringify(v));
}
} catch (e) { console.log('raw:', value.slice(0, 2000)); }
cdp.close();
child.kill();
await sleep(300);
process.exit(0);

View File

@@ -102,8 +102,14 @@ def main():
participants=[a['id']])
check("能加成员", G.add_member(c2, b['id']) is True)
check("重复加返回 False(不重复不报错)", G.add_member(c2, b['id']) is False)
check("**最后一个人不能被移出**(移掉群就空了)", G.remove_member(c2, a['id']) is False)
check("普通成员能移出", G.remove_member(c2, b['id']) is True)
# ★ 语义变了(用户要求「群聊去掉主人设定」):现在**谁都能移出**,
# 唯一的拒绝条件是"不能删到一个人都不剩"。所以原来那条
# "主智能体不能被移出" 已经废了 —— 断言跟着改。
check("第一个人也能移出(没有主人这回事了)", G.remove_member(c2, a['id']) is True)
check("删到剩一个 → 退回单聊",
not G.is_group(c2) and len(G.member_ids(c2)) == 1,
f"type={c2.get('type')} participants={G.member_ids(c2)}")
check("**最后一个人不能被移出**(移掉群就空了)", G.remove_member(c2, b['id']) is False)
# 单聊拉人 → 转成群聊
single = store.create_conversation('单聊', agent_id=a['id'])
check("单聊不是群聊", not G.is_group(single))
@@ -128,14 +134,18 @@ def main():
except ValueError as exc:
check("拉自己被拒", '自己' in str(exc), str(exc))
# 需确认模式:不直接拉人,让 AI 去问
before_ids = sorted(G.member_ids(store.get_conversation(c2['id']) or {}))
store.update_agent(a['id'], {'inviteMode': 'confirm'})
a2 = store.get_agent(a['id'])
tools_runtime.push_context(agentId=a2['id'], conversationId=c2['id'])
r = agent_tools.invite_agent({'target': '仙辰'})
check("**需确认模式不直接拉人**", r.get('needConfirm') is True, str(r))
check("需确认模式下人**没有**进群",
b['id'] not in G.member_ids(store.get_conversation(c2['id']) or {}),
str(G.member_ids(store.get_conversation(c2['id']) or {})))
# ★ 这里**不能**用"仙辰不在群里"来验证:`c2` 经过上面的增删只剩 `b`,
# 而"仙辰"就是 `b` —— 他本来就在。改成验证**成员列表一点没变**
# (这才是"没直接拉人"的正确判据,对任何初始状态都成立)。
check("需确认模式下成员一点没变",
sorted(G.member_ids(store.get_conversation(c2['id']) or {})) == sorted(before_ids),
f"{before_ids} vs {G.member_ids(store.get_conversation(c2['id']) or {})}")
check("提示 AI 去问用户", '问' in str(r.get('note')), str(r.get('note')))
# 静默模式:直接拉
store.update_agent(a['id'], {'inviteMode': 'silent'})
@@ -239,7 +249,8 @@ def main():
# 新一轮开始要重置
tools_runtime.begin_round()
check("新一轮开始后重置(可以再移交)",
tools_runtime.handoff_state() == {'to': '', 'used': False},
tools_runtime.handoff_state().get('to') == ''
and tools_runtime.handoff_state().get('used') is False,
str(tools_runtime.handoff_state()))
r3 = real_call('pass_turn', {'target': '仙辰'})
check("新一轮里又能移交了", r3.get('ok') is True, str(r3))
@@ -448,9 +459,12 @@ def main():
str(sorted(agent_tools.AGENT_TOOLS)))
if entry:
props = entry['spec'].get('parameters', {}).get('properties', {})
check("参数就是「智能体 + 内容」", set(props) == {'agent', 'content'}, str(list(props)))
check("两个都是必填",
set(entry['spec']['parameters'].get('required') or []) == {'agent', 'content'},
# ★ 参数演化过:最早是「agent + 内容」,后来加了多目标(agents)
# 和私聊(private),所以必填只剩 content —— 目标二选一。
check("参数含「目标 + 内容」",
{'agent', 'agents', 'content'} <= set(props), str(list(props)))
check("只要求 content 必填(agent/agents 二选一)",
list(entry['spec']['parameters'].get('required') or []) == ['content'],
str(entry['spec']['parameters'].get('required')))
# ★ 模型要能看见它 —— AGENT_TOOLS 会被合并进 BUILTIN_TOOLS 才是真注册
import builtin_tools
@@ -539,6 +553,51 @@ def main():
"没讲清区别 —— 模型会继续拿 pass_turn 当说话用")
check("写明了「一轮最多一次」", '一轮最多一次' in _skill, "模型会一轮调好几次")
print("\n=== 20. 加人接口必须真的进得去(真机反馈「点加人没反应」)===")
#
# ★★ 真机现场:点「加人」→ 选人 → 没反应、人也没加到,接口回 **404 未知接口**。
#
# 原因不是路由没写,而是它用 `_match_id(pathname, '/api/conversations/')`
# 去解析 id —— 那个函数要求「id 后面没有斜杠」,而这条路是
# `/api/conversations/<id>/members`,`rest` 里带 `/` 直接返回 None,
# **整个分支永远进不去**。
#
# 这条断言守的就是"别再退回去用 _match_id"。
check("成员增删路由自己解析 id(不能用 _match_id)",
"if pathname.startswith('/api/conversations/') and '/members' in pathname:" in _app,
"又用回 _match_id 了 —— 加人会 404")
print("\n=== 21. talk_to 多目标 / 私聊 + 群聊里能看到谁说的 ===")
#
# 用户的三个要求:
# ① 智能体能读到群里**所有人**的发言(不是只看到自己的)
# ② talk_to 加私聊:只有目标知道
# ③ talk_to 支持多目标:目标挨个回话
spec2 = agent_tools.AGENT_TOOLS['talk_to']['spec']['parameters']
props2 = spec2.get('properties', {})
check("talk_to 支持 `agents` 多目标", 'agents' in props2, str(list(props2)))
check("`agents` 是数组", props2.get('agents', {}).get('type') == 'array', str(props2.get('agents')))
check("talk_to 支持 `private` 私聊", 'private' in props2, str(list(props2)))
check("只要求 content 必填(agent/agents 二选一)",
spec2.get('required') == ['content'], str(spec2.get('required')))
# 移交状态要能带队列(多目标挨个回话靠它)
import tools_runtime as _tr
_tr.begin_round()
_tr.note_handoff('a', queue=['a', 'b', 'c'])
_st = _tr.handoff_state()
check("移交状态带队列(多目标挨个回)",
_st.get('to') == 'a' and _st.get('queue') == ['b', 'c'], str(_st))
_tr.begin_round()
check("新一轮把队列也清掉", _tr.handoff_state().get('queue') == [], str(_tr.handoff_state()))
# 群聊里送进模型的历史要标发言人 + 过滤别人的私聊
check("送进模型的历史标了发言人(`[名字] ` 前缀)",
'_[who]' in _app.replace('[', '_[', 1) or 'f\'[{_who}] {_content}\'' in _app,
"没标发言人 —— 模型分不清哪句是别人说的")
check("别人的私聊消息会被过滤掉(`privateTo`)",
"m.get('privateTo')" in _app, "没过滤 —— 私聊会被全群看到")
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")

View File

@@ -0,0 +1,323 @@
/**
* 扒豆包网页版 v2:不靠 CDP 取 body(会被驱逐),改用性能条目列表 + Node fetch 下载。
* 产出:截图、渲染后 DOM、离线副本、计算样式、内联 CSS、图标 SVG、全部 CDN 资源、MHTML。
*/
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const OUT = path.join(HERE, 'doubao-web-mirror');
const EDGE = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
const PORT = 9612;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
fs.rmSync(OUT, { recursive: true, force: true });
for (const d of ['screenshots', 'dom', 'styles', 'icons', 'assets', 'inline']) {
fs.mkdirSync(path.join(OUT, d), { recursive: true });
}
const child = spawn(EDGE, [
'--headless=new', '--no-sandbox', '--disable-gpu', '--disable-crash-reporter',
'--no-first-run', '--disable-extensions', '--hide-scrollbars',
`--remote-debugging-port=${PORT}`,
`--user-data-dir=${path.join(os.tmpdir(), 'doubao-scrape-profile')}`,
'--window-size=1440,900',
'about:blank',
], { stdio: 'ignore', windowsHide: true });
async function findPage() {
for (let i = 0; i < 80; i += 1) {
try {
const list = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
const page = list.find((t) => t.type === 'page');
if (page?.webSocketDebuggerUrl) return page;
} catch { /* not up */ }
await sleep(300);
}
throw new Error('CDP 连不上');
}
function connect(wsUrl) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(wsUrl);
let id = 0;
const pending = new Map();
const handlers = [];
ws.addEventListener('open', () => resolve({
send(method, params = {}) {
const msgId = ++id;
ws.send(JSON.stringify({ id: msgId, method, params }));
return new Promise((res, rej) => pending.set(msgId, { res, rej }));
},
on(fn) { handlers.push(fn); },
close() { ws.close(); },
}));
ws.addEventListener('error', reject);
ws.addEventListener('message', (ev) => {
const msg = JSON.parse(ev.data);
if (msg.id && pending.has(msg.id)) {
const { res, rej } = pending.get(msg.id);
pending.delete(msg.id);
msg.error ? rej(new Error(JSON.stringify(msg.error))) : res(msg.result);
} else if (msg.method) {
for (const fn of handlers) fn(msg);
}
});
});
}
const evaluate = async (expression) => {
const r = await cdp.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
return r.result?.value;
};
const shoot = async (name) => {
const shot = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(OUT, 'screenshots', name), Buffer.from(shot.data, 'base64'));
console.log('[scrape] 截图', name);
};
const click = async (x, y) => {
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y });
await cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });
await sleep(70);
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });
await sleep(700);
};
const page = await findPage();
const cdp = await connect(page.webSocketDebuggerUrl);
const consoleLines = [];
cdp.on((msg) => {
if (msg.method === 'Runtime.consoleAPICalled') {
consoleLines.push('[console.' + msg.params.type + '] ' + (msg.params.args || []).map((a) => a.value ?? a.description ?? a.type).join(' ').slice(0, 500));
}
if (msg.method === 'Runtime.exceptionThrown') {
consoleLines.push('[exception] ' + JSON.stringify(msg.params.exceptionDetails).slice(0, 800));
}
});
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
await cdp.send('Page.navigate', { url: 'https://www.doubao.com/chat/' });
console.log('[scrape] 导航完成,等渲染…');
await sleep(16000);
// 1) 关弹窗
const dismissed = await evaluate(`(() => {
const btns = [...document.querySelectorAll('button,div,span')].filter((el) => {
const s = getComputedStyle(el); const r = el.getBoundingClientRect();
return r.width > 10 && r.width < 60 && r.height > 10 && r.height < 60 && (s.cursor === 'pointer' || el.tagName === 'BUTTON');
});
const x = btns.find((el) => { const r = el.getBoundingClientRect(); return r.x > 1000 && r.x < 1200 && r.y > 150 && r.y < 280; });
if (x) { x.click(); return 'clicked at ' + Math.round(x.getBoundingClientRect().x) + ',' + Math.round(x.getBoundingClientRect().y); }
return 'no-modal';
})()`);
console.log('[scrape] 弹窗:', dismissed);
await sleep(2000);
await shoot('01-empty-chat-1440x900.png');
// 2) 点输入框、输入一句话,看有内容时的发送按钮
await click(860, 813);
await cdp.send('Input.insertText', { text: '帮我写一段产品介绍' });
await sleep(800);
await shoot('02-input-filled.png');
await evaluate(`(() => { const ta = document.querySelector('textarea'); if (ta) { ta.value=''; ta.dispatchEvent(new Event('input', {bubbles:true})); } document.activeElement && document.activeElement.blur(); return 1; })()`);
await sleep(600);
// 3) 切到「工作」页签看看
const seg = await evaluate(`(() => {
const els = [...document.querySelectorAll('div,span,button')].filter((el) => (el.innerText||'').trim() === '工作');
const el = els[els.length - 1];
if (!el) return null;
const r = el.getBoundingClientRect();
return [Math.round(r.x + r.width/2), Math.round(r.y + r.height/2)];
})()`);
if (seg) { await click(seg[0], seg[1]); await sleep(1500); await shoot('03-work-tab.png'); }
// 4) 回「对话」
const seg2 = await evaluate(`(() => {
const els = [...document.querySelectorAll('div,span,button')].filter((el) => (el.innerText||'').trim() === '对话');
const el = els[els.length - 1];
if (!el) return null;
const r = el.getBoundingClientRect();
return [Math.round(r.x + r.width/2), Math.round(r.y + r.height/2)];
})()`);
if (seg2) { await click(seg2[0], seg2[1]); await sleep(1200); }
// 5) 收集:DOM / 性能资源 / 计算样式 / 内联 CSS / 图标 SVG / CSS 变量
const domHtml = await evaluate(`'<!doctype html>\\n' + document.documentElement.outerHTML`);
fs.writeFileSync(path.join(OUT, 'dom', 'page.rendered.html'), domHtml, 'utf8');
console.log('[scrape] 渲染后 DOM:', (domHtml.length / 1024).toFixed(0), 'KB');
const resources = await evaluate(`JSON.stringify(performance.getEntriesByType('resource').map((e) => ({ name: e.name, type: e.initiatorType, size: e.transferSize || 0 })))`);
const resList = JSON.parse(resources || '[]');
fs.writeFileSync(path.join(OUT, 'styles', 'resource-urls.json'), JSON.stringify(resList, null, 2), 'utf8');
console.log('[scrape] 性能条目资源数:', resList.length);
const computed = await evaluate(`(() => {
const pick = (el) => {
if (!el) return null;
const s = getComputedStyle(el); const r = el.getBoundingClientRect();
return {
tag: el.tagName, cls: String(el.className).slice(0, 120),
text: (el.innerText || '').trim().slice(0, 50),
rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)],
bg: s.backgroundColor, color: s.color, fs: s.fontSize, fw: s.fontWeight, lh: s.lineHeight,
br: s.borderRadius, border: s.border, shadow: s.boxShadow, pad: s.padding,
gap: s.gap, display: s.display, font: s.fontFamily.slice(0, 90),
};
};
const at = (x, y) => document.elementFromPoint(x, y);
const byText = (needle, tag = '*') => [...document.querySelectorAll(tag)].reverse().find((el) => (el.innerText || '').trim().includes(needle));
const out = {
viewport: { w: innerWidth, h: innerHeight, dpr: devicePixelRatio },
sidebar: pick(at(10, 300)),
sidebarBrand: pick(byText('豆包', 'div')),
sidebarNavItem: pick(byText('新对话', 'div')),
greeting: pick(byText('有什么我能帮你的吗', 'h1,div,span,p')),
segmented: pick(byText('对话', 'div')),
inputBox: pick(at(860, 813)),
recommendChip: pick(byText('一吨100元', 'div')),
sendButton: pick(at(1390, 815)),
};
const vars = {};
for (const sheet of document.styleSheets) {
try {
for (const rule of sheet.cssRules) {
if (rule.style && rule.selectorText && /:root|data-theme/.test(rule.selectorText)) {
for (const name of rule.style) {
if (name.startsWith('--dbx-') || name.startsWith('--s-') || name.startsWith('--g-')) {
const val = rule.style.getPropertyValue(name).trim();
if (val) vars[name] = (name in vars ? vars[name] + ' | ' : '') + val;
}
}
}
}
} catch { /* 跨域 CSSOM */ }
}
out.cssVars = vars;
return JSON.stringify(out);
})()`);
fs.writeFileSync(path.join(OUT, 'styles', 'computed-styles.json'), computed || '{}', 'utf8');
console.log('[scrape] 计算样式 + CSS 变量已存');
const tree = await evaluate(`(() => {
const lines = [];
const walk = (el, depth, maxDepth) => {
if (!el || depth > maxDepth) return;
const r = el.getBoundingClientRect();
if (r.width < 2 || r.height < 2) return;
const s = getComputedStyle(el);
const cls = typeof el.className === 'string' ? el.className.trim().split(/\\s+/).slice(0, 3).join('.') : '';
const label = (el.innerText || '').trim().split('\\n')[0].slice(0, 34);
lines.push(' '.repeat(depth) + el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (cls ? '.' + cls : '')
+ ' [' + Math.round(r.x) + ',' + Math.round(r.y) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) + ']'
+ (s.backgroundColor !== 'rgba(0, 0, 0, 0)' ? ' bg=' + s.backgroundColor : '')
+ (s.color !== 'rgb(0, 0, 0)' ? ' c=' + s.color : '')
+ (label ? ' «' + label + '»' : ''));
if (depth < maxDepth) for (const c of el.children) walk(c, depth + 1, maxDepth);
};
walk(document.body, 0, 8);
return lines.join('\\n');
})()`);
fs.writeFileSync(path.join(OUT, 'dom', 'dom-tree.txt'), tree || '', 'utf8');
const inline = await evaluate(`JSON.stringify([...document.querySelectorAll('style')].map((s) => s.textContent))`);
fs.writeFileSync(path.join(OUT, 'inline', 'inline-styles.json'), inline || '[]', 'utf8');
const svgs = await evaluate(`JSON.stringify([...document.querySelectorAll('svg')].map((s) => s.outerHTML))`);
const svgList = JSON.parse(svgs || '[]');
const seen = new Set();
let svgIdx = 0;
for (const svg of svgList) {
const compact = svg.replace(/\s+/g, ' ').trim();
if (seen.has(compact)) continue;
seen.add(compact);
svgIdx += 1;
fs.writeFileSync(path.join(OUT, 'icons', `svg-${String(svgIdx).padStart(2, '0')}.svg`), svg, 'utf8');
}
console.log('[scrape] 图标 SVG 去重后:', svgIdx, '个');
// MHTML
try {
const mhtml = await cdp.send('Page.captureSnapshot', { format: 'mhtml' });
fs.writeFileSync(path.join(OUT, 'page.mhtml'), mhtml.data, 'utf8');
console.log('[scrape] MHTML 已存:', (fs.statSync(path.join(OUT, 'page.mhtml')).size / 1048576).toFixed(1), 'MB');
} catch (err) { console.warn('[scrape] MHTML 失败:', err.message); }
// 6) 用 Node 拉全部 CDN 资源
const safeName = (url) => {
const u = new URL(url);
let p = decodeURIComponent(u.pathname);
if (p.endsWith('/')) p += 'index.html';
const base = path.posix.basename(p) || 'file';
const dir = path.posix.dirname(p).replace(/(^|\/)\.\.?(\/|$)/g, '/');
const hash = Array.from(url).reduce((a, c) => ((a * 31 + c.charCodeAt(0)) | 0), 7).toString(36).slice(-6);
return path.posix.join('assets', dir.replace(/^\/+/, ''), `${hash}-${base.includes('.') ? base : base + '.bin'}`);
};
const localMap = new Map();
const manifest = { capturedAt: new Date().toISOString(), pageUrl: 'https://www.doubao.com/chat/', resources: [] };
const skipRe = /\/(api|mon|mcs|sami|bym|log|tracker|collect|slardar|apm|webmssdk)\b|\.gif($|\?)|googletagmanager|google-analytics|doubleclick/;
for (const res of resList) {
const url = res.name;
const entry = { url, type: res.type, size: res.size, local: null, error: null };
if (!/^https?:/.test(url) || skipRe.test(url)) { manifest.resources.push(entry); continue; }
try {
const resp = await fetch(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36',
Referer: 'https://www.doubao.com/chat/',
Origin: 'https://www.doubao.com',
},
signal: AbortSignal.timeout(30000),
});
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const buf = Buffer.from(await resp.arrayBuffer());
const rel = safeName(url);
fs.mkdirSync(path.dirname(path.join(OUT, rel)), { recursive: true });
fs.writeFileSync(path.join(OUT, rel), buf);
localMap.set(url, rel);
entry.local = rel;
entry.size = buf.length;
console.log('[scrape] 下载', (buf.length / 1024).toFixed(0) + 'KB', url.slice(0, 110));
} catch (err) {
entry.error = String(err.message || err).slice(0, 120);
}
manifest.resources.push(entry);
}
fs.writeFileSync(path.join(OUT, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf8');
console.log('[scrape] 资源下载完成:', localMap.size, '个');
// 7) 生成离线副本:绝对 URL → 本地相对路径
let offline = domHtml;
for (const [url, rel] of localMap) {
if (!offline.includes(url)) continue;
offline = offline.split(url).join(rel);
}
fs.writeFileSync(path.join(OUT, 'dom', 'page.offline.html'), offline, 'utf8');
// 把 CSS 里的 url() 也换成相对路径
let cssFixed = 0;
for (const [url, rel] of localMap) {
if (!rel.endsWith('.css')) continue;
const abs = path.join(OUT, rel);
let css = fs.readFileSync(abs, 'utf8');
let touched = false;
for (const [assetUrl, assetRel] of localMap) {
if (!css.includes(assetUrl)) continue;
const relFromCss = path.posix.relative(path.posix.dirname(rel), assetRel);
css = css.split(assetUrl).join(relFromCss);
touched = true;
}
if (touched) { fs.writeFileSync(abs, css, 'utf8'); cssFixed += 1; }
}
console.log('[scrape] 离线副本重写完成,CSS 修', cssFixed, '个');
fs.writeFileSync(path.join(OUT, 'console.log'), consoleLines.join('\n'), 'utf8');
console.log('[scrape] ✅ 完成 →', OUT);
cdp.close();
child.kill();
await sleep(500);
process.exit(0);

1692
web/assets/app.css Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
web/assets/avatars/cat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
web/assets/avatars/star.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@@ -1,227 +1,37 @@
<!doctype html>
<html lang="zh-CN">
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>豆包 · LynxJS 复刻</title>
<link rel="stylesheet" href="/static/css/client.css" />
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
background: radial-gradient(120% 120% at 50% 0%, #23262f 0%, #0e1014 60%);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
'Microsoft YaHei', sans-serif;
-webkit-font-smoothing: antialiased;
}
.stage {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
gap: 28px;
}
.phone {
position: relative;
width: 390px;
height: 844px;
border-radius: 42px;
background: #fff;
overflow: hidden;
box-shadow: 0 30px 70px rgba(0, 0, 0, 0.6), 0 0 0 10px #1b1e25,
0 0 0 11px #33373f;
}
.phone > lynx-view {
display: block;
width: 100%;
height: 100%;
}
.side {
color: #9aa3b2;
font-size: 13px;
line-height: 1.9;
max-width: 280px;
}
.side h1 {
font-size: 17px;
color: #e8ecf3;
margin: 0 0 10px;
font-weight: 600;
}
.side code {
background: #1b1f27;
padding: 1px 5px;
border-radius: 4px;
color: #9fd0ff;
}
.side button {
margin-top: 12px;
background: #2b7bff;
color: #fff;
border: 0;
border-radius: 10px;
padding: 9px 14px;
font-size: 13px;
cursor: pointer;
}
.side .tip {
margin-top: 8px;
color: #6b7482;
font-size: 12px;
}
@media (max-width: 900px) {
.side {
display: none;
}
}
@media (max-width: 460px), (max-height: 880px) {
.phone {
width: 100vw;
height: 100vh;
border-radius: 0;
box-shadow: none;
}
}
/* 桌面客户端模式:?frame=0 —— 去掉手机外壳,铺满窗口 */
html.frameless .stage {
display: block;
}
html.frameless .phone {
width: 100vw;
height: 100vh;
border-radius: 0;
box-shadow: none;
}
html.frameless .side {
display: none;
}
/* 拖拽上传遮罩 */
#drop-mask {
position: fixed;
inset: 0;
display: none;
align-items: center;
justify-content: center;
background: rgba(43, 123, 255, 0.14);
border: 3px dashed #2b7bff;
box-sizing: border-box;
color: #2b7bff;
font-size: 16px;
font-weight: 600;
z-index: 9999;
pointer-events: none;
}
#drop-mask.on {
display: flex;
}
</style>
</head>
<body>
<div class="stage">
<div class="phone">
<lynx-view url="/main.web.bundle"></lynx-view>
</div>
<aside class="side">
<h1>豆包 · LynxJS 复刻</h1>
界面由 <code>ReactLynx</code> 渲染,跑在 <code>@lynx-js/web-core</code> 上。<br />
AI 内核在 <code>/api</code>:火山方舟 / OpenAI + MCP + Python 工具。<br />
左上角 <code>☰</code> 是会话抽屉,右上角 <code>✎</code> 是内核设置。
<div>
<button id="pick">选择文件发给豆包</button>
<div class="tip">也可以直接把文件拖进这个窗口。</div>
</div>
</aside>
</div>
<div id="drop-mask">松手即可发送文件</div>
<input id="file-input" type="file" multiple style="display: none" />
<meta name="color-scheme" content="light dark" />
<title>豆包 · 网页版</title>
<link rel="stylesheet" href="/assets/app.css" />
<script>
// ?page=drawer|profile|settings|skills|agents 指定首屏;?frame=0 进桌面客户端模式
// 尽早定主题,避免白屏闪一下(自动跟随系统,用户可在设置里固定)
(function () {
var params = new URLSearchParams(location.search);
if (params.get('frame') === '0') {
document.documentElement.classList.add('frameless');
}
var wanted = params.get('page');
if (wanted) {
document
.querySelector('lynx-view')
.setAttribute('global-props', JSON.stringify({ initialPage: wanted }));
}
})();
/**
* 文件上传:浏览器和桌面版共用同一条路 ——
* 传到 /api/upload 并标记为 pending,Lynx 界面轮询到之后自动挂到输入框上。
*/
(function () {
var mask = document.getElementById('drop-mask');
function readAsDataUrl(file) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
async function upload(files) {
for (var i = 0; i < files.length; i += 1) {
var file = files[i];
try {
var dataUrl = await readAsDataUrl(file);
await fetch('/api/upload', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: file.name, dataUrl: dataUrl, pending: true }),
});
} catch (err) {
console.error('[upload] 失败', file.name, err);
}
}
}
var depth = 0;
window.addEventListener('dragenter', function (e) {
e.preventDefault();
depth += 1;
mask.classList.add('on');
});
window.addEventListener('dragover', function (e) {
e.preventDefault();
});
window.addEventListener('dragleave', function (e) {
e.preventDefault();
depth = Math.max(0, depth - 1);
if (depth === 0) mask.classList.remove('on');
});
window.addEventListener('drop', function (e) {
e.preventDefault();
depth = 0;
mask.classList.remove('on');
if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) {
upload(e.dataTransfer.files);
}
});
var pick = document.getElementById('pick');
var input = document.getElementById('file-input');
if (pick && input) {
pick.addEventListener('click', function () {
input.click();
});
input.addEventListener('change', function () {
if (input.files && input.files.length) upload(input.files);
input.value = '';
});
}
try {
var t = localStorage.getItem('doubao.theme') || 'auto';
var dark = t === 'dark' || (t === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
} catch (e) {}
})();
</script>
<script type="module" src="/static/js/client.js"></script>
</head>
<body>
<div id="app">
<aside class="sidebar" id="sidebar"></aside>
<main class="main">
<header class="topbar" id="topbar"></header>
<div id="view" class="view"></div>
</main>
</div>
<!-- 首屏骨架:state 还没回来时先亮一下,别是白屏 -->
<div id="boot" class="boot">
<div class="boot-logo">豆包</div>
<div class="boot-status" id="boot-status">正在连接内核…</div>
</div>
<script type="module" src="/js/app.js"></script>
</body>
</html>

323
web/js/api.js Normal file
View File

@@ -0,0 +1,323 @@
/**
* 和后端 Python 内核通信的一层:fetch 封装 + 全局状态(state)+ 聊天轮询。
*
* 约定(和 Android 端 KernelClient 一致):
* - 内核失败也经常返回 HTTP 200 + { ok:false, error:"人话" },所以这里统一 throw ApiError,
* 界面层 catch 后直接 toast(error.message) 即可;
* - 设置保存只发改动过的字段(内核是浅合并,空字符串会清配置 —— 这是踩过的真 bug)。
*/
export class ApiError extends Error {
constructor(message, { status, body, path } = {}) {
super(message);
this.name = 'ApiError';
this.status = status;
this.body = body;
this.path = path;
}
}
async function request(method, path, body, opts = {}) {
const init = {
method,
headers: { ...(opts.headers || {}) },
};
if (body !== undefined) {
init.headers['Content-Type'] = 'application/json';
init.body = JSON.stringify(body);
}
let res;
try {
res = await fetch(path, init);
} catch (err) {
throw new ApiError('连不上内核(它可能还没启动好)', { path, body: String(err) });
}
const text = await res.text();
let json = null;
try { json = text ? JSON.parse(text) : null; } catch { /* 非 JSON */ }
if (!res.ok) {
const msg = (json && (json.error || json.message)) || `${res.status} ${res.statusText || '请求失败'}`;
throw new ApiError(msg, { status: res.status, body: json || text, path });
}
if (json && json.ok === false && json.error) {
throw new ApiError(json.error, { status: res.status, body: json, path });
}
return json;
}
export const api = {
get: (path, opts) => request('GET', path, undefined, opts),
post: (path, body, opts) => request('POST', path, body ?? {}, opts),
put: (path, body, opts) => request('PUT', path, body ?? {}, opts),
patch: (path, body, opts) => request('PATCH', path, body ?? {}, opts),
del: (path, opts) => request('DELETE', path, undefined, opts),
};
/* ------------------------------------------------------------------ */
/* 全局状态 */
/* ------------------------------------------------------------------ */
const listeners = new Map(); // topic -> Set<fn>
export const S = {
state: null, // 最近一次 /api/state
loading: true,
error: null,
ready: false,
route: 'chat',
conversationId: null, // 当前打开的会话
collapsed: localStorage.getItem('doubao.sidebar') === '1',
theme: localStorage.getItem('doubao.theme') || 'auto',
};
export function on(topic, fn) {
if (!listeners.has(topic)) listeners.set(topic, new Set());
listeners.get(topic).add(fn);
return () => listeners.get(topic).delete(fn);
}
export function emit(topic, payload) {
const set = listeners.get(topic);
if (set) for (const fn of [...set]) { try { fn(payload); } catch (err) { console.error('[emit]', topic, err); } }
const all = listeners.get('*');
if (all) for (const fn of [...all]) { try { fn(topic, payload); } catch { /* ignore */ } }
}
/** 拉一次全量状态(首屏 / 大改动之后) */
export async function loadState({ silent = false } = {}) {
try {
const state = await api.get('/api/state');
if (state && state.error) throw new ApiError(state.error);
S.state = state;
S.error = null;
S.ready = true;
if (!silent) S.loading = false;
emit('state', state);
return state;
} catch (err) {
S.error = err;
S.loading = false;
S.ready = true;
emit('state-error', err);
throw err;
}
}
/* 常用派生数据 ------------------------------------------------------ */
export const settings = () => (S.state && S.state.settings) || {};
export const agents = () => (S.state && S.state.agents) || [];
export const conversations = () => (S.state && S.state.conversations) || [];
export const providers = () => (S.state && S.state.providers) || {};
export const platform = () => (S.state && S.state.platform) || '';
export const activeAgent = () => {
const list = agents();
const id = settings().activeAgentId;
return list.find((a) => a.id === id) || list[0] || { id: 'a_doubao', name: '豆包', avatar: 'doubao' };
};
export const conversationById = (id) => conversations().find((c) => c.id === id) || null;
/** 只发改动过的字段(内核浅合并;全量下发会把没动过的键清空 —— 真出过这个 bug) */
export async function saveSettings(patch) {
if (!patch || !Object.keys(patch).length) return;
await api.put('/api/settings', patch);
await loadState({ silent: true });
}
/** 设置面板草稿 → 只挑和当前不同的键 */
export function settingsChanges(draft) {
const cur = settings();
const changes = {};
for (const [k, v] of Object.entries(draft)) {
if (JSON.stringify(cur[k]) !== JSON.stringify(v)) changes[k] = v;
}
return changes;
}
export async function saveTimeouts(values) {
await api.put('/api/timeouts', values);
await loadState({ silent: true });
}
/** 本地更新某个会话的概要(标题/预览/时间),避免整份 state 重拉 */
export function patchConversation(id, patch) {
if (!S.state || !Array.isArray(S.state.conversations)) return;
const conv = S.state.conversations.find((c) => c.id === id);
if (!conv) return;
Object.assign(conv, patch);
emit('conversations', S.state.conversations);
}
/** 把会话排到最前(内核在下一轮 state 里也会这么做,这里是本地即时反馈) */
export function bumpConversation(id) {
if (!S.state || !Array.isArray(S.state.conversations)) return;
const list = S.state.conversations;
const idx = list.findIndex((c) => c.id === id);
if (idx <= 0) return;
const [conv] = list.splice(idx, 1);
list.unshift(conv);
emit('conversations', list);
}
export async function refreshConversations() {
const res = await api.get('/api/conversations');
if (S.state) S.state.conversations = res.conversations || [];
emit('conversations', conversations());
return conversations();
}
/* ------------------------------------------------------------------ */
/* 会话相关 */
/* ------------------------------------------------------------------ */
export async function createConversation({ agentId, title, type = 'single', participants } = {}) {
const body = { type };
if (agentId) body.agentId = agentId;
if (title) body.title = title;
if (participants && participants.length) body.participants = participants;
const res = await api.post('/api/conversations', body);
const conv = res.conversation || res;
await refreshConversations();
return conv;
}
export async function getConversation(id) {
const res = await api.get(`/api/conversations/${encodeURIComponent(id)}`);
return res.conversation || res;
}
export async function patchConversationRemote(id, patch) {
const res = await api.patch(`/api/conversations/${encodeURIComponent(id)}`, patch);
return res.conversation || res;
}
export async function deleteConversation(id) {
await api.del(`/api/conversations/${encodeURIComponent(id)}`);
await refreshConversations();
}
/** 群聊成员增删:POST/DELETE /api/conversations/<id>/members[/<agentId>] */
export async function addMember(conversationId, agentId) {
const res = await api.post(`/api/conversations/${encodeURIComponent(conversationId)}/members`, { agentId });
return res.conversation;
}
export async function removeMember(conversationId, agentId) {
const res = await api.del(`/api/conversations/${encodeURIComponent(conversationId)}/members/${encodeURIComponent(agentId)}`);
return res.conversation;
}
/** 标记/取消标记某条消息为「重要」(按内容定位 —— 内核就是这么设计的) */
export async function markImportant(conversationId, content, role = '', important = null) {
const body = { content, role };
if (important != null) body.important = important;
return api.post(`/api/conversations/${encodeURIComponent(conversationId)}/important`, body);
}
/* ------------------------------------------------------------------ */
/* 聊天:POST /api/chat → 轮询 /api/chat/poll */
/* ------------------------------------------------------------------ */
/**
* 发一条消息并消费流式事件。
*
* 协议(和 Android 端 KernelClient.chat 完全一致):
* POST /api/chat body: {conversationId, message, transport:'poll', agentId?, attachments?,
* autoContinue?, forceSpeaker?}
* → {ok, runId}
* GET /api/chat/poll?runId=&cursor= → {ok, events:[…], cursor, done}
* 事件类型:start / delta / reasoning / tool_call / tool_result / speaker / handoff /
* status / rule_error / ui_results / rebased / saved / error / done
*
* @param {object} opts
* conversationId 会话 id
* message 正文(内核字段名就叫 message,不是 text)
* agentId 用哪个智能体
* attachments 附件数组(/api/upload 的返回)
* autoContinue 群聊自动续轮(没有用户消息)
* forceSpeaker 指定这一轮谁发言(群聊「让他接着说」)
* onEvent(ev) 每个增量事件
* signal AbortSignal,用来"停止生成"(只停轮询,服务端这一轮会自然跑完)
* @returns {Promise<{runId, aborted}>}
*/
export async function runChat(opts) {
const {
conversationId, message, agentId, attachments,
autoContinue = false, forceSpeaker = '',
onEvent, signal, pollInterval = 200,
} = opts || {};
const body = {
conversationId: conversationId || '',
message: message || '',
transport: 'poll',
};
if (agentId) body.agentId = agentId;
if (attachments && attachments.length) body.attachments = attachments;
if (autoContinue) body.autoContinue = true;
if (forceSpeaker) body.forceSpeaker = forceSpeaker;
const start = await api.post('/api/chat', body);
const runId = start && start.runId;
if (!runId) throw new ApiError('内核没有返回 runId', { path: '/api/chat', body: start });
if (signal && signal.aborted) return { runId, aborted: true };
let cursor = 0;
let idle = 0;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
while (true) {
if (signal && signal.aborted) return { runId, aborted: true };
let payload;
try {
payload = await api.get(`/api/chat/poll?runId=${encodeURIComponent(runId)}&cursor=${cursor}`);
} catch (err) {
// 内核偶发 500 不该直接毁掉这一轮:等一会儿再试,连续失败太久才抛
idle += 1;
if (idle > 30) throw err;
await sleep(400);
continue;
}
const events = (payload && payload.events) || [];
if (typeof payload.cursor === 'number') cursor = payload.cursor;
let done = !!(payload && payload.done);
for (const ev of events) {
if (!ev) continue;
if (ev.type === 'done' || ev.type === 'error') done = true;
if (onEvent) onEvent(ev);
}
if (done) return { runId, aborted: false };
idle = events.length ? 0 : idle + 1;
// 3 分钟没有任何新内容 = 上游卡住了(和安卓端一致)
if (idle > 900) throw new ApiError('超过 3 分钟没有新内容,已停止等待');
await sleep(pollInterval);
}
}
/** 让 AI 主动往会话里发一条(send_message 工具/群聊面板用) */
export async function sendSessionMessage({ conversationId, text, role, reply, depth }) {
return api.post('/api/session-message', { conversationId, text, role, reply, depth });
}
/* ------------------------------------------------------------------ */
/* 附件上传 */
/* ------------------------------------------------------------------ */
export function readAsDataUrl(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
export async function uploadFile(file, { pending = false } = {}) {
const dataUrl = await readAsDataUrl(file);
const res = await api.post('/api/upload', { name: file.name, dataUrl, pending });
return res.file;
}
/** 桌面版走内核的原生选文件(Electron 弹系统对话框);浏览器会返回 ok:false */
export async function pickFilesNative() {
const res = await api.post('/api/pick-file', {});
return res;
}

694
web/js/app.js Normal file
View File

@@ -0,0 +1,694 @@
/**
* 网页版入口:侧栏 + 顶栏 + 路由(hash)。
*
* 页面模块约定:
* pages/xxx.js 默认导出 render(container, ctx) → (可选)返回 cleanup 函数
* ctx = { params, navigate, onState(fn) },onState 注册的监听在离开页面时自动清掉。
*
* 路由表:
* #/chat 对话(默认)
* #/agents 智能体列表
* #/agents/:id 智能体编辑
* #/agents/:id/memories 记忆
* #/agents/:id/usage 用量
* #/groups 群聊管理
* #/resources 资源(世界观 / Skill / 模型 / 规则包)
* #/meetings 会议模式
* #/skills 技能 · 连接器
* #/notes 笔记
* #/screens AI 界面
* #/settings 设置
* #/me 我的
* #/about 关于
*/
import {
S, api, loadState, on, emit, settings, agents, conversations, providers, activeAgent,
refreshConversations, createConversation, saveSettings,
} from './api.js';
import {
h, mount, clear, icon, avatar, toast, openMenu, openModal, confirmBox, promptBox,
fmtRelative, copyText,
} from './ui.js';
/* ------------------------------------------------------------------ */
/* 侧栏导航表 */
/* ------------------------------------------------------------------ */
const NAV_MAIN = [
{ route: 'chat', label: '新对话', icon: 'new-chat', shortcut: 'Ctrl Shift K', action: 'new-chat' },
{ route: 'agents', label: '智能体', icon: 'bot' },
{ route: 'groups', label: '群聊', icon: 'users' },
{ route: 'resources', label: '资源', icon: 'layers' },
];
const NAV_MORE = [
{ route: 'meetings', label: '会议模式', icon: 'presentation' },
{ route: 'skills', label: '技能 · 连接器', icon: 'plug' },
{ route: 'notes', label: '笔记', icon: 'notebook' },
{ route: 'screens', label: 'AI 界面', icon: 'scan' },
];
/* ------------------------------------------------------------------ */
/* 小工具 */
/* ------------------------------------------------------------------ */
const view = () => document.getElementById('view');
const sidebarEl = () => document.getElementById('sidebar');
const topbarEl = () => document.getElementById('topbar');
const appEl = () => document.getElementById('app');
function setBoot(status) {
const boot = document.getElementById('boot');
const el = document.getElementById('boot-status');
if (!boot) return;
if (status === false) {
boot.classList.add('hide');
setTimeout(() => boot.remove(), 260);
return;
}
if (el) el.textContent = status;
}
export function applyTheme() {
const t = S.theme;
const dark = t === 'dark'
|| (t === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
}
export function toggleSidebar(force) {
const narrow = appEl().classList.contains('narrow');
const el = sidebarEl();
if (narrow) {
el.classList.toggle('open', force == null ? !el.classList.contains('open') : force);
renderNarrowMask();
return;
}
S.collapsed = force == null ? !S.collapsed : !force;
el.classList.toggle('collapsed', S.collapsed);
localStorage.setItem('doubao.sidebar', S.collapsed ? '1' : '0');
renderTopbar();
}
function renderNarrowMask() {
const existing = document.querySelector('.sidebar-mask');
const narrow = appEl().classList.contains('narrow');
const open = sidebarEl().classList.contains('open');
if (narrow && open) {
if (!existing) {
appEl().appendChild(h('div.sidebar-mask', { onclick: () => toggleSidebar(false) }));
}
} else if (existing) {
existing.remove();
}
}
function applyLayout() {
const narrow = window.innerWidth < 900;
appEl().classList.toggle('narrow', narrow);
if (!narrow) {
sidebarEl().classList.remove('open');
sidebarEl().classList.toggle('collapsed', S.collapsed);
}
renderNarrowMask();
}
/* ------------------------------------------------------------------ */
/* 路由 */
/* ------------------------------------------------------------------ */
const ROUTES = [
{ re: /^$/, page: 'chat', title: '对话' },
{ re: /^chat$/, page: 'chat', title: '对话' },
{ re: /^agents$/, page: 'agents', title: '智能体' },
{ re: /^agents\/([^/]+)$/, page: 'agent-edit', title: '编辑智能体', keys: ['id'] },
{ re: /^agents\/([^/]+)\/memories$/, page: 'memories', title: '记忆', keys: ['id'] },
{ re: /^agents\/([^/]+)\/usage$/, page: 'usage', title: '用量', keys: ['id'] },
{ re: /^groups$/, page: 'groups', title: '群聊' },
{ re: /^resources$/, page: 'resources', title: '资源' },
{ re: /^meetings$/, page: 'meetings', title: '会议模式' },
{ re: /^skills$/, page: 'skills', title: '技能 · 连接器' },
{ re: /^notes$/, page: 'notes', title: '笔记' },
{ re: /^screens$/, page: 'screens', title: 'AI 界面' },
{ re: /^settings$/, page: 'settings', title: '设置' },
{ re: /^me$/, page: 'me', title: '我的' },
{ re: /^about$/, page: 'about', title: '关于豆包' },
];
const pageModules = {
chat: () => import('./pages/chat.js'),
agents: () => import('./pages/agents.js'),
'agent-edit': () => import('./pages/agent-edit.js'),
memories: () => import('./pages/memories.js'),
usage: () => import('./pages/usage.js'),
groups: () => import('./pages/groups.js'),
resources: () => import('./pages/resources.js'),
meetings: () => import('./pages/meetings.js'),
skills: () => import('./pages/skills.js'),
notes: () => import('./pages/notes.js'),
screens: () => import('./pages/screens.js'),
settings: () => import('./pages/settings.js'),
me: () => import('./pages/me.js'),
about: () => import('./pages/about.js'),
};
const pageCache = new Map();
let currentCleanup = null;
let currentPageKey = null;
let navigating = false;
function parseHash() {
let raw = location.hash.replace(/^#\/?/, '');
if (!raw) raw = 'chat';
const [pathPart, queryPart] = raw.split('?');
const params = Object.fromEntries(new URLSearchParams(queryPart || ''));
if (S.conversationId) params.conversationId = S.conversationId;
return { path: pathPart, params };
}
export function navigate(path, params, { replace = false } = {}) {
const qs = new URLSearchParams(params || {}).toString();
// conversationId 不进 hash,放在 S 里(新对话会 hash 不变)
const target = `#/${path}${qs ? '?' + qs : ''}`;
if (replace) {
history.replaceState(null, '', target);
handleRoute();
} else if (location.hash === target) {
handleRoute();
} else {
location.hash = target;
}
}
async function handleRoute() {
if (navigating) return;
const { path, params } = parseHash();
let matched = null;
for (const r of ROUTES) {
const m = path.match(r.re);
if (m) {
matched = { ...r, match: m };
break;
}
}
if (!matched) { navigate('chat', {}, { replace: true }); return; }
const routeParams = { ...params };
(matched.keys || []).forEach((k, i) => { routeParams[k] = decodeURIComponent(matched.match[i + 1]); });
if (routeParams.conversationId) S.conversationId = routeParams.conversationId;
S.route = matched.page;
const key = matched.page;
if (currentCleanup) { try { currentCleanup(); } catch { /* ignore */ } currentCleanup = null; }
// 每个页面各自滚自己的容器,切换时保留 state(chat 页不销毁:来回切不丢草稿)
const container = view();
if (key !== 'chat') {
clear(container);
container.className = 'view page';
}
renderSidebarActive();
renderTopbar();
navigating = true;
try {
let mod = pageCache.get(key);
if (!mod) {
mod = await pageModules[key]();
pageCache.set(key, mod);
}
const cleanups = [];
const ctx = {
params: routeParams,
navigate,
onState(fn) { const off = on('state', fn); cleanups.push(off); return off; },
setTitle(t) { const title = t ? `${t} · 豆包` : '豆包 · 网页版'; document.title = title; },
};
document.title = `${matched.title} · 豆包`;
const maybeCleanup = mod.default(container, ctx);
currentCleanup = () => {
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
if (typeof maybeCleanup === 'function') maybeCleanup();
};
currentPageKey = key;
} catch (err) {
console.error('[route] 页面加载失败', err);
container.innerHTML = '';
container.classList.add('page');
container.appendChild(h('div.page-inner', {},
h('div.empty-state', {},
h('div.empty-state-title', '这个页面加载失败了'),
h('div.empty-state-desc', String(err && err.message || err)),
h('div', { style: 'margin-top:16px' },
h('button.btn', { onclick: () => location.reload() }, '刷新页面')))));
} finally {
navigating = false;
}
}
/* ------------------------------------------------------------------ */
/* 侧栏 */
/* ------------------------------------------------------------------ */
function renderSidebarActive() {
for (const el of sidebarEl().querySelectorAll('.sb-item[data-route]')) {
el.classList.toggle('active', el.dataset.route === S.route);
}
}
function convTitle(conv) {
return conv.title || '新对话';
}
function renderSidebar() {
const el = sidebarEl();
const scrollTop = (el.querySelector('.sb-convs') || {}).scrollTop || 0;
el.classList.toggle('collapsed', !appEl().classList.contains('narrow') && S.collapsed);
const brand = h('div.sb-brand', {},
h('div.sb-logo', {}, h('span.logo-dot', '豆'), '豆包'),
h('div.sb-brand-actions', {},
h('button.icon-btn.sm', {
title: '收起侧栏 (Ctrl+B)',
onclick: () => toggleSidebar(false),
}, icon('panel-left-close', 17)),
h('button.icon-btn.sm', { title: '搜索对话', onclick: openSearch }, icon('search', 17))));
const nav = h('div.sb-nav');
for (const item of NAV_MAIN) {
nav.appendChild(h('button.sb-item', {
'data-route': item.route,
class: item.route === 'chat' ? 'main-action' : '',
onclick: () => {
if (item.action === 'new-chat') { startNewChat(); return; }
navigate(item.route);
if (appEl().classList.contains('narrow')) toggleSidebar(false);
},
},
icon(item.icon, 18),
h('span.sb-label', item.label),
item.shortcut ? h('span.kbd', item.shortcut) : null));
}
// 「更多」= 次级页面(豆包侧栏也是这个结构:主入口 + 更多)
const moreActive = NAV_MORE.some((m) => m.route === S.route);
nav.appendChild(h('button.sb-item', {
class: moreActive ? 'active' : '',
onclick: (e) => {
const rect = e.currentTarget.getBoundingClientRect();
openMenu(e.currentTarget, NAV_MORE.map((m) => ({
label: m.label,
icon: m.icon,
onClick: () => { navigate(m.route); if (appEl().classList.contains('narrow')) toggleSidebar(false); },
})));
},
}, icon('more-horizontal', 18), h('span.sb-label', '更多'), h('span.kbd', '›')));
el.appendChild(brand);
el.appendChild(nav);
// 最近会话
el.appendChild(h('div.sb-section', {}, h('span', '最近')));
const convs = conversations();
const list = h('div.sb-convs');
if (!convs.length) {
list.appendChild(h('div.sb-empty', '还没有对话,点「新对话」开始。'));
}
for (const conv of convs) {
const isGroup = conv.type === 'group' || conv.kind === 'group' || conv.group;
const row = h(`div.sb-conv${isGroup ? '.group' : ''}${conv.id === S.conversationId ? '.active' : ''}${conv.pinned ? '.pinned' : ''}`, {
title: convTitle(conv),
onclick: () => openConversation(conv.id),
oncontextmenu: (e) => { e.preventDefault(); openConvMenu(e.currentTarget, conv); },
},
isGroup ? icon('users', 14, 'conv-icon') : null,
h('span.conv-title', convTitle(conv)),
h('button.conv-more', {
title: '更多',
onclick: (e) => { e.stopPropagation(); openConvMenu(e.currentTarget, conv); },
}, icon('more-horizontal', 15)));
list.appendChild(row);
}
el.appendChild(list);
// 底部
const foot = h('div.sb-foot', {},
h('button.sb-item', { class: S.route === 'settings' ? 'active' : '', onclick: () => navigate('settings') },
icon('settings', 18), h('span.sb-label', '设置')),
h('button.sb-item', { class: S.route === 'me' ? 'active' : '', onclick: () => navigate('me') },
icon('user', 18), h('span.sb-label', '我的')),
h('button.sb-item', { class: S.route === 'about' ? 'active' : '', onclick: () => navigate('about') },
icon('info', 18), h('span.sb-label', '关于豆包')));
el.appendChild(foot);
requestAnimationFrame(() => {
const sc = el.querySelector('.sb-convs');
if (sc) sc.scrollTop = scrollTop;
});
}
function openSearch() {
const modal = openModal({
title: '搜索对话',
width: 560,
body: buildSearchBody(),
});
function buildSearchBody() {
const input = h('input.input', { placeholder: '按标题搜索…', autofocus: 'autofocus' });
const result = h('div.search-results');
const renderResult = () => {
const q = input.value.trim().toLowerCase();
const list = conversations().filter((c) => !q || convTitle(c).toLowerCase().includes(q));
clear(result);
if (!list.length) { result.appendChild(h('div.sb-empty', '没有匹配的对话')); return; }
for (const conv of list.slice(0, 50)) {
result.appendChild(h('div.list-row.clickable', {
onclick: () => { modal.close(); openConversation(conv.id); },
},
h('div.list-main', {},
h('div.list-title', convTitle(conv)),
h('div.list-desc', `${conv.messageCount || 0} 条 · ${fmtRelative(conv.updatedAt)}`))));
}
};
input.addEventListener('input', renderResult);
setTimeout(() => input.focus(), 30);
renderResult();
return h('div', {}, input, h('div', { style: 'margin-top:8px' }, result));
}
}
function openConvMenu(anchor, conv) {
openMenu(anchor, [
{ label: '打开', icon: 'message-circle', onClick: () => openConversation(conv.id) },
{
label: conv.pinned ? '取消置顶' : '置顶',
icon: 'pin',
onClick: async () => {
try {
await api.patch(`/api/conversations/${encodeURIComponent(conv.id)}`, { pinned: !conv.pinned });
await refreshConversations();
renderSidebar();
} catch (err) { toast(err.message, { type: 'error' }); }
},
},
{
label: '重命名',
icon: 'pencil',
onClick: async () => {
const title = await promptBox({ title: '重命名对话', value: conv.title || '', okText: '保存' });
if (title == null) return;
try {
await api.patch(`/api/conversations/${encodeURIComponent(conv.id)}`, { title });
await refreshConversations();
renderSidebar();
} catch (err) { toast(err.message, { type: 'error' }); }
},
},
'-',
{
label: '删除对话',
icon: 'trash',
danger: true,
onClick: async () => {
const ok = await confirmBox({
title: '删除这个对话?',
message: `「${convTitle(conv)}」及其消息会被删除,不可恢复。`,
danger: true,
okText: '删除',
});
if (!ok) return;
try {
await api.del(`/api/conversations/${encodeURIComponent(conv.id)}`);
if (S.conversationId === conv.id) { S.conversationId = null; startNewChat(); }
await refreshConversations();
renderSidebar();
toast('已删除', { type: 'success' });
} catch (err) { toast(err.message, { type: 'error' }); }
},
},
], { alignRight: true });
}
/* ------------------------------------------------------------------ */
/* 顶栏 */
/* ------------------------------------------------------------------ */
function providerModelLabel() {
const st = settings();
const p = providers()[st.provider] || {};
const provLabel = p.label || st.provider || '未设置模型';
const model = st.model || p.defaultModel || '';
return { provLabel, model, hasKey: !!st.hasApiKey };
}
function renderTopbar() {
const el = topbarEl();
clear(el);
const narrow = appEl().classList.contains('narrow');
const collapsed = !narrow && S.collapsed;
const left = h('div.topbar-left', {});
left.appendChild(h('button.icon-btn', {
title: collapsed ? '展开侧栏 (Ctrl+B)' : '收起侧栏 (Ctrl+B)',
onclick: () => toggleSidebar(),
}, icon(collapsed || narrow ? 'panel-left-open' : 'panel-left', 19)));
if (S.route === 'chat') {
const agent = activeAgent();
left.appendChild(h('button.agent-chip', {
title: '切换智能体',
onclick: (e) => openAgentSwitch(e.currentTarget),
},
avatar(agent, 24),
h('span.agent-name', agent.name || '豆包'),
icon('chevron-down', 14, 'chevron')));
} else {
const title = (ROUTES.find((r) => r.page === S.route) || {}).title || '';
if (title) left.appendChild(h('div.topbar-title', title));
}
const { provLabel, model, hasKey } = providerModelLabel();
const right = h('div.topbar-right', {});
right.appendChild(h(`button.model-chip${hasKey ? '' : '.warn'}`, {
title: hasKey ? `${provLabel} · ${model}` : '还没配置 API Key,点这里去设置',
onclick: (e) => openModelMenu(e.currentTarget),
},
h(`span.model-dot${hasKey ? '' : '.off'}`),
h('span.model-name', hasKey ? (model || provLabel) : '未配置模型'),
icon('chevron-down', 14)));
const st = settings();
right.appendChild(h('button.icon-btn', {
title: st.speech && st.speech.autoRead ? '关闭自动朗读' : '开启自动朗读',
class: st.speech && st.speech.autoRead ? 'active' : '',
onclick: toggleAutoRead,
}, icon('volume', 18)));
right.appendChild(h('button.icon-btn', {
title: '更多',
onclick: (e) => openMoreMenu(e.currentTarget),
}, icon('more-horizontal', 18)));
el.appendChild(left);
el.appendChild(h('div.topbar-center'));
el.appendChild(right);
el.classList.toggle('sidebar-collapsed', collapsed);
}
function openAgentSwitch(anchor) {
const list = agents();
const items = list.map((a) => ({
label: a.name + (a.builtin ? '' : ' (自定义)'),
icon: 'bot',
hint: a.tagline || '',
onClick: () => switchAgent(a),
}));
items.push('-');
items.push({ label: '管理智能体…', icon: 'settings', onClick: () => navigate('agents') });
openMenu(anchor, items);
}
async function switchAgent(agent) {
try {
await saveSettings({ activeAgentId: agent.id });
toast(`已切换到「${agent.name}」`, { type: 'success' });
} catch (err) { toast(err.message, { type: 'error' }); }
}
function openModelMenu(anchor) {
const st = settings();
const p = providers()[st.provider] || {};
const models = (p.models || []).slice(0, 12);
const toModelKey = (m) => (m && typeof m === 'object' ? (m.id || m.model || m.name) : m);
const items = [];
if (!st.hasApiKey) {
items.push({ label: '还没配置 API Key → 去设置', icon: 'key', onClick: () => navigate('settings') });
items.push('-');
}
items.push({ label: `提供商:${p.label || st.provider || '未设置'}`, icon: 'cpu', onClick: () => navigate('settings') });
if (models.length) {
items.push('-');
for (const m of models) {
const key = toModelKey(m);
items.push({
label: key,
icon: 'check',
hint: key === st.model ? '当前' : '',
onClick: async () => {
try { await saveSettings({ model: key }); toast(`模型:${key}`, { type: 'success' }); } catch (err) { toast(err.message, { type: 'error' }); }
},
});
}
}
items.push('-');
items.push({ label: '全部提供商 / 思考强度…', icon: 'settings', onClick: () => navigate('settings') });
openMenu(anchor, items, { alignRight: true });
}
async function toggleAutoRead() {
const st = settings();
const speech = st.speech || {};
try {
await saveSettings({ speech: { ...speech, autoRead: !speech.autoRead } });
renderTopbar();
toast(speech.autoRead ? '已关闭自动朗读' : '已开启自动朗读:回复会自动念出来', { type: 'success' });
} catch (err) { toast(err.message, { type: 'error' }); }
}
function openMoreMenu(anchor) {
const themeLabel = S.theme === 'auto' ? '主题:跟随系统' : S.theme === 'dark' ? '主题:深色' : '主题:浅色';
openMenu(anchor, [
{ label: '新对话', icon: 'new-chat', hint: 'Ctrl Shift K', onClick: startNewChat },
{ label: '搜索对话', icon: 'search', onClick: openSearch },
'-',
{ label: '设置', icon: 'settings', onClick: () => navigate('settings') },
{ label: '技能 · 连接器', icon: 'plug', onClick: () => navigate('skills') },
{ label: '会议模式', icon: 'presentation', onClick: () => navigate('meetings') },
'-',
{
label: themeLabel,
icon: 'sun',
onClick: () => {
S.theme = S.theme === 'auto' ? 'light' : S.theme === 'light' ? 'dark' : 'auto';
localStorage.setItem('doubao.theme', S.theme);
applyTheme();
toast(S.theme === 'auto' ? '主题跟随系统' : S.theme === 'dark' ? '已切到深色' : '已切到浅色');
},
},
{ label: '编辑主题(更多)…', icon: 'moon', onClick: () => navigate('settings') },
'-',
{ label: '重新加载界面', icon: 'refresh', onClick: () => location.reload() },
], { alignRight: true });
}
/* ------------------------------------------------------------------ */
/* 对话切换 */
/* ------------------------------------------------------------------ */
export function startNewChat() {
S.conversationId = null;
if (S.route !== 'chat') navigate('chat');
else {
// 已经在 chat 页:通知页面重置
window.dispatchEvent(new CustomEvent('doubao:new-chat'));
}
renderSidebar();
refreshConversations().then(() => renderSidebar()).catch(() => {});
}
export function openConversation(id) {
S.conversationId = id;
if (S.route !== 'chat') navigate('chat');
else window.dispatchEvent(new CustomEvent('doubao:open-conversation', { detail: id }));
renderSidebar();
}
/* ------------------------------------------------------------------ */
/* 全局事件 */
/* ------------------------------------------------------------------ */
function bindGlobalKeys() {
document.addEventListener('keydown', (e) => {
const mod = e.ctrlKey || e.metaKey;
const tag = (e.target && e.target.tagName) || '';
const typing = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable);
if (mod && e.shiftKey && (e.key === 'K' || e.key === 'k')) {
e.preventDefault();
startNewChat();
} else if (mod && (e.key === 'b' || e.key === 'B')) {
e.preventDefault();
toggleSidebar();
} else if (mod && (e.key === 'k' || e.key === 'K') && !typing) {
e.preventDefault();
openSearch();
} else if (e.key === 'Escape' && !typing) {
window.dispatchEvent(new CustomEvent('doubao:escape'));
}
});
}
function bindWindow() {
let resizeTimer = null;
window.addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => { applyLayout(); renderNarrowMask(); }, 80);
});
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (S.theme === 'auto') applyTheme();
});
}
/* ------------------------------------------------------------------ */
/* 启动 */
/* ------------------------------------------------------------------ */
async function boot() {
S.collapsed = localStorage.getItem('doubao.sidebar') === '1';
applyTheme();
applyLayout();
renderSidebarSkeleton();
bindGlobalKeys();
bindWindow();
window.addEventListener('hashchange', handleRoute);
on('state', () => {
renderSidebar();
renderTopbar();
});
try {
setBoot('正在连接内核…');
await loadState();
setBoot(false);
} catch (err) {
console.error(err);
setBoot(false);
showBootError(err);
return;
}
renderSidebar();
renderTopbar();
if (!location.hash) history.replaceState(null, '', '#/chat');
handleRoute();
}
function renderSidebarSkeleton() {
const el = sidebarEl();
clear(el);
el.appendChild(h('div.sb-brand', {}, h('div.sb-logo', {}, h('span.logo-dot', '豆'), '豆包')));
el.appendChild(h('div.sb-empty', { style: 'padding:16px 8px' }, '正在加载…'));
}
function showBootError(err) {
const el = view();
el.className = 'view page';
mount(el, h('div.page-inner', {},
h('div.empty-state', {},
h('div.empty-state-icon', {}, icon('alert-triangle', 26)),
h('div.empty-state-title', '内核没起来'),
h('div.empty-state-desc', String((err && err.message) || err)),
h('div', { style: 'margin-top:16px;display:flex;gap:8px;justify-content:center' },
h('button.btn.primary', { onclick: () => location.reload() }, '重试')))));
}
boot();

95
web/js/icons.js Normal file
View File

@@ -0,0 +1,95 @@
/**
* 图标库 —— 全部是项目自己的手写路径(Lucide 风格,24x24,stroke=2),
* 不复制豆包的图标资源,只参考其线条风格。
*
* 用法:icon('send', 18) → <svg ...>
* 也可在 h() 里:h('span.icon', {icon:'send'})
*/
const P = {
// ---- 侧栏 / 导航 ----
'panel-left': '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/>',
'panel-left-open': '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/><path d="m14 9 3 3-3 3"/>',
'panel-left-close': '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/><path d="m17 9-3 3 3 3"/>',
'pen-square': '<path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.4 2.6a2.1 2.1 0 0 1 3 3L8 19l-4 1 1-4Z"/>',
'new-chat': '<path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.4 2.6a2.1 2.1 0 0 1 3 3L8 19l-4 1 1-4Z"/>',
'message-circle': '<path d="M21 11.5a8.4 8.4 0 0 1-8.5 8.5 8.5 8.5 0 0 1-3.8-.9L3 21l1.9-5.7a8.5 8.5 0 1 1 16.1-3.8Z"/>',
'message-square': '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z"/>',
'bot': '<rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><path d="M8 16h.01"/><path d="M16 16h.01"/>',
'users': '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
'layers': '<path d="m12 2 10 5-10 5L2 7Z"/><path d="m2 17 10 5 10-5"/><path d="m2 12 10 5 10-5"/>',
'presentation': '<path d="M2 3h20"/><path d="M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"/><path d="m7 21 5-5 5 5"/>',
'plug': '<path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/>',
'settings': '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"/>',
'info': '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',
'download': '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>',
'search': '<circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/>',
'sun': '<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.9 4.9 1.4 1.4"/><path d="m17.7 17.7 1.4 1.4"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.3 17.7-1.4 1.4"/><path d="m19.1 4.9-1.4 1.4"/>',
'moon': '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>',
'user': '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
'more-horizontal': '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
'chevron-down': '<path d="m6 9 6 6 6-6"/>',
'chevron-right': '<path d="m9 18 6-6-6-6"/>',
'chevron-left': '<path d="m15 18-6-6 6-6"/>',
'arrow-left': '<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>',
'arrow-up': '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',
'plus': '<path d="M12 5v14"/><path d="M5 12h14"/>',
'mic': '<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><path d="M12 19v3"/>',
'paperclip': '<path d="m21.4 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>',
'camera': '<path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3Z"/><circle cx="12" cy="13" r="3"/>',
'image': '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/>',
'file-text': '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/>',
'globe': '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
'copy': '<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>',
'thumbs-up': '<path d="M7 10v12"/><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"/>',
'thumbs-down': '<path d="M17 14V2"/><path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"/>',
'share': '<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.59 13.51 6.83 3.98"/><path d="m15.41 6.51-6.82 3.98"/>',
'volume': '<path d="M11 5 6 9H2v6h4l5 4V5Z"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>',
'volume-x': '<path d="M11 5 6 9H2v6h4l5 4V5Z"/><path d="m22 9-6 6"/><path d="m16 9 6 6"/>',
'refresh': '<path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/>',
'x': '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
'check': '<path d="M20 6 9 17l-5-5"/>',
'trash': '<path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>',
'pin': '<path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1Z"/>',
'pencil': '<path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/>',
'sparkles': '<path d="m12 3 1.9 5.8a2 2 0 0 0 1.3 1.3L21 12l-5.8 1.9a2 2 0 0 0-1.3 1.3L12 21l-1.9-5.8a2 2 0 0 0-1.3-1.3L3 12l5.8-1.9a2 2 0 0 0 1.3-1.3Z"/>',
'brain': '<path d="M12 5a3 3 0 0 0-5.9 1 3 3 0 0 0-2 5 3 3 0 0 0 2 5 3 3 0 0 0 5.9 1"/><path d="M12 5a3 3 0 0 1 5.9 1 3 3 0 0 1 2 5 3 3 0 0 1-2 5 3 3 0 0 1-5.9 1"/><path d="M12 5v14"/>',
'square': '<rect x="4" y="4" width="16" height="16" rx="3"/>',
'clock': '<circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>',
'notebook': '<path d="M4 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2Z"/><path d="M8 2v20"/><path d="M12 7h5"/><path d="M12 11h5"/><path d="M12 15h5"/>',
'terminal': '<path d="m4 17 6-6-6-6"/><path d="M12 19h8"/>',
'key': '<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>',
'alert-triangle': '<path d="m21.7 18-8-14a2 2 0 0 0-3.4 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.7-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',
'folder': '<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>',
'external-link': '<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',
'list': '<path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/>',
'sliders': '<path d="M4 21v-7"/><path d="M4 10V3"/><path d="M12 21v-9"/><path d="M12 8V3"/><path d="M20 21v-5"/><path d="M20 12V3"/><path d="M2 14h4"/><path d="M10 8h4"/><path d="M18 16h4"/>',
'cpu': '<rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><path d="M9 2v2"/><path d="M15 2v2"/><path d="M9 20v2"/><path d="M15 20v2"/><path d="M2 9h2"/><path d="M2 15h2"/><path d="M20 9h2"/><path d="M20 15h2"/>',
'shield': '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/>',
'at-sign': '<circle cx="12" cy="12" r="4"/><path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-3.9 7.9"/>',
'hash': '<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>',
'play': '<path d="m6 3 14 9-14 9V3Z"/>',
'pause': '<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>',
'arrow-right': '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',
'arrow-down': '<path d="m7 5 5 5 5-5"/><path d="M12 5v14"/>',
'image-plus': '<path d="M21 15V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/><path d="M19 22v-6"/><path d="M16 19h6"/>',
'database': '<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/>',
'book': '<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2Z"/>',
'history': '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>',
'stop-circle': '<circle cx="12" cy="12" r="10"/><rect x="9" y="9" width="6" height="6" rx="1"/>',
'grip-vertical': '<circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/>',
'scan': '<path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><path d="M7 12h10"/>',
'types': '<path d="M12 4v16"/><path d="M4 7V5h16v2"/><path d="M9 20h6"/>',
'heart': '<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>',
'download-cloud': '<path d="M12 13v8l-4-4"/><path d="m12 21 4-4"/><path d="M4.39 15A7 7 0 1 1 15.7 6.1"/>',
};
/**
* 返回图标的 SVG 字符串(由 ui.js 负责塞进 DOM,避免反向依赖)。
*/
export function iconHtml(name, size = 18) {
const body = P[name];
if (!body) return '';
return `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
}
export const ICON_NAMES = Object.keys(P);

1208
web/js/pages/chat.js Normal file

File diff suppressed because it is too large Load Diff

608
web/js/ui.js Normal file
View File

@@ -0,0 +1,608 @@
/**
* 网页版基础 UI 库:DOM 构造、Markdown、图标、弹层、Toast、表单小部件。
*
* 设计目标:不引任何第三方依赖(要能离线装进 exe、也要能被 Python 内核直接托管),
* 所以用 200 行左右的 h() + 手写 markdown 渲染,页面全部按"函数返回 DOM"的方式写。
*/
import { iconHtml } from './icons.js';
/* ------------------------------------------------------------------ */
/* DOM */
/* ------------------------------------------------------------------ */
const SVG_NS = 'http://www.w3.org/2000/svg';
function classListOf(tag) {
let cls = null;
// div.foo.bar#id → tag=div, classes=[foo,bar], id=id
const hashAt = tag.indexOf('#');
let id = null;
if (hashAt >= 0) {
id = tag.slice(hashAt + 1);
tag = tag.slice(0, hashAt);
}
const dotAt = tag.indexOf('.');
if (dotAt >= 0) {
cls = tag.slice(dotAt + 1).split('.').filter(Boolean);
tag = tag.slice(0, dotAt);
}
return { tag: tag || 'div', cls, id };
}
function appendChild(node, child) {
if (child == null || child === false || child === true) return;
if (Array.isArray(child)) {
for (const c of child) appendChild(node, c);
return;
}
if (child instanceof Node) {
node.appendChild(child);
return;
}
node.appendChild(document.createTextNode(String(child)));
}
/**
* h('div.card', {onclick, style:{}, className}, ...children)
* style 既可以是对象也可以是字符串。
*/
export function h(tag, props, ...children) {
if (Array.isArray(props) || typeof props === 'string' || typeof props === 'number' || props instanceof Node) {
children.unshift(props);
props = null;
}
const { tag: name, cls, id } = classListOf(tag);
const node = document.createElement(name);
if (id) node.id = id;
if (cls && cls.length) node.className = cls.join(' ');
if (props) {
for (const [key, value] of Object.entries(props)) {
if (value == null || value === false) continue;
if (key === 'style') {
if (typeof value === 'string') node.setAttribute('style', value);
else for (const [k, v] of Object.entries(value)) { if (v != null && v !== '') node.style.setProperty(k, String(v)); }
} else if (key === 'className' || key === 'class') {
node.className = node.className ? `${node.className} ${value}` : String(value);
} else if (key === 'html') {
node.innerHTML = String(value);
} else if (key === 'dataset') {
for (const [k, v] of Object.entries(value)) node.dataset[k] = String(v);
} else if (key.startsWith('on') && typeof value === 'function') {
node.addEventListener(key.slice(2).toLowerCase(), value);
} else if (key === 'ref' && typeof value === 'function') {
value(node);
} else if (value === true) {
node.setAttribute(key, '');
} else {
node.setAttribute(key, String(value));
}
}
}
for (const child of children) appendChild(node, child);
return node;
}
/** HTML 字符串 → 元素(第一个子元素)。 */
export function el(html) {
const tpl = document.createElement('template');
tpl.innerHTML = html.trim();
return tpl.content.firstElementChild;
}
export function frag(...children) {
const f = document.createDocumentFragment();
for (const c of children) appendChild(f, c);
return f;
}
export function clear(node) {
while (node && node.firstChild) node.removeChild(node.firstChild);
}
export function mount(parent, ...children) {
clear(parent);
for (const c of children) appendChild(parent, c);
return parent;
}
/** 少写点 document.getElementById */
export const $ = (sel, root = document) => root.querySelector(sel);
export const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
export function on(target, type, handler, opts) {
target.addEventListener(type, handler, opts);
return () => target.removeEventListener(type, handler, opts);
}
/* ------------------------------------------------------------------ */
/* 图标 / 头像 */
/* ------------------------------------------------------------------ */
export function icon(name, size = 18, extraClass = '') {
const span = h(`span.icon${extraClass ? '.' + extraClass : ''}`);
span.innerHTML = iconHtml(name, size);
return span;
}
/** 头像:优先用立绘/头像图,退回内置 PNG,再退回首字母色块。 */
export function avatar(agent, size = 36, extraClass = '') {
const name = (agent && agent.name) || 'AI';
const key = (agent && (agent.avatar || agent.id) || 'custom').replace(/^a_/, '');
const known = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'cloud', 'robot', 'star', 'custom'];
const file = known.includes(key) ? key : 'custom';
// 智能体包里的自定义头像
const custom = agent && agent.image && agent.image.avatar;
const src = typeof custom === 'string' && custom ? custom : `/assets/avatars/${file}.png`;
const img = h('img.avatar-img', {
src,
alt: name,
onerror: (e) => { e.target.src = '/assets/avatars/custom.png'; },
});
const span = h(`span.avatar${extraClass ? '.' + extraClass : ''}`, { style: `width:${size}px;height:${size}px` }, img);
return span;
}
/* ------------------------------------------------------------------ */
/* 文本工具 */
/* ------------------------------------------------------------------ */
export function escapeHtml(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
export function fmtTime(iso) {
if (!iso) return '';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
const now = new Date();
const sameDay = d.toDateString() === now.toDateString();
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
if (sameDay) return `${hh}:${mm}`;
const y = d.getFullYear() === now.getFullYear() ? '' : `${d.getFullYear()}年`;
return `${y}${d.getMonth() + 1}月${d.getDate()}日 ${hh}:${mm}`;
}
export function fmtRelative(iso) {
if (!iso) return '';
const t = new Date(iso).getTime();
if (Number.isNaN(t)) return '';
const diff = Date.now() - t;
if (diff < 60_000) return '刚刚';
if (diff < 3600_000) return `${Math.floor(diff / 60_000)} 分钟前`;
if (diff < 86400_000) return `${Math.floor(diff / 3600_000)} 小时前`;
return fmtTime(iso);
}
export function fmtNumber(n) {
if (n == null || Number.isNaN(Number(n))) return '-';
const v = Number(n);
if (v >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
if (v >= 1e4) return `${(v / 1e4).toFixed(2)}万`;
return String(v);
}
export function fmtBytes(n) {
if (n == null) return '-';
const units = ['B', 'KB', 'MB', 'GB'];
let v = Number(n);
let i = 0;
while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }
return `${v.toFixed(i ? 1 : 0)} ${units[i]}`;
}
export function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
export function debounce(fn, ms = 200) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
export function uid(prefix = 'x') {
return `${prefix}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`;
}
/* ------------------------------------------------------------------ */
/* Markdown(够用就好:标题/列表/代码块/表格/引用/加粗/链接) */
/* ------------------------------------------------------------------ */
function inlineMd(text) {
const codes = [];
let s = text.replace(/`([^`\n]+)`/g, (_, c) => {
codes.push(c);
return `\u0000C${codes.length - 1}\u0000`;
});
s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_, alt, src) => `<a href="${src}" target="_blank" rel="noreferrer">[图片]${alt ? ' ' + alt : ''}</a>`);
s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noreferrer">$1</a>');
s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
s = s.replace(/(^|[\s(])\*([^*\n]+)\*/g, '$1<em>$2</em>');
s = s.replace(/~~([^~]+)~~/g, '<del>$1</del>');
s = s.replace(/\u0000C(\d+)\u0000/g, (_, i) => `<code>${codes[i]}</code>`);
return s;
}
function renderTable(rows) {
// rows[0] 表头,rows[1] 是 |---|---| 分隔行
const head = rows[0].split('|').map((c) => c.trim()).filter((c, i, a) => !(i === 0 && c === '') && !(i === a.length - 1 && c === ''));
const body = rows.slice(2).map((line) => line.split('|').map((c) => c.trim()).filter((c, i, a) => !(i === 0 && c === '') && !(i === a.length - 1 && c === '')));
const thead = `<thead><tr>${head.map((c) => `<th>${inlineMd(c)}</th>`).join('')}</tr></thead>`;
const tbody = `<tbody>${body.map((r) => `<tr>${r.map((c) => `<td>${inlineMd(c)}</td>`).join('')}</tr>`).join('')}</tbody>`;
return `<div class="md-table"><table>${thead}${tbody}</table></div>`;
}
/** markdown → HTML 字符串(内容先转义,代码块单独处理) */
export function mdToHtml(src) {
const text = String(src == null ? '' : src).replace(/\r\n?/g, '\n');
const lines = text.split('\n');
const out = [];
let i = 0;
const flushParagraph = (buf) => {
if (!buf.length) return;
out.push(`<p>${buf.map((l) => inlineMd(escapeHtml(l))).join('<br>')}</p>`);
buf.length = 0;
};
const para = [];
while (i < lines.length) {
const line = lines[i];
// 代码块
const fence = line.match(/^\s*```(\w*)\s*$/);
if (fence) {
flushParagraph(para);
const lang = fence[1] || '';
const code = [];
i += 1;
while (i < lines.length && !/^\s*```\s*$/.test(lines[i])) { code.push(lines[i]); i += 1; }
i += 1;
out.push(
`<div class="codeblock"><div class="codeblock-head"><span class="codeblock-lang">${escapeHtml(lang || 'code')}</span>`
+ '<button class="codeblock-copy" type="button">复制</button></div>'
+ `<pre><code>${escapeHtml(code.join('\n'))}</code></pre></div>`,
);
continue;
}
// 表格
if (/\|/.test(line) && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s:|-]*$/.test(lines[i + 1])) {
flushParagraph(para);
const rows = [line, lines[i + 1]];
i += 2;
while (i < lines.length && /\|/.test(lines[i]) && lines[i].trim()) { rows.push(lines[i]); i += 1; }
out.push(renderTable(rows));
continue;
}
// 标题
const heading = line.match(/^(#{1,6})\s+(.*)$/);
if (heading) {
flushParagraph(para);
const level = Math.min(6, heading[1].length + 2); // 聊天里 h1 太重,从 h3 起
out.push(`<h${level}>${inlineMd(escapeHtml(heading[2]))}</h${level}>`);
i += 1;
continue;
}
// 分隔线
if (/^\s*(---|\*\*\*)\s*$/.test(line)) {
flushParagraph(para);
out.push('<hr>');
i += 1;
continue;
}
// 引用
if (/^\s*>\s?/.test(line)) {
flushParagraph(para);
const quote = [];
while (i < lines.length && /^\s*>\s?/.test(lines[i])) { quote.push(lines[i].replace(/^\s*>\s?/, '')); i += 1; }
out.push(`<blockquote>${quote.map((q) => inlineMd(escapeHtml(q))).join('<br>')}</blockquote>`);
continue;
}
// 无序 / 有序列表
if (/^\s*[-*+]\s+/.test(line) || /^\s*\d+\.\s+/.test(line)) {
flushParagraph(para);
const ordered = /^\s*\d+\.\s+/.test(line);
const items = [];
while (i < lines.length && (/^\s*[-*+]\s+/.test(lines[i]) || /^\s*\d+\.\s+/.test(lines[i]))) {
items.push(lines[i].replace(/^\s*(?:[-*+]|\d+\.)\s+/, ''));
i += 1;
}
out.push(`<${ordered ? 'ol' : 'ul'}>${items.map((it) => `<li>${inlineMd(escapeHtml(it))}</li>`).join('')}</${ordered ? 'ol' : 'ul'}>`);
continue;
}
if (!line.trim()) {
flushParagraph(para);
i += 1;
continue;
}
para.push(line);
i += 1;
}
flushParagraph(para);
return out.join('\n');
}
/** 把 markdown 渲染进容器,并给代码块挂上"复制"按钮 */
export function renderMarkdown(container, src) {
container.innerHTML = mdToHtml(src);
container.classList.add('markdown');
for (const btn of container.querySelectorAll('.codeblock-copy')) {
btn.addEventListener('click', () => {
const code = btn.closest('.codeblock')?.querySelector('code');
copyText(code ? code.textContent : '').then(() => {
btn.textContent = '已复制';
setTimeout(() => { btn.textContent = '复制'; }, 1200);
});
});
}
return container;
}
/* ------------------------------------------------------------------ */
/* 剪贴板 */
/* ------------------------------------------------------------------ */
export async function copyText(text) {
const value = String(text == null ? '' : text);
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(value);
return true;
}
} catch { /* 落到下面 */ }
try {
// 非 https / 内核页面里 navigator.clipboard 可能不可用,走内核原生钩子
if (location.protocol === 'http:' && location.hostname === '127.0.0.1') {
const res = await fetch('/api/clipboard', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: value }),
});
const json = await res.json().catch(() => ({}));
if (json.ok) return true;
}
} catch { /* ignore */ }
// 最后的退路:textarea + execCommand
try {
const ta = document.createElement('textarea');
ta.value = value;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
return ok;
} catch {
return false;
}
}
/* ------------------------------------------------------------------ */
/* Toast / 弹层 */
/* ------------------------------------------------------------------ */
let toastRoot = null;
export function toast(message, opts = {}) {
if (!toastRoot) {
toastRoot = h('div.toast-root');
document.body.appendChild(toastRoot);
}
const type = opts.type || 'info';
const node = h(`div.toast.toast-${type}`, opts.html ? { html: String(message) } : {}, opts.html ? null : String(message));
toastRoot.appendChild(node);
requestAnimationFrame(() => node.classList.add('on'));
const duration = opts.duration || 2600;
setTimeout(() => {
node.classList.remove('on');
setTimeout(() => node.remove(), 220);
}, duration);
return node;
}
/** 居中弹窗:返回 { el, close }(打开时自动关掉 Esc) */
export function openModal(opts = {}) {
const wrap = h('div.modal-mask');
const box = h('div.modal', { style: opts.width ? `width:${opts.width}px` : null });
const head = h('div.modal-head', {},
h('div.modal-title', String(opts.title || '')),
h('button.icon-btn.modal-x', { onclick: () => close(), title: '关闭' }, icon('x', 18)));
const body = h('div.modal-body');
if (opts.body) appendChild(body, opts.body);
else if (opts.content != null) body.innerHTML = String(opts.content);
box.appendChild(head);
box.appendChild(body);
if (opts.footer) {
const foot = h('div.modal-foot');
appendChild(foot, opts.footer);
box.appendChild(foot);
}
wrap.appendChild(box);
document.body.appendChild(wrap);
requestAnimationFrame(() => wrap.classList.add('on'));
function onKey(e) {
if (e.key === 'Escape') { e.stopPropagation(); close(); }
}
document.addEventListener('keydown', onKey, true);
wrap.addEventListener('mousedown', (e) => { if (e.target === wrap && !opts.persistent) close(); });
let closed = false;
function close() {
if (closed) return;
closed = true;
document.removeEventListener('keydown', onKey, true);
wrap.classList.remove('on');
setTimeout(() => wrap.remove(), 180);
if (opts.onClose) opts.onClose();
}
return { el: box, body, close };
}
export function confirmBox(opts = {}) {
return new Promise((resolve) => {
let done = false;
const finish = (v) => { if (done) return; done = true; modal.close(); resolve(v); };
const modal = openModal({
title: opts.title || '确认',
width: opts.width || 420,
body: h('div.confirm-body', {},
h('div.confirm-text', String(opts.message || '')),
opts.hint ? h('div.confirm-hint', String(opts.hint)) : null),
footer: h('div.modal-actions', {},
h('button.btn', { onclick: () => finish(false) }, opts.cancelText || '取消'),
h(`button.btn.primary${opts.danger ? '.danger' : ''}`, { onclick: () => finish(true) }, opts.okText || '确定')),
onClose: () => finish(false),
});
});
}
export function promptBox(opts = {}) {
return new Promise((resolve) => {
let done = false;
const input = opts.multiline
? h('textarea.input.textarea', { rows: 5, placeholder: opts.placeholder || '' })
: h('input.input', { placeholder: opts.placeholder || '', value: opts.value || '' });
if (opts.multiline) input.value = opts.value || '';
const finish = (v) => { if (done) return; done = true; modal.close(); resolve(v); };
const modal = openModal({
title: opts.title || '输入',
width: opts.width || 480,
body: h('div.prompt-body', {}, input),
footer: h('div.modal-actions', {},
h('button.btn', { onclick: () => finish(null) }, '取消'),
h('button.btn.primary', { onclick: () => finish(input.value) }, opts.okText || '确定')),
onClose: () => finish(null),
});
setTimeout(() => input.focus(), 30);
if (!opts.multiline) {
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') finish(input.value); });
}
});
}
/** 下拉菜单:items = [{label, icon, danger, disabled, hint, onClick}] */
export function openMenu(anchor, items, opts = {}) {
closeAllMenus();
const menu = h('div.menu');
for (const item of items) {
if (item === '-') { menu.appendChild(h('div.menu-sep')); continue; }
menu.appendChild(h(`button.menu-item${item.danger ? '.danger' : ''}`, {
disabled: item.disabled ? 'disabled' : null,
onclick: (e) => {
e.stopPropagation();
if (item.disabled) return;
closeMenu();
item.onClick && item.onClick();
},
}, item.icon ? icon(item.icon, 16) : null, h('span.menu-label', String(item.label || '')), item.hint ? h('span.menu-hint', String(item.hint)) : null));
}
document.body.appendChild(menu);
const rect = anchor.getBoundingClientRect();
const mw = menu.offsetWidth;
const mh = menu.offsetHeight;
let x = opts.alignRight ? rect.right - mw : rect.left;
let y = rect.bottom + 6;
x = Math.max(8, Math.min(x, window.innerWidth - mw - 8));
if (y + mh > window.innerHeight - 8) y = Math.max(8, rect.top - mh - 6);
menu.style.left = `${x}px`;
menu.style.top = `${y}px`;
requestAnimationFrame(() => menu.classList.add('on'));
let closed = false;
function closeMenu() {
if (closed) return;
closed = true;
document.removeEventListener('mousedown', onDoc, true);
document.removeEventListener('keydown', onKey, true);
menu.remove();
}
function onDoc(e) { if (!menu.contains(e.target)) closeMenu(); }
function onKey(e) { if (e.key === 'Escape') closeMenu(); }
document.addEventListener('mousedown', onDoc, true);
document.addEventListener('keydown', onKey, true);
return { el: menu, close: closeMenu };
}
function closeAllMenus() {
for (const m of document.querySelectorAll('.menu')) m.remove();
}
/* ------------------------------------------------------------------ */
/* 表单小部件 */
/* ------------------------------------------------------------------ */
export function switchEl(opts = {}) {
const input = h('input.switch-input', { type: 'checkbox' });
input.checked = !!opts.checked;
if (opts.onChange) input.addEventListener('change', () => opts.onChange(input.checked));
const label = h('label.switch', {}, input, h('span.switch-track', {}, h('span.switch-thumb')));
if (opts.disabled) { input.disabled = true; label.classList.add('disabled'); }
return label;
}
export function fieldRow(label, control, hint) {
return h('div.field-row', {},
h('div.field-label', {},
h('div', String(label)),
hint ? h('div.field-hint', String(hint)) : null),
h('div.field-control', {}, control));
}
export function sectionTitle(text, extra) {
return h('div.section-title', {}, h('span', String(text)), extra || null);
}
export function spinner(size = 16) {
return h('span.spinner', { style: `width:${size}px;height:${size}px` });
}
export function typingDots() {
return h('span.typing-dots', {}, h('i'), h('i'), h('i'));
}
export function emptyState(iconName, title, desc, action) {
return h('div.empty-state', {},
h('div.empty-state-icon', {}, icon(iconName, 26)),
h('div.empty-state-title', String(title || '')),
desc ? h('div.empty-state-desc', String(desc)) : null,
action || null);
}
/* ------------------------------------------------------------------ */
/* 滚动 / 输入框 */
/* ------------------------------------------------------------------ */
export function scrollToBottom(container, smooth = false) {
if (!container) return;
container.scrollTo({ top: container.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });
}
export function autoGrow(textarea, maxHeight = 200) {
const resize = () => {
textarea.style.height = 'auto';
const next = Math.min(maxHeight, textarea.scrollHeight);
textarea.style.height = `${next}px`;
textarea.style.overflowY = textarea.scrollHeight > maxHeight ? 'auto' : 'hidden';
};
textarea.addEventListener('input', resize);
resize();
return resize;
}