evolcore 0.0.47 → 0.0.48
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/CHANGELOG.md +56 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +139 -39
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +34 -17
- package/dist/agents/codex-runner.js +31 -16
- package/dist/agents/ecagent-runner.js +7 -4
- package/dist/agents/gemini-runner.js +5 -2
- package/dist/agents/runner-types.js +5 -21
- package/dist/aun/aid/agentmd.js +5 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +81 -24
- package/dist/channels/daemon.js +9 -25
- package/dist/cli/aun-commands.js +86 -51
- package/dist/cli/code-stats.js +19 -8
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +44 -43
- package/dist/cli/directory.js +7 -1
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +2 -8
- package/dist/cli/init-channel.js +4 -6
- package/dist/cli/init.js +72 -50
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/role.js +61 -17
- package/dist/cli/stats.js +3 -3
- package/dist/cli/thread-command.js +16 -51
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-manager.js +2 -6
- package/dist/config/daemon-services.js +30 -3
- package/dist/config/gateway-config.js +2 -2
- package/dist/config/invoke-ipc-service.js +6 -4
- package/dist/config/peer-bind-code.js +3 -4
- package/dist/config/peer-book-store.js +62 -229
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +4 -1
- package/dist/config/provider-ipc-service.js +56 -11
- package/dist/config/provider-menu-request.js +24 -5
- package/dist/config/provider-templates.js +127 -0
- package/dist/config/providers-config.js +59 -8
- package/dist/config/providers-management.js +467 -49
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +105 -4
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +4 -0
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +3 -0
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +28 -64
- package/dist/core/capability/providers/codex-capability-provider.js +7 -8
- package/dist/core/channel-loader.js +18 -0
- package/dist/core/command/agent-control.js +32 -0
- package/dist/core/command/command-handler.js +81 -85
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +61 -149
- package/dist/core/command/menu-protocol.js +7 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +26 -43
- package/dist/core/command/team-workspace-items.js +81 -12
- package/dist/core/command/team-workspace-team.js +9 -71
- package/dist/core/command/topic-slash.js +9 -30
- package/dist/core/daemon-bootstrap.js +8 -1
- package/dist/core/daemon-control.js +7 -7
- package/dist/core/evolagent-registry.js +14 -1
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +11 -6
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +2 -1
- package/dist/core/message/aun-ipc-sender.js +165 -55
- package/dist/core/message/im-renderer.js +1 -1
- package/dist/core/message/message-bridge.js +51 -334
- package/dist/core/message/message-log.js +5 -0
- package/dist/core/message/message-queue.js +22 -0
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +429 -116
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/ownership/owner-resolver.js +328 -50
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/relation/peer-identity.js +23 -1
- package/dist/core/relation/same-owner-proof.js +81 -112
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +13 -7
- package/dist/core/session/session-fs-store.js +91 -35
- package/dist/core/session/session-manager.js +68 -24
- package/dist/core/session/session-mapper.js +14 -34
- package/dist/core/session/session-transcript.js +5 -1
- package/dist/core/task/task-activity-store.js +84 -0
- package/dist/core/task/task-recovery-service.js +12 -0
- package/dist/core/thread/command-parser.js +7 -12
- package/dist/core/thread/thread-context-storage.js +3 -2
- package/dist/core/thread/thread-operation.js +2 -13
- package/dist/core/thread/thread-service.js +15 -46
- package/dist/directory/owner-directory-admission.js +1 -1
- package/dist/directory/owner-directory-cache.js +45 -28
- package/dist/directory/owner-directory-markdown.js +13 -1
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/eck/message-renderer.js +84 -24
- package/dist/ecweb/basic-settings-service.js +3 -1
- package/dist/ecweb/message-context-service.js +1 -1
- package/dist/ecweb/pairing.js +4 -3
- package/dist/ecweb/providers-service.js +26 -1
- package/dist/ecweb/runtime/lifecycle.js +18 -8
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +4 -2
- package/dist/event-center/registry.js +13 -2
- package/dist/event-center/runtime.js +103 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +92 -59
- package/dist/ipc.js +13 -2
- package/dist/outputs/events.js +62 -0
- package/dist/outputs/protocol.js +102 -0
- package/dist/outputs/service.js +279 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +89 -4
- package/dist/services/ipc-operation.js +4 -15
- package/dist/services/pack-manager.js +12 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +1 -1
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/role-budget.js +5 -2
- package/dist/stats/writer.js +10 -6
- package/dist/trigger/audit.js +7 -0
- package/dist/trigger/authorization.js +105 -11
- package/dist/trigger/feedback.js +10 -0
- package/dist/trigger/history.js +37 -11
- package/dist/trigger/ipc-service.js +12 -1
- package/dist/trigger/manager.js +1 -0
- package/dist/trigger/scheduler.js +7 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +9 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/cross-platform.js +73 -26
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +27 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/process-introspect.js +12 -7
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/windows-shell-trust.js +2 -0
- package/dist/workbench/protocol.js +80 -0
- package/dist/workbench/service.js +359 -0
- package/ecagent/dist/types.d.ts +6 -2
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +2 -2
- package/kits/docs/evolcore/config.md +12 -0
- package/kits/docs/evolcore/directory.md +22 -3
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +123 -3
- package/kits/docs/evolcore/role.md +80 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/team-workspace.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +14 -15
- package/kits/docs/evolcore/tool-authorization.md +5 -0
- package/kits/docs/evolcore/trigger.md +10 -0
- package/kits/eck_message_manifest.json +12 -0
- package/kits/provider-templates.json +1213 -0
- package/kits/rules/04-relation.md +3 -3
- package/kits/schemas/_meta.json +14 -2
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/ec-group/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +19 -72
- package/kits/skills/ec-provider/SKILL.md +221 -0
- package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/skills/thread-ops/SKILL.md +34 -21
- package/kits/templates/message-fragments/group-batch-item.md +1 -1
- package/kits/templates/message-fragments/group-batch.md +1 -1
- package/kits/templates/message-fragments/inject-default.md +1 -1
- package/kits/templates/message-fragments/interrupt-insert.md +1 -0
- package/kits/templates/message-fragments/item-group.md +1 -1
- package/kits/templates/message-fragments/item-private.md +1 -1
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/message-fragments/trigger-session.md +1 -1
- package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
- package/kits/templates/roles/admin.json +2 -19
- package/kits/templates/roles/member.json +0 -3
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +3 -3
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +1 -1
- package/kits/templates/system-fragments/thread.md +6 -5
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +4 -1
- package/scripts/agent-template/shared/common.mjs +2 -3
- package/scripts/agent-template/shared/template-contract.mjs +2 -1
- package/scripts/agent-template/shared/template-package.mjs +9 -2
- package/scripts/agent-template/shared/template-runtime.mjs +20 -5
- package/scripts/agent-template/team-pack.mjs +6 -3
- package/dist/cli/peer.js +0 -127
- package/dist/config/peer-operation-service.js +0 -132
- package/dist/config/peer-request-service.js +0 -532
- package/dist/core/command/connect-menu.js +0 -624
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* model-resolver.ts — 统一模型参数、模型别名、价格表、网关价格缓存与计费逻辑。
|
|
3
3
|
* 供各基座、用量写入、查询和历史回填共用。
|
|
4
4
|
*/
|
|
5
5
|
import fs from 'fs';
|
|
6
6
|
import path from 'path';
|
|
7
|
-
import { getPackageRoot } from '../paths.js';
|
|
7
|
+
import { getPackageRoot, resolveRoot } from '../paths.js';
|
|
8
8
|
import { parseModelId, stripContextWindowSuffix } from '../core/model/context-window-suffix.js';
|
|
9
9
|
import { logger } from '../utils/logger.js';
|
|
10
|
+
/** 汇率合法区间:超出视为接口异常,回退默认值,避免金额被单个脏值整体扭曲。 */
|
|
11
|
+
export const MIN_USD_TO_CNY = 3;
|
|
12
|
+
export const MAX_USD_TO_CNY = 15;
|
|
13
|
+
export const DEFAULT_USD_TO_CNY = 7.23;
|
|
14
|
+
export function normalizeUsdToCny(raw) {
|
|
15
|
+
const n = typeof raw === 'number' ? raw : NaN;
|
|
16
|
+
return Number.isFinite(n) && n >= MIN_USD_TO_CNY && n <= MAX_USD_TO_CNY ? n : undefined;
|
|
17
|
+
}
|
|
10
18
|
/** Keep wire/log metadata readable while preserving full precision in storage. */
|
|
11
19
|
export function roundCostForOutput(value) {
|
|
12
20
|
return Number.isFinite(value) ? Number(value.toFixed(4)) : value;
|
|
@@ -76,6 +84,158 @@ export function resolveCanonicalModel(evolcoreHome, model) {
|
|
|
76
84
|
const entry = aliases.find(a => a.alias === model);
|
|
77
85
|
return entry ? entry.canonical : model;
|
|
78
86
|
}
|
|
87
|
+
// ── Provider 模型别名:端点持久化、人工覆盖与运行目录隔离缓存 ─────────────
|
|
88
|
+
const PROVIDER_ALIAS_CACHE_TTL_MS = 60 * 1000;
|
|
89
|
+
/**
|
|
90
|
+
* 内置兜底别名:按 Provider 主机名分组,方向与端点一致(别名 → 本端实际 ID)。
|
|
91
|
+
* 收录依据:Evol 端点 deepseek-v4.1-flash 的价格换算人民币后与 DeepSeek 官方
|
|
92
|
+
* deepseek-flash 的高峰价逐项吻合(input/output/cache_read),窗口与输出上限一致。
|
|
93
|
+
* 未核实的映射不要写进来——错误归一会让报告口径失真。
|
|
94
|
+
* 端点下发 model_aliases 后,同键以端点为准;本表可逐步清空。
|
|
95
|
+
*/
|
|
96
|
+
const DEFAULT_PROVIDER_ALIASES = {
|
|
97
|
+
'mg-new.evolai.cn': {
|
|
98
|
+
'deepseek-flash': 'deepseek-v4.1-flash',
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
let providerAliasCache = null;
|
|
102
|
+
function providerAliasCachePath(evolcoreHome) {
|
|
103
|
+
return path.join(evolcoreHome, 'data', 'stats', 'model-aliases.json');
|
|
104
|
+
}
|
|
105
|
+
/** 从 baseUrl 取 Provider 键:host[:port]。解析失败返回 undefined。 */
|
|
106
|
+
export function providerKeyFromBaseUrl(baseUrl) {
|
|
107
|
+
if (!baseUrl)
|
|
108
|
+
return undefined;
|
|
109
|
+
try {
|
|
110
|
+
const u = new URL(baseUrl);
|
|
111
|
+
return u.host || undefined;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function readProviderAliasFile(evolcoreHome) {
|
|
118
|
+
const file = providerAliasCachePath(evolcoreHome);
|
|
119
|
+
try {
|
|
120
|
+
if (!fs.existsSync(file))
|
|
121
|
+
return {};
|
|
122
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
logger.warn(`[ModelAliases] 读取 ${file} 失败,仅使用内置兜底别名: ${e}`);
|
|
126
|
+
return {};
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function mergeProviderAliasEntries(target, aliases) {
|
|
130
|
+
for (const [alias, actual] of Object.entries(aliases ?? {})) {
|
|
131
|
+
if (!alias || !actual || alias === actual)
|
|
132
|
+
continue;
|
|
133
|
+
target.set(alias, actual);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function loadProviderAliases(evolcoreHome) {
|
|
137
|
+
const now = Date.now();
|
|
138
|
+
const home = path.resolve(evolcoreHome);
|
|
139
|
+
if (providerAliasCache?.home === home && now - providerAliasCache.loadedAt < PROVIDER_ALIAS_CACHE_TTL_MS)
|
|
140
|
+
return providerAliasCache;
|
|
141
|
+
const byHost = new Map();
|
|
142
|
+
const ensure = (host) => {
|
|
143
|
+
let m = byHost.get(host);
|
|
144
|
+
if (!m) {
|
|
145
|
+
m = new Map();
|
|
146
|
+
byHost.set(host, m);
|
|
147
|
+
}
|
|
148
|
+
return m;
|
|
149
|
+
};
|
|
150
|
+
// 1. 内置兜底
|
|
151
|
+
for (const [host, aliases] of Object.entries(DEFAULT_PROVIDER_ALIASES))
|
|
152
|
+
mergeProviderAliasEntries(ensure(host), aliases);
|
|
153
|
+
const parsed = readProviderAliasFile(evolcoreHome);
|
|
154
|
+
// 2. 端点下发
|
|
155
|
+
for (const [host, entry] of Object.entries(parsed.sources ?? {})) {
|
|
156
|
+
mergeProviderAliasEntries(ensure(host), entry?.aliases);
|
|
157
|
+
}
|
|
158
|
+
// 3. 人工补录(最高优先级)
|
|
159
|
+
for (const [host, aliases] of Object.entries(parsed.overrides ?? {})) {
|
|
160
|
+
mergeProviderAliasEntries(ensure(host), aliases);
|
|
161
|
+
}
|
|
162
|
+
providerAliasCache = { home, byHost, loadedAt: now };
|
|
163
|
+
return providerAliasCache;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* 保存端点下发的对照表,写 `sources` 段。
|
|
167
|
+
* 只保留值确实出现在本次 `/v1/models` data[].id 中的条目——端点写错的映射直接丢弃,
|
|
168
|
+
* 避免把两个不同模型的价格混在一起。传 knownModels 为 undefined 时不做这一校验。
|
|
169
|
+
*/
|
|
170
|
+
export function saveProviderAliases(evolcoreHome, baseUrl, raw, knownModels) {
|
|
171
|
+
const host = providerKeyFromBaseUrl(baseUrl);
|
|
172
|
+
if (!host || !raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
173
|
+
return;
|
|
174
|
+
const known = knownModels ? new Set(knownModels) : undefined;
|
|
175
|
+
const aliases = {};
|
|
176
|
+
for (const [alias, actual] of Object.entries(raw)) {
|
|
177
|
+
if (typeof actual !== 'string' || !actual)
|
|
178
|
+
continue;
|
|
179
|
+
if (alias === actual)
|
|
180
|
+
continue;
|
|
181
|
+
if (known && !known.has(actual)) {
|
|
182
|
+
logger.warn(`[ModelAliases] Drop ${host}: ${alias} → ${actual}(目标不在 /v1/models 列表中)`);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
aliases[alias] = actual;
|
|
186
|
+
}
|
|
187
|
+
const file = providerAliasCachePath(evolcoreHome);
|
|
188
|
+
const parsed = readProviderAliasFile(evolcoreHome);
|
|
189
|
+
const sources = parsed.sources ?? {};
|
|
190
|
+
const prev = sources[host]?.aliases ?? {};
|
|
191
|
+
const changed = JSON.stringify(prev) !== JSON.stringify(aliases);
|
|
192
|
+
sources[host] = { fetched_at: new Date().toISOString(), aliases };
|
|
193
|
+
if (!changed && parsed.$schema_version === 2)
|
|
194
|
+
return; // 内容未变,省一次写盘
|
|
195
|
+
const next = {
|
|
196
|
+
$schema_version: 2,
|
|
197
|
+
updated_at: new Date().toISOString(),
|
|
198
|
+
sources,
|
|
199
|
+
overrides: parsed.overrides ?? {},
|
|
200
|
+
};
|
|
201
|
+
try {
|
|
202
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
203
|
+
fs.writeFileSync(file, JSON.stringify(next, null, 2));
|
|
204
|
+
providerAliasCache = null;
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
logger.warn(`[ModelAliases] 写入 ${file} 失败: ${e}`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* 把一次调用使用的实际模型 ID 归一为对外通用 ID。
|
|
212
|
+
* 未配置 Provider、未命中别名、或对照表缺失时,返回 undefined(调用方按原名处理)。
|
|
213
|
+
*/
|
|
214
|
+
export function resolveProviderAlias(evolcoreHome, baseUrl, model) {
|
|
215
|
+
const host = providerKeyFromBaseUrl(baseUrl);
|
|
216
|
+
if (!host)
|
|
217
|
+
return undefined;
|
|
218
|
+
const map = loadProviderAliases(evolcoreHome).byHost.get(host);
|
|
219
|
+
if (!map)
|
|
220
|
+
return undefined;
|
|
221
|
+
for (const [alias, actual] of map) {
|
|
222
|
+
if (actual === model)
|
|
223
|
+
return alias;
|
|
224
|
+
}
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
/** 某个 Provider 下的完整对照表(别名 → 实际 ID),供报告与排查使用。 */
|
|
228
|
+
export function listProviderAliases(evolcoreHome, baseUrl) {
|
|
229
|
+
const host = providerKeyFromBaseUrl(baseUrl);
|
|
230
|
+
if (!host)
|
|
231
|
+
return {};
|
|
232
|
+
const map = loadProviderAliases(evolcoreHome).byHost.get(host);
|
|
233
|
+
return map ? Object.fromEntries(map) : {};
|
|
234
|
+
}
|
|
235
|
+
/** 清除缓存,主要供测试与配置热更新使用。 */
|
|
236
|
+
export function resetModelAliasCache() {
|
|
237
|
+
providerAliasCache = null;
|
|
238
|
+
}
|
|
79
239
|
function loadPrices(evolcoreHome) {
|
|
80
240
|
const now = Date.now();
|
|
81
241
|
if (_priceCache && now - _priceCacheTs < PRICE_CACHE_TTL)
|
|
@@ -111,11 +271,45 @@ export function resolvePriceRow(evolcoreHome, model, ts) {
|
|
|
111
271
|
for (const key of modelLookupKeys(evolcoreHome, model)) {
|
|
112
272
|
const candidates = prices.filter(p => p.model === key && p.effective_from <= ts);
|
|
113
273
|
if (candidates.length) {
|
|
114
|
-
|
|
274
|
+
// 同一 effective_from 时取后出现的一行:用户覆盖层在包基线之后加载,
|
|
275
|
+
// 用 `>` 而不是 `>=` 才能让用户覆盖同时间戳的包基线行。
|
|
276
|
+
return candidates.reduce((a, b) => a.effective_from > b.effective_from ? a : b);
|
|
115
277
|
}
|
|
116
278
|
}
|
|
117
279
|
return null;
|
|
118
280
|
}
|
|
281
|
+
/**
|
|
282
|
+
* DeepSeek 高峰时段判定(北京时间):
|
|
283
|
+
* 周一至周五(不含法定节假日)9:00–12:00、14:00–18:00 为高峰,
|
|
284
|
+
* 其余时段(含周末全天、节假日全天)为空闲,空闲价 = 高峰价的一半。
|
|
285
|
+
*
|
|
286
|
+
* 实现说明:中国无夏令时,直接按 UTC+8 固定偏移换算;`getUTCDay/getUTCHours`
|
|
287
|
+
* 作用在平移后的时间戳上即得北京时间。
|
|
288
|
+
* 已知限制:法定节假日未建模——工作日的节假日仍会被算作高峰(只会高估、不会低估)。
|
|
289
|
+
*/
|
|
290
|
+
export function isDeepSeekPeakHour(ts) {
|
|
291
|
+
const at = typeof ts === 'number' && Number.isFinite(ts) ? ts : Date.now();
|
|
292
|
+
const beijing = new Date(at + 8 * 60 * 60 * 1000);
|
|
293
|
+
const day = beijing.getUTCDay(); // 0=周日, 6=周六
|
|
294
|
+
if (day === 0 || day === 6)
|
|
295
|
+
return false;
|
|
296
|
+
const hour = beijing.getUTCHours();
|
|
297
|
+
return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18);
|
|
298
|
+
}
|
|
299
|
+
/** 是否为「官方分时定价行」:必须同时标 provider 与 time_pricing。 */
|
|
300
|
+
function isOfficialTimedRow(p) {
|
|
301
|
+
return p.provider === 'deepseek-official'
|
|
302
|
+
&& p.time_pricing === 'deepseek_peak_offpeak';
|
|
303
|
+
}
|
|
304
|
+
/** 按高峰/空闲取单价:高峰优先取 `<field>_peak`,缺省按官方规则 ×2。 */
|
|
305
|
+
function timedRate(p, field, peak) {
|
|
306
|
+
const base = p[field];
|
|
307
|
+
const baseNum = typeof base === 'number' ? base : 0;
|
|
308
|
+
if (!peak)
|
|
309
|
+
return baseNum;
|
|
310
|
+
const peakVal = p[`${field}_peak`];
|
|
311
|
+
return typeof peakVal === 'number' ? peakVal : baseNum * 2;
|
|
312
|
+
}
|
|
119
313
|
export const BILLING_FNS = {
|
|
120
314
|
// 通用 per-token(Claude / OpenAI 兼容 / Kimi / MiniMax)
|
|
121
315
|
per_token_v1: (e, p) => {
|
|
@@ -125,17 +319,28 @@ export const BILLING_FNS = {
|
|
|
125
319
|
const promptTokens = e.input_tokens + e.cache_creation_tokens + e.cache_read_tokens;
|
|
126
320
|
const tier = tiers.find(t => t.up_to_input_tokens == null || promptTokens <= t.up_to_input_tokens);
|
|
127
321
|
const price = tier ?? p;
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
322
|
+
// 官方 DeepSeek 走 Anthropic 格式时也进这里(usage 是 cache_read/creation 口径),
|
|
323
|
+
// 因此分时规则要在这里同样生效;未标记的行行为不变。
|
|
324
|
+
const peak = isOfficialTimedRow(p) && isDeepSeekPeakHour(e.ts);
|
|
325
|
+
const r = timedRate(price, 'price_input', peak) * e.input_tokens / 1e6
|
|
326
|
+
+ timedRate(price, 'price_output', peak) * e.output_tokens / 1e6
|
|
327
|
+
+ timedRate(price, 'price_cache_creation', peak) * e.cache_creation_tokens / 1e6
|
|
328
|
+
+ timedRate(price, 'price_cache_read', peak) * e.cache_read_tokens / 1e6;
|
|
132
329
|
return p.currency === 'CNY' ? { cny: r } : { usd: r };
|
|
133
330
|
},
|
|
134
|
-
// DeepSeek cache_hit / cache_miss
|
|
331
|
+
// DeepSeek cache_hit / cache_miss 口径。
|
|
332
|
+
// 表里若带 time_pricing: "deepseek_peak_offpeak"(或显式 *_peak 字段),
|
|
333
|
+
// 则按调用发生时刻区分高峰/空闲:表中基准价视为空闲价,高峰取 *_peak
|
|
334
|
+
// 或按官方规则(高峰 = 空闲 ×2)折算。未标该字段的行保持原来的固定价行为。
|
|
135
335
|
per_token_deepseek_v1: (e, p) => {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
336
|
+
// 高峰/空闲分时定价只适用于 DeepSeek 官方:必须同时带
|
|
337
|
+
// provider="deepseek-official" 与 time_pricing="deepseek_peak_offpeak"。
|
|
338
|
+
// 其他 Provider 自行定价(网关 /models 的 pricing/effective_pricing 优先于本表),
|
|
339
|
+
// 即使出现同名模型也不会继承官方分时规则。
|
|
340
|
+
const peak = isOfficialTimedRow(p) && isDeepSeekPeakHour(e.ts);
|
|
341
|
+
const r = timedRate(p, 'price_cache_hit', peak) * (e.cache_hit_tokens ?? 0) / 1e6
|
|
342
|
+
+ timedRate(p, 'price_cache_miss', peak) * (e.cache_miss_tokens ?? 0) / 1e6
|
|
343
|
+
+ timedRate(p, 'price_output', peak) * e.output_tokens / 1e6;
|
|
139
344
|
return { cny: r };
|
|
140
345
|
},
|
|
141
346
|
// Gemini 分档(按 total_context_tokens 确定所在档位)
|
|
@@ -201,15 +406,67 @@ export function findModelSpec(evolcoreHome, model, ts = Date.now()) {
|
|
|
201
406
|
}
|
|
202
407
|
return undefined;
|
|
203
408
|
}
|
|
409
|
+
const gatewaySpecRegistry = new Map();
|
|
410
|
+
const GATEWAY_SPEC_TTL_MS = 60 * 60 * 1000;
|
|
411
|
+
function rememberGatewaySpecs(models) {
|
|
412
|
+
const now = Date.now();
|
|
413
|
+
for (const m of models) {
|
|
414
|
+
if (!m || typeof m !== 'object')
|
|
415
|
+
continue;
|
|
416
|
+
const id = typeof m.id === 'string' ? m.id : (typeof m.model === 'string' ? m.model : undefined);
|
|
417
|
+
if (!id)
|
|
418
|
+
continue;
|
|
419
|
+
const ctx = Number(m.context_window ?? m.contextWindow ?? m.context_length ?? 0);
|
|
420
|
+
const maxOut = Number(m.max_output_tokens ?? m.maxOutputTokens ?? 0);
|
|
421
|
+
const spec = { fetchedAt: now };
|
|
422
|
+
if (Number.isFinite(ctx) && ctx > 0)
|
|
423
|
+
spec.context_window = ctx;
|
|
424
|
+
if (Number.isFinite(maxOut) && maxOut > 0)
|
|
425
|
+
spec.max_output_tokens = maxOut;
|
|
426
|
+
if (spec.context_window === undefined && spec.max_output_tokens === undefined)
|
|
427
|
+
continue;
|
|
428
|
+
gatewaySpecRegistry.set(id, spec);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
function lookupGatewaySpec(model) {
|
|
432
|
+
const now = Date.now();
|
|
433
|
+
for (const key of [model, stripContextWindowSuffix(model)]) {
|
|
434
|
+
const hit = gatewaySpecRegistry.get(key);
|
|
435
|
+
if (hit && now - hit.fetchedAt <= GATEWAY_SPEC_TTL_MS)
|
|
436
|
+
return hit;
|
|
437
|
+
}
|
|
438
|
+
return undefined;
|
|
439
|
+
}
|
|
204
440
|
/** 取模型在 ts 时刻的能力参数。找不到时返回 fallback 或默认值。
|
|
441
|
+
* 优先级:网关 /models 自报值 > 本地表(包基线 + 用户覆盖层)> ID 窗口后缀 > 默认 200k。
|
|
205
442
|
* 带窗口后缀的 ID 复用基础模型的参数行,但窗口由后缀决定(网关的权威声明)。 */
|
|
206
443
|
export function resolveModelSpec(evolcoreHome, model, ts, fallback) {
|
|
207
|
-
const spec = findModelSpec(evolcoreHome, model, ts);
|
|
208
|
-
if (spec)
|
|
209
|
-
return spec;
|
|
210
444
|
const suffixWindow = parseModelId(model).contextWindow;
|
|
211
|
-
|
|
212
|
-
const
|
|
445
|
+
const gateway = lookupGatewaySpec(model);
|
|
446
|
+
const tableRow = findModelSpec(evolcoreHome, model, ts);
|
|
447
|
+
if (tableRow) {
|
|
448
|
+
const contextWindow = suffixWindow ?? gateway?.context_window ?? tableRow.context_window;
|
|
449
|
+
const ratio = tableRow.context_window > 0 ? tableRow.max_input_tokens / tableRow.context_window : 0.9;
|
|
450
|
+
return {
|
|
451
|
+
...tableRow,
|
|
452
|
+
model,
|
|
453
|
+
context_window: contextWindow,
|
|
454
|
+
max_input_tokens: Math.floor(contextWindow * ratio),
|
|
455
|
+
max_output_tokens: gateway?.max_output_tokens ?? tableRow.max_output_tokens,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
if (gateway?.context_window || gateway?.max_output_tokens || suffixWindow) {
|
|
459
|
+
const contextWindow = suffixWindow ?? gateway?.context_window ?? fallback?.context_window ?? 200000;
|
|
460
|
+
return {
|
|
461
|
+
model,
|
|
462
|
+
effective_from: 0,
|
|
463
|
+
context_window: contextWindow,
|
|
464
|
+
max_input_tokens: Math.floor(contextWindow * 0.9),
|
|
465
|
+
max_output_tokens: gateway?.max_output_tokens ?? fallback?.max_output_tokens ?? 8192,
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
const contextWindow = fallback?.context_window ?? 200000;
|
|
469
|
+
logger.debug(`[PriceResolver] ${model} 无网关元数据、无表项、无窗口后缀,回退默认 ${contextWindow}/8192`);
|
|
213
470
|
return {
|
|
214
471
|
model,
|
|
215
472
|
effective_from: 0,
|
|
@@ -271,6 +528,9 @@ export async function refreshGatewayPricing(baseUrl, apiKey, requestHeaders) {
|
|
|
271
528
|
: Array.isArray(json?.models) ? json.models : [];
|
|
272
529
|
const official = new Map();
|
|
273
530
|
const gateway = new Map();
|
|
531
|
+
// 能力元数据(窗口/输出上限)与价格分开记:DeepSeek 官方报窗口但无价格,
|
|
532
|
+
// 代理网关报价格但无窗口,两者都可能只命中一边。
|
|
533
|
+
rememberGatewaySpecs(arr);
|
|
274
534
|
for (const m of arr) {
|
|
275
535
|
const id = typeof m === 'string' ? m : (m?.id || m?.name || m?.model);
|
|
276
536
|
if (!id || typeof m !== 'object')
|
|
@@ -282,11 +542,19 @@ export async function refreshGatewayPricing(baseUrl, apiKey, requestHeaders) {
|
|
|
282
542
|
if (gw)
|
|
283
543
|
gateway.set(id, gw);
|
|
284
544
|
}
|
|
285
|
-
// 汇率:接口 usd_to_cny
|
|
286
|
-
const usdToCny = (
|
|
545
|
+
// 汇率:接口 usd_to_cny,缺失或超出 [3,15] 视为非法,留空由计费层用默认值。
|
|
546
|
+
const usdToCny = normalizeUsdToCny(json?.usd_to_cny);
|
|
547
|
+
if (json?.usd_to_cny !== undefined && usdToCny === undefined) {
|
|
548
|
+
logger.warn(`[GatewayPricing] Ignoring out-of-range usd_to_cny=${json.usd_to_cny} from ${baseUrl}`);
|
|
549
|
+
}
|
|
550
|
+
// 模型别名对照表:权威源是端点,这里只负责落盘缓存。值不在 data[].id 中的条目会被丢弃。
|
|
551
|
+
const knownIds = arr
|
|
552
|
+
.map(m => (typeof m === 'string' ? m : (m?.id || m?.name || m?.model)))
|
|
553
|
+
.filter((id) => typeof id === 'string' && !!id);
|
|
554
|
+
saveProviderAliases(resolveRoot(), baseUrl, json?.model_aliases, knownIds);
|
|
287
555
|
if (official.size > 0 || gateway.size > 0) {
|
|
288
556
|
gatewayPricingCache.set(baseUrl, { cache: { official, gateway, usdToCny }, fetchedAt: Date.now() });
|
|
289
|
-
logger.info(`[GatewayPricing] Refreshed from ${url}: official=${official.size} gateway=${gateway.size} usd_to_cny=${usdToCny ??
|
|
557
|
+
logger.info(`[GatewayPricing] Refreshed from ${url}: official=${official.size} gateway=${gateway.size} usd_to_cny=${usdToCny ?? `(default ${DEFAULT_USD_TO_CNY})`}`);
|
|
290
558
|
}
|
|
291
559
|
}
|
|
292
560
|
catch {
|
|
@@ -347,7 +615,9 @@ function resolveGatewayPriceRow(evolcoreHome, model, ts) {
|
|
|
347
615
|
for (const key of modelLookupKeys(evolcoreHome, model)) {
|
|
348
616
|
const candidates = prices.filter(p => p.model === key && p.effective_from <= ts);
|
|
349
617
|
if (candidates.length) {
|
|
350
|
-
|
|
618
|
+
// 同一 effective_from 时取后出现的一行:用户覆盖层在包基线之后加载,
|
|
619
|
+
// 用 `>` 而不是 `>=` 才能让用户覆盖同时间戳的包基线行。
|
|
620
|
+
return candidates.reduce((a, b) => a.effective_from > b.effective_from ? a : b);
|
|
351
621
|
}
|
|
352
622
|
}
|
|
353
623
|
return null;
|
|
@@ -396,8 +666,20 @@ function priceQuadToRecord(model, ts, quad, billing_fn, currency = 'USD') {
|
|
|
396
666
|
export function resolvePrices(evolcoreHome, event, gatewayPricing) {
|
|
397
667
|
// ── 1. 官方价格(Official Price)──────────────────────────────────────────
|
|
398
668
|
let officialCost = null;
|
|
669
|
+
// 优先级 0: 模型别名命中本地价表。Evol 等中转到官方同名模型时,
|
|
670
|
+
// 用官方的分时定价口径计算“官方价”,使两端可比。
|
|
671
|
+
const aliasModel = resolveProviderAlias(evolcoreHome, event.base_url, event.model);
|
|
672
|
+
if (aliasModel) {
|
|
673
|
+
const canonicalRow = resolvePriceRow(evolcoreHome, aliasModel, event.ts);
|
|
674
|
+
if (canonicalRow) {
|
|
675
|
+
const fn = BILLING_FNS[event.billing_fn] ?? BILLING_FNS[canonicalRow.billing_fn];
|
|
676
|
+
if (fn) {
|
|
677
|
+
officialCost = fn(event, canonicalRow);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
399
681
|
// 优先级 1: 网关接口返回的 pricing 字段
|
|
400
|
-
const officialQuad = pickGatewayQuad(evolcoreHome, gatewayPricing?.official, event.model);
|
|
682
|
+
const officialQuad = officialCost ? null : pickGatewayQuad(evolcoreHome, gatewayPricing?.official, event.model);
|
|
401
683
|
if (officialQuad) {
|
|
402
684
|
const priceRow = priceQuadToRecord(event.model, event.ts, officialQuad, event.billing_fn);
|
|
403
685
|
const fn = BILLING_FNS[event.billing_fn];
|
|
@@ -439,10 +721,9 @@ export function resolvePrices(evolcoreHome, event, gatewayPricing) {
|
|
|
439
721
|
gatewayCost = officialCost;
|
|
440
722
|
}
|
|
441
723
|
// ── 3. 转换为统一格式 ───────────────────────────────────────────────────
|
|
442
|
-
// 计费函数按价格行币种只产出一种货币(接口价恒为 USD)。用网关汇率(usd_to_cny,缺省 7)
|
|
724
|
+
// 计费函数按价格行币种只产出一种货币(接口价恒为 USD)。用网关汇率(usd_to_cny,缺省 7.23)
|
|
443
725
|
// 补齐另一种货币:有 usd 缺 cny → cny=usd*rate;有 cny 缺 usd → usd=cny/rate。
|
|
444
|
-
const rate = (
|
|
445
|
-
? gatewayPricing.usdToCny : 7;
|
|
726
|
+
const rate = normalizeUsdToCny(gatewayPricing?.usdToCny) ?? DEFAULT_USD_TO_CNY;
|
|
446
727
|
const toPair = (c) => {
|
|
447
728
|
if (!c)
|
|
448
729
|
return null;
|
package/dist/stats/normalizer.js
CHANGED
package/dist/stats/query.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* 支持跨年查询:自动附加归档库。
|
|
4
4
|
*/
|
|
5
5
|
import { openReadonlyDb, getDbPath, listArchivePaths } from './db.js';
|
|
6
|
-
import { calcCost } from './
|
|
6
|
+
import { calcCost, resolveProviderAlias } from './model-resolver.js'; // calcCost 保留用于尚未迁移的函数
|
|
7
7
|
function emptyStatusActivity() {
|
|
8
8
|
return {
|
|
9
9
|
received: null, sent: null, completed: null, errors: null, interrupts: null, avgResponseMs: null, modelCalls: null,
|
|
@@ -261,6 +261,7 @@ const GRAN_GROUP_COL = {
|
|
|
261
261
|
model: 'model',
|
|
262
262
|
peer: 'peer_key',
|
|
263
263
|
agent: 'agent_aid',
|
|
264
|
+
provider: 'COALESCE(provider_id, base_url, \'(未记录)\')',
|
|
264
265
|
};
|
|
265
266
|
function _buildWhere(f) {
|
|
266
267
|
const conds = [];
|
|
@@ -323,14 +324,15 @@ function _sumRows(rows) {
|
|
|
323
324
|
}
|
|
324
325
|
/**
|
|
325
326
|
* 聚合统计(按粒度分组)。
|
|
326
|
-
* hour
|
|
327
|
-
* 其余粒度(day/week/month/
|
|
327
|
+
* hour、provider、model 粒度读 usage_events;模型别名必须按明细中的 base_url 归一。
|
|
328
|
+
* 其余粒度(day/week/month/peer/agent)读预聚合表 usage_daily:
|
|
328
329
|
* 工作量从"全表明细"降到"天×维度"小表。rollup 永留主库,无需跨归档库 union。
|
|
329
|
-
*
|
|
330
|
+
* 成本直接累加已落库的成本列,不因别名变化重新计费。
|
|
330
331
|
*/
|
|
331
332
|
export function queryAggregated(evolcoreHome, granularity, filter) {
|
|
332
|
-
if (granularity === 'hour')
|
|
333
|
+
if (granularity === 'hour' || granularity === 'provider' || granularity === 'model') {
|
|
333
334
|
return _queryAggregatedEvents(evolcoreHome, granularity, filter);
|
|
335
|
+
}
|
|
334
336
|
return _queryAggregatedDaily(evolcoreHome, granularity, filter);
|
|
335
337
|
}
|
|
336
338
|
// rollup 时间粒度的 period 表达式(day 列是 'YYYY-MM-DD' 字符串,strftime 可直接解析)。
|
|
@@ -417,7 +419,7 @@ function _queryAggregatedDaily(evolcoreHome, granularity, filter) {
|
|
|
417
419
|
}
|
|
418
420
|
}
|
|
419
421
|
/**
|
|
420
|
-
* 走明细 usage_events
|
|
422
|
+
* 走明细 usage_events 的聚合(hour、provider、model 粒度)。
|
|
421
423
|
* 跨年时合并多个 DB 的结果,再按 period 聚合。
|
|
422
424
|
*/
|
|
423
425
|
function _queryAggregatedEvents(evolcoreHome, granularity, filter) {
|
|
@@ -429,6 +431,7 @@ function _queryAggregatedEvents(evolcoreHome, granularity, filter) {
|
|
|
429
431
|
sql = `
|
|
430
432
|
SELECT
|
|
431
433
|
${groupCol} AS period,
|
|
434
|
+
${granularity === 'model' ? 'base_url,' : ''}
|
|
432
435
|
SUM(input_tokens) AS input_tokens,
|
|
433
436
|
SUM(output_tokens) AS output_tokens,
|
|
434
437
|
SUM(cache_creation_tokens) AS cache_creation_tokens,
|
|
@@ -438,9 +441,13 @@ function _queryAggregatedEvents(evolcoreHome, granularity, filter) {
|
|
|
438
441
|
SUM(COALESCE(image_tokens,0)) AS image_tokens,
|
|
439
442
|
SUM(COALESCE(total_context_tokens,0)) AS total_context_tokens,
|
|
440
443
|
SUM(turns) AS turns,
|
|
441
|
-
COUNT(*) AS call_count
|
|
444
|
+
COUNT(*) AS call_count,
|
|
445
|
+
COALESCE(SUM(cost_official_usd), 0) AS cost_official_usd,
|
|
446
|
+
COALESCE(SUM(cost_official_cny), 0) AS cost_official_cny,
|
|
447
|
+
COALESCE(SUM(cost_gateway_usd), 0) AS cost_gateway_usd,
|
|
448
|
+
COALESCE(SUM(cost_gateway_cny), 0) AS cost_gateway_cny
|
|
442
449
|
FROM usage_events ${clause}
|
|
443
|
-
GROUP BY ${groupCol} ORDER BY (input_tokens + output_tokens) DESC
|
|
450
|
+
GROUP BY ${groupCol}${granularity === 'model' ? ', base_url' : ''} ORDER BY (input_tokens + output_tokens) DESC
|
|
444
451
|
`;
|
|
445
452
|
}
|
|
446
453
|
else {
|
|
@@ -467,15 +474,27 @@ function _queryAggregatedEvents(evolcoreHome, granularity, filter) {
|
|
|
467
474
|
GROUP BY period ORDER BY period
|
|
468
475
|
`;
|
|
469
476
|
}
|
|
477
|
+
// 模型汇总原先读取永久保留的日聚合;改读明细后仍须涵盖未指定时间的归档历史。
|
|
478
|
+
const dbPaths = granularity === 'model' && !filter.from_ts
|
|
479
|
+
? [getDbPath(evolcoreHome), ...listArchivePaths(evolcoreHome).map(entry => entry.path)]
|
|
480
|
+
: _relevantDbs(evolcoreHome, filter);
|
|
470
481
|
// 收集所有相关 DB 的原始行,再按 period 合并
|
|
471
482
|
const periodMap = new Map();
|
|
472
|
-
for (const dbPath of
|
|
483
|
+
for (const dbPath of dbPaths) {
|
|
473
484
|
const db = openReadonlyDb(dbPath);
|
|
474
485
|
if (!db)
|
|
475
486
|
continue;
|
|
476
487
|
try {
|
|
477
|
-
|
|
488
|
+
// 旧归档库只读打开,不做迁移;缺少 Provider 字段时保留原始模型名。
|
|
489
|
+
const hasBaseUrl = granularity !== 'model'
|
|
490
|
+
|| db.prepare('PRAGMA table_info(usage_events)').all().some(column => column.name === 'base_url');
|
|
491
|
+
const query = hasBaseUrl ? sql : sql.replace('base_url,', 'NULL AS base_url,').replace(', base_url ORDER BY', ' ORDER BY');
|
|
492
|
+
const rows = db.prepare(query).all(...params);
|
|
478
493
|
for (const r of rows) {
|
|
494
|
+
if (granularity === 'model') {
|
|
495
|
+
r.period = resolveProviderAlias(evolcoreHome, r.base_url, r.period) ?? r.period;
|
|
496
|
+
delete r.base_url;
|
|
497
|
+
}
|
|
479
498
|
const existing = periodMap.get(r.period);
|
|
480
499
|
periodMap.set(r.period, existing ? _sumRows([existing, r]) : r);
|
|
481
500
|
}
|
|
@@ -617,24 +636,13 @@ export function queryTopPeers(evolcoreHome, filter, limit = 10) {
|
|
|
617
636
|
db.close();
|
|
618
637
|
}
|
|
619
638
|
}
|
|
620
|
-
/** Top-N
|
|
639
|
+
/** Top-N 模型,按 Provider 别名归一后排序,与模型聚合使用同一口径。 */
|
|
621
640
|
export function queryTopModels(evolcoreHome, filter, limit = 10) {
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
GROUP BY model ORDER BY total_tokens DESC LIMIT ${limit}
|
|
628
|
-
`;
|
|
629
|
-
const db = openReadonlyDb(getDbPath(evolcoreHome));
|
|
630
|
-
if (!db)
|
|
631
|
-
return [];
|
|
632
|
-
try {
|
|
633
|
-
return db.prepare(sql).all(...params).map(r => ({ ...r }));
|
|
634
|
-
}
|
|
635
|
-
finally {
|
|
636
|
-
db.close();
|
|
637
|
-
}
|
|
641
|
+
return queryAggregated(evolcoreHome, 'model', filter).slice(0, limit).map(row => ({
|
|
642
|
+
model: row.period,
|
|
643
|
+
total_tokens: row.input_tokens + row.output_tokens,
|
|
644
|
+
call_count: row.call_count,
|
|
645
|
+
}));
|
|
638
646
|
}
|
|
639
647
|
// ── 私聊/群聊列表 + 汇总 + 对端按天明细(owner 前端用)────────────────────────
|
|
640
648
|
/** 解析 peer_key 末段为裸 peer_id(对端 AID / 群 ID)。
|
|
@@ -81,7 +81,9 @@ export function getRoleBudgetStatus(evolcoreHome, req) {
|
|
|
81
81
|
hard_blocked: pct >= 100,
|
|
82
82
|
};
|
|
83
83
|
}
|
|
84
|
-
function resolveRoleUsageLimits(role, selfAid) {
|
|
84
|
+
export function resolveRoleUsageLimits(role, selfAid) {
|
|
85
|
+
if (isManagementRole(role))
|
|
86
|
+
return null;
|
|
85
87
|
const roleDef = getRoleDefinition(role, selfAid);
|
|
86
88
|
if (!roleDef)
|
|
87
89
|
return null;
|
|
@@ -94,9 +96,10 @@ function resolveRoleUsageLimits(role, selfAid) {
|
|
|
94
96
|
return null;
|
|
95
97
|
}
|
|
96
98
|
function hasExplicitUsageLimit(limits) {
|
|
97
|
-
return limits.enabled
|
|
99
|
+
return limits.enabled !== undefined
|
|
98
100
|
|| limits.resetMode != null
|
|
99
101
|
|| limits.currency != null
|
|
102
|
+
|| (Object.hasOwn(limits, 'limitAmount') && limits.limitAmount === null)
|
|
100
103
|
|| limits.limitAmount != null
|
|
101
104
|
|| limits.costBasis != null
|
|
102
105
|
|| limits.scope != null;
|
package/dist/stats/writer.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { getDb, resetStatsDb, startDailyRollupMaintenance } from './db.js';
|
|
5
5
|
import { normalizeUsage } from './normalizer.js';
|
|
6
|
-
import { resolvePrices } from './
|
|
6
|
+
import { resolvePrices } from './model-resolver.js';
|
|
7
7
|
import { logger } from '../utils/logger.js';
|
|
8
8
|
export function insertUsageEvent(evolcoreHome, event, gatewayPricing, modelCalls) {
|
|
9
9
|
if (modelCalls?.some(call => call.source === 'subagent')) {
|
|
@@ -72,14 +72,15 @@ function writeUsageEvent(db, event, prices) {
|
|
|
72
72
|
db.exec('BEGIN');
|
|
73
73
|
db.prepare(`
|
|
74
74
|
INSERT INTO usage_events
|
|
75
|
-
(ts, agent_aid, peer_key, usage_subject_key, role, peer_type, session_id, model,
|
|
75
|
+
(ts, agent_aid, peer_key, usage_subject_key, role, peer_type, session_id, model,
|
|
76
|
+
provider_id, base_url, billing_fn,
|
|
76
77
|
input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens,
|
|
77
78
|
cache_hit_tokens, cache_miss_tokens, image_tokens, total_context_tokens,
|
|
78
79
|
turns, duration_ms, context_window_pct,
|
|
79
80
|
cost_official_usd, cost_official_cny, cost_gateway_usd, cost_gateway_cny)
|
|
80
81
|
VALUES
|
|
81
|
-
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
82
|
-
`).run(event.ts, event.agent_aid, event.peer_key, event.usage_subject_key ?? event.peer_key ?? '', event.role ?? '', event.peer_type ?? null, event.session_id ?? null, event.model, event.billing_fn, event.input_tokens, event.output_tokens, event.cache_creation_tokens, event.cache_read_tokens, event.cache_hit_tokens ?? null, event.cache_miss_tokens ?? null, event.image_tokens ?? null, event.total_context_tokens ?? null, event.turns, event.duration_ms ?? null, event.context_window_pct ?? null, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
|
|
82
|
+
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
83
|
+
`).run(event.ts, event.agent_aid, event.peer_key, event.usage_subject_key ?? event.peer_key ?? '', event.role ?? '', event.peer_type ?? null, event.session_id ?? null, event.model, event.provider_id ?? null, event.base_url ?? null, event.billing_fn, event.input_tokens, event.output_tokens, event.cache_creation_tokens, event.cache_read_tokens, event.cache_hit_tokens ?? null, event.cache_miss_tokens ?? null, event.image_tokens ?? null, event.total_context_tokens ?? null, event.turns, event.duration_ms ?? null, event.context_window_pct ?? null, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
|
|
83
84
|
// 写时增量:累加到日级预聚合表(grain 与 db.ts rebuildDailyRollup 一致)。
|
|
84
85
|
db.prepare(`
|
|
85
86
|
INSERT INTO usage_daily
|
|
@@ -223,6 +224,8 @@ function resolveCallPrices(evolcoreHome, r, gatewayPricing) {
|
|
|
223
224
|
peer_key: r.peer_key,
|
|
224
225
|
session_id: r.session_id,
|
|
225
226
|
model: r.model || 'unknown',
|
|
227
|
+
provider_id: r.provider_id,
|
|
228
|
+
base_url: r.base_url,
|
|
226
229
|
turns: 1,
|
|
227
230
|
});
|
|
228
231
|
return resolvePrices(evolcoreHome, event, gatewayPricing);
|
|
@@ -238,10 +241,11 @@ export function insertModelCalls(evolcoreHome, rows, gatewayPricing) {
|
|
|
238
241
|
const stmt = db.prepare(`
|
|
239
242
|
INSERT INTO model_calls
|
|
240
243
|
(ts, task_id, session_id, agent_session_id, agent_aid, peer_key, call_index, model,
|
|
244
|
+
provider_id, base_url,
|
|
241
245
|
source, provider_thread_id, request_id, message_id, input_tokens, output_tokens, cache_creation_tokens,
|
|
242
246
|
cache_read_tokens, context_tokens, max_tokens, auto_compact_tokens, degraded,
|
|
243
247
|
cost_official_usd, cost_official_cny, cost_gateway_usd, cost_gateway_cny)
|
|
244
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
248
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
245
249
|
`);
|
|
246
250
|
// 价格解析在读事务外算好:resolvePrices 可能读价格表文件,避免拖长写锁。
|
|
247
251
|
const priced = rows.map(r => {
|
|
@@ -256,7 +260,7 @@ export function insertModelCalls(evolcoreHome, rows, gatewayPricing) {
|
|
|
256
260
|
});
|
|
257
261
|
db.exec('BEGIN');
|
|
258
262
|
for (const { r, prices } of priced) {
|
|
259
|
-
stmt.run(r.ts, r.task_id, r.session_id ?? null, r.agent_session_id ?? null, r.agent_aid, r.peer_key, r.call_index, r.model, r.source ?? 'request', r.provider_thread_id ?? null, r.request_id ?? null, r.message_id ?? null, r.input_tokens, r.output_tokens, r.cache_creation_tokens, r.cache_read_tokens, r.context_tokens ?? null, r.max_tokens ?? null, r.auto_compact_tokens ?? null, r.degraded, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
|
|
263
|
+
stmt.run(r.ts, r.task_id, r.session_id ?? null, r.agent_session_id ?? null, r.agent_aid, r.peer_key, r.call_index, r.model, r.provider_id ?? null, r.base_url ?? null, r.source ?? 'request', r.provider_thread_id ?? null, r.request_id ?? null, r.message_id ?? null, r.input_tokens, r.output_tokens, r.cache_creation_tokens, r.cache_read_tokens, r.context_tokens ?? null, r.max_tokens ?? null, r.auto_compact_tokens ?? null, r.degraded, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
|
|
260
264
|
}
|
|
261
265
|
db.exec('COMMIT');
|
|
262
266
|
}
|
package/dist/trigger/audit.js
CHANGED
|
@@ -75,6 +75,13 @@ export class TriggerAuditLogger {
|
|
|
75
75
|
}
|
|
76
76
|
return latest;
|
|
77
77
|
}
|
|
78
|
+
summaries(triggerIds) {
|
|
79
|
+
const ids = [...new Set(triggerIds)];
|
|
80
|
+
if (this.history)
|
|
81
|
+
return this.history.summaries(ids);
|
|
82
|
+
const latest = this.latest(ids);
|
|
83
|
+
return new Map(ids.map(id => [id, { latestRun: latest.get(id), stats: this.stats(id) }]));
|
|
84
|
+
}
|
|
78
85
|
/**
|
|
79
86
|
* 汇总某 trigger 的运行统计。绑定 history 时读取长期历史;未绑定时保留旧的
|
|
80
87
|
* 日志扫描行为,供兼容调用使用。skipped 和 dry-run 不计入 fireCount。
|