github-overview 0.1.3 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -11
- package/bin/cli.mjs +28 -26
- package/package.json +1 -1
- package/public/index.html +1136 -107
- package/src/auth.mjs +279 -0
- package/src/config.mjs +10 -4
- package/src/github.mjs +122 -34
- package/src/loop.mjs +67 -0
- package/src/npm.mjs +14 -12
- package/src/server.mjs +848 -63
- package/src/store.mjs +32 -3
- package/src/summary.mjs +270 -24
package/src/store.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { dirname } from "node:path";
|
|
|
3
3
|
import { STORE_PATH } from "./config.mjs";
|
|
4
4
|
|
|
5
5
|
// GitHub traffic only keeps 14 rolling days, so every sync appends today's row.
|
|
6
|
-
const emptySlice = () => ({ days: {}, npm: {}, releases: [], meta: {} });
|
|
6
|
+
const emptySlice = () => ({ days: {}, npm: {}, releases: [], meta: {}, stars: [] });
|
|
7
7
|
const emptyStore = () => ({ version: 2, repos: {} });
|
|
8
8
|
|
|
9
9
|
export function loadStore(path = STORE_PATH) {
|
|
@@ -40,7 +40,16 @@ export function saveStore(store, path = STORE_PATH) {
|
|
|
40
40
|
|
|
41
41
|
export function repoStore(store, key) {
|
|
42
42
|
if (!store.repos[key]) store.repos[key] = emptySlice();
|
|
43
|
-
|
|
43
|
+
const s = store.repos[key];
|
|
44
|
+
if (!Array.isArray(s.stars)) s.stars = [];
|
|
45
|
+
return s;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 每次存全量星标日期(一天可多条),不 merge 也不去重:总数和窗口净增都数这份
|
|
49
|
+
export function mergeStars(slice, dates) {
|
|
50
|
+
if (!Array.isArray(dates) || !dates.length) return slice;
|
|
51
|
+
slice.stars = dates.filter(Boolean).map((d) => String(d).slice(0, 10)).sort();
|
|
52
|
+
return slice;
|
|
44
53
|
}
|
|
45
54
|
|
|
46
55
|
export function hasRepo(store, key) {
|
|
@@ -75,6 +84,26 @@ export function series(slice, days, npmDaily = {}) {
|
|
|
75
84
|
const out = [];
|
|
76
85
|
const today = new Date();
|
|
77
86
|
today.setUTCHours(0, 0, 0, 0);
|
|
87
|
+
// 1 天窗口看最近一个完整日:GitHub 当天流量要到次日才结算,今天几乎总是 0
|
|
88
|
+
if (days === 1) {
|
|
89
|
+
const pick = (back) => {
|
|
90
|
+
const d = new Date(today);
|
|
91
|
+
d.setUTCDate(d.getUTCDate() - back);
|
|
92
|
+
return d.toISOString().slice(0, 10);
|
|
93
|
+
};
|
|
94
|
+
// 当天那一格是采集占位:四个计数全 0 说明 GitHub 还没结算,不是这天真没人来。
|
|
95
|
+
// 最多往回找 4 天,全是 0 就照旧报这一天,免得把长时间断采写成「历史上的某一天」
|
|
96
|
+
const settled = (row) => row && ["v", "u", "c", "cu"].some((f) => Number(row[f]) > 0);
|
|
97
|
+
let k = pick(1);
|
|
98
|
+
if (!slice.days[k]) k = pick(2);
|
|
99
|
+
else if (!settled(slice.days[k])) {
|
|
100
|
+
for (const back of [2, 3, 4]) {
|
|
101
|
+
if (settled(slice.days[pick(back)])) { k = pick(back); break; }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const row = slice.days[k] || {};
|
|
105
|
+
return [{ d: k, v: row.v ?? null, u: row.u ?? null, c: row.c ?? null, cu: row.cu ?? null, n: npmDaily[k] ?? slice.npm?.[k] ?? null }];
|
|
106
|
+
}
|
|
78
107
|
for (let i = days - 1; i >= 0; i--) {
|
|
79
108
|
const d = new Date(today);
|
|
80
109
|
d.setUTCDate(d.getUTCDate() - i);
|
|
@@ -86,7 +115,7 @@ export function series(slice, days, npmDaily = {}) {
|
|
|
86
115
|
u: row.u ?? null,
|
|
87
116
|
c: row.c ?? null,
|
|
88
117
|
cu: row.cu ?? null,
|
|
89
|
-
n: npmDaily[k] ?? slice.npm[k] ?? null,
|
|
118
|
+
n: npmDaily[k] ?? slice.npm?.[k] ?? null,
|
|
90
119
|
});
|
|
91
120
|
}
|
|
92
121
|
return out;
|
package/src/summary.mjs
CHANGED
|
@@ -3,21 +3,35 @@ import { readConfig, writeConfig } from "./config.mjs";
|
|
|
3
3
|
const DEFAULT_MODEL = "deepseek-chat";
|
|
4
4
|
|
|
5
5
|
export function templateSummary(ctx) {
|
|
6
|
-
const { uniques, external, stars, npmWeek, days, covered } = ctx;
|
|
6
|
+
const { uniques, views, external, stars, npmWeek, days, covered, day } = ctx;
|
|
7
7
|
const lines = [];
|
|
8
|
-
//
|
|
9
|
-
const
|
|
10
|
-
if (uniques == null) lines.push(
|
|
11
|
-
|
|
12
|
-
else lines.push(
|
|
8
|
+
// GitHub 只留 14 天,范围比历史长时说明覆盖了几天,不把 14 天的数说成 30 天
|
|
9
|
+
const n = (x) => Number(x).toLocaleString("en-US");
|
|
10
|
+
if (views == null && uniques == null) lines.push(`还没有访问记录。`);
|
|
11
|
+
// 1 天窗口的访客是这一天的去重,不是 14 天去重,别挂上 14 天
|
|
12
|
+
else if (days === 1 && day) lines.push(`${String(day).slice(5)} 浏览 ${n(views ?? 0)}${uniques ? `、访客 ${n(uniques)}(当天去重)` : ""}。`);
|
|
13
|
+
else if (!uniques && !views) lines.push(`这段时间还没有访客。`);
|
|
14
|
+
else {
|
|
15
|
+
const span = ctx.span || Math.min(days, covered || days);
|
|
16
|
+
const ud = Math.min(covered || 14, 14);
|
|
17
|
+
// 访客是 GitHub 的 14 天去重值,窗口更短时要说明跨度不同,别和浏览并列
|
|
18
|
+
lines.push(span >= ud
|
|
19
|
+
? `${span} 天 ${n(views)} 次浏览${uniques ? `、访客 ${n(uniques)}(${ud} 天去重)` : ""}。`
|
|
20
|
+
: `${span} 天 ${n(views)} 次浏览${uniques ? `;访客 ${n(uniques)} 是近 ${ud} 天去重的人数` : ""}。`);
|
|
21
|
+
}
|
|
13
22
|
const ic = external.issues.length, pc = external.pulls.length;
|
|
14
|
-
|
|
15
|
-
|
|
23
|
+
// 外部 issue/PR 是区间内新开的,标上网关时长,免得被读成全时段
|
|
24
|
+
lines.push(ic || pc ? `近 ${dataSpan(ctx)} 天外部提了 ${ic} 个 issue、${pc} 个 PR。` : `近 ${dataSpan(ctx)} 天没有外部 issue 或 PR。`);
|
|
25
|
+
const sg = ctx.starGrowth;
|
|
26
|
+
// 「同期」读者没法对上跨度,直接写清楚是当天还是近几天
|
|
27
|
+
// 一天窗口写实际日期,不写「当天」,否则和 KPI 上的日期对不上
|
|
28
|
+
const sgTxt = sg && sg.delta != null
|
|
29
|
+
? (sg.span === 1 ? `${String(sg.to || "").slice(5)} +${sg.delta}` : `近 ${sg.span} 天 +${sg.delta}`)
|
|
30
|
+
: "";
|
|
31
|
+
if (stars) lines.push(`Star 共 ${stars}${sgTxt ? `(${sgTxt})` : ""}${npmWeek ? `,npm 周下载 ${n(npmWeek)}` : ""}。`);
|
|
16
32
|
return lines;
|
|
17
33
|
}
|
|
18
34
|
|
|
19
|
-
const fmt = (n) => (n >= 10000 ? `${(n / 10000).toFixed(2).replace(/0$/, "")} 万` : String(n));
|
|
20
|
-
|
|
21
35
|
// AI 配置就两样:apikey 和 baseurl,存在本机配置里,不进仓库
|
|
22
36
|
export function readAiConfig() {
|
|
23
37
|
const cfg = readConfig();
|
|
@@ -29,44 +43,276 @@ export function saveAiConfig({ apikey, baseurl, model }) {
|
|
|
29
43
|
return writeConfig({ ...cfg, apikey: apikey ?? cfg.apikey ?? "", baseurl: baseurl ?? cfg.baseurl ?? "", model: model || cfg.model || DEFAULT_MODEL });
|
|
30
44
|
}
|
|
31
45
|
|
|
46
|
+
const mmdd = (t) => (t ? String(t).slice(5, 10) : "");
|
|
47
|
+
// 只校验千位以上/带千分位的数:小数字(3 个 PR)没几个能编错,4 位以上一错就是错一栏
|
|
48
|
+
const bigNums = (s) => [...String(s || "").matchAll(/(?<![\d.,#])(\d{1,3}(?:,\d{3})+|\d{4,})(?![\d.,])/g)].map((m) => Number(m[1].replace(/,/g, "")));
|
|
49
|
+
const detailLines = (external) => {
|
|
50
|
+
const rows = [
|
|
51
|
+
...(external.pulls || []).slice(0, 4).map((p) => `PR #${p.number} ${p.author} ${p.merged ? "已合并" : p.state} ${p.comments ?? 0} 回`),
|
|
52
|
+
...(external.issues || []).map((i) => `issue #${i.number} ${i.author} ${i.state} ${i.comments ?? 0} 回${i.state === "open" && !i.comments ? "(没回)" : ""}`),
|
|
53
|
+
];
|
|
54
|
+
return rows.length ? [`外部明细:${rows.join(";")}`] : [];
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// 实际有数据的日历跨度;covered 是「有访客去重值的天数」,缺一天会少 1,别用它当跨度
|
|
58
|
+
const dataSpan = (ctx) => Math.max(1, ctx.span ?? Math.min(ctx.days ?? 1, ctx.covered || ctx.days || 1));
|
|
59
|
+
|
|
60
|
+
// 用户数没有直接口径,只能拿几个独立信号折算后交叉验证:
|
|
61
|
+
// GitHub 只给 14 天去重访客;npm 只给下载次数(含更新、重装、多机、CI、镜像)。
|
|
62
|
+
// 把两路各自折成人数区间,再把中位平均成「大约多少人」,并保留区间,避免给出假的精确值。
|
|
63
|
+
export function userEstimate({ uniques, npmWeek, covered, uniqSpan, stars } = {}) {
|
|
64
|
+
// 1 天窗口的访客是当天去重,不是 14 天去重:折算用的跨度要跟着这个数走
|
|
65
|
+
const span = Math.min(Math.max(1, Number(uniqSpan) || Number(covered) || 14), 14);
|
|
66
|
+
const u = Number(uniques) > 0 ? Number(uniques) : null;
|
|
67
|
+
const npm = Number(npmWeek) > 0 ? Number(npmWeek) : null;
|
|
68
|
+
// 单日去重不能按「每天都来」乘 30:一天的人只说明这一天有这么多人,
|
|
69
|
+
// 上面按一周来一次估,下面用这个跨度折到一个月
|
|
70
|
+
const gh = u ? { low: Math.round(u), high: Math.round((u * (span === 1 ? 7 : 30)) / span) } : null;
|
|
71
|
+
// 3–10 次/人/周:一个开发者一周内更新、重装、多机各下载几次,CI 和镜像还会再放大
|
|
72
|
+
const np = npm ? { low: Math.round(npm / 10), high: Math.round(npm / 3) } : null;
|
|
73
|
+
if (!gh && !np) return null;
|
|
74
|
+
const mid = (r) => (r.low + r.high) / 2;
|
|
75
|
+
const round = (x, step) => Math.round(x / step) * step;
|
|
76
|
+
// npm 是下载次数,不是人:窗口比一周短时它说不清这段时间有多少人,
|
|
77
|
+
// 只能当旁证。人数结论以访客那一路为准,下载那一路单独写成下载口径。
|
|
78
|
+
const blend = span >= 7 && gh && np;
|
|
79
|
+
const ranges = blend ? [gh, np] : gh ? [gh] : [np];
|
|
80
|
+
const point = round(ranges.reduce((a, r) => a + mid(r), 0) / ranges.length, 100);
|
|
81
|
+
return {
|
|
82
|
+
point,
|
|
83
|
+
low: round(Math.min(...ranges.map((r) => r.low)), 100),
|
|
84
|
+
high: round(Math.max(...ranges.map((r) => r.high)), 100),
|
|
85
|
+
gh,
|
|
86
|
+
npm: np,
|
|
87
|
+
blended: blend,
|
|
88
|
+
span,
|
|
89
|
+
stars: Number(stars) > 0 ? Number(stars) : null,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const estimateLine = (ctx) => {
|
|
94
|
+
const e = userEstimate(ctx);
|
|
95
|
+
if (!e) return [];
|
|
96
|
+
const n = (x) => Number(x).toLocaleString("en-US");
|
|
97
|
+
const parts = [];
|
|
98
|
+
if (e.gh) parts.push(e.span === 1
|
|
99
|
+
? `GitHub ${mmdd(ctx.day)} 当天去重访客 ${n(e.gh.low)} 人,一天的数据只能说明这一天,按一周到访一次估一个月大约 ${n(e.gh.low)} 到 ${n(e.gh.high)} 人`
|
|
100
|
+
: `GitHub 近 ${e.span} 天去重访客 ${n(e.gh.low)} 人,按同一批人在这段时间到访折算到一个月约 ${n(e.gh.high)} 人`);
|
|
101
|
+
if (e.npm) parts.push(e.blended
|
|
102
|
+
? `npm 周下载 ${n(ctx.npmWeek)} 次,按每人每周 3 到 10 次下载折算(更新、重装、多机、CI 和镜像重复都已含在这个倍率里)约 ${n(e.npm.low)} 到 ${n(e.npm.high)} 人`
|
|
103
|
+
// 窗口不到一周时下载量对应不上这些人,只能说明下载规模,不能当人数
|
|
104
|
+
: `npm 周下载 ${n(ctx.npmWeek)} 次(这是整周的下载次数,不等于这段时间有多少人在用),只能说明下载规模,不并进上面的人数`);
|
|
105
|
+
return [`用户规模估算(问用户数、多少人在用时用这一条,先给约数再给依据,不要逐个数字复述):约 ${n(e.point)} 人,区间 ${n(e.low)} 到 ${n(e.high)} 人。依据:${parts.join(";")}${e.stars ? `;stars ${n(e.stars)} 只作旁证,不单独换算` : ""}。这是估算,不能回答算不出来,也不能把 npm 下载次数直接说成人数`];
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const factLines = (ctx) =>
|
|
109
|
+
[
|
|
110
|
+
`范围:${ctx.scope || "本仓库"}。issue/PR/发版按图上 ${ctx.span ?? ctx.days} 天`,
|
|
111
|
+
ctx.day
|
|
112
|
+
? `访客是 ${mmdd(ctx.day)} 当天的去重人数(不是近 14 天):${ctx.uniques ?? "未知"} 人`
|
|
113
|
+
: `访客是近 ${Math.min(ctx.covered || 14, 14)} 天的去重人数(GitHub 只给这个长度):${ctx.uniques ?? "未知"} 人`,
|
|
114
|
+
...(dataSpan(ctx) < (ctx.span ?? ctx.days)
|
|
115
|
+
? [`图上选了 ${ctx.span ?? ctx.days} 天,但只有 ${dataSpan(ctx)} 天有数据;浏览 ${ctx.views ?? "未知"} 次、issue/PR 都只算这 ${dataSpan(ctx)} 天,不能说成近 ${ctx.span ?? ctx.days} 天`]
|
|
116
|
+
: [`图上的区间是 ${ctx.span ?? ctx.days} 天,区间内浏览 ${ctx.views ?? "未知"} 次;浏览比访客多,因为同一个人可以看多次`]),
|
|
117
|
+
`这两段的时间长度不同,写的时候分开说,不要合并成同一个「近 N 天」`,
|
|
118
|
+
`漏斗是固定近 ${Math.min(ctx.covered || 14, 14)} 天的一段转化;页面和来源是各仓最近一次同步拿到的热门榜,GitHub 不给这两个数字的时间跨度,引用时写「最近一次快照」,不要挂上「近 N 天」`,
|
|
119
|
+
...(ctx.topRepos ? [`全站 ${ctx.allTotal ?? "未知"} 人;最热:${ctx.topRepos.map((r) => `${r.name}(${r.u})`).join("、")}`] : []),
|
|
120
|
+
`近 ${dataSpan(ctx)} 天里外部 issue ${ctx.external.issues.length} 个、PR ${ctx.external.pulls.length} 个(只是这段时间新开的,不是全部)`,
|
|
121
|
+
...detailLines(ctx.external),
|
|
122
|
+
// 浏览和下载都取同一段 14 天,别一个写「近 14 天」一个写「周」
|
|
123
|
+
...(ctx.funnel ? [`漏斗(浏览和下载都是近 ${Math.min(ctx.covered || 14, 14)} 天):浏览 ${ctx.funnel.views ?? "—"} → 仓库主页 ${ctx.funnel.home ?? "—"} → npm 下载 ${ctx.funnel.npm == null ? "—(这个仓没有 npm 包)" : ctx.funnel.npm}`] : []),
|
|
124
|
+
...(ctx.impacts?.length ? [`各仓最近发版日均浏览:${ctx.impacts.slice(0, 6).map((i) => `${i.name} ${i.before?.views?.avg ?? "—"}→${i.after?.views?.avg ?? "—"}`).join("、")}`] : []),
|
|
125
|
+
...(ctx.impact ? [`最近发版 ${ctx.impact.name ? ctx.impact.name + " " : ""}${ctx.impact.version}(${mmdd(ctx.impact.at)}):前 7 天日均浏览 ${ctx.impact.before.views?.avg ?? "—"}、下载 ${ctx.impact.before.npm?.avg ?? "—"},后 7 天 ${ctx.impact.after.views?.avg ?? "—"}、${ctx.impact.after.npm?.avg ?? "—"}`] : []),
|
|
126
|
+
`stars 合计 ${ctx.stars}(当前总数),近 ${ctx.starGrowth?.span ?? ctx.days} 天新增 ${ctx.starGrowth?.delta ?? "—"},总数和新增要分开说,新增要带上这几天,新增恰好等于总数时只报一次`,
|
|
127
|
+
`npm 周下载 ${ctx.npmWeek ?? "未关联 npm"}`,
|
|
128
|
+
...estimateLine(ctx),
|
|
129
|
+
`最热页面(各仓最近一次快照,不是图上这段时间):${(ctx.paths || []).slice(0, 3).map((p) => `${p.p}(${p.n})`).join("、") || "暂无"}`,
|
|
130
|
+
].join("\n");
|
|
131
|
+
|
|
132
|
+
// AI 摘要只允许引用给定事实里的数字:对不上就退回模板,免得出现「个仓库」「约 1.2 万」这种错数
|
|
133
|
+
const near = (d, a) => typeof a === "number" && Math.abs(d - a) / Math.max(Math.abs(a), 1) < 0.08;
|
|
134
|
+
function aiLinesTrusted(lines, ctx) {
|
|
135
|
+
const allowed = [
|
|
136
|
+
ctx.uniques, ctx.views, ctx.days, ctx.covered, Math.min(ctx.covered || 14, 14),
|
|
137
|
+
ctx.stars, ctx.npmWeek, ctx.allTotal, ctx.funnel?.views, ctx.funnel?.home, ctx.funnel?.npm,
|
|
138
|
+
...(ctx.topRepos || []).map((r) => r.u),
|
|
139
|
+
ctx.starGrowth?.span, ctx.starGrowth?.delta,
|
|
140
|
+
ctx.external?.issues?.length, ctx.external?.pulls?.length,
|
|
141
|
+
// 明细里的编号、发版前后的日均、最热页面的次数,都会原样出现在 prompt 里
|
|
142
|
+
...(ctx.external?.issues || []).map((i) => i.number),
|
|
143
|
+
...(ctx.external?.pulls || []).map((p) => p.number),
|
|
144
|
+
...(ctx.impacts || []).flatMap((i) => [i.before?.views?.avg, i.after?.views?.avg, i.before?.npm?.avg, i.after?.npm?.avg]),
|
|
145
|
+
ctx.impact?.before?.views?.avg, ctx.impact?.after?.views?.avg,
|
|
146
|
+
ctx.impact?.before?.npm?.avg, ctx.impact?.after?.npm?.avg,
|
|
147
|
+
...(ctx.paths || []).slice(0, 3).map((p) => p.n),
|
|
148
|
+
...[userEstimate(ctx)].filter(Boolean).flatMap((e) => [e.point, e.low, e.high, e.gh?.low, e.gh?.high, e.npm?.low, e.npm?.high]),
|
|
149
|
+
].filter((v) => typeof v === "number");
|
|
150
|
+
for (const line of lines) {
|
|
151
|
+
if (/^[^\d]{0,4}个仓库/.test(line.trim())) return false;
|
|
152
|
+
// 千分位要整体当一个数,否则 9,382 会被拆成 9 和 382 再被拒
|
|
153
|
+
for (const m of line.matchAll(/(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)\s*(万|人|次|条|个)?/g)) {
|
|
154
|
+
const v = Number(String(m[1]).replace(/,/g, "")) * (m[2] === "万" ? 10000 : 1);
|
|
155
|
+
if (v < 200) continue;
|
|
156
|
+
if (!allowed.some((a) => near(v, a))) return false;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const ENDPOINT = (baseurl) => baseurl.replace(/\/$/, "") + "/chat/completions";
|
|
163
|
+
|
|
164
|
+
export async function askQuestion(ctx, question, tools = []) {
|
|
165
|
+
const { apikey, baseurl, model } = readAiConfig();
|
|
166
|
+
if (!apikey || !baseurl) return { source: "none", answer: "先在配置里填 Base URL 和 API Key。" };
|
|
167
|
+
const url = ENDPOINT(baseurl);
|
|
168
|
+
const messages = [
|
|
169
|
+
{
|
|
170
|
+
role: "system",
|
|
171
|
+
content:
|
|
172
|
+
"你是这个 GitHub 数据看板的助手。下面给了当前范围已有的数据,需要更多的就用工具查,然后再回答。" +
|
|
173
|
+
"说清楚数字和结论,可以分析、比较、估算,估算要说明依据。" +
|
|
174
|
+
"数据里没有的直说没有,不要编造。回答用纯文本,不用 markdown,控制在 3 句以内。" +
|
|
175
|
+
"数字只能引用上面事实和工具结果里出现过的原值,不要自己加总、换算或取整;日期和跨度也要和事实一致。" +
|
|
176
|
+
"事实里的「范围」就是问题限定的范围,不要换成别的范围来说。" +
|
|
177
|
+
"访客数口径是去重真人,克隆另算,机器人流量和发布峰值已经排除在外部反馈之外。" +
|
|
178
|
+
"问到用户数、多少人在用、用户规模时,用事实里的用户规模估算:第一句给约数,第二句给依据(GitHub 去重访客折算、npm 下载按每人每周 3 到 10 次折算扣掉重复)并说明是估算;不要罗列每个数字,不要回答算不出来,也不要把 npm 下载次数直接说成人数。",
|
|
179
|
+
},
|
|
180
|
+
{ role: "user", content: `${factLines(ctx)}\n\n问题:${question}` },
|
|
181
|
+
];
|
|
182
|
+
const toolDefs = tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.parameters || { type: "object", properties: {} } } }));
|
|
183
|
+
const toolText = [];
|
|
184
|
+
const runTool = async (name, args) => {
|
|
185
|
+
const t = tools.find((x) => x.name === name);
|
|
186
|
+
if (!t) return "没有这个工具";
|
|
187
|
+
try {
|
|
188
|
+
const out = await t.run(args || {});
|
|
189
|
+
const full = typeof out === "string" ? out : JSON.stringify(out ?? null);
|
|
190
|
+
toolText.push(full);
|
|
191
|
+
return full.slice(0, 2600);
|
|
192
|
+
} catch (e) {
|
|
193
|
+
return "工具出错:" + String(e.message || e).slice(0, 120);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const call = async (msgs, withTools) => {
|
|
197
|
+
const body = { model, temperature: 0.2, max_tokens: 1400, messages: msgs, ...(withTools && toolDefs.length ? { tools: toolDefs } : {}) };
|
|
198
|
+
const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${apikey}` }, body: JSON.stringify(body), signal: AbortSignal.timeout(28000) });
|
|
199
|
+
if (!res.ok) throw new Error(String(res.status));
|
|
200
|
+
return (await res.json())?.choices?.[0]?.message;
|
|
201
|
+
};
|
|
202
|
+
try {
|
|
203
|
+
let msg;
|
|
204
|
+
try {
|
|
205
|
+
msg = await call(messages, true);
|
|
206
|
+
} catch {
|
|
207
|
+
msg = await call(messages, false);
|
|
208
|
+
}
|
|
209
|
+
for (let i = 0; i < 2 && msg?.tool_calls?.length; i++) {
|
|
210
|
+
messages.push({ role: "assistant", content: msg.content || "", tool_calls: msg.tool_calls });
|
|
211
|
+
for (const c of msg.tool_calls) {
|
|
212
|
+
let args = {};
|
|
213
|
+
try {
|
|
214
|
+
args = JSON.parse(c.function?.arguments || "{}");
|
|
215
|
+
} catch (e) {}
|
|
216
|
+
messages.push({ role: "tool", tool_call_id: c.id, content: await runTool(c.function?.name, args) });
|
|
217
|
+
}
|
|
218
|
+
msg = await call(messages, true);
|
|
219
|
+
}
|
|
220
|
+
let text = (msg?.content || "").trim();
|
|
221
|
+
if (!text) {
|
|
222
|
+
const again = await call(messages.concat([{ role: "user", content: "直接回答上面的问题,不要用工具。" }]), false).catch(() => null);
|
|
223
|
+
text = (again?.content || "").trim();
|
|
224
|
+
}
|
|
225
|
+
if (!text) return { source: "error", answer: "AI 回了空内容。" };
|
|
226
|
+
const allowed = new Set();
|
|
227
|
+
const eat = (str) => { for (const n of bigNums(str)) allowed.add(n); };
|
|
228
|
+
messages.forEach((m) => eat(String(m.content || "")));
|
|
229
|
+
toolText.forEach(eat);
|
|
230
|
+
eat(question);
|
|
231
|
+
const grounded = (t) => bigNums(t).every((n) => allowed.has(n));
|
|
232
|
+
if (!grounded(text)) {
|
|
233
|
+
const again = await call(messages.concat([
|
|
234
|
+
{ role: "assistant", content: text },
|
|
235
|
+
{ role: "user", content: "上面的数字里有事实中没出现过的。只引用事实里的原值,不要加总、换算或取整;没有的数字就说没有。重新回答,3 句以内。" },
|
|
236
|
+
]), false).catch(() => null);
|
|
237
|
+
const t2 = (again?.content || "").trim();
|
|
238
|
+
if (t2 && grounded(t2)) text = t2;
|
|
239
|
+
else {
|
|
240
|
+
const lines = factLines(ctx).split("\n").filter((l) => !/这两段|外部明细|页面、来源/.test(l)).slice(0, 3);
|
|
241
|
+
return { source: "data", answer: `这轮回答的数字对不上,先按数据说:${lines.join(";")}。` };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return { source: "ai", answer: text.replace(/\s+/g, " ").slice(0, 400) };
|
|
245
|
+
} catch (e) {
|
|
246
|
+
const slow = e?.name === "TimeoutError" || /abort|timeout/i.test(e?.message || "");
|
|
247
|
+
return { source: "error", answer: slow ? "模型超时,再问一次。" : "模型没答,再问一次。" };
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
32
251
|
export async function aiSummary(ctx) {
|
|
33
252
|
const { apikey, baseurl, model } = readAiConfig();
|
|
34
|
-
if (!apikey || !baseurl) return { source: "
|
|
35
|
-
const url = baseurl
|
|
36
|
-
const facts =
|
|
37
|
-
`窗口:近 ${ctx.days} 天`,
|
|
38
|
-
`访客:${ctx.uniques ?? "未知"} 人,浏览 ${ctx.views ?? "未知"} 次`,
|
|
39
|
-
`外部 issue ${ctx.external.issues.length} 个,外部 PR ${ctx.external.pulls.length} 个`,
|
|
40
|
-
`stars ${ctx.stars},npm 周下载 ${ctx.npmWeek ?? "未知"}`,
|
|
41
|
-
`最热页面:${(ctx.paths || []).slice(0, 3).map((p) => `${p.p}(${p.n})`).join("、")}`,
|
|
42
|
-
].join("\n");
|
|
253
|
+
if (!apikey || !baseurl) return { source: "none", lines: templateSummary(ctx) };
|
|
254
|
+
const url = ENDPOINT(baseurl);
|
|
255
|
+
const facts = factLines(ctx);
|
|
43
256
|
const body = {
|
|
44
257
|
model,
|
|
45
258
|
temperature: 0.3,
|
|
46
|
-
|
|
259
|
+
// 推理模型会把 token 花在思考上,留够正文的额度,不然回来是空串
|
|
260
|
+
max_tokens: 3000,
|
|
47
261
|
messages: [
|
|
48
262
|
{
|
|
49
263
|
role: "system",
|
|
50
264
|
content:
|
|
51
265
|
"你在给一个 GitHub 仓库的数据看板写摘要。只写 2 到 3 句话,每句不超过 26 个汉字。" +
|
|
52
266
|
"只讲结论和事实:大概多少人来看、外部给了什么反馈、仓库涨了多少。" +
|
|
267
|
+
"范围天数用给定数据里的那个数字,不要换成年、月或别的时间;数据覆盖天数少于范围天数时,两句之内要写明覆盖了多少天。" +
|
|
53
268
|
"不要解释流量为什么涨,不要提机器、机器人、镜像、CI、发版带来的流量,不要用「图 1」这种编号引用。" +
|
|
54
269
|
"不要重复用户已经看到的数字之外的分析;不要用「独立」「重复」这类词。直接输出正文,不要列表,不要标题。",
|
|
55
270
|
},
|
|
56
271
|
{ role: "user", content: facts },
|
|
57
272
|
],
|
|
58
273
|
};
|
|
59
|
-
|
|
274
|
+
const send = async (payload) => {
|
|
60
275
|
const res = await fetch(url, {
|
|
61
276
|
method: "POST",
|
|
62
277
|
headers: { "content-type": "application/json", authorization: `Bearer ${apikey}` },
|
|
63
|
-
body: JSON.stringify(
|
|
278
|
+
body: JSON.stringify(payload),
|
|
279
|
+
// 推理模型写两三句话要几十秒,给足时间,不然每次都被 abort 退回模板
|
|
280
|
+
signal: AbortSignal.timeout(55000),
|
|
64
281
|
});
|
|
65
282
|
if (!res.ok) throw new Error(`${res.status}`);
|
|
66
283
|
const data = await res.json();
|
|
67
|
-
|
|
284
|
+
return (data?.choices?.[0]?.message?.content || "").trim();
|
|
285
|
+
};
|
|
286
|
+
try {
|
|
287
|
+
let text = await send(body);
|
|
288
|
+
if (!text) {
|
|
289
|
+
text = await send({
|
|
290
|
+
...body,
|
|
291
|
+
max_tokens: 4000,
|
|
292
|
+
messages: [...body.messages, { role: "user", content: "用两句话总结上面这些数字,直接给正文。" }],
|
|
293
|
+
});
|
|
294
|
+
}
|
|
68
295
|
if (!text) throw new Error("empty");
|
|
69
|
-
|
|
296
|
+
// 一天窗口里「1 天内浏览」「1 天新增」既不自然,也和 KPI 上的日期对不上,换成具体日期
|
|
297
|
+
if (ctx.days === 1 && ctx.day) {
|
|
298
|
+
const dd = String(ctx.day).slice(5);
|
|
299
|
+
text = text.replace(/(?<![\d])1\s*天内?/g, dd);
|
|
300
|
+
text = text.replace(/近?\s*14\s*天(?=\s*访客)/g, dd);
|
|
301
|
+
}
|
|
302
|
+
// 四位以上整数补千分位,跟界面上的数字写法一致
|
|
303
|
+
text = text.replace(/\b\d{4,}\b/g, (m) => Number(m).toLocaleString("en-US"));
|
|
304
|
+
// 汉字和数字之间留空格,跟界面上的排版一致
|
|
305
|
+
text = text.replace(/([\u4e00-\u9fa5])(\d)/g, "$1 $2").replace(/(\d)([\u4e00-\u9fa5])/g, "$1 $2");
|
|
306
|
+
text = text.replace(/([\u4e00-\u9fa5])([A-Za-z])/g, "$1 $2").replace(/([A-Za-z])([\u4e00-\u9fa5])/g, "$1 $2");
|
|
307
|
+
// issue8 / PR5 这种也要断开,但版本号、仓库名里的数字不动
|
|
308
|
+
text = text.replace(/\b(issues?|PRs?|stars|npm)(?=\d)/g, "$1 ");
|
|
309
|
+
// 「近 14 天访客…,7 天浏览…」是两个跨度,断成两句,别让人当成同期
|
|
310
|
+
text = text.replace(/,(?=近?\s*\d+\s*天内?[^。;]{0,2}(?:浏览|访客))/g, "。");
|
|
311
|
+
// 去掉列表前缀时要留住开头的数字,「14 天访客」不能被当成「14. 」删掉
|
|
312
|
+
// 模型被长度截断时末句会悬空,别让面板停在「8,403 次,」
|
|
313
|
+
text = text.replace(/[,、;:,]+\s*$/, "").replace(/([^。!?!?\s])$/, "$1。");
|
|
314
|
+
const lines = text.split(/\n+/).map((s) => s.replace(/^\s*(?:[-*•]\s+|\d{1,2}[.、)]\s+)/, "").trim()).filter(Boolean).slice(0, 3);
|
|
315
|
+
if (!lines.length || !aiLinesTrusted(lines, ctx)) return { source: "template", lines: templateSummary(ctx), error: "checked", raw: lines };
|
|
70
316
|
return { source: "ai", lines, model };
|
|
71
317
|
} catch (e) {
|
|
72
318
|
return { source: "template", lines: templateSummary(ctx), error: String(e.message || e) };
|