diff --git a/DEVLOG.md b/DEVLOG.md index 706dace..153d610 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -1,10 +1,30 @@ # OpenClaw Manager — 开发日志 -> 最后更新:2026-02-28 -> 当前版本:v0.7.1 +> 最后更新:2026-03-01 +> 当前版本:v0.9.0 --- + +## v0.9.0 更新日志(2026-03-01) + +### New Features + +- Agents: Add Agent / Add Sub-Agent 向导支持 Telegram + Discord + - Telegram: 传统 group 绑定 + - Discord: 主 Agent 建议绑定 Channel;Sub-Agent 建议绑定 Thread +- Routing: 删除绑定提示文案增强(支持“更换 group/thread → 先删旧绑定再加新绑定”) + +### UX / UI + +- 顶部居中显示醒目的 OCM 版本标识 +- Agents 页面:Agent Tree 支持显示 bindings 概览(Telegram/Discord)并按 parentAgentId 分组 +- Setup Guide:补全 Telegram Allow Groups 步骤;Discord guide 按 channel/thread 经验重写 + +### Fixes + +- 修复 MAIN_HTML_SCRIPT 内联 JS 语法问题(tree toggle / i18n 单引号等),避免启动自检失败 + ## Unreleased(2026-02-28) ### Dashboard / Layout diff --git a/README.md b/README.md index 6283d8f..f0acd5d 100644 --- a/README.md +++ b/README.md @@ -60,9 +60,9 @@ Open [http://localhost:3333](http://localhost:3333) in your browser. For remote - **Backups / Rollback** — Browse auto-snapshots of `openclaw.json*` and restore any previous version (current config is auto-backed up first). - **Bilingual UI** — English and Chinese interface with one-click language switching. -## What's New (v0.8.x) +## What's New (v0.9.x) -- **Docs refresh (v0.8.x)**: updated English + Chinese guides and refreshed redacted screenshots. +- **Discord support (v0.9.x)**: add agent/sub-agent flows for Discord (main agent binds channel; sub-agent binds thread). - **README screenshots gallery**: all screenshots are now grouped into one collapsible section to keep the homepage short. - **Built-in CLI terminal**: run OpenClaw commands from any page with streaming output, presets, favorites, and Tab completion. - **Ops actions**: restart gateway, view logs, health check, backups (local + NAS), and cron management. @@ -206,3 +206,9 @@ bash start.sh --dir /path/to/.openclaw --port 8080 ```json { "dir": "~/.openclaw" } ``` + + +## Discord (thread-first) notes + +- Recommended: keep top-level agents in dedicated channels, and bind sub-agents to **threads** (one thread per task). +- To switch a Telegram group / Discord thread binding: go to **Routing** → remove the old binding → add a new binding with the new ID/link. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index c1b5a28..28bc2ff 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,10 @@ This is a user-facing summary derived from `DEVLOG.md`. +## v0.9.0 +- Agents: Telegram + Discord support in Add Agent / Add Sub-Agent wizard (main agent binds channel; sub-agent binds thread). +- UI: top-center OCM version badge; improved Telegram/Discord setup guides. + ## v0.8.2 - Docs: reorganize README screenshots into a collapsible gallery to reduce scroll. - Docs: add Backups / Rollback screenshot and README feature blurb. diff --git a/docs/USAGE_GUIDE.en.md b/docs/USAGE_GUIDE.en.md index af7a29e..f803c55 100644 --- a/docs/USAGE_GUIDE.en.md +++ b/docs/USAGE_GUIDE.en.md @@ -172,6 +172,36 @@ If you use `channels.telegram.allowFrom`, OCM can take “Your Telegram User ID --- + + +## 5) Discord workflow (main agent + sub-agent) + +OCM also supports Discord: + +- **Main agent**: bind to a dedicated **Channel** (channelId) +- **Sub-agent**: bind to a dedicated **Thread** under that channel (threadId) + +### 5.1 Add a Discord main agent + +Go to **Agents** → `+ Add Agent` → set **Channel = Discord**: + +![](redacted-screenshots/agents-discord-add-agent.png) + +Steps: +1) Create/select a dedicated Discord **channel** (private recommended) +2) Right-click channel → **Copy Link** → paste into the form (auto-parses channelId) + +### 5.2 Add a Discord sub-agent (thread-first) + +Go to **Agents** → `+ Add Sub-Agent` → set **Channel = Discord (thread only)**: + +![](redacted-screenshots/agents-discord-add-subagent.png) + +Steps: +1) Create a **thread** under the main channel (one thread per task) +2) If it is a private thread, add the bot to the thread +3) Right-click thread → **Copy Link** → paste into the form (auto-parses threadId) + ## 6) Verify bindings (Channels) Go to **Channels**: diff --git a/docs/USAGE_GUIDE.zh-CN.md b/docs/USAGE_GUIDE.zh-CN.md index ba6bf3f..7c2cd15 100644 --- a/docs/USAGE_GUIDE.zh-CN.md +++ b/docs/USAGE_GUIDE.zh-CN.md @@ -155,6 +155,36 @@ OCM 的表单里可以填 “Your Telegram User ID”,让它自动把你的 us --- + + +## 5) Discord 工作流(主 Agent + Sub-Agent) + +OCM 也支持 Discord: + +- **主 Agent**:绑定到一个专用 **Channel**(channelId) +- **Sub-Agent**:绑定到该 Channel 下的专用 **Thread**(threadId,thread-first) + +### 5.1 添加 Discord 主 Agent + +进入 **Agents** → `+ Add Agent` → 选择 **渠道 = Discord**: + +![](redacted-screenshots/agents-discord-add-agent.png) + +步骤: +1) 创建/选择一个专用 Discord Channel(建议私密) +2) 右键 Channel → **Copy Link** → 粘贴到表单(自动解析 channelId) + +### 5.2 添加 Discord Sub-Agent(Thread 优先) + +进入 **Agents** → `+ Add Sub-Agent` → 选择 **渠道 = Discord (thread only)**: + +![](redacted-screenshots/agents-discord-add-subagent.png) + +步骤: +1) 在主 Channel 下新建 Thread(建议“一个任务一个 thread”) +2) 如果是 private thread,需要把 bot 拉进 thread +3) 右键 Thread → **Copy Link** → 粘贴到表单(自动解析 threadId) + ## 5) 绑定检查(Channels 页) 进入 **Channels**: diff --git a/docs/redacted-screenshots/agents-discord-add-agent.png b/docs/redacted-screenshots/agents-discord-add-agent.png new file mode 100644 index 0000000..709bdfb Binary files /dev/null and b/docs/redacted-screenshots/agents-discord-add-agent.png differ diff --git a/docs/redacted-screenshots/agents-discord-add-subagent.png b/docs/redacted-screenshots/agents-discord-add-subagent.png new file mode 100644 index 0000000..2b08bca Binary files /dev/null and b/docs/redacted-screenshots/agents-discord-add-subagent.png differ diff --git a/openclaw-manager.js b/openclaw-manager.js index fd82b5f..eb50824 100644 --- a/openclaw-manager.js +++ b/openclaw-manager.js @@ -24,7 +24,7 @@ const SCRIPT_DIR = __dirname; const MANAGER_CONFIG = path.join(SCRIPT_DIR, 'manager-config.json'); let PORT = 3333; let HOST = '0.0.0.0'; -const APP_VERSION = '0.8.2'; +const APP_VERSION = '0.9.0'; // --port 参数 const portIdx = process.argv.indexOf('--port'); if (portIdx !== -1 && process.argv[portIdx + 1]) PORT = parseInt(process.argv[portIdx + 1]) || 3333; @@ -354,6 +354,7 @@ async function handleApi(req, res, urlObj, body) { })(), primaryModel: cfg.agents?.defaults?.model?.primary || '未配置', platform: process.platform, + ocmVersion: APP_VERSION, })); } catch (e) { res.writeHead(500); res.end(JSON.stringify({ ok: false, error: e.message })); } return; @@ -423,7 +424,13 @@ async function handleApi(req, res, urlObj, body) { // Workspace: explicit per-agent, or defaults.workspace for main const workspace = a.workspace || (isMain ? defaultWorkspace : null); return { ...a, workspace, groupId, requireMention: groupId ? (groups[groupId]?.requireMention ?? true) : null, - effectiveModel: modelVal || defaults.model?.primary || '默认', hasOwnBot, accountId, parentAccountId }; + effectiveModel: modelVal || defaults.model?.primary || '默认', hasOwnBot, accountId, parentAccountId, parentAgentId: a.parentAgentId || null, bindings: (bindings||[]).filter(b=>b.agentId===a.id).map(b=>({ + idx: bindings.indexOf(b), + channel: b.match?.channel || '', + accountId: b.match?.accountId || '', + peerKind: b.match?.peer?.kind || '', + peerId: b.match?.peer?.id || '' + })) }; }); res.writeHead(200); res.end(JSON.stringify({ agents: enriched, defaults })); @@ -508,6 +515,143 @@ async function handleApi(req, res, urlObj, body) { return; } + // POST /api/agents/discord — create top-level Discord agent (single bot, channel binding) + if (method === 'POST' && pathname === '/api/agents/discord') { + const { agentId, name, workspaceFolder, model, purpose, personality, guildId, channelId } = body; + if (!agentId || !/^[a-zA-Z0-9_-]+$/.test(agentId)) { + res.writeHead(400); res.end(JSON.stringify({ error: 'Agent ID must contain only alphanumeric characters, underscores, or dashes' })); return; + } + if (!name || !name.trim()) { res.writeHead(400); res.end(JSON.stringify({ error: 'Name is required' })); return; } + const folder = (workspaceFolder || agentId).trim(); + if (!folder) { res.writeHead(400); res.end(JSON.stringify({ error: 'Workspace folder is required' })); return; } + if (!channelId || !String(channelId).trim().match(/^\d+$/)) { res.writeHead(400); res.end(JSON.stringify({ error: 'Discord channelId is required' })); return; } + const gid = (guildId || '').trim(); + + const cfg = await readConfig(); + if (cfg.agents?.list?.some(a => a.id === agentId)) { + res.writeHead(400); res.end(JSON.stringify({ error: `Agent ID \"${agentId}\" already exists` })); return; + } + // Prevent workspace reuse + const wsAlias = `~/.openclaw/workspaces/${folder}`; + if (cfg.agents?.list?.some(a => (a.workspace||'').endsWith(`/workspaces/${folder}`) || a.workspace === wsAlias)) { + res.writeHead(400); res.end(JSON.stringify({ error: `Workspace folder \"${folder}\" is already used by another agent` })); return; + } + + if (!cfg.agents) cfg.agents = { defaults: {}, list: [] }; + if (!cfg.agents.list) cfg.agents.list = []; + + const wsPath = path.join(OPENCLAW_DIR, 'workspaces', folder); + const agentEntry = { id: agentId, name: name || agentId, workspace: wsAlias }; + if (model && model !== '__default__') agentEntry.model = { primary: model }; + cfg.agents.list.push(agentEntry); + + if (!cfg.bindings) cfg.bindings = []; + cfg.bindings.unshift({ agentId, match: { channel: 'discord', peer: { kind: 'channel', id: String(channelId).trim() } } }); + + if (!cfg.channels) cfg.channels = {}; + if (!cfg.channels.discord) cfg.channels.discord = {}; + cfg.channels.discord.enabled = true; + if (gid) { + if (!cfg.channels.discord.guilds) cfg.channels.discord.guilds = {}; + if (!cfg.channels.discord.guilds[gid]) cfg.channels.discord.guilds[gid] = {}; + if (!cfg.channels.discord.guilds[gid].channels) cfg.channels.discord.guilds[gid].channels = {}; + cfg.channels.discord.guilds[gid].channels[String(channelId).trim()] = { allow: true, requireMention: false }; + if (cfg.channels.discord.guilds[gid].requireMention === undefined) cfg.channels.discord.guilds[gid].requireMention = false; + } + + const bakPath = await writeConfig(cfg, 'create'); + + await fsp.mkdir(wsPath, { recursive: true }); + await fsp.mkdir(path.join(wsPath, 'memory'), { recursive: true }); + await fsp.writeFile(path.join(wsPath, 'SOUL.md'), generateSoulMd(name || agentId, purpose || '', personality || ''), 'utf8'); + await fsp.writeFile(path.join(wsPath, 'MEMORY.md'), generateMemoryMd(name || agentId, ''), 'utf8'); + + const agentRuntimeDir = path.join(OPENCLAW_DIR, 'agents', agentId); + await fsp.mkdir(agentRuntimeDir, { recursive: true }); + await fsp.mkdir(path.join(agentRuntimeDir, 'sessions'), { recursive: true }); + + res.writeHead(200); + res.end(JSON.stringify({ ok: true, agentId, workspacePath: wsPath, configBackup: bakPath, + notes: [ + 'Discord agent created (single Discord bot)', + 'Channel binding added', + 'Workspace + runtime directories created', + 'Configuration updated and backed up', + 'Restart gateway to apply: openclaw gateway restart' + ] + })); + return; + } + + // POST /api/agents/discord-sub — create Discord sub-agent (thread-only binding, grouping under parentAgentId) + if (method === 'POST' && pathname === '/api/agents/discord-sub') { + const { agentId, displayName, workspaceFolder, model, purpose, personality, initialMemory, parentAgentId, guildId, threadId } = body; + if (!agentId || !/^[a-zA-Z0-9_-]+$/.test(agentId)) { + res.writeHead(400); res.end(JSON.stringify({ error: 'Agent ID must contain only alphanumeric characters, underscores, or dashes' })); return; + } + if (!parentAgentId || !String(parentAgentId).trim()) { + res.writeHead(400); res.end(JSON.stringify({ error: 'Parent Agent ID is required' })); return; + } + if (!threadId || !String(threadId).trim().match(/^\d+$/)) { + res.writeHead(400); res.end(JSON.stringify({ error: 'Discord threadId is required' })); return; + } + const gid = (guildId || '').trim(); + + const cfg = await readConfig(); + const parentAgent = cfg.agents?.list?.find(a => a.id === parentAgentId); + if (!parentAgent) { res.writeHead(404); res.end(JSON.stringify({ error: `Parent agent \"${parentAgentId}\" does not exist` })); return; } + if (cfg.agents?.list?.some(a => a.id === agentId)) { res.writeHead(400); res.end(JSON.stringify({ error: `Agent ID \"${agentId}\" already exists` })); return; } + + const folder = (workspaceFolder || agentId).trim(); + const wsAlias = `~/.openclaw/workspaces/${folder}`; + if (cfg.agents?.list?.some(a => (a.workspace||'').endsWith(`/workspaces/${folder}`) || a.workspace === wsAlias)) { + res.writeHead(400); res.end(JSON.stringify({ error: `Workspace folder \"${folder}\" is already used by another agent` })); return; + } + + const wsPath = path.join(OPENCLAW_DIR, 'workspaces', folder); + const agentEntry = { id: agentId, name: displayName || agentId, workspace: wsAlias, parentAgentId: String(parentAgentId).trim() }; + if (model && model !== '__default__') agentEntry.model = { primary: model }; + cfg.agents.list.push(agentEntry); + + if (!cfg.bindings) cfg.bindings = []; + cfg.bindings.unshift({ agentId, match: { channel: 'discord', peer: { kind: 'channel', id: String(threadId).trim() } } }); + + if (!cfg.channels) cfg.channels = {}; + if (!cfg.channels.discord) cfg.channels.discord = {}; + cfg.channels.discord.enabled = true; + if (gid) { + if (!cfg.channels.discord.guilds) cfg.channels.discord.guilds = {}; + if (!cfg.channels.discord.guilds[gid]) cfg.channels.discord.guilds[gid] = {}; + if (!cfg.channels.discord.guilds[gid].channels) cfg.channels.discord.guilds[gid].channels = {}; + cfg.channels.discord.guilds[gid].channels[String(threadId).trim()] = { allow: true, requireMention: false }; + if (cfg.channels.discord.guilds[gid].requireMention === undefined) cfg.channels.discord.guilds[gid].requireMention = false; + } + + const bakPath = await writeConfig(cfg, 'create'); + + await fsp.mkdir(wsPath, { recursive: true }); + await fsp.mkdir(path.join(wsPath, 'memory'), { recursive: true }); + const name = displayName || agentId; + await fsp.writeFile(path.join(wsPath, 'SOUL.md'), generateSoulMd(name, purpose || '', personality || ''), 'utf8'); + await fsp.writeFile(path.join(wsPath, 'MEMORY.md'), generateMemoryMd(name, initialMemory || ''), 'utf8'); + + const agentRuntimeDir = path.join(OPENCLAW_DIR, 'agents', agentId); + await fsp.mkdir(agentRuntimeDir, { recursive: true }); + await fsp.mkdir(path.join(agentRuntimeDir, 'sessions'), { recursive: true }); + + res.writeHead(200); + res.end(JSON.stringify({ ok: true, agentId, workspacePath: wsPath, configBackup: bakPath, + notes: [ + 'Discord sub-agent created (thread-only binding)', + 'Workspace + runtime directories created', + 'Configuration updated and backed up', + 'Restart gateway to apply: openclaw gateway restart' + ] + })); + return; + } + + // POST /api/agents — create sub-agent (shares parent bot) if (method === 'POST' && pathname === '/api/agents') { const { agentId, displayName, groupId, workspaceFolder, model, purpose, personality, initialMemory, parentAgentId, telegramUserId } = body; @@ -537,7 +681,7 @@ async function handleApi(req, res, urlObj, body) { const folder = workspaceFolder || agentId; const wsPath = path.join(OPENCLAW_DIR, 'workspaces', folder); const wsAlias= `~/.openclaw/workspaces/${folder}`; - const agentEntry = { id: agentId, name: displayName || agentId, workspace: wsAlias }; + const agentEntry = { id: agentId, name: displayName || agentId, workspace: wsAlias, parentAgentId: String(parentAgentId).trim() }; if (model && model !== '__default__') agentEntry.model = { primary: model }; cfg.agents.list.push(agentEntry); // Binding uses parent's accountId @@ -1556,6 +1700,10 @@ header { background:var(--surface); border-bottom:1px solid var(--border); paddi .lang-toggle { background:var(--border); border:none; color:var(--muted); border-radius:6px; padding:5px 10px; font-size:12px; cursor:pointer; } .lang-toggle:hover { background:#3a3f5c; color:var(--text); } +/* centered version badge */ +.top-version{ position:absolute; left:50%; transform:translateX(-50%); font-size:12px; font-weight:800; letter-spacing:.3px; color:var(--text); background:rgba(108,99,255,.18); border:1px solid rgba(108,99,255,.45); padding:4px 12px; border-radius:999px; box-shadow:0 6px 18px rgba(0,0,0,.25); } +.ver-old{ display:none; } + /* dropdown menu */ .menu-wrap { position:relative; } .menu-btn { background:var(--border); border:none; color:var(--text); border-radius:6px; padding:6px 12px; font-size:13px; cursor:pointer; display:flex; align-items:center; gap:6px; } @@ -1820,7 +1968,9 @@ const MAIN_HTML_BODY = String.raw`
+
v--
v-- + ocm v--
⚠️ @@ -2281,6 +2431,7 @@ const I18N = { 'tab.stats':'📊 Stats','tab.cron':'⏰ Cron', 'agents.title':'Agents','agents.new':'+ 新建 Subagent', 'channels.title':'路由绑定','channels.add':'+ 添加绑定','channels.hint':'用于高级路由管理:维护 Agent 与频道/群组绑定及优先级顺序。日常增减 Agent 请在 Agents 页面操作。', + 'channels.removeHint':'如果需要更换 Telegram 群或 Discord thread:请先在本页删除旧绑定,然后用新的 ID 重新绑定。也可用于修正绑定错误、群重建(ID 变化)、重复/冲突或临时断开路由。', 'channels.filterLabel':'Agent','channels.filterAll':'全部 Agent','channels.emptyFiltered':'当前 Agent 下暂无绑定', 'channels.countSuffix':'条绑定','channels.collapse':'折叠','channels.expand':'展开', 'models.title':'模型管理','models.primary':'默认主模型','models.fallback':'Fallback 链', @@ -2330,14 +2481,27 @@ const I18N = { 'guide.title':'📖 Setup Guide','guide.agent.s1':'Open Telegram, search for @BotFather', 'guide.agent.s2':'Send /newbot and follow prompts to name your Bot', 'guide.agent.s3':'Copy the Bot Token from BotFather and paste below', - 'guide.agent.s4':'Send /setprivacy → select your Bot → click Disable (allow Bot to read group messages)', + 'guide.agent.s4':'In BotFather: /mybots → select your bot → Bot SettingsAllow GroupsTurn on (allow the bot to join groups)', + 'guide.agent.s5':'Send /setprivacy → select your Bot → click Disable (allow Bot to read group messages)', 'guide.sub.s1':'在 BotFather 发送 /newbot 创建新 Bot,获取 Bot Token', 'guide.sub.s2':'在 BotFather 发送 /mybots → 选择 Bot → Bot SettingsGroup PrivacyTurn off', 'guide.sub.s3':'在 Telegram 创建新群组,将 Bot 加入群组(不要加其他人)', 'guide.sub.s4':'在群内发一条消息,从 gateway 日志中找到 peer.id(负数)', 'guide.sub.s5':'填写下方表单创建 Sub-Agent', 'guide.sub.warn':'⚠️ 安全提示:请勿将其他人加入此群组,只有你和 Bot 应在群内。否则其他人也能与 Bot 对话并产生 API 费用。', + 'guide.agent.discord.s1':'Discord 主 Agent:创建/选择一个专用 Channel(建议私密频道)。', + 'guide.agent.discord.s2':'右键该 Channel → Copy Link,粘贴到表单里(OCM 自动解析 channelId,可选 guildId)。', + 'guide.agent.discord.s3':'建议:一个 Channel 只绑定一个主 Agent,避免上下文串台。', + 'guide.sub.discord.s1':'Discord Sub-Agent:在对应主 Channel 下新建一个 Thread(强烈推荐每个任务一个 thread)。', + 'guide.sub.discord.s2':'如果是 Private Thread:需要把 Bot/Agent 拉进该 thread(否则读不到消息)。', + 'guide.sub.discord.s3':'右键该 Thread → Copy Link,粘贴到表单里(OCM 自动解析 threadId)。', + 'guide.sub.discord.warn':'⚠️ 约定:主 Agent 绑定 Channel;Sub-Agent 绑定 Thread。不要把 Sub-Agent 绑到普通 Channel。', 'wiz.telegramId':'你的 Telegram User ID','wiz.telegramIdHint':'💡 可通过 @userinfobot 获取,填写后自动配置 allowFrom 白名单','wiz.telegramIdPh':'例如: 123456789', + 'wiz.channel':'渠道', + 'wiz.discordChannel':'Discord 频道链接/ID', + 'wiz.discordChannelHint':'建议:右键频道 → Copy Link,粘贴后自动解析 channelId(可选 guildId)。', + 'wiz.discordThread':'Discord Thread 链接/ID(仅 Thread)', + 'wiz.discordThreadHint':'建议:在主频道内创建 thread → 右键 thread → Copy Link,粘贴后自动解析 threadId。', 'agents.empty':'暂无 Agent','agents.main':'主 Agent','agents.bound':'已绑群', 'agents.saveModel':'保存模型','agents.viewFiles':'查看文件', 'agents.defaultModel':'使用全局默认','agents.custom':'自定义','agents.noModel':'默认', @@ -2401,7 +2565,7 @@ const I18N = { 'tab.agents':'🤖 Agents','tab.channels':'🧭 Routing','tab.models':'🧠 Models & Auth','tab.auth':'🔑 Auth', 'tab.stats':'📊 Stats','tab.cron':'⏰ Cron', 'agents.title':'Agents','agents.new':'+ New Subagent', - 'channels.title':'Routing Bindings','channels.add':'+ Add Binding','channels.hint':'Advanced routing rules for agent-channel/group bindings and priority order. Use Agents page for daily add/remove workflows.','channels.removeHint':'When to use Remove binding: wrong agent/chat, group recreated (new id), duplicates/conflicts, decommission a sub-agent, or temporarily disconnect routing for safety.', + 'channels.title':'Routing Bindings','channels.add':'+ Add Binding','channels.hint':'Advanced routing rules for agent-channel/group bindings and priority order. Use Agents page for daily add/remove workflows.','channels.removeHint':'When to use Remove binding: if you need to switch to a new Telegram group / Discord thread, remove the old binding here, then add a new binding with the new ID. Also use this for wrong bindings, recreated groups (new id), duplicates/conflicts, decommissioning, or temporary disconnect.', 'channels.filterLabel':'Agent','channels.filterAll':'All Agents','channels.emptyFiltered':'No bindings for selected agent', 'channels.countSuffix':'bindings','channels.collapse':'Collapse','channels.expand':'Expand', 'models.title':'Model Management','models.primary':'Default Primary Model','models.fallback':'Fallback Chain', @@ -2451,14 +2615,28 @@ const I18N = { 'guide.title':'📖 Setup Guide','guide.agent.s1':'Open Telegram, search for @BotFather', 'guide.agent.s2':'Send /newbot and follow prompts to name your Bot', 'guide.agent.s3':'Copy the Bot Token from BotFather and paste below', - 'guide.agent.s4':'Send /setprivacy → select your Bot → click Disable (allow Bot to read group messages)', + 'guide.agent.s4':'In BotFather: /mybots → select your bot → Bot SettingsAllow GroupsTurn on (allow the bot to join groups)', + 'guide.agent.s5':'Send /setprivacy → select your Bot → click Disable (allow Bot to read group messages)', 'guide.sub.s1':'Send /newbot to BotFather to create a new Bot and get the Bot Token', 'guide.sub.s2':'Send /mybots to BotFather → select your Bot → Bot SettingsGroup PrivacyTurn off', 'guide.sub.s3':'Create a new Telegram group, add the Bot to the group (do NOT add anyone else)', 'guide.sub.s4':'Send a message in the group, find peer.id (negative number) in gateway logs', 'guide.sub.s5':'Fill in the form below to create the Sub-Agent', 'guide.sub.warn':'⚠️ Security: Do NOT add other people to this group. Only you and the Bot should be in the group. Otherwise others can chat with the Bot and incur API costs.', + 'guide.agent.discord.s1':'Discord main agent: create/select a dedicated channel (private recommended).', + 'guide.agent.discord.s2':'Right-click the channel → Copy Link, paste it into the form (OCM auto-parses channelId; optional guildId).', + 'guide.agent.discord.s3':'Recommended: bind one main agent per channel to avoid context bleed.', + 'guide.sub.discord.s1':'Discord sub-agent: create a thread under the main channel (one thread per task recommended).', + 'guide.sub.discord.s2':'If it is a private thread, add the bot/agent to the thread (otherwise it cannot read messages).', + 'guide.sub.discord.s3':'Right-click the thread → Copy Link, paste into the form (OCM auto-parses the threadId).', + 'guide.sub.discord.warn':'Important: main agents bind to channels; sub-agents bind to threads. Do not bind sub-agents to normal channels.', 'wiz.telegramId':'Your Telegram User ID','wiz.telegramIdHint':'💡 Get it from @userinfobot — auto-configures allowFrom whitelist','wiz.telegramIdPh':'e.g. 123456789', + 'wiz.channel':'Channel', + 'wiz.discordChannel':'Discord channel link/ID', + 'wiz.discordChannelHint':'Tip: right-click channel → Copy Link. Paste to auto-parse channelId (optional guildId).', + 'wiz.discordThread':'Discord thread link/ID (thread only)', + 'wiz.discordThreadHint':'Tip: create a thread under your main channel → Copy Link. Paste to auto-parse threadId.', + 'agents.empty':'No Agents','agents.main':'Main Agent','agents.bound':'Bound', 'agents.saveModel':'Save Model','agents.viewFiles':'View Files', 'agents.defaultModel':'Use Global Default','agents.custom':'custom','agents.noModel':'Default', @@ -2593,7 +2771,10 @@ async function checkStatus(){ if(r.needsSetup){ location.reload(); return; } setDot('ok'); document.getElementById('statusTxt').textContent = r.dir.replace(/.*[/\\\\]/,'.../')+' · v'+r.version; - document.getElementById('versionBadge').textContent = 'v'+r.version; + const tv=document.getElementById('topVersion'); + if(tv) tv.textContent = 'OCM v'+(r.ocmVersion||'--'); + const vb=document.getElementById('versionBadge'); if(vb) vb.textContent = 'v'+r.version; + const ov=document.getElementById('ocmVersionBadge'); if(ov) ov.textContent='ocm v'+(r.ocmVersion||'--'); }catch{ setDot('err'); document.getElementById('statusTxt').textContent='无法读取配置'; } } @@ -2755,24 +2936,51 @@ function buildAddAgentForm() { const modelOpts = buildModelOpts('__default__'); return '
' + '

' + t('agents.addAgentTitle') + '

' + - '
' + t('guide.title') + '
    ' + - '
  1. ' + t('guide.agent.s1') + '
  2. ' + - '
  3. ' + t('guide.agent.s2') + '
  4. ' + - '
  5. ' + t('guide.agent.s3') + '
  6. ' + - '
  7. ' + t('guide.agent.s4') + '
  8. ' + + '
    ' + + '
    ' + + + '
    ' + t('guide.title') + '
      ' + + '
    1. ' + t('guide.agent.s1') + '
    2. ' + + '
    3. ' + t('guide.agent.s2') + '
    4. ' + + '
    5. ' + t('guide.agent.s3') + '
    6. ' + + '
    7. ' + t('guide.agent.s4') + '
    8. ' + + '
    9. ' + t('guide.agent.s5') + '
    10. ' + '
    ' + - '
    ' + - '' + + + '' + + + '
    ' + + '
    ' + + '' + + '
    ' + '
    ' + - '
    ' + - '' + - 'Alphanumeric, underscore, or dash only
    ' + - '
    ' + - '' + + + '
    ' + + '
    ' + + '' + + 'Alphanumeric, underscore, or dash only
    ' + + '
    ' + + '' + + '
    ' + '
    ' + - '
    ' + - '' + + + '
    ' + + '' + + 'Each agent must have its own workspace for isolated SOUL/MEMORY.
    ' + + + '' + + '
    ' + '' + '
    ' + @@ -2787,76 +2995,144 @@ function buildAddAgentForm() { '
    '; } + +function toggleAddAgentChannel(ch){ + const tg=document.getElementById('fa-sec-telegram'); + const dg=document.getElementById('fa-sec-discord'); + const gT=document.getElementById('fa-guide-telegram'); + const gD=document.getElementById('fa-guide-discord'); + if(tg) tg.style.display = (ch==='telegram')?'block':'none'; + if(dg) dg.style.display = (ch==='discord')?'block':'none'; + if(gT) gT.style.display = (ch==='telegram')?'block':'none'; + if(gD) gD.style.display = (ch==='discord')?'block':'none'; +} function buildAddSubForm() { - // Build parent agent dropdown (agents with their own bot) const cfg = S.agents || []; - const botAgents = cfg.filter(a => a.hasOwnBot); + // Parent agent dropdown (all agents as potential parent for grouping) let parentOpts = ''; - if (botAgents.length === 0) { - parentOpts = ''; - } else { - botAgents.forEach(a => { - parentOpts += ''; - }); - } + if (cfg.length === 0) parentOpts = ''; + else cfg.forEach(a=>{ parentOpts += ''; }); + const modelOpts = buildModelOpts('__default__'); return '
    ' + '

    ' + t('agents.addSubTitle') + '

    ' + - '
    ' + t('guide.title') + '
      ' + - '
    1. ' + t('guide.sub.s1') + '
    2. ' + - '
    3. ' + t('guide.sub.s2') + '
    4. ' + - '
    5. ' + t('guide.sub.s3') + '
    6. ' + - '
    7. ' + t('guide.sub.s4') + '
    8. ' + - '
    9. ' + t('guide.sub.s5') + '
    10. ' + + '
      ' + + '' + + '
      ' + + + '
      ' + t('guide.title') + '
        ' + + '
      1. ' + t('guide.sub.s1') + '
      2. ' + + '
      3. ' + t('guide.sub.s2') + '
      4. ' + + '
      5. ' + t('guide.sub.s3') + '
      6. ' + + '
      7. ' + t('guide.sub.s4') + '
      8. ' + + '
      9. ' + t('guide.sub.s5') + '
      10. ' + '
      ' + '
      ' + t('guide.sub.warn') + '
      ' + '
      ' + + + '' + + '
      ' + - '
      ' + - '
      ' + - '' + - '' + t('wiz.groupHint') + '
      ' + - '
      ' + - '' + - '' + t('wiz.telegramIdHint') + '
      ' + + '' + + 'Used for grouping only (Discord sub-agents do not share bots).' + + '
    ' + + + '
    ' + + '
    ' + + '' + + '' + t('wiz.groupHint') + '' + + '
    ' + + '
    ' + + '' + + '' + t('wiz.telegramIdHint') + '' + + '
    ' + + '
    ' + + + '' + + '
    ' + - '
    ' + - '
    ' + - '
    ' + - '
    ' + + '
    ' + + '
    ' + + '
    ' + + '
    ' + + '
    ' + + + '
    ' + + '' + + 'Each sub-agent must have its own workspace for isolated SOUL/MEMORY.' + + '
    ' + + '
    ' + - '
    ' + + '
' + '
' + - '
' + + '
' + '
' + - '
' + + '' + '
' + - '
' + + '' + + '
' + - '' + - '' + + '' + + '' + '
'; } +function toggleAddSubChannel(ch){ + const tg=document.getElementById('fs-sec-telegram'); + const dg=document.getElementById('fs-sec-discord'); + const gT=document.getElementById('fs-guide-telegram'); + const gD=document.getElementById('fs-guide-discord'); + if(tg) tg.style.display = (ch==='telegram')?'block':'none'; + if(dg) dg.style.display = (ch==='discord')?'block':'none'; + if(gT) gT.style.display = (ch==='telegram')?'block':'none'; + if(gD) gD.style.display = (ch==='discord')?'block':'none'; +} + // ── Submit Add Agent (with own bot) ────────────────────────── async function submitAddAgent() { - const token = document.getElementById('fa-token').value.trim(); + const channel = (document.getElementById('fa-channel')?.value||'telegram').trim(); const agentId = document.getElementById('fa-agentid').value.trim(); const name = document.getElementById('fa-name').value.trim(); - const workspace = document.getElementById('fa-workspace').value.trim(); + const workspace = (document.getElementById('fa-workspace').value.trim() || agentId); const model = document.getElementById('fa-model').value; const purpose = (document.getElementById('fa-purpose')?.value||'').trim(); const personality = (document.getElementById('fa-soul')?.value||'').trim(); - if (!token) { toast(t('agents.errToken'), 'err'); return; } + if (!agentId) { toast('Agent ID is required', 'err'); return; } if (!/^[a-zA-Z0-9_-]+$/.test(agentId)) { toast('Agent ID must contain only alphanumeric characters, underscores, or dashes', 'err'); return; } if (!name) { toast(t('agents.errName'), 'err'); return; } - if (!workspace) { toast('Workspace name is required', 'err'); return; } + if (!workspace) { toast('Workspace folder is required', 'err'); return; } + try { - const payload = { botToken: token, agentId, name, workspace, model: model === '__default__' ? '' : model, purpose, personality }; - const r = await api('POST', '/api/agents/bot', payload); + if (channel === 'telegram') { + const token = document.getElementById('fa-token').value.trim(); + if (!token) { toast(t('agents.errToken'), 'err'); return; } + const payload = { botToken: token, agentId, name, workspace, model: model === '__default__' ? '' : model, purpose, personality }; + await api('POST', '/api/agents/bot', payload); + } else { + const link = (document.getElementById('fa-discord-link')?.value||'').trim(); + const parsed = parseDiscordLinkOrId(link); + if (!parsed) { toast('Discord channel link/ID is required', 'err'); return; } + const payload = { agentId, name, workspaceFolder: workspace, model: model === '__default__' ? '' : model, purpose, personality, + guildId: parsed.guildId, channelId: parsed.channelId }; + await api('POST', '/api/agents/discord', payload); + } toast('Agent created successfully', 'ok'); - closePopover(); + clearAddForm(); showRestartBanner(); await loadAll(); } catch (e) { @@ -2866,25 +3142,39 @@ async function submitAddAgent() { // ── Submit Add Sub-Agent ──────────────────────────────────── async function submitAddSub() { + const channel = (document.getElementById('fs-channel')?.value||'telegram').trim(); const parentAgentId = document.getElementById('fs-parent').value.trim(); - const groupId = document.getElementById('fs-gid').value.trim(); - const telegramUserId = (document.getElementById('fs-tgid')?.value||'').trim(); const agentId = document.getElementById('fs-aid').value.trim(); const displayName = document.getElementById('fs-name').value.trim(); + const workspaceFolder = (document.getElementById('fs-workspace')?.value||'').trim() || agentId; const model = document.getElementById('fs-model').value; const purpose = document.getElementById('fs-purpose').value.trim(); const personality = document.getElementById('fs-soul').value.trim(); const initialMemory = document.getElementById('fs-mem').value.trim(); + if (!parentAgentId) { toast('Parent Agent is required', 'err'); return; } - if (!groupId) { toast(t('wiz.errGroupId'), 'err'); return; } if (!agentId) { toast(t('wiz.errAgentId'), 'err'); return; } if (!/^[a-zA-Z0-9_-]+$/.test(agentId)) { toast(t('wiz.errIdFormat'), 'err'); return; } - if (telegramUserId && !/^\\d+$/.test(telegramUserId)) { toast('Telegram User ID must be a number', 'err'); return; } + if (!workspaceFolder) { toast('Workspace folder is required', 'err'); return; } + try { - const r = await api('POST', '/api/agents', { parentAgentId, agentId, displayName: displayName || agentId, groupId, workspaceFolder: agentId, model: model === '__default__' ? '' : model, purpose, personality, initialMemory, telegramUserId }); - if (r.error) { toast(r.error, 'err'); return; } + if (channel === 'telegram') { + const groupId = document.getElementById('fs-gid').value.trim(); + const telegramUserId = (document.getElementById('fs-tgid')?.value||'').trim(); + if (!groupId) { toast(t('wiz.errGroupId'), 'err'); return; } + if (telegramUserId && !/^\d+$/.test(telegramUserId)) { toast('Telegram User ID must be a number', 'err'); return; } + await api('POST', '/api/agents', { parentAgentId, agentId, displayName: displayName || agentId, groupId, + workspaceFolder, model: model === '__default__' ? '' : model, purpose, personality, initialMemory, telegramUserId }); + } else { + const link = (document.getElementById('fs-discord-link')?.value||'').trim(); + const parsed = parseDiscordLinkOrId(link); + if (!parsed) { toast('Discord thread link/ID is required', 'err'); return; } + await api('POST', '/api/agents/discord-sub', { parentAgentId, agentId, displayName: displayName || agentId, + workspaceFolder, model: model === '__default__' ? '' : model, purpose, personality, initialMemory, + guildId: parsed.guildId, threadId: parsed.channelId }); + } toast(t('wiz.created'), 'ok'); - document.getElementById('addFormArea').innerHTML = ''; + clearAddForm(); showRestartBanner(); await loadAll(); } catch (e) { toast(e.message, 'err'); } @@ -2895,39 +3185,59 @@ function renderAgents() { const el = document.getElementById('agentTree'); if (!S.agents.length) { el.innerHTML = '
' + t('agents.empty') + '
'; return; } - // Build tree: each hasOwnBot agent is a root, others are sub-agents grouped by parentAccountId - const roots = S.agents.filter(a => a.hasOwnBot); - const subs = S.agents.filter(a => !a.hasOwnBot); + // Build grouping: prefer explicit parentAgentId; fallback to telegram bot-root grouping. + const byId = {}; (S.agents||[]).forEach(a=>{ byId[a.id]=a; }); - // Map accountId -> root agent for sub-agent grouping - const rootByAccount = {}; - roots.forEach(a => { if (a.accountId) rootByAccount[a.accountId] = a; }); - - // Group subs under their parent - const subsByRoot = {}; - const orphanSubs = []; - subs.forEach(a => { - const parentAcct = a.parentAccountId; - if (parentAcct && rootByAccount[parentAcct]) { - const rootId = rootByAccount[parentAcct].id; - if (!subsByRoot[rootId]) subsByRoot[rootId] = []; - subsByRoot[rootId].push(a); - } else { - orphanSubs.push(a); + // infer parentAgentId for legacy telegram sub-agents if missing + const accountToRootId = {}; + (S.agents||[]).forEach(a=>{ if(a.hasOwnBot && a.accountId) accountToRootId[a.accountId]=a.id; }); + (S.agents||[]).forEach(a=>{ + if(!a.parentAgentId && !a.hasOwnBot && a.parentAccountId && accountToRootId[a.parentAccountId]){ + a._inferParentAgentId = accountToRootId[a.parentAccountId]; } }); + const roots=[]; const childrenByRoot={}; const orphans=[]; + (S.agents||[]).forEach(a=>{ + const pid = a.parentAgentId || a._inferParentAgentId || ''; + if(pid && byId[pid]){ + (childrenByRoot[pid] ||= []).push(a); + } else { + roots.push(a); + } + }); + + function fmtBinding(b){ + const ch = (b.channel||'').toLowerCase(); + const peer = b.peerId ? String(b.peerId) : ''; + const acct = b.accountId ? String(b.accountId) : ''; + if(ch==='telegram'){ + if(peer) return 'TG '+esc(peer)+''; + if(acct) return 'TG Bot '+esc(acct)+''; + } + if(ch==='discord'){ + if(peer) return 'Discord '+esc(peer)+''; + } + return ''+esc(ch||'bind')+''; + } + + function bindingsLine(a){ + const arr = (a.bindings||[]).filter(x=>x.peerId||x.accountId); + if(!arr.length) return ''; + return '
🔗 '+arr.map(fmtBinding).join(' · ')+'
'; + } + function agentCard(a, isRoot) { let h = ''; - const icon = isRoot ? '🤖' : '📱'; + const icon = isRoot ? '🤖' : '🧩'; const cls = isRoot ? 'tree-main' : 'tree-child'; h += '
'; h += '
' + icon + ' ' + esc(a.name || a.id); - if (isRoot) h += ' ' + (a.id === 'main' ? t('agents.main') : 'Bot') + ''; - if (a.groupId) h += ' ' + esc(a.groupId) + ''; + if (a.id === 'main') h += ' ' + t('agents.main') + ''; h += '
'; h += '
🧠 ' + esc(a.effectiveModel) + '
'; if (a.workspace) h += '
📁 ' + esc(a.workspace) + '
'; + h += bindingsLine(a); h += '
'; h += ''; h += ''; @@ -2938,35 +3248,27 @@ function renderAgents() { } let html = '
'; - - // Render each root with its children, side by side roots.forEach(root => { - const children = subsByRoot[root.id] || []; + const children = childrenByRoot[root.id] || []; html += '
'; html += agentCard(root, true); if (children.length) { const treeId = 'tree-' + root.id; html += '
'; - html += ''; + html += ''; html += '
'; children.forEach(c => { html += agentCard(c, false); }); html += '
'; } html += '
'; }); - - // Orphan subs (no matching root — edge case) - orphanSubs.forEach(a => { - html += '
'; - html += agentCard(a, false); - html += '
'; - }); - html += '
'; el.innerHTML = html; - // Event delegation for agent tree buttons el.onclick = function(ev) { + const tbtn = ev.target.closest('.tree-toggle'); + if (tbtn && tbtn.dataset.tree) { toggleTree(tbtn.dataset.tree, tbtn); return; } + const btn = ev.target.closest('[data-action]'); if (!btn) return; const action = btn.dataset.action; @@ -4105,6 +4407,21 @@ function assertBrowserScriptSyntax(name, scriptText) { ); } } + + +function parseDiscordLinkOrId(input){ + const raw=(input||'').trim(); + if(!raw) return null; + // URL form: https://discord.com/channels// + const m = raw.match(/discord(?:app)?\.com\/channels\/(\d+)\/(\d+)/i); + if(m) return { guildId: m[1], channelId: m[2] }; + // Accept plain numeric id + if(/^\d+$/.test(raw)) return { guildId: '', channelId: raw }; + // Accept channel: + const m2 = raw.match(/^channel:(\d+)$/i); + if(m2) return { guildId: '', channelId: m2[1] }; + return null; +} assertBrowserScriptSyntax('main-html-script', MAIN_HTML_SCRIPT); // ── HTTP 服务器 ───────────────────────────────────────────────