const http = require('http'); const fs = require('fs'); const os = require('os'); const path = require('path'); const PORT = process.env.PORT || 3000; const BASE = process.env.CODEBUDDY_BASE || 'http://127.0.0.1:8080'; const WORKSPACE = process.env.WORKSPACE || path.resolve(__dirname); const WEEK = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; function getPassword() { if (process.env.CODEBUDDY_PASSWORD) return process.env.CODEBUDDY_PASSWORD; try { const s = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.codebuddy', 'settings.json'), 'utf8')); return s.gateway?.password || s.password || null; } catch { return null; } } function getAuthHeaders() { const p = getPassword(); if (!p) throw new Error('无法读取 CodeBuddy 鉴权密码'); return { 'X-CodeBuddy-Request': '1', Authorization: 'Bearer ' + p }; } async function createJob(prompt, agent) { const res = await fetch(`${BASE}/api/v1/jobs`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, body: JSON.stringify({ prompt, cwd: WORKSPACE, agent }), }); if (!res.ok) throw new Error('创建任务失败 HTTP ' + res.status); const j = await res.json(); const id = j.data?.id || j.id; if (!id) throw new Error('创建任务失败:无任务ID'); return id; } function parseSSE(chunk, onData) { let buf = chunk, idx; while ((idx = buf.indexOf('\n\n')) >= 0) { const block = buf.slice(0, idx); buf = buf.slice(idx + 2); for (const line of block.split('\n')) if (line.startsWith('data:')) onData(line.slice(5).trim()); } return buf; } async function collectText(jobId) { const controller = new AbortController(); const res = await fetch(`${BASE}/api/v1/jobs/${jobId}/stream`, { headers: getAuthHeaders(), signal: controller.signal }); if (!res.ok) throw new Error('订阅流失败 HTTP ' + res.status); const poll = setInterval(async () => { try { const r = await fetch(`${BASE}/api/v1/jobs/${jobId}`, { headers: getAuthHeaders() }); const d = (await r.json()).data || {}; const job = d.job || d; if (job.settled) { clearInterval(poll); setTimeout(() => controller.abort(), 800); } } catch {} }, 2000); const timeout = setTimeout(() => controller.abort(), 300000); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = '', text = ''; try { while (true) { const { done, value } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); buf = parseSSE(buf, (d) => { try { const o = JSON.parse(d); if (o.type === 'message' && o.role === 'assistant' && Array.isArray(o.content)) for (const c of o.content) if (c.type === 'output_text' && c.text) text += c.text; } catch {} }); } } catch (e) { if (e.name !== 'AbortError') throw e; } finally { clearInterval(poll); clearTimeout(timeout); } return text; } function extractJson(text) { const f = text.match(/```(?:json)?\s*([\s\S]*?)```/); const a = text.indexOf('{'), b = text.lastIndexOf('}'); const cands = []; if (f) cands.push(f[1].trim()); if (a >= 0 && b > a) cands.push(text.slice(a, b + 1)); for (const c of cands) { try { return JSON.parse(c); } catch {} } return null; } const server = http.createServer((req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS'); if (req.method === 'OPTIONS') { res.writeHead(204); return res.end(); } const url = new URL(req.url, 'http://localhost'); if (req.method === 'GET') { let file = null; if (url.pathname === '/' || url.pathname === '/index.html') file = path.join(__dirname, 'public', 'index.html'); else if (url.pathname.startsWith('/charts/')) file = path.join(__dirname, 'public', 'charts', path.basename(url.pathname)); if (file && fs.existsSync(file)) { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(fs.readFileSync(file)); } } if (req.method === 'POST' && url.pathname === '/api/weather') { let body = ''; req.on('data', c => body += c); req.on('end', async () => { let city = ''; try { city = (JSON.parse(body || '{}').city || '').trim(); } catch {} if (!city) { res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' }); return res.end(JSON.stringify({ error: '请提供城市名称' })); } res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }); const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); (async () => { const t0 = Date.now(); try { send('meta', { stage: 'node1', message: '节点1:调用 weather Agent 查询未来3天天气…' }); const id1 = await createJob(`请查询「${city}」未来3天的天气,并按你的输出格式返回 JSON。`, 'weather'); const t1 = Date.now(); const wtext = await collectText(id1); const t2 = Date.now(); const weather = extractJson(wtext); if (!weather || !Array.isArray(weather.days)) throw new Error('天气数据解析失败'); const summary = weather.days.map(d => ({ date: d.date, week: WEEK[new Date(d.date + 'T00:00:00').getDay()], max: d.max, min: d.min, weather: d.desc || '未知', })); send('summary', { city: weather.city || city, summary }); send('meta', { stage: 'node2', message: '节点2:调用 chart Agent 生成曲线图…' }); const id2 = await createJob(`请把以下天气数据生成温度曲线图:\n${JSON.stringify(weather)}`, 'chart'); const t3 = Date.now(); const ctext = await collectText(id2); const t4 = Date.now(); const info = extractJson(ctext); const file = info?.file; if (!file) throw new Error('图表生成失败'); send('chart', { chartUrl: '/charts/' + file }); send('done', {}); console.log(`[计时] 节点1 创建=${t1 - t0}ms 执行=${t2 - t1}ms | 节点2 创建=${t3 - t2}ms 执行=${t4 - t3}ms | 总计=${t4 - t0}ms`); } catch (e) { console.log(`[计时] 失败于 ${Date.now() - t0}ms: ${e && e.message}`); send('error', { message: String(e && e.message || e) }); } finally { res.end(); } })(); }); return; } res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify({ error: 'not found' })); }); server.listen(PORT, () => console.log(`页面: http://localhost:${PORT}`));