670 lines
27 KiB
JavaScript
670 lines
27 KiB
JavaScript
/**
|
||
* AgentHub 接入网关 — DeepSeek Harness Host 半(静态持久插件)
|
||
*
|
||
* 作用:把当前 DSH 实例变成一个 **可被 AgentHub 纳管的 Agent**。插件常驻一条出站
|
||
* WebSocket,nanobot 渠道 / connector 桥接进程用的是同一套 Frame 协议,所以 hub 控制台
|
||
* 里这个 Agent 和别的 Agent 长得一模一样:能派活、能看到 delta/reasoning/tool 事件。
|
||
*
|
||
* 映射关系(hub ↔ DSH):
|
||
* task.run → ctx.sessionController.create(会话) + prompt(内容)
|
||
* agent/assistant-stream → agent.event{type: delta|reasoning}
|
||
* session/event tool/call|tool/result → agent.event{type: tool}
|
||
* session/event turn/end → res{ok,text}(turn/end 是这一轮的权威终点)
|
||
* task.cancel → ctx.sessionController.cancel(会话)
|
||
*
|
||
* 一个 hub session_key = 一个 DSH 会话(sessionId 由 key 哈希成稳定 UUID),
|
||
* 所以 hub 上同一段对话的上下文能跨进程重启续上:sessionController.create 会
|
||
* 「有就认领、没有就新建」,并且顺手把这个会话的 agent preset 与模型选择装好
|
||
* ——这正是 WebUI 走的同一条路(少了这一步,DSH 的系统提示词里 {{model}} 变量
|
||
* 没人填,组装阶段就会直接报错)。
|
||
*
|
||
* 挂载:~/.dsh/profiles/web/cordis.patch.yml 的 insert 行 + profile package.json 的 link 依赖,
|
||
* 详细步骤见本包 README.md。
|
||
*/
|
||
|
||
import { createHash, randomUUID } from 'node:crypto'
|
||
import fs from 'node:fs'
|
||
import os from 'node:os'
|
||
import path from 'node:path'
|
||
|
||
import { AgentHubGateway, readLegacyIdentity, resolveSettings } from './gateway.js'
|
||
|
||
const PLUGIN = '@nex/dsh-agenthub'
|
||
|
||
/**
|
||
* 一个进程只保留一份网关。
|
||
*
|
||
* DSH 的 live patch 热重载会把同一个 entry 应用两遍(实测:每存一次 cordis.patch.yml,
|
||
* 插件就起两个实例、各拨一条 hub socket)。多出来的实例会和当前实例抢同一个 hub
|
||
* channel:被取代的那份还挂着通道时,派进来的任务会落到一个已经 dispose 的 context 上
|
||
* (报 `cannot get required service "agents" in inactive context`)。
|
||
* 所以新实例上手第一件事是把上一份停掉,并把自己登记为唯一在册的那份。
|
||
*/
|
||
const LIVE = { gateway: null }
|
||
|
||
export const inject = ['agents']
|
||
|
||
/**
|
||
* 面板设置(hub 地址 / 名字)落在一个插件自己的配置文件里。
|
||
*
|
||
* 只放"连到哪、叫什么"这类配置,**不放凭证**(agent_token 只在内存,面板填完不落盘)——
|
||
* 这个文件是全局的、不分 profile,写进去的东西会被下一个 profile 当成自己的身份。
|
||
* 不写进 cordis.patch.yml 是因为那份文件归 dsh 的 loader 管,插件不该去改它;
|
||
* 这两个值也可以直接写在插件 config 里,面板上的值优先。
|
||
*/
|
||
function panelPath() {
|
||
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
||
return path.join(home, 'agenthub.json')
|
||
}
|
||
|
||
function loadPanel() {
|
||
try {
|
||
const data = JSON.parse(fs.readFileSync(panelPath(), 'utf8'))
|
||
const out = {}
|
||
for (const key of ['server', 'name']) {
|
||
if (typeof data[key] === 'string' && data[key]) out[key] = data[key]
|
||
}
|
||
if (out.server) out.hubUrl = out.server
|
||
return out
|
||
} catch {
|
||
return {}
|
||
}
|
||
}
|
||
|
||
function savePanel(values) {
|
||
const file = panelPath()
|
||
fs.mkdirSync(path.dirname(file), { recursive: true })
|
||
fs.writeFileSync(file, JSON.stringify(values, null, 2) + '\n', { mode: 0o600 })
|
||
try {
|
||
fs.chmodSync(file, 0o600)
|
||
} catch {
|
||
/* best effort */
|
||
}
|
||
}
|
||
|
||
export function apply(ctx, config = {}) {
|
||
const settings = resolveSettings(config || {})
|
||
// 面板填过就以面板为准(它是操作员的显式选择),没填过才用插件 config / env。
|
||
// 例外:config 里写了凭证(刚从控制台粘来的 agentToken)时面板让位——
|
||
// 那个文件是全局的(~/.dsh/agenthub.json,不分 profile),上一次连别的 hub 留下的
|
||
// server 会把刚签发的凭证送去敲上一个 hub 的门,于是永远注册不上来。
|
||
const anchored = Boolean((config || {}).agentToken)
|
||
if (anchored) {
|
||
const panel = loadPanel()
|
||
if (panel.hubUrl && panel.hubUrl !== settings.hubUrl) {
|
||
console.warn(
|
||
'[agenthub] 插件 config 里有身份,忽略面板里那份旧地址(' +
|
||
panel.hubUrl +
|
||
' → ' +
|
||
settings.hubUrl +
|
||
');要换 hub 就先清掉 config 里的凭证',
|
||
)
|
||
}
|
||
} else {
|
||
Object.assign(settings, loadPanel())
|
||
}
|
||
/** hub session_key -> { agent } */
|
||
const sessions = new Map()
|
||
/** dsh sessionId -> 待结算的轮次队列(队首就是正在跑的那一轮) */
|
||
const queues = new Map()
|
||
const log = (message) => console.log('[' + PLUGIN + '] ' + message)
|
||
// 入场令牌(enrollment / enr_…)和 Hub ID(hubId / hub_…)两套机制已经取消,
|
||
// 接入只剩「hub 地址 + ag_ 凭证」。老配置里还留着就明确说一声,别默默忽略。
|
||
for (const gone of ['enrollment', 'hubId', 'takeOver']) {
|
||
if ((config || {})[gone]) {
|
||
log('已取消的插件配置 ' + gone + ':入场令牌 / Hub ID 都不再有,请删掉这行,' +
|
||
'把这台 Agent 的凭证(ag_…,控制台「接入」页签发)写在 agentToken 里')
|
||
}
|
||
}
|
||
|
||
if (LIVE.gateway) {
|
||
log('已有网关在跑(热重载):停掉上一份,只留最新这一份')
|
||
void LIVE.gateway.stop()
|
||
}
|
||
/** 服务访问:属性与 get() 两条路都试,热加载/不同组合下都拿得到 Agent 注册表。 */
|
||
const agentRegistry = () => (typeof ctx.get === 'function' ? ctx.get('agents') : undefined) || ctx.agents
|
||
/** WebUI 用的那套会话/模型策略服务;没装(例如别的 profile)时才走回退路径。 */
|
||
const controller = () => (typeof ctx.get === 'function' ? ctx.get('sessionController') : ctx.sessionController)
|
||
const defaultModel = () => (typeof ctx.get === 'function' ? ctx.get('agentDefaultModel') : ctx.agentDefaultModel)
|
||
|
||
// ---------------------------------------------------------------- 会话
|
||
/** 稳定但不冲突的 sessionId:同一个 hub session_key 永远落到同一个 DSH 会话。 */
|
||
function sessionIdFor(sessionKey) {
|
||
const digest = createHash('sha1').update('agenthub:' + sessionKey).digest('hex')
|
||
return (
|
||
digest.slice(0, 8) + '-' + digest.slice(8, 12) + '-' + digest.slice(12, 16) + '-' + digest.slice(16, 20) + '-' + digest.slice(20, 32)
|
||
)
|
||
}
|
||
|
||
async function ensureAgent(sessionKey) {
|
||
const cached = sessions.get(sessionKey)
|
||
if (cached && agentRegistry().get(cached.agent.id) === cached.agent) return cached.agent
|
||
const sessionId = sessionIdFor(sessionKey)
|
||
const agent = (await resolveAgent(sessionId, sessionKey)) || agentRegistry().get(sessionId)
|
||
if (!agent) throw new Error('无法为 hub session "' + sessionKey + '" 打开 DSH 会话 ' + sessionId)
|
||
sessions.set(sessionKey, { agent })
|
||
return agent
|
||
}
|
||
|
||
/**
|
||
* 打开(或认领)一个 DSH 会话。
|
||
*
|
||
* 首选 sessionController:它就是 WebUI 的入口——create 会走 ensureSession,
|
||
* 把 agent preset 与该会话的模型选择一起装好,冷会话自动 resume,多人同一
|
||
* sessionId 并发时还会去重。没有它时退回 agents.create/resume,并自己把
|
||
* 模型选择补上,保证系统提示词里的 {{provider}}/{{model}} 有值。
|
||
*/
|
||
async function resolveAgent(sessionId, sessionKey) {
|
||
const sessionsService = controller()
|
||
if (sessionsService && typeof sessionsService.create === 'function') {
|
||
await sessionsService.create({ sessionId, cwd: settings.cwd })
|
||
const agent = agentRegistry().get(sessionId)
|
||
if (agent) {
|
||
log('session ' + sessionId + ' ready for hub session "' + sessionKey + '"')
|
||
return agent
|
||
}
|
||
}
|
||
const selection = configuredSelection()
|
||
let handle
|
||
try {
|
||
handle = await agentRegistry().resume({
|
||
resumeSessionId: sessionId,
|
||
...(selection ? { agentOptions: { provider: selection.provider, model: selection.model } } : {}),
|
||
setup: (agentCtx) => installSelection(agentCtx, selection),
|
||
})
|
||
log('resumed session ' + sessionId + ' for hub session "' + sessionKey + '"')
|
||
} catch {
|
||
handle = await agentRegistry().create({
|
||
sessionId,
|
||
meta: { cwd: settings.cwd },
|
||
...(selection ? { agentOptions: { provider: selection.provider, model: selection.model } } : {}),
|
||
setup: (agentCtx) => installSelection(agentCtx, selection),
|
||
})
|
||
log('created session ' + sessionId + ' for hub session "' + sessionKey + '"')
|
||
}
|
||
return handle.agent
|
||
}
|
||
|
||
/** 本实例"正在用"的模型:给面板与 hub 自省上报用(不是注册字段)。 */
|
||
function currentSelection() {
|
||
const service = defaultModel()
|
||
if (service && typeof service.currentSelection === 'function') {
|
||
try {
|
||
const selection = service.currentSelection()
|
||
if (selection && selection.provider && selection.model) return selection
|
||
} catch {
|
||
/* 没配默认模型 */
|
||
}
|
||
}
|
||
if (settings.model) return { provider: settings.provider, model: settings.model }
|
||
return undefined
|
||
}
|
||
|
||
/** 回退路径(没有 sessionController 时)要用的模型:插件 config > harness 默认模型。 */
|
||
function configuredSelection() {
|
||
if (settings.provider && settings.model) return { provider: settings.provider, model: settings.model }
|
||
return currentSelection()
|
||
}
|
||
|
||
/**
|
||
* 没有 sessionController 时才需要:补上 {{provider}}/{{model}} 变量与请求路由。
|
||
* 与 dsh-agent 的 installModelSelection 做同一件事(两个 waterfall 监听)。
|
||
*/
|
||
function installSelection(agentCtx, selection) {
|
||
if (!selection) return
|
||
agentCtx.on('system-prompt/assemble', async (_assembly, _context, next) => {
|
||
const assembled = await next()
|
||
return {
|
||
...assembled,
|
||
variables: { ...assembled.variables, provider: selection.provider, model: selection.model },
|
||
}
|
||
})
|
||
agentCtx.on('agent/request', async (_payload, next) => {
|
||
const resolved = await next()
|
||
return { ...resolved, provider: selection.provider, model: selection.model }
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 把一条 hub 任务交给会话:优先 sessionController.prompt(WebUI 同路)。
|
||
* 公开的 prompt(request, signal) 会先 signal.throwIfAborted(),所以必须给信号。
|
||
*/
|
||
async function submitPrompt(agent, sessionId, text, signal) {
|
||
const sessionsService = controller()
|
||
if (sessionsService && typeof sessionsService.prompt === 'function') {
|
||
try {
|
||
await sessionsService.prompt(
|
||
{
|
||
requestId: randomUUID(),
|
||
sessionId,
|
||
mode: 'queue',
|
||
content: [{ type: 'text', text }],
|
||
},
|
||
signal,
|
||
)
|
||
} catch (error) {
|
||
log('prompt rejected: ' + String((error && error.message) || error))
|
||
throw error
|
||
}
|
||
return
|
||
}
|
||
agent.followup(userMessage(text))
|
||
}
|
||
|
||
function cancelTurn(agent, sessionId) {
|
||
const sessionsService = controller()
|
||
if (sessionsService && typeof sessionsService.cancel === 'function') {
|
||
sessionsService.cancel({ sessionId })
|
||
return
|
||
}
|
||
agent.cancel({ kind: 'user' })
|
||
}
|
||
|
||
function userMessage(text) {
|
||
return {
|
||
id: randomUUID(),
|
||
role: 'user',
|
||
content: [{ type: 'text', text }],
|
||
source: { kind: 'user' },
|
||
}
|
||
}
|
||
|
||
const head = (sessionId) => {
|
||
const queue = queues.get(sessionId)
|
||
return queue && queue.length ? queue[0] : undefined
|
||
}
|
||
|
||
function dequeue(sessionId) {
|
||
const queue = queues.get(sessionId)
|
||
if (!queue) return undefined
|
||
const entry = queue.shift()
|
||
if (!queue.length) queues.delete(sessionId)
|
||
if (entry && entry.timer) clearTimeout(entry.timer)
|
||
return entry
|
||
}
|
||
|
||
/** Drop one specific entry — used when a *queued* (not yet running) turn is cancelled. */
|
||
function remove(sessionId, entry) {
|
||
const queue = queues.get(sessionId)
|
||
if (!queue) return false
|
||
const index = queue.indexOf(entry)
|
||
if (index < 0) return false
|
||
queue.splice(index, 1)
|
||
if (!queue.length) queues.delete(sessionId)
|
||
if (entry.timer) clearTimeout(entry.timer)
|
||
return true
|
||
}
|
||
|
||
// ------------------------------------------------------------ 事件接线
|
||
const offStream = ctx.on('agent/assistant-stream', ({ agent, frame }) => {
|
||
const entry = head(agent.id)
|
||
if (!entry || frame.type !== 'chunk') return
|
||
const chunk = frame.chunk || {}
|
||
if (chunk.type === 'text-delta' && chunk.text) entry.emit('delta', { text: chunk.text })
|
||
else if (chunk.type === 'reasoning-delta' && chunk.text) entry.emit('reasoning', { text: chunk.text })
|
||
else if (chunk.type === 'tool-call-delta' && chunk.name) entry.emit('tool', { name: chunk.name })
|
||
})
|
||
|
||
const offSession = ctx.on('session/event', (session, event) => {
|
||
const entry = head(session.id)
|
||
if (!entry) return
|
||
const data = event.data || {}
|
||
switch (event.type) {
|
||
case 'tool/call':
|
||
entry.emit('tool', { name: data.name, call_id: data.callId, input: safeJson(data.arguments) })
|
||
break
|
||
case 'tool/result':
|
||
entry.emit('tool', { name: 'result', call_id: data.message && data.message.source && data.message.source.callId, is_error: Boolean(data.error) })
|
||
break
|
||
case 'assistant/message':
|
||
entry.answer = textOf(data.message) || entry.answer
|
||
if (data.usage) entry.usage = data.usage
|
||
break
|
||
case 'turn/end':
|
||
settle(session.id, entry, data.reason)
|
||
break
|
||
default:
|
||
break
|
||
}
|
||
})
|
||
|
||
const offError = ctx.on('agent/error', ({ agent, error }) => {
|
||
const entry = head(agent.id)
|
||
if (!entry) return
|
||
fail(agent.id, entry, error)
|
||
})
|
||
|
||
const offDisposed = ctx.on('agent/disposed', ({ agent }) => {
|
||
for (const [key, value] of sessions) if (value.agent.id === agent.id) sessions.delete(key)
|
||
for (let entry = dequeue(agent.id); entry; entry = dequeue(agent.id)) {
|
||
entry.reject(new Error('agent disposed while the task was running'))
|
||
}
|
||
})
|
||
|
||
function settle(sessionId, entry, reason) {
|
||
dequeue(sessionId)
|
||
const kind = (reason && reason.kind) || 'completed'
|
||
if (kind === 'completed') {
|
||
entry.resolve(entry.answer || '')
|
||
return
|
||
}
|
||
if (kind === 'aborted' && entry.cancelled) {
|
||
const abort = new Error('cancelled by hub')
|
||
abort.name = 'AbortError'
|
||
entry.reject(abort)
|
||
return
|
||
}
|
||
entry.reject(new Error('turn ended: ' + kind + (reason && reason.reason ? ' (' + describeCause(reason.reason) + ')' : '')))
|
||
}
|
||
|
||
function fail(sessionId, entry, error) {
|
||
dequeue(sessionId)
|
||
entry.reject(error instanceof Error ? error : new Error(String((error && error.message) || error)))
|
||
}
|
||
|
||
// ------------------------------------------------------------ 任务执行
|
||
async function onTask(payload, emit, control) {
|
||
if (!gateway || LIVE.gateway !== gateway) {
|
||
// 被取代的实例不再吃活:与其让它抛一个谜之 inactive context,不如把错因说清楚。
|
||
throw new Error('这个网关实例已被热重载取代,请把任务重派;若持续出现,重启 dsh web')
|
||
}
|
||
const prompt = String(payload.prompt || '').trim()
|
||
const sessionKey = String(payload.session_key || payload.task_id || 'default')
|
||
if (!prompt) throw new Error('task.run without a prompt')
|
||
const agent = await ensureAgent(sessionKey)
|
||
const queued = (queues.get(agent.id) || []).length
|
||
await emit('status', {
|
||
message: queued ? 'queued behind ' + queued + ' running turn(s)' : 'running in deepseek-harness',
|
||
session_id: agent.id,
|
||
model: modelOf(agent),
|
||
})
|
||
|
||
// 每轮一个信号:它同时是「投产时给 controller.prompt 的取消信号」和「被取消的标记」。
|
||
const abort = new AbortController()
|
||
const promise = new Promise((resolve, reject) => {
|
||
const entry = {
|
||
agent,
|
||
resolve,
|
||
reject,
|
||
emit: (type, extra = {}) => void emit(type, extra),
|
||
answer: '',
|
||
usage: null,
|
||
cancelled: false,
|
||
abort,
|
||
timer: null,
|
||
}
|
||
entry.timer = setTimeout(() => {
|
||
entry.abort.abort()
|
||
fail(agent.id, entry, new Error('deepseek-harness turn timed out after ' + settings.timeoutS + 's'))
|
||
try {
|
||
cancelTurn(agent, agent.id)
|
||
} catch {
|
||
/* already idle */
|
||
}
|
||
}, settings.timeoutS * 1000)
|
||
const queue = queues.get(agent.id) || []
|
||
queue.push(entry)
|
||
queues.set(agent.id, queue)
|
||
control.setCancel(() => {
|
||
entry.cancelled = true
|
||
entry.abort.abort()
|
||
// 正在跑的是队首:打断它。还没轮到的直接撤下来 —— 但别动队首那条。
|
||
if (head(agent.id) === entry) {
|
||
cancelTurn(agent, agent.id)
|
||
return
|
||
}
|
||
if (remove(agent.id, entry)) {
|
||
entry.reject(Object.assign(new Error('cancelled by hub'), { name: 'AbortError' }))
|
||
}
|
||
})
|
||
})
|
||
// DSH 自己的 inbox 就会排队:连着派两个任务,第二个会在这一轮结束后自动开始。
|
||
await submitPrompt(agent, agent.id, prompt, abort.signal)
|
||
return promise
|
||
}
|
||
|
||
// ------------------------------------------------------------- Gateway
|
||
/** 本进程当前在册的那一份网关(面板"上线/下线"会换掉它)。 */
|
||
let gateway = null
|
||
|
||
const handlers = {
|
||
onTask,
|
||
// 任何一项自述失败都不该让整段能力描述消失——把错因带出去,控制台一眼能看见。
|
||
describe: () => {
|
||
const capabilities = {
|
||
runtime: 'deepseek-harness',
|
||
streaming: true,
|
||
reasoning: true,
|
||
tools: true,
|
||
workspace: settings.cwd,
|
||
}
|
||
// 自省上报:hub 显示的模型只来自这里,不来自任何渠道/插件配置。
|
||
const selection = currentSelection()
|
||
if (selection && selection.model) capabilities.model = selection.model
|
||
try {
|
||
capabilities.sessions = agentRegistry().list().length
|
||
} catch (error) {
|
||
capabilities.describe_error = 'agents.list failed: ' + String((error && error.message) || error)
|
||
}
|
||
return capabilities
|
||
},
|
||
}
|
||
|
||
/**
|
||
* 开一条网关(先停上一份):面板点「上线」、插件加载时自动接入,都走这里。
|
||
*
|
||
* `next` 里给的是连接与身份(hub 地址 + agentToken);
|
||
* 换 server 等于换身份,旧凭证必须清掉,否则会拿着上一个 hub 的 token 去敲门。
|
||
*/
|
||
function spin(next = {}) {
|
||
if (LIVE.gateway) {
|
||
void LIVE.gateway.stop()
|
||
LIVE.gateway = null
|
||
}
|
||
// 换 hub = 换身份:上一个 hub 签的凭证不能拿去敲这扇门。先清旧的、再覆盖新的,
|
||
// 顺序反了就会把 next 里刚填的那份一起抹掉(真实踩过:面板填完点上线,
|
||
// 因为顺手补了端口导致地址变了,于是报「没有可用身份」)。
|
||
if (next.hubUrl && next.hubUrl !== settings.hubUrl) {
|
||
settings.agentId = ''
|
||
settings.agentToken = ''
|
||
}
|
||
Object.assign(settings, next)
|
||
gateway = new AgentHubGateway(settings, handlers)
|
||
// 面板这次填的凭证不写盘,来源如实标出来,别让面板显示成"来自插件 config"。
|
||
if (next.agentToken) gateway.identitySource = 'panel'
|
||
LIVE.gateway = gateway
|
||
gateway.loadIdentity()
|
||
log('dialing ' + settings.hubUrl + ' as "' + settings.name + '"')
|
||
void gateway.start()
|
||
return gateway
|
||
}
|
||
|
||
/** 下线:停掉网关,但保留配置(下次「上线」用同一套地址与 hub id)。 */
|
||
function leave(reason = 'panel') {
|
||
if (!LIVE.gateway) return false
|
||
void LIVE.gateway.stop()
|
||
LIVE.gateway = null
|
||
gateway = null
|
||
log('left the hub (' + reason + ')')
|
||
return true
|
||
}
|
||
|
||
const snapshot = () => ({
|
||
...(gateway ? gateway.snapshot() : { hub: settings.hubUrl, connected: false, tasks: [] }),
|
||
plugin: PLUGIN,
|
||
server: settings.hubUrl,
|
||
name: settings.name,
|
||
joined: Boolean(gateway),
|
||
hasCredential: Boolean(settings.agentToken),
|
||
})
|
||
|
||
if (settings.autoConnect) {
|
||
// 迁移兜底要在"决定接不接入"之前跑:老实例的身份可能只存在于旧状态文件里。
|
||
if (readLegacyIdentity(settings)) settings.identitySource = 'legacy-file'
|
||
// 有凭证就接。
|
||
if (settings.agentToken) {
|
||
spin()
|
||
} else {
|
||
log('未配置接入身份:插件已加载但不会接入 —— 在 profile 的 cordis.patch.yml 里补一行 `agentToken: ag_…`(控制台「接入」页签发),或按面板里的提示填一次凭证')
|
||
}
|
||
}
|
||
|
||
// 可选的 DSH 能力:模型工具 + 面板 RPC + 提示词段落。缺哪个服务就跳过哪一段。
|
||
ctx.inject(['tools'], (toolsCtx) => {
|
||
try {
|
||
toolsCtx.tools.register({
|
||
name: 'agenthub_status',
|
||
description: 'AgentHub 接入状态:本 DSH 实例在 hub 上的身份、连接状态、最近被派的任务。用于排查"面板上看不到我 / 收不到任务"。',
|
||
parameters: { type: 'object', additionalProperties: false, properties: {} },
|
||
output: {
|
||
schema: { type: 'object', additionalProperties: true },
|
||
render(_args, value) {
|
||
return [{ type: 'text', text: JSON.stringify(value, null, 1) }]
|
||
},
|
||
},
|
||
async execute() {
|
||
return snapshot()
|
||
},
|
||
})
|
||
} catch (error) {
|
||
log('注册 agenthub_status 工具失败:' + String((error && error.message) || error))
|
||
}
|
||
})
|
||
|
||
// 面板数据走 /api 共享通道上的精确 Fetch 路由,而不是 connection.rpc.handle('/agenthub'):
|
||
// 后者在注册时会去访问调用方 context 的 webServer,dsh 0.1.5 里即使从
|
||
// ctx.inject(['connection','webServer'], …) 的子 context 调用也仍抛
|
||
// `cannot get property "webServer" without inject`;而 /api 上的精确路由不需要
|
||
// webServer,且天生在 Host/Origin + 浏览器鉴权围栏之内——dsh 自己的
|
||
// client-file-upload / api-session-controller 也是这么挂的。
|
||
ctx.inject(['connection'], (rpcCtx) => {
|
||
try {
|
||
const respond = (value) => Response.json({ ok: true, value })
|
||
const fail = (error) =>
|
||
Response.json({ ok: false, error: { code: 'internal', message: String((error && error.message) || error), details: {} } })
|
||
rpcCtx.connection.fetch.register({
|
||
path: '/api/agenthub/status',
|
||
methods: ['POST'],
|
||
requestBody: 'buffered',
|
||
async fetch(request) {
|
||
// 面板用一个端点做三件事:看状态、上线(地址+端口+Agent 凭证)、下线。
|
||
let body = {}
|
||
try {
|
||
body = (await request.json()) || {}
|
||
} catch {
|
||
body = {}
|
||
}
|
||
const action = String(body.action || 'status')
|
||
try {
|
||
if (action === 'connect') {
|
||
const raw = String(body.server || '').trim()
|
||
if (!raw) throw new Error('请填 hub 服务器地址(例如 http://127.0.0.1)')
|
||
const port = String(body.port ?? '').trim()
|
||
const server = /^https?:\/\/[^/]+:\d+$/.test(raw) || !port ? raw : `${raw.replace(/\/+$/, '')}:${port}`
|
||
// 只要这一份凭证:地址是地址、身份是身份,和桥接进程的 --token 一模一样。
|
||
const token = String(body.agentToken || '').trim()
|
||
if (!token) {
|
||
throw new Error('请填这台 Agent 的凭证(ag_…)—— 控制台「接入」页签发的那个')
|
||
}
|
||
if (!/^ag_/.test(token)) {
|
||
if (/^ah_/.test(token)) {
|
||
throw new Error(
|
||
'这是 hub 的 API Key(ah_…),不是 Agent 凭证 —— 它只有控制台和管理 API 用;' +
|
||
'Agent 侧要的是「接入」页签发的 ag_…',
|
||
)
|
||
}
|
||
if (/^enr_|^hub_/.test(token)) {
|
||
throw new Error(
|
||
'这是已取消的旧机制发的东西(enr_… 入场令牌 / hub_… Hub ID)—— 接入现在只有' +
|
||
'「hub 地址 + ag_ 凭证」一条路,请回控制台「接入」页为这台 Agent 签发 ag_…',
|
||
)
|
||
}
|
||
throw new Error('凭证应以 ag_ 开头(控制台「接入」页签发)')
|
||
}
|
||
spin({
|
||
hubUrl: server,
|
||
agentToken: token,
|
||
name: String(body.name || '').trim() || settings.name,
|
||
agentId: '',
|
||
})
|
||
// 等一次心跳往返落地(最多 3 秒):面板一回来就知道连没连上、为什么没连上。
|
||
for (let i = 0; i < 30 && !(gateway && (gateway.connected || gateway.lastError)); i += 1) {
|
||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||
}
|
||
// 凭证不落盘(这个文件不分 profile),下次重启请写在 profile 的 config 里。
|
||
await savePanel({ server: settings.hubUrl, name: settings.name })
|
||
return respond(snapshot())
|
||
}
|
||
if (action === 'leave') {
|
||
leave('panel')
|
||
return respond(snapshot())
|
||
}
|
||
return respond(snapshot())
|
||
} catch (error) {
|
||
return fail(error)
|
||
}
|
||
},
|
||
})
|
||
log('面板 RPC /api/agenthub/status 已挂载')
|
||
} catch (error) {
|
||
log('注册面板 RPC /api/agenthub/status 失败:' + String((error && error.message) || error))
|
||
}
|
||
})
|
||
|
||
ctx.effect(() => () => {
|
||
// 卸载路径必须「永不抛」:cordis 会把 disposer 里的异常当成 load failure。
|
||
// 所以先把在跑的轮次收起来,再用一个宏任务把它们判失败——那时卸载链已经走完。
|
||
const abandoned = []
|
||
for (const queue of queues.values()) {
|
||
for (const entry of queue) {
|
||
if (entry.timer) clearTimeout(entry.timer)
|
||
entry.abort.abort()
|
||
abandoned.push(entry)
|
||
}
|
||
}
|
||
queues.clear()
|
||
for (const off of [offStream, offSession, offError, offDisposed]) {
|
||
try {
|
||
off()
|
||
} catch {
|
||
/* 已经解绑过了 */
|
||
}
|
||
}
|
||
if (gateway) void gateway.stop()
|
||
if (gateway && LIVE.gateway === gateway) LIVE.gateway = null
|
||
if (abandoned.length) {
|
||
setTimeout(() => {
|
||
for (const entry of abandoned) entry.reject(new Error('plugin unloaded'))
|
||
}, 0)
|
||
}
|
||
})
|
||
}
|
||
|
||
function modelOf(agent) {
|
||
const options = agent && agent.options
|
||
if (!options) return ''
|
||
return String(options.model || (options.selection && options.selection.model) || '')
|
||
}
|
||
|
||
function describeCause(cause) {
|
||
if (!cause) return ''
|
||
return String(cause.kind || cause.reason || cause)
|
||
}
|
||
|
||
function textOf(message) {
|
||
const blocks = (message && message.content) || []
|
||
return blocks
|
||
.filter((block) => block && block.type === 'text' && block.text)
|
||
.map((block) => block.text)
|
||
.join('')
|
||
}
|
||
|
||
function safeJson(value) {
|
||
if (typeof value !== 'string') return value
|
||
try {
|
||
return JSON.parse(value)
|
||
} catch {
|
||
return value.slice(0, 500)
|
||
}
|
||
}
|