@kangyishuai/dsh-advisor 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +193 -2
- package/README.zh-CN.md +181 -0
- package/cordis.patch.yml +3 -0
- package/lib/adoption.js +87 -0
- package/lib/anchors.js +140 -0
- package/lib/budget.js +100 -0
- package/lib/call.js +220 -0
- package/lib/catalog.js +143 -0
- package/lib/client.js +3424 -0
- package/lib/guard.js +185 -0
- package/lib/index.js +5 -0
- package/lib/ledger.js +311 -0
- package/lib/prompt.js +281 -0
- package/lib/redact.js +135 -0
- package/lib/route.js +117 -0
- package/lib/service.js +1747 -0
- package/lib/settings.js +258 -0
- package/lib/tool-schema.js +153 -0
- package/lib/transcript.js +220 -0
- package/lib/twopass.js +60 -0
- package/lib/verifier.js +107 -0
- package/locale/en.json +153 -0
- package/locale/zh.json +153 -0
- package/package.json +60 -4
package/lib/guard.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 纯函数守卫:预算、去重、免疫窗口、配对。不 import 宿主包,单测可直接跑。
|
|
3
|
+
// 设计原则:所有判断都可以用「整数 + 时间戳」表达,不依赖会话对象的形状。
|
|
4
|
+
|
|
5
|
+
/** 去重指纹的默认窗口:24 小时。 */
|
|
6
|
+
export const DEDUPE_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
7
|
+
/** 去重表上限(有界 FIFO)。 */
|
|
8
|
+
export const DEDUPE_MAX = 4096;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 稳定指纹:小写 + 折叠空白 + 去掉标点后取 djb2 的 16 进制串。
|
|
12
|
+
* 同一句建议换个标点不该再投递一次。
|
|
13
|
+
* @param {string} text
|
|
14
|
+
* @returns {string}
|
|
15
|
+
*/
|
|
16
|
+
export function fingerprint(text) {
|
|
17
|
+
const normalized = String(text ?? "")
|
|
18
|
+
.toLowerCase()
|
|
19
|
+
.replace(/[.,;:!?'"`()[\]{}<>、。,;:!?「」『』()【】—–-]/gu, " ")
|
|
20
|
+
.replace(/[\s\u3000]+/gu, " ")
|
|
21
|
+
.trim();
|
|
22
|
+
let hash = 5381;
|
|
23
|
+
for (let index = 0; index < normalized.length; index += 1) {
|
|
24
|
+
hash = ((hash << 5) + hash + normalized.charCodeAt(index)) | 0;
|
|
25
|
+
}
|
|
26
|
+
return `f${(hash >>> 0).toString(16)}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 去重表:`Map<指纹, 首次命中时间>`,超过上限时丢最旧的。
|
|
31
|
+
* @param {Map<string, number>} table
|
|
32
|
+
* @param {string} id
|
|
33
|
+
* @param {number} now
|
|
34
|
+
* @param {number} [windowMs]
|
|
35
|
+
* @returns {{ duplicate: boolean, table: Map<string, number> }}
|
|
36
|
+
*/
|
|
37
|
+
export function rememberFingerprint(table, id, now, windowMs = DEDUPE_WINDOW_MS) {
|
|
38
|
+
const next = new Map(table);
|
|
39
|
+
for (const [key, at] of next) {
|
|
40
|
+
if (now - at > windowMs) next.delete(key);
|
|
41
|
+
}
|
|
42
|
+
const seenAt = next.get(id);
|
|
43
|
+
if (seenAt !== undefined) return { duplicate: true, table: next };
|
|
44
|
+
next.set(id, now);
|
|
45
|
+
while (next.size > DEDUPE_MAX) {
|
|
46
|
+
const oldest = next.keys().next();
|
|
47
|
+
if (oldest.done) break;
|
|
48
|
+
next.delete(oldest.value);
|
|
49
|
+
}
|
|
50
|
+
return { duplicate: false, table: next };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 免疫窗口:上次投递之后的 `immuneTurns` 个回合内不再投递打断性建议。
|
|
55
|
+
* @param {{ lastDeliveryTurn: number|null, currentTurn: number, immuneTurns: number }} input
|
|
56
|
+
* @returns {boolean}
|
|
57
|
+
*/
|
|
58
|
+
export function immuneActive(input) {
|
|
59
|
+
const { lastDeliveryTurn, currentTurn, immuneTurns } = input;
|
|
60
|
+
if (lastDeliveryTurn === null || lastDeliveryTurn === undefined) return false;
|
|
61
|
+
if (!Number.isFinite(currentTurn) || !Number.isFinite(lastDeliveryTurn)) return false;
|
|
62
|
+
if (immuneTurns <= 0) return false;
|
|
63
|
+
return currentTurn - lastDeliveryTurn < immuneTurns;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @typedef {object} BudgetCounters
|
|
68
|
+
* @property {number} turnCalls 本回合已徵询次数
|
|
69
|
+
* @property {number} sessionCalls 本会话已徵询次数
|
|
70
|
+
* @property {number[]} hourStamps 最近一小时内的徵询时间戳(毫秒)
|
|
71
|
+
* @property {number} dayCostUsd 今日已花(美元,估算值)
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @typedef {object} BudgetInput
|
|
76
|
+
* @property {typeof import("./settings.js").DEFAULT_SETTINGS} settings
|
|
77
|
+
* @property {BudgetCounters} counters
|
|
78
|
+
* @property {number} now
|
|
79
|
+
* @property {number} [estimatedCostUsd] 本次预计花费,用于「日预算」预判
|
|
80
|
+
*/
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 四级预算检查。返回**第一个**不满足的条件(顺序固定,便于测试与文案稳定)。
|
|
84
|
+
* 每个字段为 0 都表示「不限制」。
|
|
85
|
+
* @param {BudgetInput} input
|
|
86
|
+
* @returns {{ ok: true } | { ok: false, code: "turn_limit"|"session_limit"|"hour_limit"|"day_budget", limit: number, used: number }}
|
|
87
|
+
*/
|
|
88
|
+
export function checkBudget(input) {
|
|
89
|
+
const { settings, counters, now, estimatedCostUsd = 0 } = input;
|
|
90
|
+
|
|
91
|
+
if (settings.maxCallsPerTurn > 0 && counters.turnCalls >= settings.maxCallsPerTurn) {
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
code: "turn_limit",
|
|
95
|
+
limit: settings.maxCallsPerTurn,
|
|
96
|
+
used: counters.turnCalls,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
if (settings.maxCallsPerSession > 0 && counters.sessionCalls >= settings.maxCallsPerSession) {
|
|
100
|
+
return {
|
|
101
|
+
ok: false,
|
|
102
|
+
code: "session_limit",
|
|
103
|
+
limit: settings.maxCallsPerSession,
|
|
104
|
+
used: counters.sessionCalls,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (settings.maxCallsPerHour > 0) {
|
|
108
|
+
const hourAgo = now - 60 * 60 * 1000;
|
|
109
|
+
const used = counters.hourStamps.filter((at) => at > hourAgo).length;
|
|
110
|
+
if (used >= settings.maxCallsPerHour) {
|
|
111
|
+
return { ok: false, code: "hour_limit", limit: settings.maxCallsPerHour, used };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (
|
|
115
|
+
settings.maxCostPerDayUsd > 0 &&
|
|
116
|
+
counters.dayCostUsd + estimatedCostUsd > settings.maxCostPerDayUsd
|
|
117
|
+
) {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
code: "day_budget",
|
|
121
|
+
limit: settings.maxCostPerDayUsd,
|
|
122
|
+
used: counters.dayCostUsd,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
return { ok: true };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 估算一次调用的美元成本。单价为 0 时返回 0(= 不算钱,只记 token)。
|
|
130
|
+
* @param {{ inputTokens: number, outputTokens: number, priceInputPerMTok: number, priceOutputPerMTok: number }} input
|
|
131
|
+
* @returns {number}
|
|
132
|
+
*/
|
|
133
|
+
export function estimateCostUsd(input) {
|
|
134
|
+
const { inputTokens, outputTokens, priceInputPerMTok, priceOutputPerMTok } = input;
|
|
135
|
+
const inCost = (Math.max(0, inputTokens) / 1_000_000) * Math.max(0, priceInputPerMTok);
|
|
136
|
+
const outCost = (Math.max(0, outputTokens) / 1_000_000) * Math.max(0, priceOutputPerMTok);
|
|
137
|
+
return inCost + outCost;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 严重度排序(用于「多条发现折叠成一条」时取最高的)。
|
|
142
|
+
* @param {"nit"|"concern"|"blocker"} severity
|
|
143
|
+
* @returns {number}
|
|
144
|
+
*/
|
|
145
|
+
export function severityRank(severity) {
|
|
146
|
+
if (severity === "blocker") return 3;
|
|
147
|
+
if (severity === "concern") return 2;
|
|
148
|
+
return 1;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 瞳孔式收窄:输入若为极其空洞的建议(英文/中文的「没问题」「可以了」),返回 true。
|
|
153
|
+
* 只做**精确匹配**,不做包含匹配 —— 包含匹配会误杀真正的 blocker。
|
|
154
|
+
* @param {string} text
|
|
155
|
+
* @returns {boolean}
|
|
156
|
+
*/
|
|
157
|
+
export function isHollowAdvice(text) {
|
|
158
|
+
const normalized = String(text ?? "")
|
|
159
|
+
.toLowerCase()
|
|
160
|
+
.replace(/[\s\u3000]+/gu, " ")
|
|
161
|
+
.replace(/[.,;:!?'"`。,;:!?]/gu, "")
|
|
162
|
+
.trim();
|
|
163
|
+
/** @type {Set<string>} */
|
|
164
|
+
const hollow = new Set([
|
|
165
|
+
"stop",
|
|
166
|
+
"done",
|
|
167
|
+
"complete",
|
|
168
|
+
"completed",
|
|
169
|
+
"lgtm",
|
|
170
|
+
"looks good",
|
|
171
|
+
"nothing to add",
|
|
172
|
+
"no issues",
|
|
173
|
+
"no problems",
|
|
174
|
+
"all good",
|
|
175
|
+
"ok",
|
|
176
|
+
"okay",
|
|
177
|
+
"没问题",
|
|
178
|
+
"没有问题",
|
|
179
|
+
"可以了",
|
|
180
|
+
"看起来不错",
|
|
181
|
+
"完成",
|
|
182
|
+
"无需建议",
|
|
183
|
+
]);
|
|
184
|
+
return hollow.has(normalized);
|
|
185
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// host 半入口:导出 Typert Remote Service 类本身(Cordis 插件形态)。
|
|
3
|
+
// Remote 方法必须声明在这个被导出的类自身原型上(见 ./service.js 的 declareRemote),
|
|
4
|
+
// 不要再包一层子类,否则 /api/advisor/* 会 404(docs/runtime/0.2.1-rc.5.md §6.10)。
|
|
5
|
+
export { AdvisorService, AdvisorService as default } from "./service.js";
|
package/lib/ledger.js
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 账本:宿主**不**给额外模型调用记 usage(只有主循环写 assistant/message 的 usage),
|
|
3
|
+
// 所以顾问花了多少 token 必须由我们自己记账。这里同时是四级预算的计数器来源。
|
|
4
|
+
//
|
|
5
|
+
// 落盘:`<dataRoot>/advisor/usage.jsonl`,一次徵询一行;文件只追加,超过上限时滚动重命名。
|
|
6
|
+
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
|
|
9
|
+
/** 账本目录名(位于数据根下)。 */
|
|
10
|
+
export const LEDGER_DIR = "advisor";
|
|
11
|
+
/** 账本文件名。 */
|
|
12
|
+
export const LEDGER_FILE = "usage.jsonl";
|
|
13
|
+
/** 建议账本(跨会话汇总用,一行一条建议)。 */
|
|
14
|
+
export const ADVICE_FILE = "advice.jsonl";
|
|
15
|
+
/** 滚动阈值:超过这个字节数就把旧文件改名(保留一份历史,不做无界增长)。 */
|
|
16
|
+
export const LEDGER_MAX_BYTES = 2 * 1024 * 1024;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {object} LedgerEntry
|
|
20
|
+
* @property {string} at ISO 时间
|
|
21
|
+
* @property {string} sessionId
|
|
22
|
+
* @property {"tool"|"shadow"|"manual"|"post-answer"} trigger
|
|
23
|
+
* @property {string} provider
|
|
24
|
+
* @property {string} model
|
|
25
|
+
* @property {string} effort
|
|
26
|
+
* @property {"reviewed"|"declined"|"unavailable"} verdict
|
|
27
|
+
* @property {string} [severity]
|
|
28
|
+
* @property {number} inputTokens
|
|
29
|
+
* @property {number} outputTokens
|
|
30
|
+
* @property {number} cacheReadTokens
|
|
31
|
+
* @property {number} costUsd
|
|
32
|
+
* @property {number} ms
|
|
33
|
+
* @property {string} [code]
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @typedef {object} SessionCounters
|
|
38
|
+
* @property {number} turn 最近一次记录的回合号(0 = 未知)
|
|
39
|
+
* @property {number} turnCalls
|
|
40
|
+
* @property {number} sessionCalls
|
|
41
|
+
* @property {number[]} hourStamps
|
|
42
|
+
* @property {number} dayCostUsd
|
|
43
|
+
* @property {string} dayKey YYYY-MM-DD(本地时间)
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 本地日键,用于「每日预算」跨重启续算。
|
|
48
|
+
* @param {Date} [date]
|
|
49
|
+
* @returns {string}
|
|
50
|
+
*/
|
|
51
|
+
export function dayKey(date = new Date()) {
|
|
52
|
+
const year = date.getFullYear();
|
|
53
|
+
const month = `${date.getMonth() + 1}`.padStart(2, "0");
|
|
54
|
+
const day = `${date.getDate()}`.padStart(2, "0");
|
|
55
|
+
return `${year}-${month}-${day}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {{ home: string, logger?: DSH.Logger }} options
|
|
60
|
+
* @returns {{
|
|
61
|
+
* record: (entry: LedgerEntry) => Promise<void>,
|
|
62
|
+
* counters: (sessionId: string, now?: number) => SessionCounters,
|
|
63
|
+
* noteCall: (sessionId: string, input: { turn: number, costUsd: number, at: number }) => void,
|
|
64
|
+
* resetTurn: (sessionId: string, turn: number) => void,
|
|
65
|
+
* totals: () => { calls: number, inputTokens: number, outputTokens: number, costUsd: number, byTrigger: Record<string, number> },
|
|
66
|
+
* recent: (limit?: number) => LedgerEntry[],
|
|
67
|
+
* ready: () => Promise<void>,
|
|
68
|
+
* recordAdvice: (entry: any) => Promise<void>,
|
|
69
|
+
* adviceTotals: () => Promise<{ total: number, bySeverity: Record<string, number>, byModel: Record<string, number>, byDay: Record<string, number>, byConfidence: Record<string, number> }>,
|
|
70
|
+
* path: string,
|
|
71
|
+
* advicePath: string,
|
|
72
|
+
* }}
|
|
73
|
+
*/
|
|
74
|
+
export function createLedger(options) {
|
|
75
|
+
const dir = join(options.home, LEDGER_DIR);
|
|
76
|
+
const path = join(dir, LEDGER_FILE);
|
|
77
|
+
/** @type {Map<string, SessionCounters>} */
|
|
78
|
+
const countersBySession = new Map();
|
|
79
|
+
/** @type {LedgerEntry[]} */
|
|
80
|
+
const recent = [];
|
|
81
|
+
/** @type {{ calls: number, inputTokens: number, outputTokens: number, costUsd: number, byTrigger: Record<string, number> }} */
|
|
82
|
+
const totals = { calls: 0, inputTokens: 0, outputTokens: 0, costUsd: 0, byTrigger: {} };
|
|
83
|
+
let loaded = false;
|
|
84
|
+
|
|
85
|
+
/** 读历史账本,恢复「今日花费」与累计数(只读尾部 2MB,避免大文件拖慢启动)。 */
|
|
86
|
+
const ensureLoaded = async () => {
|
|
87
|
+
if (loaded) return;
|
|
88
|
+
loaded = true;
|
|
89
|
+
try {
|
|
90
|
+
const info = await stat(path);
|
|
91
|
+
const start = Math.max(0, info.size - LEDGER_MAX_BYTES);
|
|
92
|
+
const text = await readFile(path, "utf8");
|
|
93
|
+
const tail = start > 0 ? text.slice(text.lastIndexOf("\n", start) + 1) : text;
|
|
94
|
+
const today = dayKey();
|
|
95
|
+
for (const line of tail.split("\n")) {
|
|
96
|
+
if (line.trim() === "") continue;
|
|
97
|
+
/** @type {any} */
|
|
98
|
+
let entry;
|
|
99
|
+
try {
|
|
100
|
+
entry = JSON.parse(line);
|
|
101
|
+
} catch {
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const cost = Number(entry.costUsd ?? 0) || 0;
|
|
105
|
+
const inputTokens = Number(entry.inputTokens ?? 0) || 0;
|
|
106
|
+
const outputTokens = Number(entry.outputTokens ?? 0) || 0;
|
|
107
|
+
totals.calls += 1;
|
|
108
|
+
totals.inputTokens += inputTokens;
|
|
109
|
+
totals.outputTokens += outputTokens;
|
|
110
|
+
totals.costUsd += cost;
|
|
111
|
+
const trigger = typeof entry.trigger === "string" ? entry.trigger : "tool";
|
|
112
|
+
totals.byTrigger[trigger] = (totals.byTrigger[trigger] ?? 0) + 1;
|
|
113
|
+
if (recent.length < 50) recent.push(entry);
|
|
114
|
+
const sessionId = typeof entry.sessionId === "string" ? entry.sessionId : "";
|
|
115
|
+
if (sessionId === "") continue;
|
|
116
|
+
const day = typeof entry.at === "string" ? entry.at.slice(0, 10) : "";
|
|
117
|
+
if (day !== today) continue;
|
|
118
|
+
const counters = countersBySession.get(sessionId) ?? {
|
|
119
|
+
turn: 0,
|
|
120
|
+
turnCalls: 0,
|
|
121
|
+
sessionCalls: 0,
|
|
122
|
+
hourStamps: [],
|
|
123
|
+
dayCostUsd: 0,
|
|
124
|
+
dayKey: today,
|
|
125
|
+
};
|
|
126
|
+
counters.dayCostUsd += cost;
|
|
127
|
+
countersBySession.set(sessionId, counters);
|
|
128
|
+
}
|
|
129
|
+
} catch (error) {
|
|
130
|
+
const code = /** @type {any} */ (error)?.code;
|
|
131
|
+
if (code !== "ENOENT") options.logger?.warn?.(`[advisor] 读取账本失败:${String(error)}`);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 取某会话的计数器(惰性初始化;跨日自动清零当日花费)。
|
|
137
|
+
* @param {string} sessionId
|
|
138
|
+
* @param {number} [now]
|
|
139
|
+
* @returns {SessionCounters}
|
|
140
|
+
*/
|
|
141
|
+
const counters = (sessionId, now = Date.now()) => {
|
|
142
|
+
const today = dayKey(new Date(now));
|
|
143
|
+
let current = countersBySession.get(sessionId);
|
|
144
|
+
if (current === undefined) {
|
|
145
|
+
current = {
|
|
146
|
+
turn: 0,
|
|
147
|
+
turnCalls: 0,
|
|
148
|
+
sessionCalls: 0,
|
|
149
|
+
hourStamps: [],
|
|
150
|
+
dayCostUsd: 0,
|
|
151
|
+
dayKey: today,
|
|
152
|
+
};
|
|
153
|
+
countersBySession.set(sessionId, current);
|
|
154
|
+
}
|
|
155
|
+
if (current.dayKey !== today) {
|
|
156
|
+
current.dayCostUsd = 0;
|
|
157
|
+
current.dayKey = today;
|
|
158
|
+
}
|
|
159
|
+
const hourAgo = now - 60 * 60 * 1000;
|
|
160
|
+
current.hourStamps = current.hourStamps.filter((at) => at > hourAgo);
|
|
161
|
+
return current;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const advicePath = join(dir, ADVICE_FILE);
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
path,
|
|
168
|
+
advicePath,
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 记录一次徵询(先落盘再更新内存;落盘失败不让调用失败)。
|
|
172
|
+
* @param {LedgerEntry} entry
|
|
173
|
+
* @returns {Promise<void>}
|
|
174
|
+
*/
|
|
175
|
+
async record(entry) {
|
|
176
|
+
recent.unshift(entry);
|
|
177
|
+
if (recent.length > 50) recent.pop();
|
|
178
|
+
totals.calls += 1;
|
|
179
|
+
totals.inputTokens += entry.inputTokens;
|
|
180
|
+
totals.outputTokens += entry.outputTokens;
|
|
181
|
+
totals.costUsd += entry.costUsd;
|
|
182
|
+
totals.byTrigger[entry.trigger] = (totals.byTrigger[entry.trigger] ?? 0) + 1;
|
|
183
|
+
|
|
184
|
+
try {
|
|
185
|
+
await mkdir(dir, { recursive: true });
|
|
186
|
+
const info = await stat(path).catch(() => undefined);
|
|
187
|
+
if (info && info.size > LEDGER_MAX_BYTES) {
|
|
188
|
+
await rename(path, `${path}.1`).catch(() => undefined);
|
|
189
|
+
}
|
|
190
|
+
const line = `${JSON.stringify(entry)}\n`;
|
|
191
|
+
const existing =
|
|
192
|
+
info && info.size <= LEDGER_MAX_BYTES ? await readFile(path, "utf8").catch(() => "") : "";
|
|
193
|
+
const next = `${existing}${line}`;
|
|
194
|
+
// 一次性重写而不是 append:保证写入原子性(账本比吞吐重要)。
|
|
195
|
+
await writeFile(path, next, "utf8");
|
|
196
|
+
} catch (error) {
|
|
197
|
+
options.logger?.warn?.(`[advisor] 写账本失败:${String(error)}`);
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
|
|
201
|
+
counters,
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* 记一次调用:更新会话/回合/小时/当日计数。
|
|
205
|
+
* @param {string} sessionId
|
|
206
|
+
* @param {{ turn: number, costUsd: number, at: number }} input
|
|
207
|
+
* @returns {void}
|
|
208
|
+
*/
|
|
209
|
+
noteCall(sessionId, input) {
|
|
210
|
+
const current = counters(sessionId, input.at);
|
|
211
|
+
if (input.turn > 0 && input.turn !== current.turn) {
|
|
212
|
+
current.turn = input.turn;
|
|
213
|
+
current.turnCalls = 0;
|
|
214
|
+
}
|
|
215
|
+
current.turnCalls += 1;
|
|
216
|
+
current.sessionCalls += 1;
|
|
217
|
+
current.hourStamps.push(input.at);
|
|
218
|
+
current.dayCostUsd += input.costUsd;
|
|
219
|
+
},
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* 换回合时清零「本回合」计数(工具调用处也会顺带调用)。
|
|
223
|
+
* @param {string} sessionId
|
|
224
|
+
* @param {number} turn
|
|
225
|
+
* @returns {void}
|
|
226
|
+
*/
|
|
227
|
+
resetTurn(sessionId, turn) {
|
|
228
|
+
const current = counters(sessionId);
|
|
229
|
+
if (turn !== current.turn) {
|
|
230
|
+
current.turn = turn;
|
|
231
|
+
current.turnCalls = 0;
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
|
|
235
|
+
/** @returns {{ calls: number, inputTokens: number, outputTokens: number, costUsd: number, byTrigger: Record<string, number> }} */
|
|
236
|
+
totals() {
|
|
237
|
+
return { ...totals, byTrigger: { ...totals.byTrigger } };
|
|
238
|
+
},
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 最近若干条(新→旧)。
|
|
242
|
+
* @param {number} [limit]
|
|
243
|
+
* @returns {LedgerEntry[]}
|
|
244
|
+
*/
|
|
245
|
+
recent(limit = 10) {
|
|
246
|
+
return recent.slice(0, Math.max(0, limit));
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* 追加一条建议到跨会话账本(失败只告警,不影响徵询)。
|
|
251
|
+
* @param {any} entry
|
|
252
|
+
* @returns {Promise<void>}
|
|
253
|
+
*/
|
|
254
|
+
async recordAdvice(entry) {
|
|
255
|
+
try {
|
|
256
|
+
await mkdir(dir, { recursive: true });
|
|
257
|
+
const line = `${JSON.stringify(entry)}\n`;
|
|
258
|
+
const existing = await readFile(advicePath, "utf8").catch(() => "");
|
|
259
|
+
await writeFile(advicePath, `${existing}${line}`, "utf8");
|
|
260
|
+
} catch (error) {
|
|
261
|
+
options.logger?.warn?.(`[advisor] 写建议账本失败:${String(error)}`);
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* 跨会话建议汇总(读整个 advice.jsonl;文件很小,一行一条)。
|
|
267
|
+
* @returns {Promise<{ total: number, bySeverity: Record<string, number>, byModel: Record<string, number>, byDay: Record<string, number>, byConfidence: Record<string, number> }>}
|
|
268
|
+
*/
|
|
269
|
+
async adviceTotals() {
|
|
270
|
+
/** @type {Record<string, number>} */
|
|
271
|
+
const bySeverity = {};
|
|
272
|
+
/** @type {Record<string, number>} */
|
|
273
|
+
const byModel = {};
|
|
274
|
+
/** @type {Record<string, number>} */
|
|
275
|
+
const byDay = {};
|
|
276
|
+
/** @type {Record<string, number>} */
|
|
277
|
+
const byConfidence = {};
|
|
278
|
+
let total = 0;
|
|
279
|
+
try {
|
|
280
|
+
const text = await readFile(advicePath, "utf8");
|
|
281
|
+
for (const line of text.split("\n")) {
|
|
282
|
+
if (line.trim() === "") continue;
|
|
283
|
+
let entry;
|
|
284
|
+
try {
|
|
285
|
+
entry = JSON.parse(line);
|
|
286
|
+
} catch {
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
total += 1;
|
|
290
|
+
const severity = String(entry?.severity ?? "nit");
|
|
291
|
+
const model = String(entry?.model ?? "unknown");
|
|
292
|
+
const day = typeof entry?.at === "string" ? entry.at.slice(0, 10) : "unknown";
|
|
293
|
+
const confidence = String(entry?.confidence ?? "low");
|
|
294
|
+
bySeverity[severity] = (bySeverity[severity] ?? 0) + 1;
|
|
295
|
+
byModel[model] = (byModel[model] ?? 0) + 1;
|
|
296
|
+
byDay[day] = (byDay[day] ?? 0) + 1;
|
|
297
|
+
byConfidence[confidence] = (byConfidence[confidence] ?? 0) + 1;
|
|
298
|
+
}
|
|
299
|
+
} catch (error) {
|
|
300
|
+
const code = /** @type {any} */ (error)?.code;
|
|
301
|
+
if (code !== "ENOENT") options.logger?.warn?.(`[advisor] 读建议账本失败:${String(error)}`);
|
|
302
|
+
}
|
|
303
|
+
return { total, bySeverity, byModel, byDay, byConfidence };
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
/** 首次读取时恢复「今日花费」与累计数(调用方不必 await,失败静默)。 */
|
|
307
|
+
ready() {
|
|
308
|
+
return ensureLoaded();
|
|
309
|
+
},
|
|
310
|
+
};
|
|
311
|
+
}
|