/** * AgentHub 接入网关插件 — 离线自检(不需要 DSH 运行时,也不需要真的 hub) * * 用法: * node plugins/dsh-agenthub/selfcheck.mjs * * 校验三件事: * 1) apply() 能在伪 Cordis ctx 上完成接线(事件监听、工具、RPC、卸载清理); * 2) Gateway 客户端说的帧和 hub 协议一致:带着凭证拨 ws → hub.hello → agent.hello; * 3) 派活链路:task.run → agent.followup(user message) → assistant-stream / tool / turn/end * 一路变成 agent.event(delta|reasoning|tool) 帧,最后回 res{ok,text};task.cancel 能打断。 * * 真机验证:把 plugins/dsh-agenthub link 进 ~/.dsh/profiles/web,起一个真 hub * (agenthub serve)后从控制台派活。 */ import assert from 'node:assert/strict' import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { apply } from './lib/index.js' const HERE = path.dirname(fileURLToPath(import.meta.url)) let failures = 0 function check(name, fn) { try { fn() console.log(' ✓ ' + name) } catch (error) { failures += 1 console.log(' ✗ ' + name + ' — ' + String((error && error.message) || error)) } } const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) const jsonResponse = (status, payload) => ({ ok: status < 400, status, text: async () => JSON.stringify(payload), }) // ---------------------------------------------------------------- 假 hub // 接入只剩一条路:拿凭证拨 socket。HTTP 侧只剩心跳(凭证体检), // register / join / enrollment 那些老路由一律 404 —— 插件一旦再去敲就该测挂。 const requests = [] const hubFetch = async (url, init) => { requests.push(String(url)) if (String(url).endsWith('/api/v1/gateway/heartbeat')) { const auth = String((init && init.headers && init.headers.authorization) || '') if (auth.includes('ag_stale')) return jsonResponse(401, { detail: 'unknown agent credential' }) return jsonResponse(200, { ok: true }) } return jsonResponse(404, { detail: 'no route ' + url }) } /** 除心跳外不该再有任何 HTTP 往返。 */ const nonHeartbeat = () => requests.filter((u) => !/\/gateway\/heartbeat$/.test(u)) globalThis.fetch = hubFetch /** 够用的 WebSocket 打桩:记下 send 的内容,也能把 hub 帧喂回去。 */ const sockets = [] class FakeSocket { constructor(url) { this.url = url this.readyState = 0 this.sent = [] this.listeners = {} sockets.push(this) setTimeout(() => { this.readyState = 1 this.emit('open') }, 0) } addEventListener(type, handler) { ;(this.listeners[type] || (this.listeners[type] = [])).push(handler) } emit(type, event) { for (const handler of this.listeners[type] || []) handler(event) } send(raw) { this.sent.push(JSON.parse(raw)) } close() { this.readyState = 3 this.emit('close') } /** hub → agent */ deliver(frame) { this.emit('message', { data: JSON.stringify(frame) }) } } globalThis.WebSocket = FakeSocket const frames = (socket, kind, predicate = () => true) => socket.sent.filter((frame) => frame.kind === kind).filter(predicate) const req = (kind, payload, id) => ({ v: 1, id, ts: Date.now() / 1000, type: 'req', kind, actor: 'hub', payload, }) // ------------------------------------------------------------ 假 Cordis ctx function fakeCtx({ withController = true } = {}) { const handlers = new Map() const live = new Map() const root = { tools: [], routes: new Map(), created: [], resumed: [], prompted: [], cancelled: [], installed: [], createRequests: [], cleanup: null, get(name) { if (name === 'sessionController' && withController) return root.sessionController if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'fake-local', model: 'fake-1' }) } return undefined }, sessionController: { async create(request) { const sessionId = request.sessionId root.created.push(sessionId) root.createRequests.push(request) if (!live.has(sessionId)) live.set(sessionId, makeAgent(sessionId)) return { sessionId } }, async prompt(request) { root.prompted.push(request) return { accepted: true } }, cancel(request) { root.cancelled.push(request.sessionId) return { accepted: true } }, }, agents: { get: (id) => live.get(id), list: () => [...live.values()], async create({ sessionId, setup }) { root.created.push(sessionId) const agent = makeAgent(sessionId) live.set(sessionId, agent) if (typeof setup === 'function') setup(fakeAgentCtx(root, agent)) return { agent, dispose: async () => live.delete(sessionId) } }, async resume({ resumeSessionId, setup }) { root.resumed.push(resumeSessionId) const agent = makeAgent(resumeSessionId) live.set(resumeSessionId, agent) if (typeof setup === 'function') setup(fakeAgentCtx(root, agent)) return { agent, dispose: async () => live.delete(resumeSessionId) } }, }, on(event, handler) { const list = handlers.get(event) || [] list.push(handler) handlers.set(event, list) return () => { const current = handlers.get(event) || [] const index = current.indexOf(handler) if (index >= 0) current.splice(index, 1) } }, emit(event, ...args) { for (const handler of handlers.get(event) || []) handler(...args) }, effect(fn) { root.cleanup = fn() }, inject(services, callback) { if (services.includes('tools')) callback({ tools: { register: (tool) => root.tools.push(tool) } }) if (services.includes('connection')) { callback({ connection: { fetch: { register: (route) => { root.routes.set(route.path, route) return () => root.routes.delete(route.path) }, }, }, }) } }, } return root } /** 伪 agentCtx:只记下插件在会话作用域里订了哪些事件。 */ function fakeAgentCtx(root, agent) { return { on(event, handler) { root.installed.push({ sessionId: agent.id, event, handler }) return () => {} }, } } function makeAgent(id) { return { id, options: { model: 'deepseek-v4-pro' }, followups: [], cancels: [], followup(message) { this.followups.push(message) }, cancel(cause) { this.cancels.push(cause) }, } } async function main() { const stateFile = path.join(HERE, '.selfcheck-state.json') // 面板设置落在这个目录里(真机是 ~/.dsh/agenthub.json),测试期间别碰真文件。 const dshHome = path.join(HERE, '.selfcheck-dsh') process.env.DSH_HOME = dshHome const ctx = fakeCtx() apply(ctx, { hubUrl: 'http://hub.test', agentToken: 'ag_test_token', name: 'dsh-dev', statePath: stateFile, cwd: '/tmp', }) await sleep(20) const socket = sockets[0] check('config 里有凭证就直连:探一次心跳,不再有任何注册往返', () => { assert.equal(socket.url, 'ws://hub.test/api/v1/gateway/ws?agent_token=ag_test_token') assert.equal(nonHeartbeat().length, 0, '不该再发请求:' + nonHeartbeat().join(',')) }) socket.deliver({ kind: 'hub.hello', payload: { heartbeat_interval_s: 15, agent_id: 'agt_dsh_1' } }) await sleep(10) check('hub.hello 之后回 agent.hello(带能力自述)', () => { const hello = frames(socket, 'agent.hello')[0] assert.ok(hello, '没有 agent.hello') assert.equal(hello.payload.client, 'dsh-agenthub') assert.equal(hello.payload.capabilities.runtime, 'deepseek-harness') assert.equal(hello.payload.capabilities.streaming, true) }) socket.deliver(req('task.run', { task_id: 'tsk_1', invocation_id: 'inv_1', session_key: 'console-1', prompt: '你好,读一下 README', }, 'frm_task_1')) await sleep(10) check('task.run 走 sessionController:开一个 DSH 会话并投递 prompt', () => { assert.equal(ctx.created.length, 1) assert.equal(ctx.createRequests.length, 1) assert.equal(ctx.createRequests[0].cwd, '/tmp') assert.equal(ctx.prompted.length, 1) const prompt = ctx.prompted[0] assert.equal(prompt.sessionId, ctx.created[0]) assert.equal(prompt.mode, 'queue') assert.equal(prompt.content[0].type, 'text') assert.equal(prompt.content[0].text, '你好,读一下 README') assert.ok(prompt.requestId, 'prompt 需要客户端铸造的 requestId') }) const agent = ctx.agents.list()[0] const chunk = (value) => ({ agent, frame: { type: 'chunk', chunk: value } }) ctx.emit('agent/assistant-stream', chunk({ type: 'reasoning-delta', text: '先看看文件…' })) ctx.emit('agent/assistant-stream', chunk({ type: 'text-delta', text: '好的' })) ctx.emit('agent/assistant-stream', chunk({ type: 'text-delta', text: ',这是摘要。' })) ctx.emit('session/event', { id: agent.id }, { type: 'tool/call', data: { turn: 1, step: 1, callId: 'call_1', name: 'read_file', arguments: '{"path":"README.md"}' }, }) ctx.emit('session/event', { id: agent.id }, { type: 'assistant/message', data: { turn: 1, step: 1, message: { content: [{ type: 'text', text: '好的,这是摘要。' }] } }, }) await sleep(10) check('推理 / 正文 / 工具调用都变成了 agent.event 帧', () => { const kinds = frames(socket, 'agent.event').map((item) => item.payload.type) // 开头两条 status:网关的 "accepted by dsh plugin" + 插件的 "running in deepseek-harness" assert.deepEqual(kinds.slice(0, 2), ['status', 'status']) assert.deepEqual(kinds.filter((kind) => kind !== 'status'), ['reasoning', 'delta', 'delta', 'tool']) const tool = frames(socket, 'agent.event', (item) => item.payload.type === 'tool')[0] assert.equal(tool.payload.name, 'read_file') assert.equal(tool.payload.input.path, 'README.md') assert.equal(tool.task_id, 'tsk_1') }) ctx.emit('session/event', { id: agent.id }, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } }) await sleep(10) check('turn/end 用 res 帧把答案交回 hub', () => { const response = frames(socket, 'task.run', (item) => item.type === 'res' && item.reply_to === 'frm_task_1')[0] assert.ok(response, '没有 res 帧') assert.equal(response.payload.ok, true) assert.equal(response.payload.text, '好的,这是摘要。') }) socket.deliver(req('task.run', { task_id: 'tsk_2', invocation_id: 'inv_2', session_key: 'console-1', prompt: '再写一版', }, 'frm_task_2')) await sleep(10) socket.deliver(req('task.cancel', { invocation_id: 'inv_2' }, 'frm_cancel_2')) await sleep(10) check('task.cancel 打到 sessionController.cancel', () => { assert.deepEqual(ctx.cancelled, [agent.id]) assert.equal(agent.cancels.length, 0) const ack = frames(socket, 'task.cancel', (item) => item.type === 'res')[0] assert.equal(ack.payload.ok, true) }) ctx.emit('session/event', { id: agent.id }, { type: 'turn/end', data: { turn: 2, reason: { kind: 'aborted', reason: { kind: 'user' } } }, }) await sleep(10) check('被取消的轮次既不报成功也不报失败,而是 cancelled', () => { const run = frames(socket, 'task.run', (item) => item.type === 'res' && item.reply_to === 'frm_task_2')[0] assert.equal(run.payload.cancelled, true) const kinds = frames(socket, 'agent.event', (item) => item.task_id === 'tsk_2').map((item) => item.payload.type) assert.ok(kinds.includes('cancelled'), '缺 cancelled 事件:' + kinds.join(',')) }) socket.deliver(req('agent.ping', {}, 'frm_ping')) socket.deliver(req('agent.describe', {}, 'frm_desc')) await sleep(10) check('agent.ping / agent.describe 有应答', () => { assert.equal(frames(socket, 'agent.ping', (item) => item.type === 'res')[0].payload.ok, true) assert.equal(frames(socket, 'agent.describe')[0].payload.streaming, true) }) check('注册了 agenthub_status 工具和 /api/agenthub/status 面板路由', () => { assert.equal(ctx.tools.length, 1) assert.equal(ctx.tools[0].name, 'agenthub_status') assert.ok(ctx.routes.has('/api/agenthub/status'), '面板路由没挂上:' + [...ctx.routes.keys()].join(',')) }) const panel = await (await ctx.routes.get('/api/agenthub/status').fetch()).json() check('面板路由返回连接快照', () => { assert.equal(panel.ok, true) assert.equal(panel.value.agent_id, 'agt_dsh_1') assert.equal(panel.value.connected, true) assert.ok(panel.value.tasks.length >= 2) }) check('会话 id 由 hub session_key 决定(同一段对话跨重启续得上)', () => { const before = ctx.created.length + ctx.resumed.length assert.equal(before, 1) assert.equal(agent.id, ctx.created.concat(ctx.resumed)[0]) }) // --- 热重载:DSH 存一次 patch 文件就会把这个 entry 应用两遍,只能留一份网关 --- const reloaded = fakeCtx() const reloadedState = stateFile + '.reload' apply(reloaded, { hubUrl: 'http://hub.test', agentToken: 'ag_test_token', name: 'dsh-reloaded', statePath: reloadedState, cwd: '/tmp', }) await sleep(20) const reloadedSocket = sockets[sockets.length - 1] check('热重载只留一份网关:旧 socket 关掉并报 deregister', () => { assert.equal(socket.readyState, 3, '旧 socket 没关') assert.ok(frames(socket, 'agent.deregister').length >= 1, '旧实例没向 hub 报 deregister') assert.equal(reloadedSocket.readyState, 1, '新 socket 没连上') }) reloadedSocket.deliver({ kind: 'hub.hello', payload: { heartbeat_interval_s: 15 } }) reloadedSocket.deliver(req('task.run', { task_id: 'tsk_reload', invocation_id: 'inv_reload', session_key: 'console-reload', prompt: '热重载后照常派活', }, 'frm_reload')) // 旧实例的监听还在:它已经让位了,不该再吃任务 const staleBefore = { created: ctx.created.length, prompted: ctx.prompted.length } socket.deliver(req('task.run', { task_id: 'tsk_stale', invocation_id: 'inv_stale', session_key: 'console-stale', prompt: '不该跑到被取代的实例上', }, 'frm_stale')) await sleep(20) check('热重载后:新实例接活,旧实例不再抢活', () => { assert.equal(reloaded.prompted.length, 1) assert.equal(reloaded.prompted[0].content[0].text, '热重载后照常派活') assert.equal(ctx.created.length, staleBefore.created, '被取代的实例又多开了会话') assert.equal(ctx.prompted.length, staleBefore.prompted, '被取代的实例又吃了一条 prompt') }) // --- 客户端半:浏览器 bundle 能在伪 ModuleLoader 下加载、挂上设置面板、打到正确接口 --- const clientState = { entry: null, styles: [] } const clientCalls = [] globalThis.window = { __ModuleLoader__: { load: (entry) => (clientState.entry = entry) } } globalThis.document = { querySelector: () => null, createElement: () => ({ dataset: {} }), head: { appendChild: (node) => clientState.styles.push(node) }, } globalThis.fetch = async (url, init) => { clientCalls.push({ url: String(url), method: (init && init.method) || 'GET' }) return { ok: true, status: 200, json: async () => ({ ok: true, value: { connected: true, hub: 'http://hub.test', agent_id: 'agt_dsh_1', name: 'dsh-dev', tasks: [] } }), } } const fakeReact = { createElement: (type, props, ...children) => ({ type, props, children }), useState: (initial) => [initial, () => {}], useEffect: (effect) => { effect() }, useCallback: (fn) => fn, } const clientSlots = { injected: [], registered: [] } clientSlots.inject = (name, callback) => { clientSlots.injected.push(name) callback() } clientSlots.register = (options, render) => { clientSlots.registered.push({ options, render }) return () => {} } eval(readFileSync(path.join(HERE, 'lib/client.js'), 'utf8')) const clientModule = clientState.entry.factory((name) => { if (name === 'react') return fakeReact throw new Error('客户端 bundle 不认识的模块:' + name) }) const clientCtx = { get: (name) => (name === 'slots' ? clientSlots : undefined), slots: clientSlots } clientModule.apply(clientCtx) const panelEntry = clientSlots.registered[0] const element = panelEntry.render() // -> el(Panel, { ctx }) const tree = element.type(element.props) // 跑一遍 Panel:触发它自己的取数 await sleep(10) check('客户端半:注册「设置 → AgentHub」面板', () => { assert.equal(clientState.entry.id, '@nex/dsh-agenthub') assert.ok(clientModule.inject.includes('slots'), 'inject 里没有 slots') assert.equal(panelEntry.options.name, 'settings.section') assert.equal(panelEntry.options.label, 'AgentHub') assert.equal(clientState.styles.length, 1, '没有注入面板样式') }) check('客户端半:面板打的是 /api/agenthub/status(而不是自建通道)', () => { const call = clientCalls[0] assert.ok(call, '面板没有发起取数请求') assert.equal(call.url, '/api/agenthub/status') assert.equal(call.method, 'POST') }) globalThis.fetch = hubFetch // 后面的回退路径还要跟假 hub 说话 // --- P2:身份即配置 —— 没有身份文件,旧文件只读兜底,凭证来源可辨认 --- const configState = stateFile + '.config' const beforeConfig = nonHeartbeat().length const configCtx = fakeCtx() apply(configCtx, { server: 'http://hub.test', name: 'dsh-config', agentId: 'agt_from_config', agentToken: 'ag_from_config', statePath: configState, cwd: '/tmp', }) await sleep(20) const configSocket = sockets[sockets.length - 1] const configPanel = await (await configCtx.routes.get('/api/agenthub/status').fetch()).json() check('config 里给了 agentId+agentToken:直接用它连,不注册、不落盘', () => { assert.equal(configSocket.url.includes('agent_token=ag_from_config'), true, configSocket.url) assert.equal(nonHeartbeat().length, beforeConfig, '不该再走 register') assert.equal(existsSync(configState), false, '不该写出身份文件') assert.equal(configPanel.value.agent_id, 'agt_from_config') assert.equal(configPanel.value.credential, 'config') }) // 旧版本把凭证写在 ~/.agenthub/agent-.json:只读兜底,绝不再改写 const legacyState = stateFile + '.legacy' const legacyPayload = { agent_id: 'agt_legacy', agent_token: 'ag_legacy', name: 'dsh-legacy', hub: 'http://hub.test', } writeFileSync(legacyState, JSON.stringify(legacyPayload, null, 2) + '\n') const legacyCtx = fakeCtx() apply(legacyCtx, { hubUrl: 'http://hub.test', name: 'dsh-legacy', statePath: legacyState, cwd: '/tmp' }) await sleep(20) const legacySocket = sockets[sockets.length - 1] check('旧身份文件只读兜底:拿它连上,且文件一个字节都没改', () => { assert.equal(legacySocket.url.includes('agent_token=ag_legacy'), true, legacySocket.url) assert.deepEqual(JSON.parse(readFileSync(legacyState, 'utf8')), legacyPayload) }) // 同名 Agent 重新接入:config 里贴了新凭证,机器上还躺着上一世的状态文件 const mixedState = stateFile + '.mixed' writeFileSync(mixedState, JSON.stringify({ agent_id: 'agt_stale', agent_token: 'ag_stale', hub: 'http://hub.test' })) const mixedCtx = fakeCtx() apply(mixedCtx, { server: 'http://hub.test', name: 'dsh-mixed', agentToken: 'ag_fresh', statePath: mixedState, cwd: '/tmp' }) await sleep(20) const mixedSocket = sockets[sockets.length - 1] const beforeMixed = nonHeartbeat().length const mixedPanel = await (await mixedCtx.routes.get('/api/agenthub/status').fetch()).json() check('config 里有凭证时,旧状态文件里的 agentId 不许拼进来(两个身份 = 401)', () => { assert.equal(mixedSocket.url.includes('agent_token=ag_fresh'), true, mixedSocket.url) assert.equal(mixedSocket.url.includes('agt_stale'), false, mixedSocket.url) assert.equal(mixedPanel.value.agent_id, '', 'agent_id 等 hub 在 hub.hello 里回送') assert.equal(mixedPanel.value.credential, 'config') assert.equal(nonHeartbeat().length, beforeMixed, '有凭证就是直接连,不该去敲任何注册路由') }) // --- 回退路径:profile 里没有 sessionController 时(例如 headless/sdk 组合)--- const bare = fakeCtx({ withController: false }) const bareState = stateFile + '.bare' apply(bare, { hubUrl: 'http://hub.test', agentToken: 'ag_test_token', name: 'dsh-bare', statePath: bareState, cwd: '/tmp', }) await sleep(20) const bareSocket = sockets[sockets.length - 1] bareSocket.deliver({ kind: 'hub.hello', payload: { heartbeat_interval_s: 15 } }) bareSocket.deliver(req('task.run', { task_id: 'tsk_bare', invocation_id: 'inv_bare', session_key: 'console-bare', prompt: '你好', }, 'frm_bare')) await sleep(20) check('没有 sessionController 时退回 agents.create + 自装模型选择', () => { const rows = bare.agents.list() assert.equal(rows.length, 1) // 回退路径必须自己把 {{provider}}/{{model}} 装进装配过程,否则系统提示词组装会报错 const events = bare.installed.map((item) => item.event) assert.ok(events.includes('system-prompt/assemble'), '缺 prompt 变量注入:' + events.join(',')) assert.ok(events.includes('agent/request'), '缺请求模型路由:' + events.join(',')) assert.equal(rows[0].followups.length, 1) assert.equal(rows[0].followups[0].content[0].text, '你好') }) // --- 面板:填「地址 + 端口 + Agent 凭证」点上线 --- const panelFile = path.join(dshHome, 'agenthub.json') const beforePanel = nonHeartbeat().length const joinCtx = fakeCtx() apply(joinCtx, { server: 'http://hub.test', name: 'dsh-joined', autoConnect: false, cwd: '/tmp' }) await sleep(20) const joinRoute = joinCtx.routes.get('/api/agenthub/status') const callPanel = async (body) => ( await ( await joinRoute.fetch( new Request('http://x/api/agenthub/status', { method: 'POST', body: JSON.stringify(body) }), ) ).json() ) const joinedPanel = await callPanel({ action: 'connect', server: 'http://hub.test', port: '8100', agentToken: 'ag_panel_token', name: 'dsh-joined', }) await sleep(20) const joinedSocket = sockets[sockets.length - 1] // 面板这条路上只有 ag_ 凭证,agent_id 得靠 hub 在 hub.hello 里告诉我 joinedSocket.deliver({ kind: 'hub.hello', payload: { heartbeat_interval_s: 15, agent_id: 'agt_panel_1' } }) await sleep(20) check('填地址+端口+凭证点上线:拿这份凭证直接连,不再问 Hub ID', () => { assert.equal(joinedPanel.value.joined, true) assert.equal(joinedPanel.value.connected, true, JSON.stringify(joinedPanel.value)) assert.equal(joinedPanel.value.credential, 'panel') assert.equal(nonHeartbeat().length, beforePanel, '有凭证就不该再发任何注册请求') assert.equal(joinedSocket.url.includes('agent_token=ag_panel_token'), true, joinedSocket.url) assert.equal(joinedSocket.url.startsWith('ws://hub.test:8100/api/v1/gateway/ws'), true, joinedSocket.url) }) const afterHello = await callPanel({ action: 'status' }) check('只给凭证也认得出自己是谁:agent_id 由 hub 在 hub.hello 里告知', () => { assert.equal(afterHello.value.agent_id, 'agt_panel_1', JSON.stringify(afterHello.value)) }) check('面板设置落盘:只有地址和名字,没有凭证', () => { const saved = JSON.parse(readFileSync(panelFile, 'utf8')) assert.deepEqual(saved, { server: 'http://hub.test:8100', name: 'dsh-joined' }) assert.equal(/ag_|enr_|hub_/.test(JSON.stringify(saved)), false, '凭证不该进这个文件') }) const leftPanel = await callPanel({ action: 'leave' }) check('点下线:socket 关掉,配置留着下次用', () => { assert.equal(leftPanel.value.joined, false) assert.equal(joinedSocket.readyState, 3) assert.equal(existsSync(panelFile), true) }) const badApiKey = await callPanel({ action: 'connect', server: 'http://hub.test', port: '8100', agentToken: 'ah_pasted_api_key', name: 'x', }) check('把 Hub API Key 填进凭证栏:面板直接说清楚,不去连', () => { assert.equal(badApiKey.ok, false) assert.ok(/API Key/.test(badApiKey.error.message), badApiKey.error.message) assert.equal(nonHeartbeat().length, beforePanel, '不该再发任何请求') }) const badHubId = await callPanel({ action: 'connect', server: 'http://hub.test', port: '8100', agentToken: 'hub_vFyLBu3ATfUPpZ1VAPNVtQ', name: 'x', }) check('把已取消的 Hub ID 填进凭证栏:面板说清它不是凭证', () => { assert.equal(badHubId.ok, false) assert.ok(/Hub ID/.test(badHubId.error.message), badHubId.error.message) assert.equal(nonHeartbeat().length, beforePanel, '不该再发任何请求') }) const badEnrollment = await callPanel({ action: 'connect', server: 'http://hub.test', port: '8100', agentToken: 'enr_pasted_here_by_mistake', name: 'x', }) check('把已取消的入场令牌填进凭证栏:面板说清只剩 ag_ 一条路', () => { assert.equal(badEnrollment.ok, false) assert.ok(/入场令牌/.test(badEnrollment.error.message), badEnrollment.error.message) assert.equal(nonHeartbeat().length, beforePanel, '不该再发任何请求') }) // 事故复盘一:config 里刚粘了新凭证,可全局面板文件(~/.dsh/agenthub.json 不分 profile) // 还指着上一个 hub —— 面板不能把刚签发的凭证盖掉。 const anchoredBefore = nonHeartbeat().length writeFileSync(panelFile, JSON.stringify({ server: 'http://other-hub.test', name: 'dsh-stale' })) const anchoredCtx = fakeCtx() apply(anchoredCtx, { server: 'http://hub.test', name: 'dsh-anchored', agentId: 'agt_config', agentToken: 'ag_config_token', statePath: stateFile + '.anchored', cwd: '/tmp', }) await sleep(30) const anchoredSocket = sockets[sockets.length - 1] check('config 里粘了新凭证:面板文件里那个旧 hub 不再盖掉它', () => { assert.equal(anchoredSocket.url.startsWith('ws://hub.test/api/v1/gateway/ws'), true, anchoredSocket.url) assert.equal(anchoredSocket.url.includes('agent_token=ag_config_token'), true, anchoredSocket.url) assert.equal(nonHeartbeat().length, anchoredBefore, 'config 有凭证就不该再发任何注册请求') }) // 事故复盘二:凭证被轮换/吊销过。别把启动堵死,更别退回去敲已经删掉的老路由。 const poisonBefore = nonHeartbeat().length const poisonCtx = fakeCtx() apply(poisonCtx, { server: 'http://hub.test', name: 'dsh-poison', agentToken: 'ag_stale_credential', statePath: stateFile + '.poison', cwd: '/tmp', }) await sleep(30) const poisonPanel = await (await poisonCtx.routes.get('/api/agenthub/status').fetch()).json() check('凭证被 hub 拒:报清楚去哪儿换一份,且不去敲任何老路由', () => { assert.equal(poisonPanel.value.connected, false, JSON.stringify(poisonPanel.value)) assert.ok(/「接入」页签发/.test(poisonPanel.value.last_error), JSON.stringify(poisonPanel.value)) assert.equal(nonHeartbeat().length, poisonBefore, '不该再发任何注册请求') }) check('卸载时断开 socket', () => { anchoredCtx.cleanup?.() poisonCtx.cleanup?.() bare.cleanup() assert.equal(bareSocket.readyState, 3) assert.equal(reloadedSocket.readyState, 3, '被接管的实例没关掉自己的 socket') }) try { rmSync(stateFile, { force: true }) rmSync(stateFile + '.bare', { force: true }) rmSync(stateFile + '.legacy', { force: true }) rmSync(stateFile + '.reload', { force: true }) rmSync(stateFile + '.poison', { force: true }) rmSync(stateFile + '.anchored', { force: true }) rmSync(panelFile, { force: true }) rmSync(dshHome, { force: true, recursive: true }) } catch { /* ignore */ } console.log(failures === 0 ? '\nOK — 插件接线与 Gateway 帧协议自检通过' : '\nFAILED — ' + failures + ' 项不通过') process.exit(failures === 0 ? 0 : 1) } void main()