542 lines
19 KiB
JavaScript
542 lines
19 KiB
JavaScript
/**
|
||
* AgentHub Gateway 客户端(Node 版,零依赖)
|
||
*
|
||
* 与 deploy/nanobot-gateway/channel/agenthub/agenthub_client.py 说的是同一套 Frame 协议:
|
||
* 1) WS <hub>/api/v1/gateway/ws?agent_token=… —— 接入只有这一条路;
|
||
* 2) hub 下发 req 帧:task.run / task.cancel / agent.ping / agent.describe;
|
||
* Agent 回 res/err(reply_to 对上 id),过程事件用 agent.event 帧往上推。
|
||
*
|
||
* 接入要填的就两样,跟桥接进程、nanobot 渠道一模一样:
|
||
* `server` —— hub 的地址(IP + 端口)
|
||
* `agentToken` —— hub 给这台 Agent 签发的凭证(ag_…),控制台「接入」页
|
||
*
|
||
* 没有 Hub ID,也没有入场令牌,连 agentId 都不用填:凭证本身就是身份,
|
||
* 连上之后 hub 在 `hub.hello` 里把自己的 id 告诉 Agent。
|
||
* 旧的 ~/.agenthub/agent-<name>.json 只读一次做迁移兜底,不再写入。
|
||
*/
|
||
|
||
import { randomBytes, randomUUID } from 'node:crypto'
|
||
import fs from 'node:fs'
|
||
import os from 'node:os'
|
||
import path from 'node:path'
|
||
|
||
export const PROTOCOL_VERSION = 1
|
||
|
||
const DEFAULT_HEADERS = { 'content-type': 'application/json' }
|
||
|
||
/** hub 侧 Frame.to_dict() 的形状,字段一个不多一个不少。 */
|
||
function frame(kind, fields = {}) {
|
||
const out = {
|
||
v: PROTOCOL_VERSION,
|
||
id: 'frm_' + randomBytes(8).toString('hex'),
|
||
ts: Date.now() / 1000,
|
||
type: fields.type || 'event',
|
||
kind,
|
||
topic: fields.topic || 'hub.events',
|
||
actor: 'agent',
|
||
}
|
||
if (fields.payload) out.payload = fields.payload
|
||
for (const key of ['reply_to', 'agent_id', 'task_id', 'run_id']) {
|
||
if (fields[key]) out[key] = fields[key]
|
||
}
|
||
return out
|
||
}
|
||
|
||
function hostname() {
|
||
try {
|
||
return os.hostname()
|
||
} catch {
|
||
return 'unknown-host'
|
||
}
|
||
}
|
||
|
||
function safeName(value) {
|
||
return String(value || 'agent').replace(/[^A-Za-z0-9_-]/g, '_')
|
||
}
|
||
|
||
export class EnrollError extends Error {}
|
||
|
||
/**
|
||
* Read the pre-0.3 identity file once and fold it into `settings`.
|
||
*
|
||
* Identity is config now, so nothing writes this file any more; it exists only
|
||
* to carry running installs across the upgrade —— and only for someone who has
|
||
* no credential in their config yet. A config credential is the whole identity,
|
||
* so the file's stale ``agent_id`` must never be paired with it (that is two
|
||
* identities wearing one socket, and the hub answers 401).
|
||
*/
|
||
export function readLegacyIdentity(settings, explicitFile = '') {
|
||
if (settings.agentToken) return false // config 里已经有凭证:它就是身份,不用回头读
|
||
if (settings._legacyIdentityRead) return false // once per plugin instance
|
||
settings._legacyIdentityRead = true
|
||
const safe = String(settings.name || 'agent').replace(/[^A-Za-z0-9_-]/g, '_')
|
||
const file =
|
||
explicitFile || settings.statePath || path.join(os.homedir(), '.agenthub', 'agent-' + safe + '.json')
|
||
try {
|
||
const data = JSON.parse(fs.readFileSync(file, 'utf8'))
|
||
if (data.hub && data.hub !== String(settings.hubUrl || '').replace(/\/+$/, '')) return false
|
||
settings.agentId = String(settings.agentId || data.agent_id || '')
|
||
settings.agentToken = String(data.agent_token || '')
|
||
if (!settings.agentId || !settings.agentToken) return false
|
||
console.warn(
|
||
'[agenthub] 身份文件已废弃(' +
|
||
file +
|
||
'):把 agentId/agentToken 写进插件 config 后即可删除它 → ' +
|
||
JSON.stringify({
|
||
server: settings.hubUrl,
|
||
name: settings.name,
|
||
agentId: settings.agentId,
|
||
agentToken: settings.agentToken,
|
||
}),
|
||
)
|
||
return true
|
||
} catch {
|
||
return false
|
||
}
|
||
}
|
||
|
||
export class AgentHubGateway {
|
||
/**
|
||
* @param {object} settings hub 地址 + 凭证(见 resolveSettings)。
|
||
* @param {object} handlers onTask(payload, emit, control) / onCancel(invocationId) / describe()
|
||
*/
|
||
constructor(settings, handlers = {}) {
|
||
this.settings = settings
|
||
this.handlers = handlers
|
||
this.socket = null
|
||
this.connected = false
|
||
this.stopping = false
|
||
this.heartbeatIntervalMs = 15000
|
||
this.startedAt = Date.now()
|
||
this.lastError = ''
|
||
this.lastHelloAt = null
|
||
this.reattached = false
|
||
// 凭证来源:'config'(插件 config)/ 'panel'(面板这次填的)/ 'legacy-file'(老状态文件)
|
||
this.identitySource = settings.agentToken ? 'config' : 'none'
|
||
this.runs = new Map() // invocation_id -> { taskId, cancel }
|
||
this.tasks = [] // 最近的派活记录,给面板看
|
||
this._loop = null
|
||
this._heartbeat = null
|
||
this._backoff = null
|
||
}
|
||
|
||
get base() {
|
||
return String(this.settings.hubUrl || '').replace(/\/+$/, '')
|
||
}
|
||
|
||
get wsUrl() {
|
||
const url = this.base.replace(/^https:\/\//, 'wss://').replace(/^http:\/\//, 'ws://')
|
||
return url + '/api/v1/gateway/ws?agent_token=' + encodeURIComponent(this.settings.agentToken || '')
|
||
}
|
||
|
||
statePath() {
|
||
if (this.settings.statePath) return String(this.settings.statePath).replace(/^~(?=\/)/, os.homedir())
|
||
return path.join(os.homedir(), '.agenthub', 'agent-' + safeName(this.settings.name) + '.json')
|
||
}
|
||
|
||
loadIdentity() {
|
||
// 迁移兜底:老版本把凭证写在 ~/.agenthub/agent-<name>.json 里。读到就用一次,
|
||
// 并打印可以直接粘进 config 的片段 —— 但绝不再写回去(身份即配置)。
|
||
if (readLegacyIdentity(this.settings, this.statePath())) this.identitySource = 'legacy-file'
|
||
}
|
||
|
||
async post(route, payload, token = '', timeoutMs = 30000) {
|
||
const headers = { ...DEFAULT_HEADERS }
|
||
if (token) headers.authorization = 'Bearer ' + token
|
||
const response = await fetch(this.base + route, {
|
||
method: 'POST',
|
||
headers,
|
||
body: JSON.stringify(payload),
|
||
signal: AbortSignal.timeout(timeoutMs),
|
||
})
|
||
const text = await response.text()
|
||
if (!response.ok) {
|
||
const error = new EnrollError(response.status + ': ' + text.slice(0, 300))
|
||
error.status = response.status
|
||
throw error
|
||
}
|
||
return text.trim() ? JSON.parse(text) : {}
|
||
}
|
||
|
||
/**
|
||
* 凭证体检:hub 认不认我们。
|
||
*
|
||
* 返回 true = 认识,继续用这份凭证;
|
||
* 返回 false = 明确拒绝(401/403/409)→ 该去换一份;
|
||
* 直接抛 = 连不上 hub(网络/超时/5xx)→ 退避重试,**别把凭证丢了**。
|
||
*/
|
||
async credentialOk() {
|
||
if (!this.settings.agentToken) return false
|
||
try {
|
||
await this.post('/api/v1/gateway/heartbeat', { status: 'online', active_tasks: this.runs.size }, this.settings.agentToken, 10000)
|
||
return true
|
||
} catch (error) {
|
||
const status = Number(error && error.status)
|
||
if (!status) throw error // 不是 HTTP 拒绝:网络不可达,交给重试
|
||
if (status >= 500) throw error // hub 自己有问题,同样重试
|
||
return false // 401/403/409:凭证被轮换 / 吊销 / 删号
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 决定"我是谁":config(或面板)里那份 ag_… 凭证,没有第二条路。
|
||
*
|
||
* 先探一次心跳而不是直接拨 socket,是为了把话说清楚:401 和 4401 都只说明
|
||
* 「这份凭证 hub 不认」,而人要知道的是去哪儿换一份。hub 连不上抛的是
|
||
* HubUnreachable,不会走到这条报错上来。
|
||
*/
|
||
async ensureIdentity() {
|
||
if (await this.credentialOk()) return
|
||
throw new EnrollError(
|
||
(this.settings.agentToken
|
||
? 'hub 不认 config 里的 agentToken(刚被轮换/吊销,或粘的是别的 hub 签的那份):'
|
||
: '插件 config 里还没有凭证:') +
|
||
'回控制台「接入」页签发一份 ag_…(或 `agenthub agent rotate ' +
|
||
this.settings.name +
|
||
'`),写进 config 的 agentToken —— Agent 侧要的就是地址 + 这一格',
|
||
)
|
||
}
|
||
|
||
/** 常驻循环:凭证体检 → 拨 socket → 断了就退避重连。 */
|
||
start() {
|
||
this.stopping = false
|
||
this._loop = this.runLoop()
|
||
return this._loop
|
||
}
|
||
|
||
async runLoop() {
|
||
this.loadIdentity() // 幂等:老状态文件最多被读一次
|
||
let attempt = 0
|
||
while (!this.stopping) {
|
||
try {
|
||
await this.ensureIdentity()
|
||
if (this.stopping) break
|
||
await this.session()
|
||
attempt = 0
|
||
} catch (error) {
|
||
if (this.stopping) break
|
||
this.lastError = String((error && error.message) || error)
|
||
console.log('[agenthub] 没连上:' + this.lastError)
|
||
}
|
||
if (this.stopping) break
|
||
attempt += 1
|
||
const delay = Math.min(60000, Math.round(1500 ** Math.min(attempt, 6))) + Math.random() * 1000
|
||
await this.backoff(delay)
|
||
}
|
||
}
|
||
|
||
/** 退避等待。stop() 会立刻把它叫醒,避免「已经卸载了还在后台重连」。 */
|
||
backoff(ms) {
|
||
return new Promise((resolve) => {
|
||
this._backoff = setTimeout(() => {
|
||
this._backoff = null
|
||
resolve()
|
||
}, ms)
|
||
})
|
||
}
|
||
|
||
async session() {
|
||
if (typeof WebSocket !== 'function') {
|
||
throw new Error('这个 Node 版本没有全局 WebSocket(需要 Node 22+)')
|
||
}
|
||
const socket = new WebSocket(this.wsUrl)
|
||
this.socket = socket
|
||
await new Promise((resolve, reject) => {
|
||
const onOpen = () => resolve()
|
||
const onError = (event) => reject(new Error('websocket error: ' + String((event && event.message) || 'unknown')))
|
||
socket.addEventListener('open', onOpen, { once: true })
|
||
socket.addEventListener('error', onError, { once: true })
|
||
})
|
||
if (this.stopping) {
|
||
// 拨号的过程中被叫停:立刻收摊,别再把心跳挂上去。
|
||
this.socket = null
|
||
try {
|
||
socket.close()
|
||
} catch {
|
||
/* already closed */
|
||
}
|
||
return
|
||
}
|
||
this.connected = true
|
||
this.lastError = ''
|
||
console.log('[agenthub] 已上线:' + this.wsUrl.replace(/[?].*$/, '?agent_token=…'))
|
||
this._heartbeat = setInterval(async () => {
|
||
this.send(frame('agent.heartbeat', {
|
||
topic: 'agent.' + this.settings.agentId + '.status',
|
||
agent_id: this.settings.agentId,
|
||
payload: {
|
||
status: 'online',
|
||
active_tasks: this.runs.size,
|
||
connector_version: this.settings.clientVersion,
|
||
health: { uptime_s: Math.round((Date.now() - this.startedAt) / 100) / 10, runtime: 'deepseek-harness' },
|
||
// 自省上报:hub 显示的模型/能力只来自这里(插件 config 里没有 model)
|
||
capabilities: await this.capabilities(),
|
||
},
|
||
}))
|
||
this.credentialOk().catch(() => undefined)
|
||
}, this.heartbeatIntervalMs)
|
||
try {
|
||
await new Promise((resolve, reject) => {
|
||
socket.addEventListener('close', () => resolve())
|
||
socket.addEventListener('error', () => resolve())
|
||
socket.addEventListener('message', (event) => {
|
||
this.onRaw(String(event.data)).catch((error) => reject(error))
|
||
})
|
||
})
|
||
} finally {
|
||
clearInterval(this._heartbeat)
|
||
this._heartbeat = null
|
||
this.connected = false
|
||
this.socket = null
|
||
try {
|
||
socket.close()
|
||
} catch {
|
||
/* already closed */
|
||
}
|
||
}
|
||
}
|
||
|
||
async stop() {
|
||
if (this.stopping && !this.socket) return
|
||
this.stopping = true
|
||
if (this._backoff) {
|
||
clearTimeout(this._backoff)
|
||
this._backoff = null
|
||
}
|
||
if (this._heartbeat) {
|
||
clearInterval(this._heartbeat)
|
||
this._heartbeat = null
|
||
}
|
||
if (this.socket) {
|
||
try {
|
||
this.send(frame('agent.deregister', { agent_id: this.settings.agentId }))
|
||
} catch {
|
||
/* best effort */
|
||
}
|
||
try {
|
||
this.socket.close()
|
||
} catch {
|
||
/* already closed */
|
||
}
|
||
this.socket = null
|
||
}
|
||
this.connected = false
|
||
}
|
||
|
||
send(value) {
|
||
if (!this.socket || this.socket.readyState !== 1) return false
|
||
this.socket.send(JSON.stringify(value))
|
||
return true
|
||
}
|
||
|
||
/** Push one run event up to the hub(status / delta / reasoning / tool / log / completed / failed)。 */
|
||
async emit(taskId, type, payload = {}) {
|
||
if (!taskId) return
|
||
this.send(frame('agent.event', {
|
||
topic: 'task.' + taskId + '.event',
|
||
agent_id: this.settings.agentId,
|
||
task_id: taskId,
|
||
payload: { type, ...payload },
|
||
}))
|
||
}
|
||
|
||
reply(request, payload, ok = true) {
|
||
this.send(frame(String(request.kind || 'hub.event'), {
|
||
type: ok ? 'res' : 'err',
|
||
reply_to: String(request.id || ''),
|
||
agent_id: this.settings.agentId,
|
||
payload,
|
||
}))
|
||
}
|
||
|
||
async onRaw(raw) {
|
||
let value
|
||
try {
|
||
value = JSON.parse(raw)
|
||
} catch {
|
||
return
|
||
}
|
||
if (!value || typeof value !== 'object') return
|
||
|
||
if (value.kind === 'hub.hello') {
|
||
const payload = value.payload || {}
|
||
// 只给了凭证(面板点上线 / config 里只写 agentToken)时 agent_id 是空的:
|
||
// hub 在 hello 里把它认出来的那个 id 告诉我,帧的 topic 和面板才不会显示 "-"。
|
||
if (payload.agent_id && !this.settings.agentId) this.settings.agentId = String(payload.agent_id)
|
||
if (payload.heartbeat_interval_s) {
|
||
this.heartbeatIntervalMs = Math.max(3000, Number(payload.heartbeat_interval_s) * 1000)
|
||
}
|
||
this.lastHelloAt = new Date().toISOString()
|
||
const capabilities = await this.capabilities()
|
||
this.send(frame('agent.hello', {
|
||
topic: 'agent.' + this.settings.agentId + '.status',
|
||
agent_id: this.settings.agentId,
|
||
payload: {
|
||
client: 'dsh-agenthub',
|
||
client_version: this.settings.clientVersion,
|
||
connection_mode: this.settings.connectionMode,
|
||
capabilities,
|
||
active_tasks: this.runs.size,
|
||
},
|
||
}))
|
||
return
|
||
}
|
||
|
||
if (value.type !== 'req') return
|
||
switch (value.kind) {
|
||
case 'task.run':
|
||
this.onTaskRun(value)
|
||
return
|
||
case 'task.cancel':
|
||
await this.onTaskCancel(value)
|
||
return
|
||
case 'agent.ping':
|
||
this.reply(value, { ok: true, rtt_ms: Math.round((Date.now() / 1000 - Number(value.ts || 0)) * 1000) })
|
||
return
|
||
case 'agent.describe':
|
||
this.reply(value, { streaming: true, active_tasks: this.runs.size, ...(await this.capabilities()) })
|
||
return
|
||
default:
|
||
this.reply(value, { error: 'unsupported kind ' + String(value.kind) }, false)
|
||
}
|
||
}
|
||
|
||
onTaskRun(request) {
|
||
if (this.stopping) {
|
||
this.reply(request, { error: 'agent is shutting down' }, false)
|
||
return
|
||
}
|
||
const payload = request.payload || {}
|
||
const invocationId = String(payload.invocation_id || request.id || randomUUID())
|
||
const taskId = String(payload.task_id || '')
|
||
const record = { taskId, cancel: null, startedAt: Date.now() }
|
||
this.runs.set(invocationId, record)
|
||
this.tasks.unshift({
|
||
invocation_id: invocationId,
|
||
task_id: taskId,
|
||
prompt: String(payload.prompt || '').slice(0, 200),
|
||
session_key: String(payload.session_key || ''),
|
||
status: 'running',
|
||
started_at: new Date().toISOString(),
|
||
})
|
||
this.tasks = this.tasks.slice(0, 20)
|
||
const emit = (type, extra = {}) => this.emit(taskId, type, extra)
|
||
const control = {
|
||
invocationId,
|
||
taskId,
|
||
setCancel: (fn) => {
|
||
record.cancel = fn
|
||
},
|
||
}
|
||
void this.runTask(request, payload, invocationId, emit, control)
|
||
}
|
||
|
||
async runTask(request, payload, invocationId, emit, control) {
|
||
await emit('status', { message: 'accepted by dsh plugin', invocation_id: invocationId })
|
||
try {
|
||
const text = await this.handlers.onTask(payload, emit, control)
|
||
this.finish(invocationId, 'completed')
|
||
this.reply(request, { ok: true, text: String(text || '').slice(0, 8000) })
|
||
} catch (error) {
|
||
if (error && error.name === 'AbortError') {
|
||
this.finish(invocationId, 'cancelled')
|
||
await emit('cancelled', { reason: 'cancelled by hub' })
|
||
this.reply(request, { ok: true, cancelled: true })
|
||
return
|
||
}
|
||
this.finish(invocationId, 'failed')
|
||
await emit('failed', { error: String((error && error.message) || error) })
|
||
this.reply(request, { error: String((error && error.message) || error) }, false)
|
||
}
|
||
}
|
||
|
||
async onTaskCancel(request) {
|
||
const payload = request.payload || {}
|
||
const invocationId = String(payload.invocation_id || '')
|
||
const record = this.runs.get(invocationId)
|
||
if (!record) {
|
||
this.reply(request, { ok: false, reason: 'unknown invocation' })
|
||
return
|
||
}
|
||
if (record.cancel) {
|
||
try {
|
||
record.cancel()
|
||
} catch (error) {
|
||
console.warn('[agenthub] cancel failed:', String((error && error.message) || error))
|
||
}
|
||
}
|
||
this.reply(request, { ok: true })
|
||
}
|
||
|
||
finish(invocationId, status) {
|
||
this.runs.delete(invocationId)
|
||
const row = this.tasks.find((item) => item.invocation_id === invocationId)
|
||
if (row) {
|
||
row.status = status
|
||
row.finished_at = new Date().toISOString()
|
||
}
|
||
}
|
||
|
||
async capabilities() {
|
||
const base = { ...(this.settings.capabilities || {}) }
|
||
if (typeof this.handlers.describe !== 'function') return base
|
||
try {
|
||
return { ...base, ...(await this.handlers.describe()) }
|
||
} catch (error) {
|
||
// 不能静默吞掉:面板与 describe 都要能看见"自述失败"的原因。
|
||
const why = 'capability describe failed: ' + String((error && error.message) || error)
|
||
this.lastError = why
|
||
return { ...base, describe_error: why }
|
||
}
|
||
}
|
||
|
||
/** 给 DSH 面板用的快照。 */
|
||
snapshot() {
|
||
return {
|
||
hub: this.base,
|
||
agent_id: this.settings.agentId,
|
||
name: this.settings.name,
|
||
connected: this.connected,
|
||
last_hello_at: this.lastHelloAt,
|
||
last_error: this.lastError,
|
||
active_tasks: this.runs.size,
|
||
// 身份不落盘:凭证只可能来自 config 或面板这次填的。
|
||
credential: this.identitySource,
|
||
legacy_state_file: this.statePath(),
|
||
tasks: this.tasks.slice(0, 10),
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 配置优先级:插件 config > 环境变量 > 默认值。 */
|
||
export function resolveSettings(config = {}) {
|
||
const env = process.env
|
||
return {
|
||
// 连接:server 是规范名,hubUrl / AGENTHUB_HUB_URL 是兼容读的旧名。
|
||
hubUrl: config.server || config.hubUrl || env.AGENTHUB_SERVER || env.AGENTHUB_HUB_URL || 'http://127.0.0.1:8100',
|
||
name: config.name || env.AGENTHUB_NAME || 'dsh',
|
||
displayName: config.displayName || env.AGENTHUB_DISPLAY_NAME || '',
|
||
description: config.description || env.AGENTHUB_DESCRIPTION || 'DeepSeek Harness agent',
|
||
// 身份只有这一格:控制台签发的凭证。agentId 不用填——hub 在 hello 里会告诉 Agent。
|
||
agentToken: config.agentToken || env.AGENTHUB_AGENT_TOKEN || '',
|
||
agentId: config.agentId || env.AGENTHUB_AGENT_ID || '',
|
||
driver: config.driver || 'deepseek_harness',
|
||
connectionMode: config.connectionMode || 'embedded',
|
||
deploymentKind: config.deploymentKind || env.AGENTHUB_DEPLOYMENT_KIND || 'local',
|
||
deploymentRef: config.deploymentRef || env.AGENTHUB_DEPLOYMENT_REF || '',
|
||
emoji: config.emoji || '🧭',
|
||
// 回退路径(组合里没有 sessionController 时)用的模型 —— 这是本进程的运行时
|
||
// 配置,不是上报给 hub 的注册字段;上报的模型来自 harness 的默认模型设置(自省)。
|
||
provider: config.provider || env.AGENTHUB_PROVIDER || '',
|
||
model: config.model || '',
|
||
labels: config.labels || {},
|
||
capabilities: config.capabilities || {},
|
||
maxConcurrency: Number(config.maxConcurrency || 1),
|
||
cwd: config.cwd || env.AGENTHUB_WORKSPACE || process.cwd(),
|
||
statePath: config.statePath || env.AGENTHUB_STATE_PATH || '',
|
||
timeoutS: Number(config.timeoutS || env.AGENTHUB_TASK_TIMEOUT_S || 900),
|
||
clientVersion: config.clientVersion || '0.1.0',
|
||
autoConnect: config.autoConnect !== false,
|
||
}
|
||
}
|