dsh-dpharness 0.6.3 → 0.6.5
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 +28 -0
- package/lib/changelog.js +22 -0
- package/lib/client.js +829 -69
- package/lib/index.js +237 -2
- package/lib/usage.js +307 -0
- package/package.json +6 -1
package/lib/index.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* GET /api/dpharness/updates
|
|
11
11
|
* GET /api/dpharness/postinstall?pkg=<pkg>&via=<local|market>&at=<epochMs>
|
|
12
12
|
* POST /api/dpharness/event → relayed to https://dpharness.com/api/track/event
|
|
13
|
+
* POST /api/dpharness/subscribe → relayed to https://dpharness.com/api/subscribe
|
|
13
14
|
* POST /api/dpharness/install → spawns `dsh plugin --profile <p> add <pkg>`
|
|
14
15
|
* GET /api/dpharness/install → progress of the one in-flight install job
|
|
15
16
|
*
|
|
@@ -47,7 +48,7 @@ export const name = "dpharness";
|
|
|
47
48
|
/** The dsh web server service used to register HTTP routes. */
|
|
48
49
|
export const inject = ["webServer"];
|
|
49
50
|
|
|
50
|
-
export const VERSION = "0.6.
|
|
51
|
+
export const VERSION = "0.6.5";
|
|
51
52
|
|
|
52
53
|
/**
|
|
53
54
|
* 本插件在 npm 上的包名 —— 与 dsh 的插件 id(上面的 `name = "dpharness"`)**不是一回事**,
|
|
@@ -137,6 +138,20 @@ const BEST_UPSTREAM = "https://dpharness.com/api/best";
|
|
|
137
138
|
const SETS_UPSTREAM = "https://dpharness.com/api/sets";
|
|
138
139
|
const SITE = "https://dpharness.com";
|
|
139
140
|
const TRACK = "https://dpharness.com/api/track/event";
|
|
141
|
+
/**
|
|
142
|
+
* Newsletter subscription relay target.
|
|
143
|
+
*
|
|
144
|
+
* The site's `/api/subscribe` is double opt-in: it stores the address as
|
|
145
|
+
* pending and sends the confirmation mail itself. This host only forwards the
|
|
146
|
+
* address — it never stores it. It has to be a local route because the site
|
|
147
|
+
* sends no CORS headers (measured; same reason the event relay exists).
|
|
148
|
+
*/
|
|
149
|
+
const SUBSCRIBE = "https://dpharness.com/api/subscribe";
|
|
150
|
+
const SUBSCRIBE_TIMEOUT_MS = 10 * 1000;
|
|
151
|
+
const SUBSCRIBE_WINDOW_MS = 60 * 1000;
|
|
152
|
+
/** Kept tight on purpose: a stuck UI must not be able to spray the site. */
|
|
153
|
+
const SUBSCRIBE_MAX_PER_WINDOW = 5;
|
|
154
|
+
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
140
155
|
const DEFAULT_TAKE = 30;
|
|
141
156
|
const MAX_TAKE = 100;
|
|
142
157
|
const CACHE_TTL_MS = 5 * 60 * 1000;
|
|
@@ -703,6 +718,8 @@ let bestCache = { at: 0, value: null };
|
|
|
703
718
|
/** /api/sets 单键缓存(套装同样每月才同步一次,缓存策略与 /best 一致) */
|
|
704
719
|
let setsCache = { at: 0, value: null };
|
|
705
720
|
let eventWindow = { startedAt: 0, count: 0 };
|
|
721
|
+
/* 订阅走独立窗口:与埋点共用预算会让「点了一次订阅」挤掉后续埋点(反之亦然) */
|
|
722
|
+
let subscribeWindow = { startedAt: 0, count: 0 };
|
|
706
723
|
|
|
707
724
|
/**
|
|
708
725
|
* 分类中文名 —— 抄自站点 `lib/category.ts` 的 `CATEGORY_LABEL`(2026-09-17)。
|
|
@@ -1062,14 +1079,119 @@ async function fetchSets() {
|
|
|
1062
1079
|
}
|
|
1063
1080
|
}
|
|
1064
1081
|
|
|
1082
|
+
/**
|
|
1083
|
+
* 「周榜」两条线(站点 /api/board/{top,installs},2026-10-20 新增的只读接口)。
|
|
1084
|
+
*
|
|
1085
|
+
* ── 两个榜不是一回事,**不要合并**──────────────────────────────────────────
|
|
1086
|
+
* top = 精选插件 Top 榜:按 npm **全网周下载量**排序,20 条,周一落期次快照
|
|
1087
|
+
* installs = 真装机周榜:按站内 `copy_install` **去重访客**排序,30 条,滚动 7 天
|
|
1088
|
+
* 前者衡量"全网有多热",后者衡量"本站真有人在装"。两者差好几个数量级,
|
|
1089
|
+
* 放在同一个榜单里用户会互相对照并得出错误结论(站点侧同样是两个独立页面)。
|
|
1090
|
+
*
|
|
1091
|
+
* ── 字段为什么要重新拼 ─────────────────────────────────────────────────────
|
|
1092
|
+
* 两条上游的条目形状不同:
|
|
1093
|
+
* · top 直接给 `installCheck { status, pkgName }`(与 catalog 同形);
|
|
1094
|
+
* · installs 给的是扁平 `installStatus` + `pkgName`。
|
|
1095
|
+
* 若不在这里归一,`slim()` 就要长出第二个分支 —— 而它承载的是「命令该用包名
|
|
1096
|
+
* 还是 owner/repo」这条唯一口径。⇒ 归一放在本层,`slim()` 一行不改。
|
|
1097
|
+
*
|
|
1098
|
+
* ⚠️ 份额(sharePct)**有意不透传**:站内复制安装也计入本榜口径,榜进插件后
|
|
1099
|
+
* 上榜条目曝光更多、复制更多,份额会自我强化。卡片只给「本周 / 上周 / 增减」,
|
|
1100
|
+
* 足以判断趋势,不把百分比摊到用户面前。
|
|
1101
|
+
*/
|
|
1102
|
+
const BOARD_UPSTREAM = `${SITE}/api/board`;
|
|
1103
|
+
/** 两个榜的缓存:top 一周才变(5 分钟足够),installs 与站点侧 60s 缓存对齐 */
|
|
1104
|
+
const BOARD_TTL_MS = { top: 300_000, installs: 60_000 };
|
|
1105
|
+
const boardCache = { top: { at: 0, value: null }, installs: { at: 0, value: null } };
|
|
1106
|
+
|
|
1107
|
+
async function fetchBoard(kind) {
|
|
1108
|
+
const now = Date.now();
|
|
1109
|
+
const slot = boardCache[kind];
|
|
1110
|
+
if (slot.value && now - slot.at < BOARD_TTL_MS[kind]) {
|
|
1111
|
+
return { ...slot.value, cached: true, fetchedAt: slot.at };
|
|
1112
|
+
}
|
|
1113
|
+
const controller = new AbortController();
|
|
1114
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
1115
|
+
try {
|
|
1116
|
+
const response = await fetch(`${BOARD_UPSTREAM}/${kind}`, {
|
|
1117
|
+
headers: { accept: "application/json", "user-agent": `dsh-dpharness/${VERSION}` },
|
|
1118
|
+
signal: controller.signal,
|
|
1119
|
+
});
|
|
1120
|
+
// 站点接口尚未发版时是 404 —— 让调用方拿到明确的状态码,不要伪装成"空榜单"
|
|
1121
|
+
if (!response.ok) throw new Error(`upstream HTTP ${response.status}`);
|
|
1122
|
+
const body = await response.json();
|
|
1123
|
+
const installed = installedMap();
|
|
1124
|
+
const items = (Array.isArray(body && body.items) ? body.items : []).map((raw) => {
|
|
1125
|
+
/* installs 侧的形状归一:扁平 installStatus → installCheck 对象。
|
|
1126
|
+
只搬事实(pkgName 原样带过来,不做 pass 过滤),是否可信由 slim() 判定。 */
|
|
1127
|
+
const normalized =
|
|
1128
|
+
raw && raw.installCheck === undefined
|
|
1129
|
+
? { ...raw, installCheck: raw.pkgName ? { status: raw.installStatus || null, pkgName: raw.pkgName } : null }
|
|
1130
|
+
: raw;
|
|
1131
|
+
const shaped = slim(normalized);
|
|
1132
|
+
const extra =
|
|
1133
|
+
kind === "top"
|
|
1134
|
+
? { rank: Number(raw && raw.rank) || null, weekly: Number(raw && raw.weeklyDownloads) || 0 }
|
|
1135
|
+
: {
|
|
1136
|
+
rank: null,
|
|
1137
|
+
weekly: null,
|
|
1138
|
+
thisUv: Number(raw && raw.thisUv) || 0,
|
|
1139
|
+
prevUv: Number(raw && raw.prevUv) || 0,
|
|
1140
|
+
delta: Number(raw && raw.delta) || 0,
|
|
1141
|
+
};
|
|
1142
|
+
return Object.assign(shaped, extra, { installed: installedOf(shaped, installed) });
|
|
1143
|
+
});
|
|
1144
|
+
const value =
|
|
1145
|
+
kind === "top"
|
|
1146
|
+
? {
|
|
1147
|
+
total: items.length,
|
|
1148
|
+
period: (body && body.period) || null,
|
|
1149
|
+
periodNo: (body && body.periodNo) || null,
|
|
1150
|
+
weekStart: (body && body.weekStart) || null,
|
|
1151
|
+
capturedAt: (body && body.capturedAt) || null,
|
|
1152
|
+
dataFrom: (body && body.dataFrom) || null,
|
|
1153
|
+
dataTo: (body && body.dataTo) || null,
|
|
1154
|
+
/* true = 当期快照还没回填,此次是实时口径(页面不得显示"第 N 期") */
|
|
1155
|
+
live: !!(body && body.isLive),
|
|
1156
|
+
eligibleCount: Number(body && body.eligibleCount) || 0,
|
|
1157
|
+
totalPlugins: Number(body && body.totalPlugins) || 0,
|
|
1158
|
+
items,
|
|
1159
|
+
}
|
|
1160
|
+
: {
|
|
1161
|
+
total: items.length,
|
|
1162
|
+
windowStart: (body && body.windowStart) || null,
|
|
1163
|
+
prevWindowStart: (body && body.prevWindowStart) || null,
|
|
1164
|
+
totalUv: Number(body && body.totalUv) || 0,
|
|
1165
|
+
totalPrevUv: Number(body && body.totalPrevUv) || 0,
|
|
1166
|
+
mappedUv: Number(body && body.mappedUv) || 0,
|
|
1167
|
+
items,
|
|
1168
|
+
};
|
|
1169
|
+
boardCache[kind] = { at: Date.now(), value };
|
|
1170
|
+
return { ...value, cached: false, fetchedAt: Date.now() };
|
|
1171
|
+
} finally {
|
|
1172
|
+
clearTimeout(timer);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1065
1176
|
function withinEventBudget() {
|
|
1066
|
-
const now = Date.now();
|
|
1177
|
+
const now = Date.now();
|
|
1178
|
+
if (now - eventWindow.startedAt > EVENT_WINDOW_MS) {
|
|
1067
1179
|
eventWindow = { startedAt: now, count: 0 };
|
|
1068
1180
|
}
|
|
1069
1181
|
eventWindow.count += 1;
|
|
1070
1182
|
return eventWindow.count <= EVENT_MAX_PER_WINDOW;
|
|
1071
1183
|
}
|
|
1072
1184
|
|
|
1185
|
+
/** Same sliding-window shape as withinEventBudget, separate budget. */
|
|
1186
|
+
function withinSubscribeBudget() {
|
|
1187
|
+
const now = Date.now();
|
|
1188
|
+
if (now - subscribeWindow.startedAt > SUBSCRIBE_WINDOW_MS) {
|
|
1189
|
+
subscribeWindow = { startedAt: now, count: 0 };
|
|
1190
|
+
}
|
|
1191
|
+
subscribeWindow.count += 1;
|
|
1192
|
+
return subscribeWindow.count <= SUBSCRIBE_MAX_PER_WINDOW;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1073
1195
|
const clampText = (value, max) => (typeof value === "string" ? value.slice(0, max) : "");
|
|
1074
1196
|
|
|
1075
1197
|
/**
|
|
@@ -1646,6 +1768,50 @@ export function apply(ctx) {
|
|
|
1646
1768
|
}
|
|
1647
1769
|
});
|
|
1648
1770
|
|
|
1771
|
+
/**
|
|
1772
|
+
* 「周榜」:站点两条榜单线的同源数据(精选 Top 榜 / 真装机周榜)。
|
|
1773
|
+
*
|
|
1774
|
+
* kind 必填且白名单化:不给默认值 —— 默认成任何一个都会让
|
|
1775
|
+
* 「我明明点的是装机榜,怎么显示下载量」变成难查的静默错误。
|
|
1776
|
+
* 非法 kind 返回 400 + 允许值,而不是回落 top。
|
|
1777
|
+
*/
|
|
1778
|
+
registerRoute(ctx, "/api/dpharness/board", async (req, res) => {
|
|
1779
|
+
if (req.method !== "GET") {
|
|
1780
|
+
res.writeHead(405, { allow: "GET" });
|
|
1781
|
+
res.end();
|
|
1782
|
+
return;
|
|
1783
|
+
}
|
|
1784
|
+
const kind = (readParams(req).get("kind") || "").trim();
|
|
1785
|
+
if (kind !== "top" && kind !== "installs") {
|
|
1786
|
+
sendJson(res, 400, {
|
|
1787
|
+
ok: false,
|
|
1788
|
+
error: "kind 必须是 top 或 installs",
|
|
1789
|
+
allowed: ["top", "installs"],
|
|
1790
|
+
});
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
try {
|
|
1794
|
+
const result = await fetchBoard(kind);
|
|
1795
|
+
const { cached, fetchedAt, ...payload } = result;
|
|
1796
|
+
sendJson(res, 200, {
|
|
1797
|
+
ok: true,
|
|
1798
|
+
kind,
|
|
1799
|
+
source: `${SITE}/api/board/${kind}`,
|
|
1800
|
+
cached,
|
|
1801
|
+
fetchedAt: new Date(fetchedAt).toISOString(),
|
|
1802
|
+
...payload,
|
|
1803
|
+
});
|
|
1804
|
+
} catch (error) {
|
|
1805
|
+
sendJson(res, 502, {
|
|
1806
|
+
ok: false,
|
|
1807
|
+
kind,
|
|
1808
|
+
error: String((error && error.message) || error),
|
|
1809
|
+
/* 站点接口未上线时是 404:给客户端一句能照做的解释,别只丢状态码 */
|
|
1810
|
+
hint: "站点榜单接口暂不可用(可能尚未发版),可点「打开官网」查看完整榜单",
|
|
1811
|
+
});
|
|
1812
|
+
}
|
|
1813
|
+
});
|
|
1814
|
+
|
|
1649
1815
|
registerRoute(ctx, "/api/dpharness/search", async (req, res) => {
|
|
1650
1816
|
if (req.method !== "GET") {
|
|
1651
1817
|
res.writeHead(405, { allow: "GET" });
|
|
@@ -1719,6 +1885,74 @@ export function apply(ctx) {
|
|
|
1719
1885
|
}
|
|
1720
1886
|
});
|
|
1721
1887
|
|
|
1888
|
+
/**
|
|
1889
|
+
* Newsletter subscription relay (2026-10-20).
|
|
1890
|
+
*
|
|
1891
|
+
* Why it lives here and not in the browser: the site's `/api/subscribe` sends
|
|
1892
|
+
* no CORS headers (measured — the event relay above exists for the same
|
|
1893
|
+
* reason), so a cross-origin POST from the dsh web GUI is refused before it
|
|
1894
|
+
* ever reaches the route.
|
|
1895
|
+
*
|
|
1896
|
+
* Scope is deliberately narrow — one field in, one result out. No visitor id,
|
|
1897
|
+
* no inbox storage, no address logged. The site owns double opt-in: it stores
|
|
1898
|
+
* the address as pending and mails the confirmation link itself, so this
|
|
1899
|
+
* handler returning `ok` only means "the site accepted the request".
|
|
1900
|
+
*/
|
|
1901
|
+
registerRoute(ctx, "/api/dpharness/subscribe", async (req, res) => {
|
|
1902
|
+
if (req.method !== "POST") {
|
|
1903
|
+
res.writeHead(405, { allow: "POST" });
|
|
1904
|
+
res.end();
|
|
1905
|
+
return;
|
|
1906
|
+
}
|
|
1907
|
+
if (!withinSubscribeBudget()) {
|
|
1908
|
+
sendJson(res, 429, { ok: false, error: "操作太频繁,请稍后再试" });
|
|
1909
|
+
return;
|
|
1910
|
+
}
|
|
1911
|
+
let input;
|
|
1912
|
+
try {
|
|
1913
|
+
input = JSON.parse((await readBody(req, 2048)) || "{}");
|
|
1914
|
+
} catch (error) {
|
|
1915
|
+
sendJson(res, 400, { ok: false, error: "请求格式不正确" });
|
|
1916
|
+
return;
|
|
1917
|
+
}
|
|
1918
|
+
const email = String((input && input.email) || "").trim().toLowerCase().slice(0, 254);
|
|
1919
|
+
if (!EMAIL_RE.test(email)) {
|
|
1920
|
+
sendJson(res, 400, { ok: false, error: "邮箱格式不正确" });
|
|
1921
|
+
return;
|
|
1922
|
+
}
|
|
1923
|
+
const controller = new AbortController();
|
|
1924
|
+
const timer = setTimeout(() => controller.abort(), SUBSCRIBE_TIMEOUT_MS);
|
|
1925
|
+
try {
|
|
1926
|
+
const response = await fetch(SUBSCRIBE, {
|
|
1927
|
+
method: "POST",
|
|
1928
|
+
headers: {
|
|
1929
|
+
"content-type": "application/json",
|
|
1930
|
+
accept: "application/json",
|
|
1931
|
+
"user-agent": `dsh-dpharness/${VERSION}`,
|
|
1932
|
+
},
|
|
1933
|
+
body: JSON.stringify({ email, source: "dsh-plugin" }),
|
|
1934
|
+
signal: controller.signal,
|
|
1935
|
+
});
|
|
1936
|
+
const data = await response.json().catch(() => ({}));
|
|
1937
|
+
if (!response.ok) {
|
|
1938
|
+
/* 站点的 error 是给人看的中文(格式/频率),优先透出;没有就自己兜一句 */
|
|
1939
|
+
sendJson(res, 502, { ok: false, error: (data && data.error) || "订阅服务暂时不可用,请稍后再试" });
|
|
1940
|
+
return;
|
|
1941
|
+
}
|
|
1942
|
+
sendJson(res, 200, {
|
|
1943
|
+
ok: !(data && data.ok === false),
|
|
1944
|
+
message: typeof (data && data.message) === "string" ? data.message : "",
|
|
1945
|
+
already: !!(data && data.already === true),
|
|
1946
|
+
error: typeof (data && data.error) === "string" ? data.error : "",
|
|
1947
|
+
});
|
|
1948
|
+
} catch (error) {
|
|
1949
|
+
const message = error && error.name === "AbortError" ? "订阅请求超时,请稍后再试" : "无法连接 dpharness.com";
|
|
1950
|
+
sendJson(res, 502, { ok: false, error: message });
|
|
1951
|
+
} finally {
|
|
1952
|
+
clearTimeout(timer);
|
|
1953
|
+
}
|
|
1954
|
+
});
|
|
1955
|
+
|
|
1722
1956
|
/**
|
|
1723
1957
|
* One-click install.
|
|
1724
1958
|
*
|
|
@@ -1995,6 +2229,7 @@ export function apply(ctx) {
|
|
|
1995
2229
|
"/api/dpharness/best",
|
|
1996
2230
|
"/api/dpharness/sets",
|
|
1997
2231
|
"/api/dpharness/event",
|
|
2232
|
+
"/api/dpharness/subscribe",
|
|
1998
2233
|
"/api/dpharness/install",
|
|
1999
2234
|
"/api/dpharness/postinstall",
|
|
2000
2235
|
"/api/dpharness/toggle",
|
package/lib/usage.js
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* usage.js — 插件使用频次引擎(本机、只读、离线)。
|
|
3
|
+
*
|
|
4
|
+
* 数据源(2026-10-16 实测):
|
|
5
|
+
* · 会话真源 `~/.dsh/sessions/<cwd>/session-<id>/session.v4.jsonl.zstd`
|
|
6
|
+
* —— **多帧 zstd** JSONL;`tool/call` 事件含 `{name, callId, time}`。
|
|
7
|
+
* ⚠️ Node 原生 zstd 只解首帧(sync 与 stream 都不跨帧),这里按帧魔数
|
|
8
|
+
* (`28 B5 2F FD`) 切片逐帧解压,并对每帧做「全行可 JSON 解析」校验以
|
|
9
|
+
* 丢弃压缩流内部的伪魔数。实测全量 30 天扫描约 1.5s。
|
|
10
|
+
*
|
|
11
|
+
* 归属策略(v1,静态表;动态归属见设计方案 M2 原型):
|
|
12
|
+
* · 只有**确定归属**的工具才计入单插件(前缀/精确表);
|
|
13
|
+
* · `web_search`/`web_fetch`/`read_page` 是「通道类」——由多个提供方动态
|
|
14
|
+
* 接管(实测:某会话里 web_search 由 modsearch 服务、web_fetch 由
|
|
15
|
+
* free-search 服务),v1 单列通道桶,不计给任何单一插件;
|
|
16
|
+
* · 内核工具(bash/read/write/…)不进表 → 未归属桶。
|
|
17
|
+
*
|
|
18
|
+
* 三态纪律:引擎不可用 / 插件无可归属工具 → 不产出结论(由调用方标
|
|
19
|
+
* 「无法度量」),**绝不**把「没测到」写成「没在用」。
|
|
20
|
+
*
|
|
21
|
+
* 缓存:`~/.dsh/dpharness/usage-cache.json`(按文件 size+mtime 增量,
|
|
22
|
+
* 只重解析变化过的会话文件;删除的文件自动修剪)。
|
|
23
|
+
*/
|
|
24
|
+
import fs from "node:fs";
|
|
25
|
+
import os from "node:os";
|
|
26
|
+
import path from "node:path";
|
|
27
|
+
import zlib from "node:zlib";
|
|
28
|
+
|
|
29
|
+
/** 统计窗口(天)。拍板值:30。 */
|
|
30
|
+
export const USAGE_WINDOW_DAYS = 30;
|
|
31
|
+
|
|
32
|
+
/** 缓存超过该时长就在下次读取时重扫(毫秒)。 */
|
|
33
|
+
const CACHE_MAX_AGE_MS = 6 * 60 * 60 * 1000;
|
|
34
|
+
|
|
35
|
+
/** 前缀归属:[正则, 包名]。 */
|
|
36
|
+
const TOOL_PREFIX_OWNERS = [
|
|
37
|
+
[/^ego_/u, "dsh-ego-browser"],
|
|
38
|
+
[/^mnemon_/u, "dsh-mnemon"],
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
/** 精确归属(实测自各插件注册名)。 */
|
|
42
|
+
const TOOL_EXACT_OWNERS = {
|
|
43
|
+
advanced_search: "dsh-free-search",
|
|
44
|
+
cache_search: "dsh-free-search",
|
|
45
|
+
domain_search: "dsh-free-search",
|
|
46
|
+
compress: "billion-context",
|
|
47
|
+
decompress: "billion-context",
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** 通道类工具:多提供方动态接管,v1 不计单插件归属。 */
|
|
51
|
+
const CHANNEL_TOOLS = new Set(["web_search", "web_fetch", "read_page"]);
|
|
52
|
+
|
|
53
|
+
/** 有可归属工具的包集合(即使 0 次调用,也算「可度量」)。 */
|
|
54
|
+
export const PKGS_WITH_TOOLS = new Set([
|
|
55
|
+
...TOOL_PREFIX_OWNERS.map(([, pkg]) => pkg),
|
|
56
|
+
...Object.values(TOOL_EXACT_OWNERS),
|
|
57
|
+
]);
|
|
58
|
+
|
|
59
|
+
/** 工具名 → 归属包(null = 通道或未归属)。 */
|
|
60
|
+
export function ownerOfTool(name) {
|
|
61
|
+
if (typeof name !== "string" || name === "") return null;
|
|
62
|
+
if (CHANNEL_TOOLS.has(name)) return null;
|
|
63
|
+
for (const [re, pkg] of TOOL_PREFIX_OWNERS) {
|
|
64
|
+
if (re.test(name)) return pkg;
|
|
65
|
+
}
|
|
66
|
+
return TOOL_EXACT_OWNERS[name] ?? null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 保留价值等级(供 rows 直接下发)。
|
|
71
|
+
* @param enabled - true/false/null(null = 宿主查不到启用状态,不下结论)
|
|
72
|
+
* @param usage - usage 对象或 null(null = 引擎不可用)
|
|
73
|
+
*/
|
|
74
|
+
export function classifyUsage(enabled, usage) {
|
|
75
|
+
if (enabled === false) return "disabled";
|
|
76
|
+
if (usage === null || usage === undefined) return "unknown";
|
|
77
|
+
if (!usage.measurable) return "unmeasurable";
|
|
78
|
+
const calls = Number(usage.calls) || 0;
|
|
79
|
+
const sessions = Number(usage.sessions) || 0;
|
|
80
|
+
if (calls >= 20 && sessions >= 3) return "core";
|
|
81
|
+
if (calls >= 5) return "common";
|
|
82
|
+
if (calls >= 1) return "occasional";
|
|
83
|
+
return "silent";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function dshHome() {
|
|
87
|
+
return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function cachePath() {
|
|
91
|
+
return path.join(dshHome(), "dpharness", "usage-cache.json");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const FRAME_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
95
|
+
|
|
96
|
+
/** 解一个多帧 zstd 缓冲 → 逐帧文本(校验失败/伪魔数的帧丢弃)。 */
|
|
97
|
+
export function decompressFrames(buf) {
|
|
98
|
+
const offsets = [];
|
|
99
|
+
let at = buf.indexOf(FRAME_MAGIC, 0);
|
|
100
|
+
while (at >= 0) {
|
|
101
|
+
offsets.push(at);
|
|
102
|
+
at = buf.indexOf(FRAME_MAGIC, at + 4);
|
|
103
|
+
}
|
|
104
|
+
const out = [];
|
|
105
|
+
for (const off of offsets) {
|
|
106
|
+
let text;
|
|
107
|
+
try {
|
|
108
|
+
text = zlib.zstdDecompressSync(buf.subarray(off)).toString("utf8");
|
|
109
|
+
} catch {
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (!text) continue;
|
|
113
|
+
let ok = true;
|
|
114
|
+
for (const line of text.split("\n")) {
|
|
115
|
+
if (!line.trim()) continue;
|
|
116
|
+
try {
|
|
117
|
+
JSON.parse(line);
|
|
118
|
+
} catch {
|
|
119
|
+
ok = false;
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (ok) out.push(text);
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 解析单个会话真源 → { calls, tools: {name:[count,lastMs]}, maxMs }。 */
|
|
129
|
+
function parseSessionFile(file) {
|
|
130
|
+
const buf = fs.readFileSync(file);
|
|
131
|
+
const tools = {};
|
|
132
|
+
let calls = 0;
|
|
133
|
+
let maxMs = 0;
|
|
134
|
+
for (const text of decompressFrames(buf)) {
|
|
135
|
+
for (const line of text.split("\n")) {
|
|
136
|
+
if (!line.trim()) continue;
|
|
137
|
+
let ev;
|
|
138
|
+
try {
|
|
139
|
+
ev = JSON.parse(line);
|
|
140
|
+
} catch {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (!ev || ev.type !== "tool/call") continue;
|
|
144
|
+
const name = ev.data && typeof ev.data.name === "string" ? ev.data.name : "";
|
|
145
|
+
if (!name) continue;
|
|
146
|
+
const time = Number(ev.time) || 0;
|
|
147
|
+
calls += 1;
|
|
148
|
+
if (time > maxMs) maxMs = time;
|
|
149
|
+
const prev = tools[name];
|
|
150
|
+
tools[name] = prev ? [prev[0] + 1, Math.max(prev[1], time)] : [1, time];
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return { calls, tools, maxMs };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 枚举会话真源文件(~/.dsh/sessions/<slug>/session-<id>/session.v4.jsonl.zstd)。 */
|
|
157
|
+
function listSessionFiles() {
|
|
158
|
+
const root = path.join(dshHome(), "sessions");
|
|
159
|
+
const files = [];
|
|
160
|
+
let slugs;
|
|
161
|
+
try {
|
|
162
|
+
slugs = fs.readdirSync(root, { withFileTypes: true });
|
|
163
|
+
} catch {
|
|
164
|
+
return files;
|
|
165
|
+
}
|
|
166
|
+
for (const slug of slugs) {
|
|
167
|
+
if (!slug.isDirectory()) continue;
|
|
168
|
+
const slugDir = path.join(root, slug.name);
|
|
169
|
+
let sessions;
|
|
170
|
+
try {
|
|
171
|
+
sessions = fs.readdirSync(slugDir, { withFileTypes: true });
|
|
172
|
+
} catch {
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
for (const session of sessions) {
|
|
176
|
+
if (!session.isDirectory() || !session.name.startsWith("session-")) continue;
|
|
177
|
+
const file = path.join(slugDir, session.name, "session.v4.jsonl.zstd");
|
|
178
|
+
try {
|
|
179
|
+
const st = fs.statSync(file);
|
|
180
|
+
if (st.isFile()) files.push({ file, size: st.size, mtimeMs: st.mtimeMs });
|
|
181
|
+
} catch {
|
|
182
|
+
/* 没有真源文件的会话(如仅投影)跳过 */
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return files;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function readCache() {
|
|
190
|
+
try {
|
|
191
|
+
const parsed = JSON.parse(fs.readFileSync(cachePath(), "utf8"));
|
|
192
|
+
if (parsed && parsed.version === 1 && parsed.files && typeof parsed.files === "object") return parsed;
|
|
193
|
+
} catch {
|
|
194
|
+
/* 无缓存 / 损坏 → 重建 */
|
|
195
|
+
}
|
|
196
|
+
return { version: 1, generatedAtMs: 0, files: {} };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function writeCache(cache) {
|
|
200
|
+
try {
|
|
201
|
+
const file = cachePath();
|
|
202
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
203
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
204
|
+
fs.writeFileSync(tmp, JSON.stringify(cache));
|
|
205
|
+
fs.renameSync(tmp, file);
|
|
206
|
+
} catch {
|
|
207
|
+
/* 写不进缓存不是错误:下次重扫即可 */
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 增量扫描 + 聚合。
|
|
213
|
+
* @param options.force - true 时忽略缓存新鲜度,重扫变化文件
|
|
214
|
+
* @param options.now - 注入时钟(测试用)
|
|
215
|
+
*/
|
|
216
|
+
export function getUsageReport(options = {}) {
|
|
217
|
+
const now = Number(options.now) || Date.now();
|
|
218
|
+
const windowDays = Number(options.windowDays) || USAGE_WINDOW_DAYS;
|
|
219
|
+
const cutoff = now - windowDays * 24 * 3600 * 1000;
|
|
220
|
+
const cache = readCache();
|
|
221
|
+
const fresh = cache.generatedAtMs && now - cache.generatedAtMs < CACHE_MAX_AGE_MS;
|
|
222
|
+
let parsedFiles = 0;
|
|
223
|
+
|
|
224
|
+
if (!fresh || options.force === true) {
|
|
225
|
+
const files = listSessionFiles();
|
|
226
|
+
const seen = new Set();
|
|
227
|
+
for (const entry of files) {
|
|
228
|
+
seen.add(entry.file);
|
|
229
|
+
const prev = cache.files[entry.file];
|
|
230
|
+
if (prev && prev.size === entry.size && prev.mtimeMs === entry.mtimeMs) continue;
|
|
231
|
+
try {
|
|
232
|
+
const parsed = parseSessionFile(entry.file);
|
|
233
|
+
cache.files[entry.file] = { size: entry.size, mtimeMs: entry.mtimeMs, ...parsed };
|
|
234
|
+
parsedFiles += 1;
|
|
235
|
+
} catch {
|
|
236
|
+
/* 单文件失败不影响其它会话 */
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
for (const key of Object.keys(cache.files)) {
|
|
240
|
+
if (!seen.has(key)) delete cache.files[key];
|
|
241
|
+
}
|
|
242
|
+
cache.generatedAtMs = now;
|
|
243
|
+
writeCache(cache);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/* ---- 聚合(窗口内文件) ---- */
|
|
247
|
+
const perPkg = {};
|
|
248
|
+
const unattributed = {};
|
|
249
|
+
const channel = {};
|
|
250
|
+
let filesInWindow = 0;
|
|
251
|
+
let sessionsWithCalls = 0;
|
|
252
|
+
let totalCalls = 0;
|
|
253
|
+
for (const [file, info] of Object.entries(cache.files)) {
|
|
254
|
+
if (!info || info.mtimeMs < cutoff) continue;
|
|
255
|
+
filesInWindow += 1;
|
|
256
|
+
if (info.calls > 0) sessionsWithCalls += 1;
|
|
257
|
+
const touchedPkgs = new Set();
|
|
258
|
+
for (const [tool, pair] of Object.entries(info.tools || {})) {
|
|
259
|
+
const count = pair[0];
|
|
260
|
+
const lastMs = pair[1] || 0;
|
|
261
|
+
totalCalls += count;
|
|
262
|
+
const owner = ownerOfTool(tool);
|
|
263
|
+
if (owner === null) {
|
|
264
|
+
if (CHANNEL_TOOLS.has(tool)) channel[tool] = (channel[tool] || 0) + count;
|
|
265
|
+
else unattributed[tool] = (unattributed[tool] || 0) + count;
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const slot = perPkg[owner] || (perPkg[owner] = { calls: 0, sessions: 0, lastUsedMs: 0, tools: {} });
|
|
269
|
+
slot.calls += count;
|
|
270
|
+
slot.tools[tool] = (slot.tools[tool] || 0) + count;
|
|
271
|
+
if (lastMs > slot.lastUsedMs) slot.lastUsedMs = lastMs;
|
|
272
|
+
if (!touchedPkgs.has(owner)) {
|
|
273
|
+
touchedPkgs.add(owner);
|
|
274
|
+
slot.sessions += 1;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/* 可归属但窗口内没有调用的包补零,保证「可度量 + 沉默」可被区分 */
|
|
280
|
+
for (const pkg of PKGS_WITH_TOOLS) {
|
|
281
|
+
if (!perPkg[pkg]) perPkg[pkg] = { calls: 0, sessions: 0, lastUsedMs: 0, tools: {} };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const plugins = {};
|
|
285
|
+
for (const [pkg, slot] of Object.entries(perPkg)) {
|
|
286
|
+
plugins[pkg] = {
|
|
287
|
+
measurable: true,
|
|
288
|
+
calls: slot.calls,
|
|
289
|
+
sessions: slot.sessions,
|
|
290
|
+
lastUsedMs: slot.lastUsedMs || null,
|
|
291
|
+
tools: Object.entries(slot.tools)
|
|
292
|
+
.sort((a, b) => b[1] - a[1])
|
|
293
|
+
.slice(0, 6),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return {
|
|
298
|
+
ok: true,
|
|
299
|
+
windowDays,
|
|
300
|
+
generatedAtMs: cache.generatedAtMs || null,
|
|
301
|
+
cacheAgeMs: cache.generatedAtMs ? now - cache.generatedAtMs : null,
|
|
302
|
+
scanned: { files: filesInWindow, parsed: parsedFiles, sessions: sessionsWithCalls, calls: totalCalls },
|
|
303
|
+
plugins,
|
|
304
|
+
channel,
|
|
305
|
+
unattributed,
|
|
306
|
+
};
|
|
307
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-dpharness",
|
|
3
3
|
"icon": "./icon.svg",
|
|
4
|
-
"version": "0.6.
|
|
4
|
+
"version": "0.6.5",
|
|
5
5
|
"description": "Curated dpharness.com plugin catalog inside the DeepSeek Harness Web GUI: a conversation-view tab, a sidebar entry and a dismissible site-wide floating panel, offering a searchable full catalog, a monthly by-category shortlist, a daily pick and an update check (this plugin plus every installed plugin) with a red-dot reminder, with one-click install via dshmarket or the dsh CLI. Includes a settings page (General row + Plugins tab) for the widget visibility, the daily pick, the update check and the opt-out telemetry relay covering the full install funnel.",
|
|
6
6
|
"author": "zhanghao3693 <zhanghao3693@qq.com>",
|
|
7
7
|
"repository": {
|
|
@@ -14,6 +14,10 @@
|
|
|
14
14
|
},
|
|
15
15
|
"type": "module",
|
|
16
16
|
"main": "lib/index.js",
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node test-local.mjs",
|
|
19
|
+
"release": "node scripts/release.mjs"
|
|
20
|
+
},
|
|
17
21
|
"exports": {
|
|
18
22
|
"./locale/*.json": "./locale/*.json",
|
|
19
23
|
".": "./lib/index.js",
|
|
@@ -58,6 +62,7 @@
|
|
|
58
62
|
"files": ["icon.svg", "locale", "lib/index.js",
|
|
59
63
|
"lib/changelog.js",
|
|
60
64
|
"lib/client.js",
|
|
65
|
+
"lib/usage.js",
|
|
61
66
|
"README.md",
|
|
62
67
|
"cordis.patch.yml"],
|
|
63
68
|
"keywords": [
|