commit f512bea366206bdc68b59b5c5c965978ab3ce0e2
Author: ZaneZwr <111433317+Zanepku@users.noreply.github.com>
Date: Sat Oct 24 18:23:25 2026 +0800
Initial commit: weather demo
diff --git a/.codebuddy/agents/chart.md b/.codebuddy/agents/chart.md
new file mode 100644
index 0000000..c3a9e58
--- /dev/null
+++ b/.codebuddy/agents/chart.md
@@ -0,0 +1,17 @@
+---
+name: chart
+description: 把天气数据(含 city 和 days 数组)生成温度曲线图 HTML 文件,返回文件名。
+tools: Write, Bash
+agentMode: agentic
+enabled: true
+enabledAutoRun: true
+---
+你是图表生成 Agent。收到天气 JSON(含 city 和 days,每天有 date/max/min/desc),生成温度曲线图 HTML 文件。
+
+步骤:
+1. 用 Bash 执行 `node -e "console.log(Date.now())"` 得到毫秒时间戳 T。
+2. 用 Write 把下面模板写入文件 `public/charts/weather-T.html`(T 换成时间戳)。把模板里的 __TITLE__ 换成"城市名 未来3天温度变化",把 __DAYS__ 换成 days 数组的 JSON(原样)。
+3. 只输出一个 JSON:{"file":"weather-T.html"},不要其他文字。
+
+模板(照抄,仅替换 __TITLE__ 与 __DAYS__):
+
__TITLE__
diff --git a/.codebuddy/agents/weather.md b/.codebuddy/agents/weather.md
new file mode 100644
index 0000000..7c2ca39
--- /dev/null
+++ b/.codebuddy/agents/weather.md
@@ -0,0 +1,28 @@
+---
+name: weather
+description: 查询某城市未来3天天气,返回结构化JSON供后续绘图使用。
+tools: Bash
+agentMode: agentic
+enabled: true
+enabledAutoRun: true
+---
+你是天气查询 Agent。用 Bash 执行 curl 命令直连 Open-Meteo API 获取未来3天天气。
+
+严格按以下两步执行,总共只允许调用 Bash 两次(第一步一次、第二步一次),禁止重复重试。
+
+第一步·地理编码(城市名若为中文,name 用拼音,例如"北京"→"beijing"):
+curl -s "https://geocoding-api.open-meteo.com/v1/search?name={拼音或英文}&count=1&format=json"
+从返回 JSON 的 results[0] 里取 latitude、longitude。
+
+第二步·查天气:
+curl -s "https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&daily=weather_code,temperature_2m_max,temperature_2m_min&timezone=auto&forecast_days=3"
+从 daily 里取 time、temperature_2m_max、temperature_2m_min、weather_code。
+
+weather_code 转中文:0晴 1大致晴朗 2多云 3阴 45/48雾 51/53/55毛毛雨 61/63/65雨 71/73/75雪 80/81/82阵雨 95/96/99雷暴,其余记"多云"。
+
+拿到数据后立即输出,禁止再调用任何工具。只输出一个 JSON 对象,不要解释、不要代码块标记。格式:
+{"city":"城市名","days":[{"date":"2026-10-24","max":15,"min":8,"desc":"多云"}]}
+
+规则:
+- days 取 3 天(time 数组的全部 3 项),date 用 time 的 YYYY-MM-DD,max/min 用 temperature_2m_max/min 四舍五入成整数,desc 用 weather_code 映射的中文。
+- 所有数值必须是数字类型。
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e69de29
diff --git a/public/charts/weather-1792831742774.html b/public/charts/weather-1792831742774.html
new file mode 100644
index 0000000..975aa49
--- /dev/null
+++ b/public/charts/weather-1792831742774.html
@@ -0,0 +1,14 @@
+北京·中国 未来3天温度变化
+
+
+
\ No newline at end of file
diff --git a/public/charts/weather-1792832335208.html b/public/charts/weather-1792832335208.html
new file mode 100644
index 0000000..df78488
--- /dev/null
+++ b/public/charts/weather-1792832335208.html
@@ -0,0 +1 @@
+北京 未来3天温度变化
diff --git a/public/charts/weather-1792832738877.html b/public/charts/weather-1792832738877.html
new file mode 100644
index 0000000..df78488
--- /dev/null
+++ b/public/charts/weather-1792832738877.html
@@ -0,0 +1 @@
+北京 未来3天温度变化
diff --git a/public/charts/weather-1792832846620.html b/public/charts/weather-1792832846620.html
new file mode 100644
index 0000000..df78488
--- /dev/null
+++ b/public/charts/weather-1792832846620.html
@@ -0,0 +1 @@
+北京 未来3天温度变化
diff --git a/public/charts/weather-1792834656013.html b/public/charts/weather-1792834656013.html
new file mode 100644
index 0000000..0995651
--- /dev/null
+++ b/public/charts/weather-1792834656013.html
@@ -0,0 +1 @@
+北京 未来3天温度变化
diff --git a/public/charts/weather-1792834751721.html b/public/charts/weather-1792834751721.html
new file mode 100644
index 0000000..0995651
--- /dev/null
+++ b/public/charts/weather-1792834751721.html
@@ -0,0 +1 @@
+北京 未来3天温度变化
diff --git a/public/charts/weather-1792835009151.html b/public/charts/weather-1792835009151.html
new file mode 100644
index 0000000..0995651
--- /dev/null
+++ b/public/charts/weather-1792835009151.html
@@ -0,0 +1 @@
+北京 未来3天温度变化
diff --git a/public/charts/weather-1792835024144.html b/public/charts/weather-1792835024144.html
new file mode 100644
index 0000000..0995651
--- /dev/null
+++ b/public/charts/weather-1792835024144.html
@@ -0,0 +1 @@
+北京 未来3天温度变化
diff --git a/public/charts/weather-1792835428128.html b/public/charts/weather-1792835428128.html
new file mode 100644
index 0000000..3363c32
--- /dev/null
+++ b/public/charts/weather-1792835428128.html
@@ -0,0 +1 @@
+深圳 未来3天温度变化
\ No newline at end of file
diff --git a/public/charts/weather-1792835865645.html b/public/charts/weather-1792835865645.html
new file mode 100644
index 0000000..bfa22d2
--- /dev/null
+++ b/public/charts/weather-1792835865645.html
@@ -0,0 +1 @@
+深圳 未来3天温度变化
diff --git a/public/index.html b/public/index.html
new file mode 100644
index 0000000..de0d7d7
--- /dev/null
+++ b/public/index.html
@@ -0,0 +1,234 @@
+
+
+
+
+
+ AI 天气工作流
+
+
+
+
+ 工作流:查天气 → 生成曲线图
+ 未来3天天气曲线
+ 输入城市提交后,系统自动查询未来3天天气并生成温度变化曲线图。
+
+ 正在查询并生成曲线图…
+
+
+
+
+
+
diff --git a/server.js b/server.js
new file mode 100644
index 0000000..071601f
--- /dev/null
+++ b/server.js
@@ -0,0 +1,160 @@
+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}`));