feat(agent-v1.1): 第三阶段 —— 世界观/Skill/模型的管理界面 + 多模型真的生效
## 管理界面(需求 3.3 / 3.6 / 3.7)
- 新增 ResourcesScreen:一个全屏界面 + 三个 Tab(世界观 / Skill / 模型)。
三种东西是**同一层**的(都是全局资源、都被智能体引用、都是列表+增删改+导入导出),
拆成三个入口只会让用户记"哪个在哪"。
- **表单是字段驱动的**:三种资源的字段完全不同,但长得一模一样(label + 输入框),
所以用 List<Field> 描述、渲染只写一份。写三份的话加一个字段就要改三处 ——
而"加了 list 类型但某张表没跟上"在这个仓库里已经反复出现过。
- 世界观沿用智能体那套四件套(需求 3.6 原话"图片资源沿用四件套与同一套默认回退机制"):
内核的 /asset 接口泛化成 agents/worldviews 两种,Kotlin 侧只是换路径。
- 导入导出走 SAF(zip 是 base64、Skill 是纯 JSON 文本)。
入口:更多功能 →「世界观·技能·模型」。
## ★★ 补上一个真实的功能缺口:引用了模型却不会用
需求 3.3 说"智能体按 UUID 引用全局列表中的一个模型"。界面有了、字段存了,
但 `store.provider_info` **根本不看 modelId** —— 引用了照样走全局配置,
等于一个假功能。这类"数据通了但没接上"的缺口最难被发现:界面看着完全正常。
修成**四层优先级**:
模型列表那一项(地址/Key/模型标识,**整组覆盖**)
↓ 没引用
智能体自己的 provider/model/baseUrl
↓ 留空
全局设置
↓ 还没填
提供商预设
「整组覆盖」是刻意的:只覆盖 model 而 Key 还用全局的,必然出现
"选了 DeepSeek 的模型、拿方舟的 Key 去调"→ 401。所以 `provider_info`
现在也返回 apiKey,调用方(agent_loop / agent_api)改成用它。
探针第 11 节专门钉住这件事:地址/标识/提供商/**Key** 四项都要跟着换,
没引用时回落全局且**不带**那一项的 Key。
## 验证
- 探针 12 节 70+ 项全绿。
- 装机实测:更多功能入口 → 资源界面三个 Tab → 模型 Tab 新建 →
填显示名和模型标识 → 保存 → 列表出现该模型(带导出/删除)。
- 构建期 Python 语法自检运行正常(上一轮加的那道闸)。
This commit is contained in:
@@ -150,6 +150,8 @@ fun AppRoot(
|
||||
onManage = { vm.screen = Screen.Agents },
|
||||
onBack = { vm.screen = Screen.Chat },
|
||||
)
|
||||
// 世界观 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)
|
||||
Screen.Resources -> ResourcesScreen(vm) { vm.screen = Screen.Chat }
|
||||
Screen.Meetings -> MeetingsScreen(vm)
|
||||
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
|
||||
}
|
||||
@@ -202,6 +204,10 @@ fun AppRoot(
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Skills
|
||||
},
|
||||
onOpenResources = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Resources
|
||||
},
|
||||
onOpenMeetings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Meetings
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
@@ -29,7 +29,7 @@ import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应;AgentSelect 是需求 v1.1 新增的选择页) */
|
||||
enum class Screen { Chat, Profile, Settings, Skills, Agents, AgentSelect, Terminal, Meetings }
|
||||
enum class Screen { Chat, Profile, Settings, Skills, Agents, AgentSelect, Resources, Terminal, Meetings }
|
||||
|
||||
/**
|
||||
* 全局状态。界面只读这里的状态、只调这里的方法,网络全在 KernelClient 里。
|
||||
@@ -240,6 +240,136 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------- 三种资源:世界观 / Skill / 模型列表 -------------------- */
|
||||
|
||||
/**
|
||||
* 保存一种资源。
|
||||
*
|
||||
* ★ 三种资源的 CRUD 长得一样(列表 + 增删改 + 刷新),所以**走同一个方法**,
|
||||
* 用 [kind] 分派 —— 写三份的话加一个字段就要改三处,
|
||||
* 而这个仓库里"加了 list 类型但某张表没跟上"已经反复出现过。
|
||||
* (界面上它们的**表单**是分开的:字段完全不同,硬凑一个通用表单只会更绕。)
|
||||
*/
|
||||
fun saveResource(
|
||||
kind: String,
|
||||
id: String?,
|
||||
name: String,
|
||||
text: String,
|
||||
extra: Map<String, Any?> = emptyMap(),
|
||||
onDone: (Boolean) -> Unit,
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val ok = runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
when (kind) {
|
||||
"worldviews" -> client.saveWorldview(
|
||||
com.doubao.lynxclone.data.WorldviewItem(
|
||||
name = name,
|
||||
setting = text,
|
||||
image = (extra["image"] as? com.doubao.lynxclone.data.AgentImage)
|
||||
?: com.doubao.lynxclone.data.AgentImage(),
|
||||
),
|
||||
id,
|
||||
)
|
||||
"skills" -> client.saveSkill(
|
||||
com.doubao.lynxclone.data.SkillItem(name = name, content = text),
|
||||
id,
|
||||
)
|
||||
else -> client.saveModelEntry(
|
||||
com.doubao.lynxclone.data.ModelEntry(
|
||||
name = name,
|
||||
apiBase = text,
|
||||
model = extra["model"] as? String ?: "",
|
||||
apiKey = extra["apiKey"] as? String ?: "",
|
||||
provider = extra["provider"] as? String ?: "",
|
||||
pricePerK = (extra["pricePerK"] as? Double) ?: 0.0,
|
||||
),
|
||||
id,
|
||||
)
|
||||
}
|
||||
}
|
||||
}.isSuccess
|
||||
refresh()
|
||||
if (!ok) showHint("保存失败")
|
||||
onDone(ok)
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteResource(kind: String, id: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
when (kind) {
|
||||
"worldviews" -> client.deleteWorldview(id)
|
||||
"skills" -> client.deleteSkill(id)
|
||||
else -> client.deleteModelEntry(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传世界观的一张外观图(和智能体走同一个接口形状,只是路径不同) */
|
||||
fun uploadWorldviewAsset(id: String, key: String, name: String, base64: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) { client.setWorldviewAsset(id, key, name, base64) }
|
||||
}
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------- 包的导入导出 --------------------------- */
|
||||
|
||||
/**
|
||||
* 导入一个包(智能体 / 世界观 / Skill 都走这里)。
|
||||
*
|
||||
* ★ **一次导两次 = 两个独立实体**(需求 2.5):内核每次都生成新 UUID,
|
||||
* 这里不做"按名字去重"—— 用户想覆盖就该自己先删掉那个。
|
||||
* ★ 结果要**说清楚导入了什么**:成功什么都不提示的话,
|
||||
* 用户不知道是成功了还是没反应。
|
||||
*/
|
||||
fun importPackage(kind: String, base64: String, textJson: String) {
|
||||
viewModelScope.launch {
|
||||
val msg = runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
when (kind) {
|
||||
"agents" -> "已导入智能体「${client.importAgentPackage(base64).name}」"
|
||||
"worldviews" -> "已导入世界观「${client.importWorldviewPackage(base64).name}」"
|
||||
else -> "已导入 Skill「${client.importSkill(textJson).name}」"
|
||||
}
|
||||
}
|
||||
}.getOrElse { "导入失败:${it.message ?: it.javaClass.simpleName}" }
|
||||
showHint(msg)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
fun exportPackage(kind: String, id: String, onDone: (String, String) -> Unit) {
|
||||
viewModelScope.launch {
|
||||
val res = runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
when (kind) {
|
||||
"agents" -> Triple(
|
||||
client.exportAgentPackage(id), "zip", "application/zip",
|
||||
)
|
||||
"worldviews" -> Triple(
|
||||
client.exportWorldviewPackage(id), "zip", "application/zip",
|
||||
)
|
||||
else -> Triple(client.exportSkill(id), "json", "application/json")
|
||||
}
|
||||
}
|
||||
}.getOrNull()
|
||||
if (res == null) {
|
||||
showHint("导出失败")
|
||||
} else {
|
||||
// zip 是 base64(二进制没法直接塞进 JSON 文本),json 直接给文本
|
||||
onDone(res.first, res.second)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 选择界面上"开始对话":把这个人设为当前,然后回聊天页。
|
||||
*
|
||||
|
||||
@@ -22,6 +22,7 @@ import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.Layers
|
||||
import androidx.compose.material.icons.filled.Public
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -55,6 +56,7 @@ import androidx.compose.ui.unit.sp
|
||||
fun MoreSheetScreen(
|
||||
onOpenAiScreens: () -> Unit,
|
||||
onOpenSkills: () -> Unit,
|
||||
onOpenResources: () -> Unit,
|
||||
onOpenMeetings: () -> Unit,
|
||||
onOpenTerminal: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
@@ -81,6 +83,15 @@ fun MoreSheetScreen(
|
||||
subtitle = "AI 弹过的界面都存着,点一下就能再打开",
|
||||
) { onOpenAiScreens() }
|
||||
}
|
||||
item {
|
||||
// 世界观 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)——
|
||||
// 它们是"全局资源"那一层:都被智能体引用,都是列表 + 增删改 + 导入导出
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Public,
|
||||
title = "世界观 · 技能 · 模型",
|
||||
subtitle = "共享记忆的世界、AI 的工具手册、可选模型列表",
|
||||
) { onOpenResources() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Layers,
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.ModelEntry
|
||||
import com.doubao.lynxclone.data.SkillItem
|
||||
import com.doubao.lynxclone.data.WorldviewItem
|
||||
|
||||
/*
|
||||
* 世界观 / Skill / 模型列表的管理界面(需求 3.3 / 3.6 / 3.7)。
|
||||
*
|
||||
* ## 为什么三种东西挤在一个界面里
|
||||
*
|
||||
* 它们是**同一层的东西**:都是"全局资源",都被智能体引用,都是"列表 + 增删改 +
|
||||
* 导入导出"。分开成三个入口的话,用户要记住"世界观在哪、技能在哪、模型在哪"——
|
||||
* 而它们其实是一件事("这个 App 里有哪些可复用的东西")。
|
||||
*
|
||||
* ## 表单是**字段驱动**的,不是写三份
|
||||
*
|
||||
* 三种资源的表单字段完全不同(世界观有设定文本 + 四件套;Skill 就两行;
|
||||
* 模型有地址/标识/Key/单价),但**长得一模一样** —— 都是一个 label + 一个输入框。
|
||||
* 所以用 `List<Field>` 描述,渲染只有一份。
|
||||
*
|
||||
* 写三份的话,加一个字段就要改三处,而这个仓库里"加了 list 类型但某张表没跟上"
|
||||
* 已经反复出现过(AGENTS.md 第一条就是它)。
|
||||
*/
|
||||
|
||||
/** 表单里的一个字段 */
|
||||
private data class Field(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val placeholder: String = "",
|
||||
val multiline: Boolean = false,
|
||||
val password: Boolean = false,
|
||||
val number: Boolean = false,
|
||||
)
|
||||
|
||||
private val WORLD_FIELDS = listOf(
|
||||
Field("name", "名字", "比如:九霄"),
|
||||
Field(
|
||||
"setting", "世界观设定",
|
||||
"这个世界的规则、背景、称呼……(绑定了它的智能体,提示词里会整段带上)",
|
||||
multiline = true,
|
||||
),
|
||||
)
|
||||
|
||||
private val SKILL_FIELDS = listOf(
|
||||
Field("name", "名字", "比如:写代码的规矩"),
|
||||
Field(
|
||||
"content", "内容",
|
||||
"告诉 AI 有哪些工具、什么时候用、用完之后不许干什么",
|
||||
multiline = true,
|
||||
),
|
||||
)
|
||||
|
||||
private val MODEL_FIELDS = listOf(
|
||||
Field("name", "显示名", "比如:豆包 Pro"),
|
||||
Field("apiBase", "API 地址", "https://ark.cn-beijing.volces.com/api/v3"),
|
||||
Field("model", "模型标识", "doubao-seed-2-1-pro-260628"),
|
||||
Field("apiKey", "API Key", "留空则用全局设置里那个", password = true),
|
||||
Field("provider", "提供商", "ark / openai / deepseek …(留空则跟随全局)"),
|
||||
Field("pricePerK", "单价(元/千 Token)", "留空 = 不显示费用估算", number = true),
|
||||
)
|
||||
|
||||
/** 三张表:kind → (标题、字段、说明、是不是包) */
|
||||
private class Kind(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val tabLabel: String,
|
||||
val fields: List<Field>,
|
||||
val hint: String,
|
||||
/** 导入导出是 zip 包(世界观)还是单个 JSON(Skill) */
|
||||
val isZip: Boolean,
|
||||
)
|
||||
|
||||
private val KINDS = listOf(
|
||||
Kind(
|
||||
"worldviews", "世界观", "世界观", WORLD_FIELDS, isZip = true,
|
||||
hint = "绑定同一个世界观的智能体**共用一份记忆**。导出是一个 zip 包(含设定和四件套图片)。",
|
||||
),
|
||||
Kind(
|
||||
"skills", "Skill", "Skill", SKILL_FIELDS, isZip = false,
|
||||
hint = "纯文本的「工具使用手册」。内置的记忆/情绪/用量手册**默认就生效**;这里写的是你自己加的规矩。",
|
||||
),
|
||||
Kind(
|
||||
"models", "模型", "模型", MODEL_FIELDS, isZip = false,
|
||||
hint = "全局模型列表。智能体按 id 引用这里的某一项 —— 所以换 Key 只改一处," +
|
||||
"而且**导出智能体包时不会把 Key 带出去**。",
|
||||
),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
var tab by remember { mutableStateOf(0) }
|
||||
// 正在编辑的那一项(null 且 editing 为 true = 新建)
|
||||
var editing by remember { mutableStateOf<Boolean>(false) }
|
||||
var editId by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
val kind = KINDS[tab]
|
||||
val items: List<Pair<String, Triple<String, String, AgentImage>>> = when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.map {
|
||||
it.id to Triple(it.name, it.setting, it.image)
|
||||
}
|
||||
"skills" -> vm.state.skills.map { it.id to Triple(it.name, it.content, AgentImage()) }
|
||||
else -> vm.state.modelEntries.map {
|
||||
it.id to Triple(
|
||||
it.name,
|
||||
listOf(it.model, it.apiBase).filter { s -> s.isNotBlank() }.joinToString(" · "),
|
||||
AgentImage(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导入导出(SAF)----------------
|
||||
* zip 走 base64(二进制没法塞进 JSON 文本),Skill 是纯 JSON 文本。
|
||||
*/
|
||||
val ctx = LocalContext.current
|
||||
var pendingExport by remember { mutableStateOf<Triple<String, String, String>?>(null) }
|
||||
val saveDoc = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { uri ->
|
||||
val data = pendingExport
|
||||
pendingExport = null
|
||||
if (uri != null && data != null) {
|
||||
runCatching {
|
||||
val bytes = if (data.second == "zip") Base64.decode(data.first, Base64.DEFAULT)
|
||||
else data.first.toByteArray(Charsets.UTF_8)
|
||||
ctx.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
val openDoc = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
if (kind.isZip) {
|
||||
vm.importPackage(kind.id, Base64.encodeToString(bytes, Base64.NO_WRAP), "")
|
||||
} else {
|
||||
vm.importPackage(kind.id, "", bytes.toString(Charsets.UTF_8))
|
||||
}
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = "资源",
|
||||
subtitle = "世界观 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("导入") {
|
||||
if (kind.isZip) openDoc.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
else openDoc.launch(arrayOf("application/json", "text/plain", "*/*"))
|
||||
}
|
||||
},
|
||||
) {
|
||||
// ---- Tab ----
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
for ((i, k) in KINDS.withIndex()) {
|
||||
val on = i == tab
|
||||
Text(
|
||||
k.tabLabel,
|
||||
fontSize = 13.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.padding(end = 8.dp)
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { tab = i }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("新建") { editId = null; editing = true }
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState())) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.07f))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(kind.hint.replace("**", ""), fontSize = 11.sp, lineHeight = 16.sp, color = Doubao.Blue)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
if (items.isEmpty()) {
|
||||
Text(
|
||||
"还没有。点右上角「新建」,或者用「导入」拿一个现成的包。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 20.dp),
|
||||
)
|
||||
}
|
||||
|
||||
for ((id, info) in items) {
|
||||
val (name, preview, image) = info
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { editId = id; editing = true }
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (kind.id == "worldviews") {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = image.front,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name.ifBlank { "未命名" }, fontSize = 14.sp, color = doubaoText())
|
||||
if (preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
preview.replace("\n", " ").take(70),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
RowAction("导出") {
|
||||
vm.exportPackage(kind.id, id) { content, ext ->
|
||||
pendingExport = Triple(content, ext, "x")
|
||||
saveDoc.launch("${name.ifBlank { "resource" }}.${if (kind.isZip) "zip" else "json"}")
|
||||
}
|
||||
}
|
||||
RowAction("删除", danger = true) { vm.deleteResource(kind.id, id) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
ResourceEditScreen(
|
||||
vm = vm,
|
||||
kind = kind,
|
||||
id = editId,
|
||||
onDone = { editing = false; editId = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 字段驱动的编辑表单 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun ResourceEditScreen(
|
||||
vm: AppViewModel,
|
||||
kind: Kind,
|
||||
id: String?,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
// 三种资源的初始值从内存里那份拿(列表就是它渲染的,不会对不上)
|
||||
val initial: Map<String, String> = remember(id, kind.id) {
|
||||
when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "setting" to it.setting)
|
||||
} ?: emptyMap()
|
||||
"skills" -> vm.state.skills.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "content" to it.content)
|
||||
} ?: emptyMap()
|
||||
else -> vm.state.modelEntries.firstOrNull { it.id == id }?.let {
|
||||
mapOf(
|
||||
"name" to it.name, "apiBase" to it.apiBase, "model" to it.model,
|
||||
"apiKey" to "", "provider" to it.provider,
|
||||
"pricePerK" to if (it.pricePerK > 0) it.pricePerK.toString() else "",
|
||||
)
|
||||
} ?: emptyMap()
|
||||
}
|
||||
}
|
||||
var values by remember(id, kind.id) { mutableStateOf(initial) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var worldImage by remember(id, kind.id) {
|
||||
mutableStateOf(vm.state.worldviews.firstOrNull { it.id == id }?.image ?: AgentImage())
|
||||
}
|
||||
val ctx = LocalContext.current
|
||||
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank() || id == null) return@rememberLauncherForActivityResult
|
||||
runCatching {
|
||||
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
|
||||
vm.uploadWorldviewAsset(id, slot, name, Base64.encodeToString(bytes, Base64.NO_WRAP))
|
||||
}.onFailure { vm.showHint("读不出这张图") }
|
||||
}
|
||||
// 上传完 image 会变,跟着刷新预览
|
||||
vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
if (it.image != worldImage) worldImage = it.image
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = if (id == null) "新建${kind.title}" else "编辑${kind.title}",
|
||||
subtitle = values["name"].orEmpty().ifBlank { kind.title },
|
||||
onBack = onDone,
|
||||
actions = {
|
||||
TopAction("保存", enabled = !saving) {
|
||||
saving = true
|
||||
val name = values["name"].orEmpty().trim()
|
||||
val text = values[
|
||||
if (kind.id == "models") "apiBase" else if (kind.id == "skills") "content" else "setting"
|
||||
].orEmpty()
|
||||
val extra = mutableMapOf<String, Any?>()
|
||||
if (kind.id == "models") {
|
||||
extra["model"] = values["model"].orEmpty()
|
||||
extra["apiKey"] = values["apiKey"].orEmpty()
|
||||
extra["provider"] = values["provider"].orEmpty()
|
||||
extra["pricePerK"] = values["pricePerK"]?.toDoubleOrNull() ?: 0.0
|
||||
}
|
||||
if (kind.id == "worldviews") extra["image"] = worldImage
|
||||
vm.saveResource(kind.id, id, name, text, extra) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
SectionLabel("基本信息")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
for (f in kind.fields) {
|
||||
Text(f.label, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = values[f.key].orEmpty(),
|
||||
onValueChange = { v ->
|
||||
// 单价只收数字和小数点;别的字段原样收
|
||||
values = values + (f.key to if (f.number) v.filter { c -> c.isDigit() || c == '.' } else v)
|
||||
},
|
||||
placeholder = { Text(f.placeholder, fontSize = 12.sp) },
|
||||
singleLine = !f.multiline,
|
||||
visualTransformation = if (f.password) PasswordVisualTransformation()
|
||||
else androidx.compose.ui.text.input.VisualTransformation.None,
|
||||
keyboardOptions = if (f.number) KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
else KeyboardOptions.Default,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.then(if (f.multiline) Modifier.heightIn(min = 120.dp, max = 300.dp) else Modifier),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 世界观的四件套(需求 3.6:沿用智能体那一套)---- */
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("外观(四件套)")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
if (id == null) {
|
||||
Text(
|
||||
"先保存,再回来加外观图片(图片要落到这个世界观自己的目录里)。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
val slots = listOf(
|
||||
Triple("front", "封面 / 代表图", "智能体选择界面上用的那张"),
|
||||
Triple("back", "背景图", "铺在展示区最底层"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本"),
|
||||
)
|
||||
for ((key, title, desc) in slots) {
|
||||
val path = when (key) {
|
||||
"front" -> worldImage.front
|
||||
"back" -> worldImage.back
|
||||
"border-main" -> worldImage.borderMain
|
||||
else -> worldImage.borderInfo
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
RowAction("选择") {
|
||||
pendingSlot = key
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
}
|
||||
if (path.isNotBlank()) {
|
||||
RowAction("清除", danger = true) {
|
||||
vm.uploadWorldviewAsset(id, key, "", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
if (id != null && kind.id == "skills") {
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
TextButton(onClick = { vm.deleteResource(kind.id, id); onDone() }) {
|
||||
Text("删除这个 Skill", color = Color(0xFFD93025), fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
@@ -164,7 +164,7 @@ def _llm_once(settings: dict, agent: dict, system: str, user: str):
|
||||
for ev in providers.stream_chat(
|
||||
provider=provider.get('provider') or settings.get('provider'),
|
||||
base_url=provider.get('baseUrl'),
|
||||
api_key=settings.get('apiKey') or '',
|
||||
api_key=provider.get('apiKey') or '',
|
||||
model=provider.get('model'),
|
||||
messages=[
|
||||
{'role': 'system', 'content': system},
|
||||
@@ -373,7 +373,7 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
|
||||
# ---------------- 外观图片(四件套)----------------
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||||
return _set_asset(handler, seg[2], body(), err)
|
||||
return _set_asset(handler, 'agents', seg[2], body(), err)
|
||||
|
||||
# ---------------- 单条记忆 ----------------
|
||||
if seg[1] == 'memories' and len(seg) == 3:
|
||||
@@ -637,6 +637,9 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
# 包 / JSON 的导入导出(世界观包、Skill 文件)
|
||||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _resource_import(handler, name, body(), err)
|
||||
if len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||||
# 世界观的外观图(需求 3.6:沿用同一套四件套)
|
||||
return _set_asset(handler, 'worldviews', seg[2], body(), err)
|
||||
if len(seg) == 4 and seg[3] == 'package' and method == 'GET':
|
||||
return _resource_export(handler, name, seg[2], err)
|
||||
if len(seg) == 4 and seg[3] == 'export' and method == 'GET':
|
||||
@@ -735,27 +738,40 @@ def _export_agent(handler, agent_id: str, err) -> bool:
|
||||
ASSET_KEYS = ('front', 'back', 'border-main', 'border-info')
|
||||
|
||||
|
||||
def _set_asset(handler, agent_id: str, body: dict, err) -> bool:
|
||||
def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||||
"""
|
||||
设置外观四件套里的**一个槽位**(需求 2.5)。
|
||||
设置外观四件套里的**一个槽位**。
|
||||
|
||||
[kind] 是 `'agents'` 或 `'worldviews'` —— 两者用的是同一套四件套
|
||||
(需求 3.6 明确说世界观"图片资源沿用四件套与同一套默认回退机制"),
|
||||
所以这里只写一份,按 kind 分派到对应的存储。
|
||||
|
||||
界面把图片读成 base64 发过来,这里落盘到 `agent-assets/<id>/`,
|
||||
再把**路径**写进 `agent.image`。
|
||||
再把**路径**写进 `image`。
|
||||
|
||||
★ 存路径不存字节:展示区和列表每次都要显示它,每次从 base64 解一遍太贵。
|
||||
★ `data` 传空 = **清掉这个槽位**(回到内置默认 / 方框)——
|
||||
这是"我不想要这张图了"的唯一出口,不给的话用户只能换、不能删。
|
||||
"""
|
||||
agent = store.get_agent(agent_id)
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
if kind == 'agents':
|
||||
owner = store.get_agent(owner_id)
|
||||
else:
|
||||
owner = store.get_resource('worldviews', owner_id)
|
||||
if not owner:
|
||||
err(404, '没有这一项')
|
||||
return True
|
||||
|
||||
key = str(body.get('key') or '').strip()
|
||||
if key not in ASSET_KEYS:
|
||||
err(400, f'不认识的外观槽位:{key}(可选:{"、".join(ASSET_KEYS)})')
|
||||
return True
|
||||
|
||||
image = dict(agent.get('image') or {})
|
||||
def save(image: dict):
|
||||
if kind == 'agents':
|
||||
return store.update_agent(owner_id, {'image': image})
|
||||
return store.update_resource('worldviews', owner_id, {'image': image})
|
||||
|
||||
image = dict(owner.get('image') or {})
|
||||
raw = body.get('data') or body.get('base64') or ''
|
||||
if not raw:
|
||||
old = image.pop(key, '')
|
||||
@@ -764,7 +780,7 @@ def _set_asset(handler, agent_id: str, body: dict, err) -> bool:
|
||||
os.remove(old)
|
||||
except OSError:
|
||||
pass
|
||||
return _send_json_ok(handler, {'agent': store.update_agent(agent_id, {'image': image}), 'cleared': True})
|
||||
return _send_json_ok(handler, {'item': save(image), 'cleared': True})
|
||||
|
||||
try:
|
||||
blob = base64.b64decode(raw)
|
||||
@@ -776,12 +792,12 @@ def _set_asset(handler, agent_id: str, body: dict, err) -> bool:
|
||||
return True
|
||||
|
||||
name = _safe_segment(str(body.get('name') or f'{key}.png'))
|
||||
dest = os.path.join(_asset_dir(agent_id), f'{key}-{name}')
|
||||
dest = os.path.join(_asset_dir(owner_id), f'{key}-{name}')
|
||||
with open(dest, 'wb') as fh:
|
||||
fh.write(blob)
|
||||
image[key] = dest
|
||||
return _send_json_ok(handler, {
|
||||
'agent': store.update_agent(agent_id, {'image': image}),
|
||||
'item': save(image),
|
||||
'path': dest,
|
||||
'bytes': len(blob),
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||||
@@ -213,7 +213,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
# provider 是"提供商名字"(ark/openai),已经按"智能体 > 全局"解析过了
|
||||
provider=provider_key,
|
||||
base_url=provider.get('baseUrl'),
|
||||
api_key=settings.get('apiKey') or '',
|
||||
api_key=provider.get('apiKey') or '',
|
||||
model=provider.get('model'),
|
||||
messages=convo,
|
||||
tools=tool_defs if tool_defs else None,
|
||||
|
||||
@@ -245,13 +245,50 @@ def write_settings(patch: dict) -> dict:
|
||||
|
||||
def provider_info(settings: dict, agent: dict = None) -> dict:
|
||||
"""
|
||||
当前提供商的完整信息(预设 + 生效的 baseUrl/model)。
|
||||
当前提供商的完整信息(预设 + 生效的 baseUrl/model/apiKey)。
|
||||
|
||||
★ agent 不为空时,智能体自己的 provider/model/baseUrl **优先**,留空则继承全局。
|
||||
这样"某个智能体用 DeepSeek、其它还用方舟"是改一个智能体的事,
|
||||
不用来回切全局设置 —— 而全局设置仍然是没配过的智能体的默认值。
|
||||
|
||||
★★ v1.1 新增一层:智能体可以**引用全局模型列表里的一项**(`modelId`,需求 3.3)。
|
||||
优先级是:
|
||||
|
||||
模型列表那一项(地址/Key/模型标识都从它来,**整组覆盖**)
|
||||
↓ 没引用
|
||||
智能体自己的 provider/model/baseUrl
|
||||
↓ 留空
|
||||
全局设置
|
||||
↓ 还没填
|
||||
提供商预设
|
||||
|
||||
「整组覆盖」是刻意的:模型列表存在的意义就是"配一次到处用、
|
||||
改 Key 只改一处"。如果只覆盖 model 而 Key 还用全局的,
|
||||
就会出现"选了 DeepSeek 的模型、却拿方舟的 Key 去调"这种必然 401 的组合。
|
||||
"""
|
||||
agent = agent or {}
|
||||
entry = None
|
||||
model_id = (agent.get('modelId') or '').strip()
|
||||
if model_id:
|
||||
try:
|
||||
entry = get_resource('models', model_id)
|
||||
except Exception: # noqa: BLE001 - 列表坏了不该让对话发不出去
|
||||
entry = None
|
||||
|
||||
if entry:
|
||||
provider_key = (entry.get('provider') or '').strip() or settings.get('provider')
|
||||
preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings)
|
||||
return {
|
||||
**preset,
|
||||
'provider': provider_key,
|
||||
'baseUrl': (entry.get('apiBase') or '').strip() or preset.get('baseUrl', ''),
|
||||
'model': (entry.get('model') or '').strip() or preset.get('defaultModel', ''),
|
||||
# ★ Key 也从那一项来(留空才回落全局)——
|
||||
# "只覆盖 model 不覆盖 Key"必然 401,见上面的注释
|
||||
'apiKey': (entry.get('apiKey') or '').strip() or settings.get('apiKey') or '',
|
||||
'modelEntryId': model_id,
|
||||
}
|
||||
|
||||
provider_key = (agent.get('provider') or '').strip() or settings.get('provider')
|
||||
preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings)
|
||||
return {
|
||||
@@ -260,6 +297,7 @@ def provider_info(settings: dict, agent: dict = None) -> dict:
|
||||
# baseUrl 也是三层:智能体 > 全局 > 预设
|
||||
'baseUrl': (agent.get('baseUrl') or '').strip() or settings.get('baseUrl') or preset.get('baseUrl', ''),
|
||||
'model': (agent.get('model') or '').strip() or settings.get('model') or preset.get('defaultModel', ''),
|
||||
'apiKey': settings.get('apiKey') or '',
|
||||
}
|
||||
|
||||
|
||||
|
||||
BIN
docs/screenshots/agent-resources.png
Normal file
BIN
docs/screenshots/agent-resources.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 58 KiB |
@@ -288,7 +288,26 @@ def main():
|
||||
check("覆盖模式:情绪也换了", agentdb.emotion_get(a1["id"]) == "换掉了", agentdb.emotion_get(a1["id"]))
|
||||
|
||||
# ---------------------------------------------------------------- 11
|
||||
section("11. 资源 CRUD + Skill 导入导出")
|
||||
section("11. 多模型:引用了就真的用(需求 3.3)")
|
||||
entry = store.create_resource("models", {
|
||||
"name": "DeepSeek R1", "apiBase": "https://api.deepseek.com/v1",
|
||||
"apiKey": "sk-abc", "model": "deepseek-r1-250528", "provider": "deepseek",
|
||||
})
|
||||
store.update_agent(a1["id"], {"modelId": entry["id"]})
|
||||
info = store.provider_info(store.read_settings(), store.get_agent(a1["id"]))
|
||||
check("地址来自模型列表那一项", info["baseUrl"] == "https://api.deepseek.com/v1", info["baseUrl"])
|
||||
check("模型标识也来自它", info["model"] == "deepseek-r1-250528", info["model"])
|
||||
check("提供商跟着换", info["provider"] == "deepseek", info["provider"])
|
||||
# ★ Key 也必须换:只换 model 不换 Key 必然 401(这是"整组覆盖"的理由)
|
||||
check("**Key 也是那一项的**(不是全局的)", info["apiKey"] == "sk-abc", info["apiKey"])
|
||||
# 没引用时回落全局
|
||||
store.update_agent(a1["id"], {"modelId": ""})
|
||||
info2 = store.provider_info(store.read_settings(), store.get_agent(a1["id"]))
|
||||
check("没引用时回落全局", info2.get("modelEntryId") is None)
|
||||
check("回落时不再带那一项的 Key", info2["apiKey"] != "sk-abc")
|
||||
|
||||
# ---------------------------------------------------------------- 12
|
||||
section("12. 资源 CRUD + Skill 导入导出")
|
||||
r = h.call("/api/skills", "POST", {"name": "另一个", "content": "内容"})
|
||||
sid = (r.get("item") or {}).get("id")
|
||||
r = h.call(f"/api/skills/{sid}", "PATCH", {"content": "改过的内容"})
|
||||
|
||||
Reference in New Issue
Block a user