import { createSkill, tool } from '@kevisual/router'; import { app, cnb } from '../../app.ts'; import { createKeepAlive } from '../../../src/keep.ts'; type AliveInfo = { startTime: number; updatedTime?: number; KeepAlive: ReturnType; } const keepAliveMap = new Map(); // 保持工作空间存活技能 app.route({ path: 'cnb', key: 'keep-workspace-alive', description: '保持工作空间存活技能,参数wsUrl:工作空间访问URL,cookie:访问工作空间所需的cookie', middleware: ['auth'], metadata: { tags: [], ...({ args: { wsUrl: tool.schema.string().describe('工作空间的访问URL'), cookie: tool.schema.string().describe('访问工作空间所需的cookie') } }) } }).define(async (ctx) => { const wsUrl = ctx.query?.wsUrl as string; const cookie = ctx.query?.cookie as string; if (!wsUrl) { ctx.throw(400, '缺少工作空间访问URL参数'); } if (!cookie) { ctx.throw(400, '缺少访问工作空间所需的cookie参数'); } // 检测是否已在运行 const existing = keepAliveMap.get(wsUrl); if (existing) { ctx.body = { message: `工作空间 ${wsUrl} 的保持存活任务已在运行中` }; return; } console.log(`启动保持工作空间 ${wsUrl} 存活的任务`); const keep = createKeepAlive({ wsUrl, cookie, onConnect: () => { console.log(`工作空间 ${wsUrl} 保持存活任务已连接`); }, onMessage: (data) => { // 可选:处理收到的消息 // console.log(`工作空间 ${wsUrl} 收到消息: ${data}`); const aliveInfo = keepAliveMap.get(wsUrl); if (aliveInfo) { aliveInfo.updatedTime = Date.now(); } }, debug: true, onExit: (code) => { console.log(`工作空间 ${wsUrl} 保持存活任务已退出,退出码: ${code}`); keepAliveMap.delete(wsUrl); } }); keepAliveMap.set(wsUrl, { startTime: Date.now(), updatedTime: Date.now(), KeepAlive: keep }); ctx.body = { message: `已启动保持工作空间 ${wsUrl} 存活的任务` }; }).addTo(app); // 获取保持工作空间存活任务列表技能 app.route({ path: 'cnb', key: 'list-keep-alive-tasks', description: '获取保持工作空间存活任务列表技能', middleware: ['auth'], metadata: { tags: [], } }).define(async (ctx) => { const list = Array.from(keepAliveMap.entries()).map(([wsUrl, info]) => ({ wsUrl, startTime: info.startTime, updatedTime: info.updatedTime })); ctx.body = { list }; }).addTo(app); // 停止保持工作空间存活技能 app.route({ path: 'cnb', key: 'stop-keep-workspace-alive', description: '停止保持工作空间存活技能, 参数wsUrl:工作空间访问URL', middleware: ['auth'], metadata: { tags: [], ...({ args: { wsUrl: tool.schema.string().describe('工作空间的访问URL'), } }) } }).define(async (ctx) => { const wsUrl = ctx.query?.wsUrl as string; if (!wsUrl) { ctx.throw(400, '缺少工作空间访问URL参数'); } const keepAlive = keepAliveMap.get(wsUrl); if (keepAlive) { const endTime = Date.now(); const duration = endTime - keepAlive.startTime; keepAlive?.KeepAlive?.disconnect(); keepAliveMap.delete(wsUrl); ctx.body = { message: `已停止保持工作空间 ${wsUrl} 存活的任务,持续时间: ${duration}ms` }; } else { ctx.body = { message: `没有找到工作空间 ${wsUrl} 的保持存活任务` }; } }).addTo(app);