@kangyishuai/dsh-advisor 0.1.0 → 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/README.md +20 -12
- package/lib/adoption.js +12 -6
- package/lib/budget.js +100 -0
- package/lib/call.js +8 -3
- package/lib/catalog.js +143 -0
- package/lib/client.js +550 -10
- package/lib/ledger.js +66 -1
- package/lib/prompt.js +21 -0
- package/lib/route.js +5 -2
- package/lib/service.js +331 -13
- package/lib/settings.js +34 -0
- package/lib/twopass.js +60 -0
- package/lib/verifier.js +107 -0
- package/locale/en.json +29 -0
- package/locale/zh.json +29 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -91,6 +91,10 @@ Example (placeholder route and model names — use the ones the picker shows you
|
|
|
91
91
|
}
|
|
92
92
|
```
|
|
93
93
|
|
|
94
|
+
**Two-pass evidence (opt-in).** With `advisorTools: true` the advisor may answer with `needs: [{kind:"file", ref:"path"}]`. The plugin reads those files **inside the session working directory only** (≤5 files, ≤64 KiB each, `../` and symlink escapes rejected), then calls the advisor once more with the quoted evidence so it can revise. This is the "advisor can check the facts" mode; it costs one extra model call. A rejected or unreadable path is reported back as unavailable evidence instead of failing the consultation.
|
|
95
|
+
|
|
96
|
+
**Workspace budget.** Besides the per-session ceilings, a shared pool (`<DSH_HOME>/advisor/budget.json`) counts calls and estimated cost per local day across sessions (`workspaceMaxCallsPerDay`, `workspaceMaxCostPerDayUsd`).
|
|
97
|
+
|
|
94
98
|
**Evidence anchors.** Each advice item may cite `{kind, ref}` anchors (a tool-call id, a message id, a file path). The plugin checks every ref against the session and marks the item unverified when nothing matches; if **none** of the cited anchors exist, the severity is downgraded one step and the advice says so. This is how a hallucinated "that failing command" gets caught.
|
|
95
99
|
|
|
96
100
|
**Advice line and report.** Each consultation is recorded as a session plugin record (not part of the model-visible surface), so the turn gets a compact advisor line in the chat and `/advisor report` can attribute adoption over time. Attribution is deliberately conservative: no signal, no credit.
|
|
@@ -99,18 +103,21 @@ Example (placeholder route and model names — use the ones the picker shows you
|
|
|
99
103
|
|
|
100
104
|
## Commands
|
|
101
105
|
|
|
102
|
-
| Command | What it does
|
|
103
|
-
| -------------------------------------- |
|
|
104
|
-
| `/advisor` | Opens the model picker (client half). Routes and models are re-read every time; nothing is cached across openings.
|
|
105
|
-
| `/advisor status` | Mode, chosen route, consultations this session and this turn against the limits, cumulative tokens, the last result, and why the last consultation was skipped.
|
|
106
|
-
| `/advisor on` | Sets `advisory`. Refuses with a pointer to the picker when no advisor model is configured.
|
|
107
|
-
| `/advisor off` | Sets `off`: no consultation is made, no request is sent.
|
|
108
|
-
| `/advisor shadow` | Sets `shadow`: consult after each completed turn and record it, without feeding it back.
|
|
109
|
-
| `/advisor ask` | Runs one consultation **now** and returns the advice as command output.
|
|
110
|
-
| `/advisor cancel` | Aborts the in-flight consultation — the request is aborted, not merely ignored.
|
|
111
|
-
| `/advisor
|
|
112
|
-
| `/advisor
|
|
113
|
-
| `/advisor
|
|
106
|
+
| Command | What it does |
|
|
107
|
+
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
108
|
+
| `/advisor` | Opens the model picker (client half). Routes and models are re-read every time; nothing is cached across openings. |
|
|
109
|
+
| `/advisor status` | Mode, chosen route, consultations this session and this turn against the limits, cumulative tokens, the last result, and why the last consultation was skipped. |
|
|
110
|
+
| `/advisor on` | Sets `advisory`. Refuses with a pointer to the picker when no advisor model is configured. |
|
|
111
|
+
| `/advisor off` | Sets `off`: no consultation is made, no request is sent. |
|
|
112
|
+
| `/advisor shadow` | Sets `shadow`: consult after each completed turn and record it, without feeding it back. |
|
|
113
|
+
| `/advisor ask` | Runs one consultation **now** and returns the advice as command output. |
|
|
114
|
+
| `/advisor cancel` | Aborts the in-flight consultation — the request is aborted, not merely ignored. |
|
|
115
|
+
| `/advisor preview` | **Sends nothing.** Prints exactly what the next consultation would transmit: target route, scope, character/token estimate, omitted host context, tool traffic, redaction hits, allowlist verdict, cross-provider confirmation state, price source and today's workspace usage. |
|
|
116
|
+
| `/advisor confirm` | Allows sending the conversation to the current provider when it differs from the main model's provider. |
|
|
117
|
+
| `/advisor report all` | Cross-session report from the advice ledger (`<DSH_HOME>/advisor/advice.jsonl`): totals by severity, model and day. |
|
|
118
|
+
| `/advisor report` | Per-session advice report: how many were delivered, how many were **adopted** (heuristic: a path / backticked command / anchored ref from the advice shows up in later events), and how many evidence anchors verified. |
|
|
119
|
+
| `/advisor doctor` | Self-check: host `llm` service, registered routes, route resolution and context window, supported efforts, mode, session budget, ledger state, last failure. Each line states its conclusion and, where relevant, the next step. |
|
|
120
|
+
| `/advisor <provider>/<model> [effort]` | Sets the advisor route directly, with the same validation as the picker (unknown route, missing credentials and unsupported effort are rejected with a readable reason). |
|
|
114
121
|
|
|
115
122
|
The `advisor` **tool** is separate from the command: the model calls it, not you. It takes no required arguments; its optional `focus` is one sentence naming the doubt you want settled — not the task itself, because the transcript always is.
|
|
116
123
|
|
|
@@ -147,6 +154,7 @@ The plugin declares no `engines.dsh` and no `@deepseek-ai/*` peer range: DSH is
|
|
|
147
154
|
Nothing else: no workspace files, no session-log records of its own (a consultation shows up as an ordinary tool call and tool result in the transcript), no telemetry.
|
|
148
155
|
|
|
149
156
|
- **The advice is model output.** It can be wrong, vague, or confidently wrong. The plugin validates the _shape_ — a JSON object, a known verdict and severity, length caps, declared evidence anchors — not the content. Weigh it and verify it; the main model still owns the decision.
|
|
157
|
+
- **Command surface is UI-only.** `ctx.commands` is a human command registry: UI-less hosts (headless `-p`, ACP automation) provide no command adapter, so `/advisor` is unavailable there. The tool, the settings file and the RPCs still work; "three-end parity" for the command surface is not achievable by design, not a missing feature.
|
|
150
158
|
- **Semi-public host seams.** `llm.prepareCall`, `llm.resolveModelInfo`, `session.deriveMessages`, `tools.register`, `commands.register` and `session/event` on the host side, and `commandUi.decorate` (the picker) on the client side, are not a stable public API. A DSH upgrade can silently disable the tool, the picker or the command. Run `pnpm probe:runtime` after every upgrade; installation failures are logged rather than thrown, so check `/advisor doctor` and the host logs.
|
|
151
159
|
- **Pairing needs your declaration.** DSH has no cross-vendor capability catalog, so "is the advisor at least as strong as the main model" can only come from your `tiers`. Without an entry the result says **unverified** and the consultation proceeds; it never pretends the check passed. With `pairingEnforcement: "block"` a lower declared tier rejects the consultation.
|
|
152
160
|
- **Token counts can be low on an aborted call.** If a consultation is cancelled or times out, no usage chunk may arrive; the ledger then records the call with zero tokens and a cost budget can lag real spend. Treat the ledger as a good estimate, not an invoice.
|
package/lib/adoption.js
CHANGED
|
@@ -28,32 +28,37 @@ export function signalsOf(data) {
|
|
|
28
28
|
* @param {any[]} events 会话全量事件
|
|
29
29
|
* @param {number} fromIndex 建议记录所在的事件下标
|
|
30
30
|
* @param {any} data 建议记录的数据
|
|
31
|
-
* @returns {{ verdict: "adopted"|"unknown", why: string }}
|
|
31
|
+
* @returns {{ verdict: "adopted"|"unknown", why: string, confidence: "high"|"medium"|"low" }}
|
|
32
32
|
*/
|
|
33
33
|
export function attributeAdoption(events, fromIndex, data) {
|
|
34
34
|
const signals = signalsOf(data);
|
|
35
|
-
if (signals.length === 0)
|
|
35
|
+
if (signals.length === 0)
|
|
36
|
+
return { verdict: "unknown", why: "建议里没有可追踪的信号", confidence: "low" };
|
|
36
37
|
const list = Array.isArray(events) ? events : [];
|
|
37
38
|
for (let index = fromIndex + 1; index < list.length; index += 1) {
|
|
38
39
|
const haystack = JSON.stringify(list[index]?.data ?? "");
|
|
39
40
|
for (const signal of signals) {
|
|
40
|
-
if (haystack.includes(signal))
|
|
41
|
+
if (haystack.includes(signal)) {
|
|
42
|
+
// 路径/证据 ref 比反引号命令更有区分度(命令常被复述)。
|
|
43
|
+
const specific = signal.includes("/") || signal.includes("_");
|
|
44
|
+
return { verdict: "adopted", why: signal, confidence: specific ? "high" : "medium" };
|
|
45
|
+
}
|
|
41
46
|
}
|
|
42
47
|
}
|
|
43
|
-
return { verdict: "unknown", why: "后续没有出现建议里的信号" };
|
|
48
|
+
return { verdict: "unknown", why: "后续没有出现建议里的信号", confidence: "low" };
|
|
44
49
|
}
|
|
45
50
|
|
|
46
51
|
/**
|
|
47
52
|
* 汇总一批建议记录(供 `/advisor report` 与未来的设置页使用)。
|
|
48
53
|
* @param {any[]} events
|
|
49
54
|
* @param {Array<{ index: number, data: any }>} records
|
|
50
|
-
* @returns {{ total: number, adopted: number, unknown: number, anchorsChecked: number, anchorsVerified: number, items: Array<{ severity: string, summary: string, verdict: string, why: string, adviceId: string }> }}
|
|
55
|
+
* @returns {{ total: number, adopted: number, unknown: number, anchorsChecked: number, anchorsVerified: number, items: Array<{ severity: string, summary: string, verdict: string, why: string, confidence: string, adviceId: string }> }}
|
|
51
56
|
*/
|
|
52
57
|
export function summarizeAdoption(events, records) {
|
|
53
58
|
let adopted = 0;
|
|
54
59
|
let anchorsChecked = 0;
|
|
55
60
|
let anchorsVerified = 0;
|
|
56
|
-
/** @type {Array<{ severity: string, summary: string, verdict: string, why: string, adviceId: string }>} */
|
|
61
|
+
/** @type {Array<{ severity: string, summary: string, verdict: string, why: string, confidence: string, adviceId: string }>} */
|
|
57
62
|
const items = [];
|
|
58
63
|
for (const { index, data } of Array.isArray(records) ? records : []) {
|
|
59
64
|
const outcome = attributeAdoption(events, index, data);
|
|
@@ -67,6 +72,7 @@ export function summarizeAdoption(events, records) {
|
|
|
67
72
|
.slice(0, 80),
|
|
68
73
|
verdict: outcome.verdict,
|
|
69
74
|
why: outcome.why,
|
|
75
|
+
confidence: outcome.confidence,
|
|
70
76
|
adviceId: String(data?.adviceId ?? ""),
|
|
71
77
|
});
|
|
72
78
|
}
|
package/lib/budget.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 工作区级共享预算池:多个会话共用一份「今天已经花掉多少」的账。
|
|
3
|
+
//
|
|
4
|
+
// 为什么需要:会话级上限挡不住「开十个会话各花满一次」,而日报表又要跨会话累计。
|
|
5
|
+
// 落盘 `<dataRoot>/advisor/budget.json`,按本地日键滚动;写入走临时文件 + rename。
|
|
6
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
|
|
9
|
+
/** 预算池文件名(位于数据根下的 advisor/ 目录)。 */
|
|
10
|
+
export const BUDGET_FILE = "budget.json";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 本地日键 YYYY-MM-DD。
|
|
14
|
+
* @param {Date} [date]
|
|
15
|
+
* @returns {string}
|
|
16
|
+
*/
|
|
17
|
+
export function dayKey(date = new Date()) {
|
|
18
|
+
const year = date.getFullYear();
|
|
19
|
+
const month = `${date.getMonth() + 1}`.padStart(2, "0");
|
|
20
|
+
const day = `${date.getDate()}`.padStart(2, "0");
|
|
21
|
+
return `${year}-${month}-${day}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 规整预算池内容:跨日自动清零。
|
|
26
|
+
* @param {unknown} raw
|
|
27
|
+
* @param {string} today
|
|
28
|
+
* @returns {{ day: string, calls: number, costUsd: number }}
|
|
29
|
+
*/
|
|
30
|
+
export function normalizePool(raw, today) {
|
|
31
|
+
const input = raw !== null && typeof raw === "object" ? /** @type {any} */ (raw) : {};
|
|
32
|
+
if (input.day !== today) return { day: today, calls: 0, costUsd: 0 };
|
|
33
|
+
return {
|
|
34
|
+
day: today,
|
|
35
|
+
calls: Math.max(0, Math.round(Number(input.calls ?? 0) || 0)),
|
|
36
|
+
costUsd: Math.max(0, Number(input.costUsd ?? 0) || 0),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 池子是否还能容纳一次调用。
|
|
42
|
+
* @param {{ calls: number, costUsd: number }} pool
|
|
43
|
+
* @param {{ workspaceMaxCallsPerDay: number, workspaceMaxCostPerDayUsd: number }} settings
|
|
44
|
+
* @param {number} [estimatedCostUsd]
|
|
45
|
+
* @returns {{ ok: true } | { ok: false, code: "workspace_calls"|"workspace_budget", used: number, limit: number }}
|
|
46
|
+
*/
|
|
47
|
+
export function checkPool(pool, settings, estimatedCostUsd = 0) {
|
|
48
|
+
const maxCalls = Number(settings?.workspaceMaxCallsPerDay ?? 0) || 0;
|
|
49
|
+
if (maxCalls > 0 && pool.calls >= maxCalls) {
|
|
50
|
+
return { ok: false, code: "workspace_calls", used: pool.calls, limit: maxCalls };
|
|
51
|
+
}
|
|
52
|
+
const maxCost = Number(settings?.workspaceMaxCostPerDayUsd ?? 0) || 0;
|
|
53
|
+
if (maxCost > 0 && pool.costUsd + estimatedCostUsd >= maxCost) {
|
|
54
|
+
return { ok: false, code: "workspace_budget", used: pool.costUsd, limit: maxCost };
|
|
55
|
+
}
|
|
56
|
+
return { ok: true };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {{ home: string, logger?: DSH.Logger }} options
|
|
61
|
+
* @returns {{ read: () => Promise<{ day: string, calls: number, costUsd: number }>, add: (input: { calls?: number, costUsd?: number }) => Promise<{ day: string, calls: number, costUsd: number }>, path: string }}
|
|
62
|
+
*/
|
|
63
|
+
export function createBudgetPool(options) {
|
|
64
|
+
const dir = join(options.home, "advisor");
|
|
65
|
+
const path = join(dir, BUDGET_FILE);
|
|
66
|
+
|
|
67
|
+
/** @returns {Promise<{ day: string, calls: number, costUsd: number }>} */
|
|
68
|
+
const read = async () => {
|
|
69
|
+
const today = dayKey();
|
|
70
|
+
try {
|
|
71
|
+
const text = await readFile(path, "utf8");
|
|
72
|
+
return normalizePool(JSON.parse(text), today);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
const code = /** @type {any} */ (error)?.code;
|
|
75
|
+
if (code !== "ENOENT") options.logger?.warn?.(`[advisor] 读取预算池失败:${String(error)}`);
|
|
76
|
+
return { day: today, calls: 0, costUsd: 0 };
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** @param {{ calls?: number, costUsd?: number }} input */
|
|
81
|
+
const add = async (input) => {
|
|
82
|
+
const current = await read();
|
|
83
|
+
const next = {
|
|
84
|
+
day: current.day,
|
|
85
|
+
calls: current.calls + Math.max(0, Math.round(Number(input?.calls ?? 0) || 0)),
|
|
86
|
+
costUsd: current.costUsd + Math.max(0, Number(input?.costUsd ?? 0) || 0),
|
|
87
|
+
};
|
|
88
|
+
try {
|
|
89
|
+
await mkdir(dir, { recursive: true });
|
|
90
|
+
const temp = `${path}.tmp`;
|
|
91
|
+
await writeFile(temp, `${JSON.stringify(next, null, 2)}\n`, "utf8");
|
|
92
|
+
await rename(temp, path);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
options.logger?.warn?.(`[advisor] 写预算池失败:${String(error)}`);
|
|
95
|
+
}
|
|
96
|
+
return next;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
return { read, add, path };
|
|
100
|
+
}
|
package/lib/call.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// 一次顾问调用:prepareCall → stream → 聚合文本 / usage / 错误分类。
|
|
3
3
|
// 这是整个插件唯一会花钱的地方,所有失败都必须变成**结构化结果**,绝不向上抛。
|
|
4
4
|
import { BlockAssembler } from "@deepseek-ai/dsh-llm";
|
|
5
|
-
import {
|
|
5
|
+
import { advisorSystemPrompt, buildAdvisorInput, mintNonce } from "./prompt.js";
|
|
6
6
|
|
|
7
7
|
/** 额外调用统一打这个 purpose:也是递归防护的判据(监听器按它跳过自己)。 */
|
|
8
8
|
export const PURPOSE = "advisor";
|
|
@@ -37,6 +37,8 @@ export function classifyError(error) {
|
|
|
37
37
|
* @property {string} [focus]
|
|
38
38
|
* @property {string} [locale]
|
|
39
39
|
* @property {string} sessionId
|
|
40
|
+
* @property {string} [extra] 第二轮取证时追加的上下文
|
|
41
|
+
* @property {boolean} [canRequestEvidence]
|
|
40
42
|
* @property {AbortSignal} [signal]
|
|
41
43
|
* @property {DSH.Logger} [logger]
|
|
42
44
|
*/
|
|
@@ -76,12 +78,15 @@ export async function callAdvisor(input) {
|
|
|
76
78
|
}
|
|
77
79
|
|
|
78
80
|
const nonce = mintNonce();
|
|
79
|
-
const
|
|
81
|
+
const baseText = buildAdvisorInput({
|
|
80
82
|
transcript,
|
|
81
83
|
nonce,
|
|
82
84
|
focus: input.focus,
|
|
83
85
|
locale: input.locale,
|
|
84
86
|
});
|
|
87
|
+
const userText =
|
|
88
|
+
input.extra === undefined || input.extra === "" ? baseText : `${baseText}\n\n${input.extra}`;
|
|
89
|
+
const system = advisorSystemPrompt({ canRequestEvidence: input.canRequestEvidence === true });
|
|
85
90
|
const messages = /** @type {any} */ ([
|
|
86
91
|
{ role: "user", content: [{ type: "text", text: userText }] },
|
|
87
92
|
]);
|
|
@@ -134,7 +139,7 @@ export async function callAdvisor(input) {
|
|
|
134
139
|
for await (const chunk of prepared.stream({
|
|
135
140
|
...prepared.config,
|
|
136
141
|
messages,
|
|
137
|
-
system
|
|
142
|
+
system,
|
|
138
143
|
sessionId,
|
|
139
144
|
purpose: PURPOSE,
|
|
140
145
|
...(signal === undefined ? {} : { signal }),
|
package/lib/catalog.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 内置模型目录:**兜底用的能力档位与价格表**。
|
|
3
|
+
//
|
|
4
|
+
// DSH 的 `LlmModelInfo` 没有 rank、没有价格(见 docs/runtime §9.15),所以配对与金额只能靠元数据。
|
|
5
|
+
// 这里给一张很小的、刻意保守的表:
|
|
6
|
+
// - 只覆盖确定了解的型号;**认不出就返回 undefined**,绝不猜(猜错比不知道更糟);
|
|
7
|
+
// - 用户可以在设置里用 `tiers` / 单价覆盖这里的值(覆盖优先);
|
|
8
|
+
// - 表里的价格是「量级参考」,不是报价;设置页会标「估算」。
|
|
9
|
+
//
|
|
10
|
+
// 纯数据 + 纯函数,不 import 宿主包。
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 能力档位(越大越强)。同一族按代际与规格排序;跨族只保证「明显更强/更弱」的关系。
|
|
14
|
+
* 键是模型 id 的小写匹配片段,按**从长到短**匹配,避免 `deepseek-v4` 抢走 `deepseek-v4.1-flash`。
|
|
15
|
+
* @type {ReadonlyArray<{ match: string, rank: number }>}
|
|
16
|
+
*/
|
|
17
|
+
export const MODEL_RANKS = Object.freeze([
|
|
18
|
+
{ match: "deepseek-v4.1-flash", rank: 3 },
|
|
19
|
+
{ match: "deepseek-v4.1", rank: 5 },
|
|
20
|
+
{ match: "deepseek-v4-pro", rank: 6 },
|
|
21
|
+
{ match: "deepseek-v3.2", rank: 3 },
|
|
22
|
+
{ match: "deepseek-reasoner", rank: 5 },
|
|
23
|
+
{ match: "deepseek-chat", rank: 3 },
|
|
24
|
+
{ match: "claude-opus-4", rank: 7 },
|
|
25
|
+
{ match: "claude-sonnet-4", rank: 5 },
|
|
26
|
+
{ match: "claude-haiku-4", rank: 2 },
|
|
27
|
+
{ match: "gpt-5", rank: 6 },
|
|
28
|
+
{ match: "gpt-4.1", rank: 4 },
|
|
29
|
+
{ match: "o3", rank: 6 },
|
|
30
|
+
{ match: "o4-mini", rank: 4 },
|
|
31
|
+
{ match: "kimi-k3", rank: 5 },
|
|
32
|
+
{ match: "qwen3.8-max", rank: 6 },
|
|
33
|
+
{ match: "qwen3.8-flash", rank: 3 },
|
|
34
|
+
{ match: "glm-5.3", rank: 4 },
|
|
35
|
+
{ match: "glm-5.3-flash", rank: 3 },
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 价格(USD / 百万 token),只用于「估算」。缺失即未知。
|
|
40
|
+
* @type {ReadonlyArray<{ match: string, input: number, output: number }>}
|
|
41
|
+
*/
|
|
42
|
+
export const MODEL_PRICES = Object.freeze([
|
|
43
|
+
{ match: "deepseek-v4.1-flash", input: 0.1, output: 0.3 },
|
|
44
|
+
{ match: "deepseek-v4-pro", input: 0.6, output: 2.4 },
|
|
45
|
+
{ match: "deepseek-v4.1", input: 0.3, output: 1.2 },
|
|
46
|
+
{ match: "deepseek-reasoner", input: 0.6, output: 2.4 },
|
|
47
|
+
{ match: "deepseek-chat", input: 0.3, output: 1.2 },
|
|
48
|
+
{ match: "claude-haiku-4", input: 1, output: 5 },
|
|
49
|
+
{ match: "claude-sonnet-4", input: 3, output: 15 },
|
|
50
|
+
{ match: "claude-opus-4", input: 15, output: 75 },
|
|
51
|
+
{ match: "kimi-k3", input: 0.6, output: 2.4 },
|
|
52
|
+
{ match: "qwen3.8-flash", input: 0.1, output: 0.3 },
|
|
53
|
+
]);
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 在表里按「最长匹配优先」找一行。
|
|
57
|
+
* @template T
|
|
58
|
+
* @param {readonly T[]} table
|
|
59
|
+
* @param {string} id
|
|
60
|
+
* @param {(row: T) => string} key
|
|
61
|
+
* @returns {T|undefined}
|
|
62
|
+
*/
|
|
63
|
+
function lookup(table, id, key) {
|
|
64
|
+
const model = String(id ?? "").toLowerCase();
|
|
65
|
+
if (model === "") return undefined;
|
|
66
|
+
/** @type {T|undefined} */
|
|
67
|
+
let best;
|
|
68
|
+
let bestLength = 0;
|
|
69
|
+
for (const row of table) {
|
|
70
|
+
const needle = key(row);
|
|
71
|
+
if (!model.includes(needle)) continue;
|
|
72
|
+
if (needle.length > bestLength) {
|
|
73
|
+
best = row;
|
|
74
|
+
bestLength = needle.length;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return best;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 内置档位;认不出返回 undefined。
|
|
82
|
+
* @param {string} modelId
|
|
83
|
+
* @returns {number|undefined}
|
|
84
|
+
*/
|
|
85
|
+
export function builtinRank(modelId) {
|
|
86
|
+
const row = lookup(MODEL_RANKS, modelId, (item) => item.match);
|
|
87
|
+
return row === undefined ? undefined : row.rank;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 内置价格;认不出返回 undefined。
|
|
92
|
+
* @param {string} modelId
|
|
93
|
+
* @returns {{ input: number, output: number }|undefined}
|
|
94
|
+
*/
|
|
95
|
+
export function builtinPrice(modelId) {
|
|
96
|
+
const row = lookup(MODEL_PRICES, modelId, (item) => item.match);
|
|
97
|
+
return row === undefined ? undefined : { input: row.input, output: row.output };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 有效档位:用户声明 > 内置;都没有返回 undefined(= 未校验)。
|
|
102
|
+
* @param {Record<string, number>} tiers
|
|
103
|
+
* @param {{ provider: string, model: string }} route
|
|
104
|
+
* @returns {number|undefined}
|
|
105
|
+
*/
|
|
106
|
+
export function effectiveRank(tiers, route) {
|
|
107
|
+
const key = `${route.provider}/${route.model}`;
|
|
108
|
+
const declared = tiers !== null && typeof tiers === "object" ? tiers[key] : undefined;
|
|
109
|
+
if (typeof declared === "number" && Number.isFinite(declared)) return declared;
|
|
110
|
+
return builtinRank(route.model);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 有效单价:用户声明 > 内置;都没有返回 `{ input: 0, output: 0 }`(= 不算钱)。
|
|
115
|
+
* @param {{ priceInputPerMTok: number, priceOutputPerMTok: number }} settings
|
|
116
|
+
* @param {string} modelId
|
|
117
|
+
* @returns {{ input: number, output: number, source: "settings"|"builtin"|"none" }}
|
|
118
|
+
*/
|
|
119
|
+
export function effectivePrice(settings, modelId) {
|
|
120
|
+
const input = Number(settings?.priceInputPerMTok ?? 0) || 0;
|
|
121
|
+
const output = Number(settings?.priceOutputPerMTok ?? 0) || 0;
|
|
122
|
+
if (input > 0 || output > 0) return { input, output, source: "settings" };
|
|
123
|
+
const builtin = builtinPrice(modelId);
|
|
124
|
+
if (builtin !== undefined) return { ...builtin, source: "builtin" };
|
|
125
|
+
return { input: 0, output: 0, source: "none" };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 用户白名单:`allowedModels` 为空表示不限制;否则只允许列出的 `provider/model` 或裸 model id。
|
|
130
|
+
* @param {string[]} allowedModels
|
|
131
|
+
* @param {{ provider: string, model: string }} route
|
|
132
|
+
* @returns {{ allowed: boolean, reason: string }}
|
|
133
|
+
*/
|
|
134
|
+
export function checkAllowlist(allowedModels, route) {
|
|
135
|
+
const list = Array.isArray(allowedModels)
|
|
136
|
+
? allowedModels.filter((item) => typeof item === "string" && item !== "")
|
|
137
|
+
: [];
|
|
138
|
+
if (list.length === 0) return { allowed: true, reason: "未设置白名单" };
|
|
139
|
+
const full = `${route.provider}/${route.model}`;
|
|
140
|
+
if (list.includes(full) || list.includes(route.model))
|
|
141
|
+
return { allowed: true, reason: "在白名单内" };
|
|
142
|
+
return { allowed: false, reason: `不在 allowedModels 白名单内(${list.length} 条)` };
|
|
143
|
+
}
|