@@ -24,7 +24,7 @@ const SCRIPT_DIR = __dirname;
const MANAGER _CONFIG = path . join ( SCRIPT _DIR , 'manager-config.json' ) ;
const MANAGER _CONFIG = path . join ( SCRIPT _DIR , 'manager-config.json' ) ;
let PORT = 3333 ;
let PORT = 3333 ;
let HOST = '0.0.0.0' ;
let HOST = '0.0.0.0' ;
const APP _VERSION = '0.8.2 ' ;
const APP _VERSION = '0.9.0 ' ;
// --port 参数
// --port 参数
const portIdx = process . argv . indexOf ( '--port' ) ;
const portIdx = process . argv . indexOf ( '--port' ) ;
if ( portIdx !== - 1 && process . argv [ portIdx + 1 ] ) PORT = parseInt ( process . argv [ portIdx + 1 ] ) || 3333 ;
if ( portIdx !== - 1 && process . argv [ portIdx + 1 ] ) PORT = parseInt ( process . argv [ portIdx + 1 ] ) || 3333 ;
@@ -423,7 +423,13 @@ async function handleApi(req, res, urlObj, body) {
// Workspace: explicit per-agent, or defaults.workspace for main
// Workspace: explicit per-agent, or defaults.workspace for main
const workspace = a . workspace || ( isMain ? defaultWorkspace : null ) ;
const workspace = a . workspace || ( isMain ? defaultWorkspace : null ) ;
return { ... a , workspace , groupId , requireMention : groupId ? ( groups [ groupId ] ? . requireMention ? ? true ) : 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 . writeHead ( 200 ) ;
res . end ( JSON . stringify ( { agents : enriched , defaults } ) ) ;
res . end ( JSON . stringify ( { agents : enriched , defaults } ) ) ;
@@ -508,6 +514,143 @@ async function handleApi(req, res, urlObj, body) {
return ;
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)
// POST /api/agents — create sub-agent (shares parent bot)
if ( method === 'POST' && pathname === '/api/agents' ) {
if ( method === 'POST' && pathname === '/api/agents' ) {
const { agentId , displayName , groupId , workspaceFolder , model , purpose , personality , initialMemory , parentAgentId , telegramUserId } = body ;
const { agentId , displayName , groupId , workspaceFolder , model , purpose , personality , initialMemory , parentAgentId , telegramUserId } = body ;
@@ -537,7 +680,7 @@ async function handleApi(req, res, urlObj, body) {
const folder = workspaceFolder || agentId ;
const folder = workspaceFolder || agentId ;
const wsPath = path . join ( OPENCLAW _DIR , 'workspaces' , folder ) ;
const wsPath = path . join ( OPENCLAW _DIR , 'workspaces' , folder ) ;
const wsAlias = ` ~/.openclaw/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 } ;
if ( model && model !== '__default__' ) agentEntry . model = { primary : model } ;
cfg . agents . list . push ( agentEntry ) ;
cfg . agents . list . push ( agentEntry ) ;
// Binding uses parent's accountId
// Binding uses parent's accountId
@@ -1556,6 +1699,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 { 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); }
.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 */
/* dropdown menu */
.menu-wrap { position:relative; }
.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; }
.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 +1967,9 @@ const MAIN_HTML_BODY = String.raw`
<!-- Header / Toolbar -->
<!-- Header / Toolbar -->
<header>
<header>
<span class="logo" title="OpenClaw Manager">🦀 OpenClaw</span>
<span class="logo" title="OpenClaw Manager">🦀 OpenClaw</span>
<div class="top-version" id="topVersion">v--</div>
<span class="ver" id="versionBadge">v--</span>
<span class="ver" id="versionBadge">v--</span>
<span class="ver ver-old" id="ocmVersionBadge">ocm v--</span>
<div class="spacer"></div>
<div class="spacer"></div>
<div id="healthBadge" title="">
<div id="healthBadge" title="">
<span id="healthIcon">⚠️</span>
<span id="healthIcon">⚠️</span>
@@ -2281,6 +2430,7 @@ const I18N = {
'tab.stats':'📊 Stats','tab.cron':'⏰ Cron',
'tab.stats':'📊 Stats','tab.cron':'⏰ Cron',
'agents.title':'Agents','agents.new':'+ 新建 Subagent',
'agents.title':'Agents','agents.new':'+ 新建 Subagent',
'channels.title':'路由绑定','channels.add':'+ 添加绑定','channels.hint':'用于高级路由管理:维护 Agent 与频道/群组绑定及优先级顺序。日常增减 Agent 请在 Agents 页面操作。',
'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.filterLabel':'Agent','channels.filterAll':'全部 Agent','channels.emptyFiltered':'当前 Agent 下暂无绑定',
'channels.countSuffix':'条绑定','channels.collapse':'折叠','channels.expand':'展开',
'channels.countSuffix':'条绑定','channels.collapse':'折叠','channels.expand':'展开',
'models.title':'模型管理','models.primary':'默认主模型','models.fallback':'Fallback 链',
'models.title':'模型管理','models.primary':'默认主模型','models.fallback':'Fallback 链',
@@ -2330,13 +2480,21 @@ const I18N = {
'guide.title':'📖 Setup Guide','guide.agent.s1':'Open Telegram, search for <code>@BotFather</code>',
'guide.title':'📖 Setup Guide','guide.agent.s1':'Open Telegram, search for <code>@BotFather</code>',
'guide.agent.s2':'Send <code>/newbot</code> and follow prompts to name your Bot',
'guide.agent.s2':'Send <code>/newbot</code> and follow prompts to name your Bot',
'guide.agent.s3':'Copy the <code>Bot Token</code> from BotFather and paste below',
'guide.agent.s3':'Copy the <code>Bot Token</code> from BotFather and paste below',
'guide.agent.s4':'Send <code>/setprivacy </code> → select your B ot → click <code>Disable</code > (allow B ot to read group message s)',
'guide.agent.s4':'In BotFather: <code>/mybots </code> → select your b ot → <b>Bot Settings</b> → <b>Allow Groups</b> → <b>Turn on</b > (allow the b ot to join groups)',
'guide.agent.s5':'Send <code>/setprivacy</code> → select your Bot → click <code>Disable</code> (allow Bot to read group messages)',
'guide.sub.s1':'在 BotFather 发送 <code>/newbot</code> 创建新 Bot,获取 Bot Token',
'guide.sub.s1':'在 BotFather 发送 <code>/newbot</code> 创建新 Bot,获取 Bot Token',
'guide.sub.s2':'在 BotFather 发送 <code>/mybots</code> → 选择 Bot → <b>Bot Settings</b> → <b>Group Privacy</b> → <b>Turn off</b>',
'guide.sub.s2':'在 BotFather 发送 <code>/mybots</code> → 选择 Bot → <b>Bot Settings</b> → <b>Group Privacy</b> → <b>Turn off</b>',
'guide.sub.s3':'在 Telegram 创建新群组,将 Bot 加入群组(<b>不要加其他人</b>) ',
'guide.sub.s3':'在 Telegram 创建新群组,将 Bot 加入群组(<b>不要加其他人</b>) ',
'guide.sub.s4':'在群内发一条消息,从 gateway 日志中找到 <code>peer.id</code>(负数)',
'guide.sub.s4':'在群内发一条消息,从 gateway 日志中找到 <code>peer.id</code>(负数)',
'guide.sub.s5':'填写下方表单创建 Sub-Agent',
'guide.sub.s5':'填写下方表单创建 Sub-Agent',
'guide.sub.warn':'⚠️ 安全提示:请勿将其他人加入此群组,只有你和 Bot 应在群内。否则其他人也能与 Bot 对话并产生 API 费用。',
'guide.sub.warn':'⚠️ 安全提示:请勿将其他人加入此群组,只有你和 Bot 应在群内。否则其他人也能与 Bot 对话并产生 API 费用。',
'guide.agent.discord.s1':'Discord 主 Agent:创建/选择一个专用 <b>Channel</b>(建议私密频道)。',
'guide.agent.discord.s2':'右键该 Channel → <b>Copy Link</b>,粘贴到表单里(OCM 自动解析 <code>channelId</code>,可选 <code>guildId</code>)。',
'guide.agent.discord.s3':'建议:一个 Channel 只绑定一个主 Agent,避免上下文串台。',
'guide.sub.discord.s1':'Discord Sub-Agent:在对应主 Channel 下新建一个 <b>Thread</b>(强烈推荐每个任务一个 thread)。',
'guide.sub.discord.s2':'如果是 Private Thread:需要把 Bot/Agent 拉进该 thread(否则读不到消息)。',
'guide.sub.discord.s3':'右键该 Thread → <b>Copy Link</b>,粘贴到表单里(OCM 自动解析 <code>threadId</code>)。',
'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.telegramId':'你的 Telegram User ID','wiz.telegramIdHint':'💡 可通过 @userinfobot 获取,填写后自动配置 allowFrom 白名单','wiz.telegramIdPh':'例如: 123456789',
'agents.empty':'暂无 Agent','agents.main':'主 Agent','agents.bound':'已绑群',
'agents.empty':'暂无 Agent','agents.main':'主 Agent','agents.bound':'已绑群',
'agents.saveModel':'保存模型','agents.viewFiles':'查看文件',
'agents.saveModel':'保存模型','agents.viewFiles':'查看文件',
@@ -2401,7 +2559,7 @@ const I18N = {
'tab.agents':'🤖 Agents','tab.channels':'🧭 Routing','tab.models':'🧠 Models & Auth','tab.auth':'🔑 Auth',
'tab.agents':'🤖 Agents','tab.channels':'🧭 Routing','tab.models':'🧠 Models & Auth','tab.auth':'🔑 Auth',
'tab.stats':'📊 Stats','tab.cron':'⏰ Cron',
'tab.stats':'📊 Stats','tab.cron':'⏰ Cron',
'agents.title':'Agents','agents.new':'+ New Subagent',
'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 temporaril y 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.filterLabel':'Agent','channels.filterAll':'All Agents','channels.emptyFiltered':'No bindings for selected agent',
'channels.countSuffix':'bindings','channels.collapse':'Collapse','channels.expand':'Expand',
'channels.countSuffix':'bindings','channels.collapse':'Collapse','channels.expand':'Expand',
'models.title':'Model Management','models.primary':'Default Primary Model','models.fallback':'Fallback Chain',
'models.title':'Model Management','models.primary':'Default Primary Model','models.fallback':'Fallback Chain',
@@ -2451,13 +2609,21 @@ const I18N = {
'guide.title':'📖 Setup Guide','guide.agent.s1':'Open Telegram, search for <code>@BotFather</code>',
'guide.title':'📖 Setup Guide','guide.agent.s1':'Open Telegram, search for <code>@BotFather</code>',
'guide.agent.s2':'Send <code>/newbot</code> and follow prompts to name your Bot',
'guide.agent.s2':'Send <code>/newbot</code> and follow prompts to name your Bot',
'guide.agent.s3':'Copy the <code>Bot Token</code> from BotFather and paste below',
'guide.agent.s3':'Copy the <code>Bot Token</code> from BotFather and paste below',
'guide.agent.s4':'Send <code>/setprivacy </code> → select your B ot → click <code>Disable</code > (allow B ot to read group message s)',
'guide.agent.s4':'In BotFather: <code>/mybots </code> → select your b ot → <b>Bot Settings</b> → <b>Allow Groups</b> → <b>Turn on</b > (allow the b ot to join groups)',
'guide.agent.s5':'Send <code>/setprivacy</code> → select your Bot → click <code>Disable</code> (allow Bot to read group messages)',
'guide.sub.s1':'Send <code>/newbot</code> to BotFather to create a new Bot and get the Bot Token',
'guide.sub.s1':'Send <code>/newbot</code> to BotFather to create a new Bot and get the Bot Token',
'guide.sub.s2':'Send <code>/mybots</code> to BotFather → select your Bot → <b>Bot Settings</b> → <b>Group Privacy</b> → <b>Turn off</b>',
'guide.sub.s2':'Send <code>/mybots</code> to BotFather → select your Bot → <b>Bot Settings</b> → <b>Group Privacy</b> → <b>Turn off</b>',
'guide.sub.s3':'Create a new Telegram group, add the Bot to the group (<b>do NOT add anyone else</b>)',
'guide.sub.s3':'Create a new Telegram group, add the Bot to the group (<b>do NOT add anyone else</b>)',
'guide.sub.s4':'Send a message in the group, find <code>peer.id</code> (negative number) in gateway logs',
'guide.sub.s4':'Send a message in the group, find <code>peer.id</code> (negative number) in gateway logs',
'guide.sub.s5':'Fill in the form below to create the Sub-Agent',
'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.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 <b>channel</b> (private recommended).',
'guide.agent.discord.s2':'Right-click the channel → <b>Copy Link</b>, paste it into the form (OCM auto-parses <code>channelId</code>; optional <code>guildId</code>).',
'guide.agent.discord.s3':'Recommended: bind one main agent per channel to avoid context bleed.',
'guide.sub.discord.s1':'Discord sub-agent: create a <b>thread</b> 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 → <b>Copy Link</b>, paste into the form (OCM auto-parses the <code>threadId</code>).',
'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.telegramId':'Your Telegram User ID','wiz.telegramIdHint':'💡 Get it from @userinfobot — auto-configures allowFrom whitelist','wiz.telegramIdPh':'e.g. 123456789',
'agents.empty':'No Agents','agents.main':'Main Agent','agents.bound':'Bound',
'agents.empty':'No Agents','agents.main':'Main Agent','agents.bound':'Bound',
'agents.saveModel':'Save Model','agents.viewFiles':'View Files',
'agents.saveModel':'Save Model','agents.viewFiles':'View Files',
@@ -2593,7 +2759,10 @@ async function checkStatus(){
if(r.needsSetup){ location.reload(); return; }
if(r.needsSetup){ location.reload(); return; }
setDot('ok');
setDot('ok');
document.getElementById('statusTxt').textContent = r.dir.replace(/.*[/ \\ \\ ]/,'.../')+' · v'+r.version;
document.getElementById('statusTxt').textContent = r.dir.replace(/.*[/ \\ \\ ]/,'.../')+' · v'+r.version;
document.getElementById('v ersionBadge').textContent = 'v'+r.version ;
const tv= document.getElementById('topV ersion') ;
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='无法读取配置'; }
}catch{ setDot('err'); document.getElementById('statusTxt').textContent='无法读取配置'; }
}
}
@@ -2755,24 +2924,51 @@ function buildAddAgentForm() {
const modelOpts = buildModelOpts('__default__');
const modelOpts = buildModelOpts('__default__');
return '<div class="add-form">' +
return '<div class="add-form">' +
'<h3>' + t('agents.addAgentTitle') + '</h3>' +
'<h3>' + t('agents.addAgentTitle') + '</h3>' +
'<details class="guide-box" open><summary>' + t('guide.title') + '</summary><o l>' +
'<div class="form-group"><label>' + t('wiz.channel') + '</labe l>' +
'<li>' + t('guide.agent.s1') + '</li >' +
'<select id="fa-channel" onchange="toggleAddAgentChannel(this.value)" >' +
'<li>' + t('guide.agent.s2') + '</li >' +
'<option value="telegram">Telegram</option >' +
'<li>' + t('guide.agent.s3') + '</li >' +
'<option value="discord">Discord</option >' +
'<li>' + t('guide.agent.s4') + '</li >' +
'</select></div >' +
'<details class="guide-box" open id="fa-guide-telegram"><summary>' + t('guide.title') + '</summary><ol>' +
'<li>' + t('guide.agent.s1') + '</li>' +
'<li>' + t('guide.agent.s2') + '</li>' +
'<li>' + t('guide.agent.s3') + '</li>' +
'<li>' + t('guide.agent.s4') + '</li>' +
'<li>' + t('guide.agent.s5') + '</li>' +
'</ol></details>' +
'</ol></details>' +
'<div class="form-group"><label>' + t('agents.botToken') + '</label>' +
'<input id="fa-token " type="text" placeholder="123456:ABC-DEF..." >' +
'<details class="guide-box" open id="fa-guide-discord " s tyle="display:none"><summary>' + t('guide.title') + '</summary><ol >' +
'<li>' + t('guide.agent.discord.s1') + '</li>' +
'<li>' + t('guide.agent.discord.s2') + '</li>' +
'<li>' + t('guide.agent.discord.s3') + '</li>' +
'</ol></details>' +
'<div id="fa-sec-telegram">' +
'<div class="form-group"><label>' + t('agents.botToken') + '</label>' +
'<input id="fa-token" type="text" placeholder="123456:ABC-DEF...">' +
'</div>' +
'</div>' +
'</div>' +
'<div class="form-group"><label>Agent ID</label>' +
'<input id="fa-agentid" type="text" placeholder="research, alice_bot, etc." pattern="[a-zA-Z0-9_-]+ ">' +
'<div class="form-row ">' +
'<span class="hint-text">Alphanumeric, underscore, or dash only</span></div >' +
'<div class="form-group"><label>Agent ID</label >' +
'<div class="form-group"><label>' + t('agents.botName') + '</label >' +
'<input id="fa-agentid" type="text" placeholder="research, travel_assistant, etc." pattern="[a-zA-Z0-9_-]+" >' +
'<input id="fa-name" type="text" placeholder="' + t('agents.botNamePh') + '" >' +
'<span class="hint-text">Alphanumeric, underscore, or dash only</span></div >' +
'<div class="form-group"><label>' + t('agents.botName') + '</label>' +
'<input id="fa-name" type="text" placeholder="' + t('agents.botNamePh') + '">' +
'</div>' +
'</div>' +
'</div>' +
'<div class="form-group"><label>Workspace Name</label>' +
'<input id="fa-workspace" type="text" placeholder="research, alice_workspace, etc." >' +
'<div class="form-group"><label>Workspace Folder</label >' +
'<input id="fa-workspace" type="text" placeholder="(default = Agent ID)">' +
'<span class="hint-text">Each agent must have its own workspace for isolated SOUL/MEMORY.</span></div>' +
'<div id="fa-sec-discord" style="display:none">' +
'<div class="form-group"><label>' + t('wiz.discordChannel') + '</label>' +
'<input id="fa-discord-link" type="text" placeholder="https://discord.com/channels/<guildId>/<channelId> or <channelId>">' +
'<span class="hint-text">' + t('wiz.discordChannelHint') + '</span></div>' +
'</div>' +
'</div>' +
'<div class="form-group"><label>' + t('wiz.model') + '</label>' +
'<div class="form-group"><label>' + t('wiz.model') + '</label>' +
'<select id="fa-model">' + modelOpts + '</select>' +
'<select id="fa-model">' + modelOpts + '</select>' +
'</div>' +
'</div>' +
@@ -2787,76 +2983,144 @@ function buildAddAgentForm() {
'</div></div>';
'</div></div>';
}
}
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() {
function buildAddSubForm() {
// Build parent agent dropdown (agents with their own bot)
const cfg = S.agents || [];
const cfg = S.agents || [];
const botAgents = cfg.filter(a => a.hasOwnBot);
// Parent agent dropdown (all agents as potential parent for grouping)
let parentOpts = '';
let parentOpts = '';
if (botAgents .length === 0) {
if (cfg .length === 0) parentOpts = '<option value="">No agents available</option>';
parentOpts = '<option value="">No agents with bot available </option>';
else cfg.forEach(a=>{ parentOpts + = '<option value="'+esc(a.id)+'">'+esc(a.name||a.id)+' </option>'; });
} else {
botAgents.forEach(a => {
parentOpts += '<option value="' + esc(a.id) + '">' + esc(a.name || a.id) + '</option>';
});
}
const modelOpts = buildModelOpts('__default__');
const modelOpts = buildModelOpts('__default__');
return '<div class="add-form">' +
return '<div class="add-form">' +
'<h3>' + t('agents.addSubTitle') + '</h3>' +
'<h3>' + t('agents.addSubTitle') + '</h3>' +
'<details class="guide-box" open><summary>' + t('guide.title') + '</summary><o l>' +
'<div class="form-group"><label>' + t('wiz.channel') + '</labe l>' +
'<li>' + t('guide.sub.s1') + '</li >' +
'<select id="fs-channel" onchange="toggleAddSubChannel(this.value)" >' +
'<li>' + t('guide.sub.s2') + '</li >' +
'<option value="telegram">Telegram</option >' +
'<li>' + t('guide.sub.s3') + '</li >' +
'<option value="discord">Discord (thread only)</option >' +
'<li>' + t('guide.sub.s4') + '</li >' +
'</select >' +
'<li>' + t('guide.sub.s5') + '</li >' +
'</div >' +
'<details class="guide-box" open id="fs-guide-telegram"><summary>' + t('guide.title') + '</summary><ol>' +
'<li>' + t('guide.sub.s1') + '</li>' +
'<li>' + t('guide.sub.s2') + '</li>' +
'<li>' + t('guide.sub.s3') + '</li>' +
'<li>' + t('guide.sub.s4') + '</li>' +
'<li>' + t('guide.sub.s5') + '</li>' +
'</ol>' +
'</ol>' +
'<div style="margin-top:10px;padding:10px 12px;background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.3);border-radius:8px;font-size:13px;line-height:1.5">' + t('guide.sub.warn') + '</div>' +
'<div style="margin-top:10px;padding:10px 12px;background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.3);border-radius:8px;font-size:13px;line-height:1.5">' + t('guide.sub.warn') + '</div>' +
'</details>' +
'</details>' +
'<details class="guide-box" open id="fs-guide-discord" style="display:none"><summary>' + t('guide.title') + '</summary><ol>' +
'<li>' + t('guide.sub.discord.s1') + '</li>' +
'<li>' + t('guide.sub.discord.s2') + '</li>' +
'<li>' + t('guide.sub.discord.s3') + '</li>' +
'</ol>' +
'<div style="margin-top:10px;padding:10px 12px;background:rgba(234,179,8,0.12);border:1px solid rgba(234,179,8,0.35);border-radius:8px;font-size:13px;line-height:1.5">' + t('guide.sub.discord.warn') + '</div>' +
'</details>' +
'<div class="form-group"><label>Parent Agent</label>' +
'<div class="form-group"><label>Parent Agent</label>' +
'<select id="fs-parent">' + parentOpts + '</select></div> ' +
'<select id="fs-parent">' + parentOpts + '</select>' +
'<div class=" form- group"><label>' + t('wiz.groupId') + '</label >' +
'<span class="hint-text">Used for grouping only (Discord sub-agents do not share bots).</span >' +
'<input id="fs-gid" placeholder="-100XXXXXXXXXX" >' +
'</div >' +
'<span class="hint-text">' + t('wiz.groupHint') + '</span></div>' +
'<div class="form-group"><label>' + t('wiz.telegramId') + '</label >' +
'<div id="fs-sec-telegram" >' +
'<input id="fs-tgid" placeholder="' + t('wiz.telegramIdPh') + '" >' +
'<div class="form-group"><label>' + t('wiz.groupId') + '</label >' +
'<span class="hint-text">' + t('wiz.telegramIdHint') + '</span></div >' +
'<input id="fs-gid" placeholder="-100XXXXXXXXXX" >' +
'<span class="hint-text">' + t('wiz.groupHint') + '</span>' +
'</div>' +
'<div class="form-group"><label>' + t('wiz.telegramId') + '</label>' +
'<input id="fs-tgid" placeholder="' + t('wiz.telegramIdPh') + '">' +
'<span class="hint-text">' + t('wiz.telegramIdHint') + '</span>' +
'</div>' +
'</div>' +
'<div id="fs-sec-discord" style="display:none">' +
'<div class="form-group"><label>' + t('wiz.discordThread') + '</label>' +
'<input id="fs-discord-link" placeholder="https://discord.com/channels/<guildId>/<threadId> or <threadId>">' +
'<span class="hint-text">' + t('wiz.discordThreadHint') + '</span>' +
'</div>' +
'</div>' +
'<div class="form-row">' +
'<div class="form-row">' +
'<div class="form-group"><label>' + t('wiz.agentId') + ' <span style="color:var(--muted);font-weight:400">' + t('wiz.agentIdHint') + '</span></label>' +
'<div class="form-group"><label>' + t('wiz.agentId') + ' <span style="color:var(--muted);font-weight:400">' + t('wiz.agentIdHint') + '</span></label>' +
'<input id="fs-aid" placeholder="' + t('wiz.agentIdPh') + '"></div>' +
'<input id="fs-aid" placeholder="' + t('wiz.agentIdPh') + '"></div>' +
'<div class="form-group"><label>' + t('wiz.displayName') + '</label>' +
'<div class="form-group"><label>' + t('wiz.displayName') + '</label>' +
'<input id="fs-name" placeholder="' + t('wiz.displayNamePh') + '"></div></div> ' +
'<input id="fs-name" placeholder="' + t('wiz.displayNamePh') + '"></div>' +
'</div>' +
'<div class="form-group"><label>Workspace Folder</label>' +
'<input id="fs-workspace" placeholder="(default = Agent ID)">' +
'<span class="hint-text">Each sub-agent must have its own workspace for isolated SOUL/MEMORY.</span>' +
'</div>' +
'<div class="form-group"><label>' + t('wiz.model') + '</label>' +
'<div class="form-group"><label>' + t('wiz.model') + '</label>' +
'<select id="fs-model">' + modelOpts + '</select></div>' +
'<select id="fs-model">' + modelOpts + '</select></div>' +
'<div class="form-group"><label>' + t('wiz.purpose') + '</label>' +
'<div class="form-group"><label>' + t('wiz.purpose') + '</label>' +
'<textarea id="fs-purpose" placeholder="' + t('wiz.purposePh') + '" rows="2"></textarea></div>' +
'<textarea id="fs-purpose" placeholder="' + t('wiz.purposePh') + '" rows="2"></textarea></div>' +
'<div class="form-group"><label>' + t('wiz.soul') + ' <span style="color:var(--muted);font-weight:400">' + t('wiz.soulHint') + '</span></label>' +
'<div class="form-group"><label>' + t('wiz.soul') + ' <span style="color:var(--muted);font-weight:400">' + t('wiz.soulHint') + '</span></label>' +
'<input id="fs-soul" placeholder="' + t('wiz.soulPh') + '"></div>' +
'<input id="fs-soul" placeholder="' + t('wiz.soulPh') + '"></div>' +
'<div class="form-group"><label>' + t('wiz.memory') + ' <span style="color:var(--muted);font-weight:400">' + t('wiz.memoryHint') + '</span></label>' +
'<div class="form-group"><label>' + t('wiz.memory') + ' <span style="color:var(--muted);font-weight:400">' + t('wiz.memoryHint') + '</span></label>' +
'<textarea id="fs-mem" placeholder="' + t('wiz.memoryPh') + '" rows="2"></textarea></div>' +
'<textarea id="fs-mem" placeholder="' + t('wiz.memoryPh') + '" rows="2"></textarea></div>' +
'<div style="display:flex;gap:8px;margin-top:14px">' +
'<div style="display:flex;gap:8px;margin-top:14px">' +
'<button class="btn-primary" onclick="submitAddSub()">' + t('agents.addSubSubmit') + '</button>' +
'<button class="btn-primary" onclick="submitAddSub()">' + t('agents.addSubSubmit') + '</button>' +
'<button class="btn-ghost" onclick="clearAddForm()">' + t('btn.cancel') + '</button>' +
'<button class="btn-ghost" onclick="clearAddForm()">' + t('btn.cancel') + '</button>' +
'</div></div>';
'</div></div>';
}
}
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) ──────────────────────────
// ── Submit Add Agent (with own bot) ──────────────────────────
async function submitAddAgent() {
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 agentId = document.getElementById('fa-agentid').value.trim();
const name = document.getElementById('fa-name').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 model = document.getElementById('fa-model').value;
const purpose = (document.getElementById('fa-purpose')?.value||'').trim();
const purpose = (document.getElementById('fa-purpose')?.value||'').trim();
const personality = (document.getElementById('fa-soul')?.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 (!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 (!/^[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 (!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 {
try {
const payload = { botToken: token, agentId, name, workspace, model: model === '__default__' ? '' : model, purpose, personality };
if (channel === 'telegram') {
const r = await api('POST', '/api/agents/bot', payload );
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');
toast('Agent created successfully', 'ok');
closePopover ();
clearAddForm ();
showRestartBanner();
showRestartBanner();
await loadAll();
await loadAll();
} catch (e) {
} catch (e) {
@@ -2866,25 +3130,39 @@ async function submitAddAgent() {
// ── Submit Add Sub-Agent ────────────────────────────────────
// ── Submit Add Sub-Agent ────────────────────────────────────
async function submitAddSub() {
async function submitAddSub() {
const channel = (document.getElementById('fs-channel')?.value||'telegram').trim();
const parentAgentId = document.getElementById('fs-parent').value.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 agentId = document.getElementById('fs-aid').value.trim();
const displayName = document.getElementById('fs-name').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 model = document.getElementById('fs-model').value;
const purpose = document.getElementById('fs-purpose').value.trim();
const purpose = document.getElementById('fs-purpose').value.trim();
const personality = document.getElementById('fs-soul').value.trim();
const personality = document.getElementById('fs-soul').value.trim();
const initialMemory = document.getElementById('fs-mem').value.trim();
const initialMemory = document.getElementById('fs-mem').value.trim();
if (!parentAgentId) { toast('Parent Agent is required', 'err'); return; }
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 (!agentId) { toast(t('wiz.errAgentId'), 'err'); return; }
if (!/^[a-zA-Z0-9_-]+ $ /.test(agentId)) { toast(t('wiz.errIdFormat'), '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 {
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 (channel === 'telegram') {
if (r.error) { toast(r.error, 'err'); return; }
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');
toast(t('wiz.created'), 'ok');
document.getElementById('addFormArea').innerHTML = '' ;
clearAddForm() ;
showRestartBanner();
showRestartBanner();
await loadAll();
await loadAll();
} catch (e) { toast(e.message, 'err'); }
} catch (e) { toast(e.message, 'err'); }
@@ -2895,39 +3173,59 @@ function renderAgents() {
const el = document.getElementById('agentTree');
const el = document.getElementById('agentTree');
if (!S.agents.length) { el.innerHTML = '<div class="empty">' + t('agents.empty') + '</div>'; return; }
if (!S.agents.length) { el.innerHTML = '<div class="empty">' + t('agents.empty') + '</div>'; return; }
// Build tree: each hasOwnBot agent is a root, others are sub-agents grouped by parentAccountId
// Build grouping: prefer explicit parentAgentId; fallback to telegram bot-root grouping.
const roots = S.agents.filter (a => a.hasOwnBot );
const byId = {}; (S.agents||[]).forEach (a=>{ byId[a.id]=a; } );
const subs = S.agents.filter(a => !a.hasOwnBot);
// Map accountId -> root agent for sub-agent group ing
// infer parentAgentId for legacy telegram sub-agents if miss ing
const rootByAccount = {};
const accountToRootId = {};
roots .forEach(a => { if (a.accountId) rootByAccount [a.accountId] = a ; });
(S.agents||[]) .forEach(a=>{ if(a.hasOwnBot && a.accountId) accountToRootId [a.accountId]=a.id ; });
(S.agents||[]).forEach(a=>{
// Group subs under their parent
if(!a.parentAgentId && !a.hasOwnBot && a.parentAccountId && accountToRootId[a.parentAccountId]){
const subsByRoot = {} ;
a._inferParentAgentId = accountToRootId[a.parentAccountId] ;
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);
}
}
});
});
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 '<span class="badge ok ch-badge ch-tg">TG</span> <span class="badge ok">'+esc(peer)+'</span>';
if(acct) return '<span class="badge ok ch-badge ch-tg">TG Bot</span> <span class="badge">'+esc(acct)+'</span>';
}
if(ch==='discord'){
if(peer) return '<span class="badge ok ch-badge ch-any">Discord</span> <span class="badge">'+esc(peer)+'</span>';
}
return '<span class="badge">'+esc(ch||'bind')+'</span>';
}
function bindingsLine(a){
const arr = (a.bindings||[]).filter(x=>x.peerId||x.accountId);
if(!arr.length) return '';
return '<div class="tree-meta">🔗 '+arr.map(fmtBinding).join(' · ')+'</div>';
}
function agentCard(a, isRoot) {
function agentCard(a, isRoot) {
let h = '';
let h = '';
const icon = isRoot ? '🤖' : '📱 ';
const icon = isRoot ? '🤖' : '🧩 ';
const cls = isRoot ? 'tree-main' : 'tree-child';
const cls = isRoot ? 'tree-main' : 'tree-child';
h += '<div class="' + cls + '">';
h += '<div class="' + cls + '">';
h += '<div class="tree-title">' + icon + ' ' + esc(a.name || a.id);
h += '<div class="tree-title">' + icon + ' ' + esc(a.name || a.id);
if (isRoot ) h += ' <span class="badge main">' + (a.id === 'main' ? t('agents.main') : 'Bot') + '</span>';
if (a.id === 'main' ) h += ' <span class="badge main">' + t('agents.main') + '</span>';
if (a.groupId) h += ' <span class="badge ok">' + esc(a.groupId) + '</span>';
h += '</div>';
h += '</div>';
h += '<div class="tree-meta">🧠 ' + esc(a.effectiveModel) + '</div>';
h += '<div class="tree-meta">🧠 ' + esc(a.effectiveModel) + '</div>';
if (a.workspace) h += '<div class="tree-meta">📁 ' + esc(a.workspace) + '</div>';
if (a.workspace) h += '<div class="tree-meta">📁 ' + esc(a.workspace) + '</div>';
h += bindingsLine(a);
h += '<div class="tree-actions">';
h += '<div class="tree-actions">';
h += '<select class="inline-sel" id="msel-' + a.id + '">' + buildModelOpts(a.effectiveModel !== t('agents.noModel') ? a.effectiveModel : '__default__') + '</select>';
h += '<select class="inline-sel" id="msel-' + a.id + '">' + buildModelOpts(a.effectiveModel !== t('agents.noModel') ? a.effectiveModel : '__default__') + '</select>';
h += '<button class="btn-secondary" data-action="saveModel" data-id="' + esc(a.id) + '">' + t('agents.saveModel') + '</button>';
h += '<button class="btn-secondary" data-action="saveModel" data-id="' + esc(a.id) + '">' + t('agents.saveModel') + '</button>';
@@ -2938,35 +3236,27 @@ function renderAgents() {
}
}
let html = '<div class="agents-roots">';
let html = '<div class="agents-roots">';
// Render each root with its children, side by side
roots.forEach(root => {
roots.forEach(root => {
const children = subs ByRoot[root.id] || [];
const children = children ByRoot[root.id] || [];
html += '<div class="agent-tree-root">';
html += '<div class="agent-tree-root">';
html += agentCard(root, true);
html += agentCard(root, true);
if (children.length) {
if (children.length) {
const treeId = 'tree-' + root.id;
const treeId = 'tree-' + root.id;
html += '<div class="tree-children-wrap">';
html += '<div class="tree-children-wrap">';
html += '<button class="tree-toggle" onclick="toggleTree( \\ ' ' + treeId + '\\ ',this) " title="Expand / Collapse">− </button>';
html += '<button class="tree-toggle" data-tree=" ' + treeId + '" title="Expand / Collapse">− </button>';
html += '<div class="tree-children" id="' + treeId + '">';
html += '<div class="tree-children" id="' + treeId + '">';
children.forEach(c => { html += agentCard(c, false); });
children.forEach(c => { html += agentCard(c, false); });
html += '</div></div>';
html += '</div></div>';
}
}
html += '</div>';
html += '</div>';
});
});
// Orphan subs (no matching root — edge case)
orphanSubs.forEach(a => {
html += '<div class="agent-tree-root">';
html += agentCard(a, false);
html += '</div>';
});
html += '</div>';
html += '</div>';
el.innerHTML = html;
el.innerHTML = html;
// Event delegation for agent tree buttons
el.onclick = function(ev) {
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]');
const btn = ev.target.closest('[data-action]');
if (!btn) return;
if (!btn) return;
const action = btn.dataset.action;
const action = btn.dataset.action;
@@ -4105,6 +4395,21 @@ function assertBrowserScriptSyntax(name, scriptText) {
) ;
) ;
}
}
}
}
function parseDiscordLinkOrId ( input ) {
const raw = ( input || '' ) . trim ( ) ;
if ( ! raw ) return null ;
// URL form: https://discord.com/channels/<guildId>/<channelId>
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:<id>
const m2 = raw . match ( /^channel:(\d+)$/i ) ;
if ( m2 ) return { guildId : '' , channelId : m2 [ 1 ] } ;
return null ;
}
assertBrowserScriptSyntax ( 'main-html-script' , MAIN _HTML _SCRIPT ) ;
assertBrowserScriptSyntax ( 'main-html-script' , MAIN _HTML _SCRIPT ) ;
// ── HTTP 服务器 ───────────────────────────────────────────────
// ── HTTP 服务器 ───────────────────────────────────────────────