evolcore 0.0.39 → 0.0.41-test.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/CHANGELOG.md +93 -0
- package/README.md +31 -20
- package/bin/codex-managed-hook.mjs +11 -0
- package/bin/ec-safe-output.js +25 -3
- package/dist/agents/baseagent-availability.js +1 -0
- package/dist/agents/claude-runner.js +53 -152
- package/dist/agents/codex-runner.js +485 -241
- package/dist/agents/ecagent-runner.js +48 -18
- package/dist/agents/gemini-runner.js +27 -8
- package/dist/agents/runner-types.js +39 -9
- package/dist/aun/ability-device-routing.js +26 -0
- package/dist/aun/aid/client.js +1 -1
- package/dist/aun/aid/control-aid.js +23 -98
- package/dist/aun/aid/ownership-operation.js +1 -3
- package/dist/aun/group/identity.js +8 -0
- package/dist/aun/group/invite-service.js +6 -0
- package/dist/aun/msg/managed-operation.js +4 -4
- package/dist/aun/msg/p2p.js +28 -12
- package/dist/aun/storage/download.js +30 -0
- package/dist/aun/storage/index.js +14 -6
- package/dist/channels/aun.js +99 -52
- package/dist/channels/daemon.js +24 -4
- package/dist/channels/dingtalk.js +8 -2
- package/dist/channels/feishu.js +6 -1
- package/dist/channels/wecom.js +7 -3
- package/dist/cli/agent-command.js +2 -0
- package/dist/cli/agent-create.js +121 -23
- package/dist/cli/agent.js +10 -3
- package/dist/cli/aid-bind-command.js +4 -1
- package/dist/cli/aun-commands.js +82 -22
- package/dist/cli/daemon-commands.js +260 -26
- package/dist/cli/index.js +25 -13
- package/dist/cli/memory-command.js +33 -14
- package/dist/cli/restart-monitor.js +52 -13
- package/dist/cli/session-command.js +128 -13
- package/dist/cli/stats.js +60 -4
- package/dist/cli/task-context.js +1 -0
- package/dist/cli/trigger-command.js +2 -2
- package/dist/config/access-policy.js +2 -0
- package/dist/config/config-field-policy.js +1 -0
- package/dist/config/config-operation-service.js +17 -6
- package/dist/config/gateway-config.js +1 -1
- package/dist/config/peer-role-resolver.js +10 -8
- package/dist/contracts/ecweb-service-protocol.js +44 -0
- package/dist/core/agent-application-service.js +11 -1
- package/dist/core/agent-ipc-registration.js +4 -0
- package/dist/core/agent-runtime.js +6 -0
- package/dist/core/auth/agent-delegation.js +87 -9
- package/dist/core/auth/auth-gateway.js +3 -1
- package/dist/core/auth/authorization-audit.js +25 -4
- package/dist/core/auth/debug-context.js +5 -1
- package/dist/core/auth/operation-catalog.js +24 -0
- package/dist/core/command/agent-control.js +91 -12
- package/dist/core/command/command-handler.js +64 -47
- package/dist/core/command/connect-menu.js +23 -2
- package/dist/core/command/menu-catalog.js +49 -12
- package/dist/core/command/menu-handler.js +110 -105
- package/dist/core/command/menu-protocol.js +29 -3
- package/dist/core/command/role-menu.js +7 -6
- package/dist/core/command/slash-gate.js +22 -5
- package/dist/core/command/slash-handler.js +121 -102
- package/dist/core/event-catalog.js +17 -0
- package/dist/core/interaction-router.js +2 -1
- package/dist/core/ipc-registration.js +44 -8
- package/dist/core/memory/batch-meta.js +2 -0
- package/dist/core/memory/consolidation-context.js +42 -51
- package/dist/core/memory/consolidation-ops-records.js +39 -7
- package/dist/core/memory/consolidation-trigger.js +72 -65
- package/dist/core/memory/consolidation.js +226 -20
- package/dist/core/memory/memory-writer.js +160 -34
- package/dist/core/memory/relation-idle-monitor.js +287 -0
- package/dist/core/memory/relation-sweep.js +206 -0
- package/dist/core/message/aun-ipc-sender.js +31 -5
- package/dist/core/message/aun-request-registry.js +97 -3
- package/dist/core/message/im-renderer.js +4 -0
- package/dist/core/message/message-admission.js +8 -4
- package/dist/core/message/message-bridge.js +96 -53
- package/dist/core/message/message-log.js +72 -0
- package/dist/core/message/message-queue.js +11 -5
- package/dist/core/message/outbound.js +70 -0
- package/dist/core/message/peer-mode.js +7 -2
- package/dist/core/message/response-engine.js +633 -191
- package/dist/core/model/model-catalog.js +7 -6
- package/dist/core/ownership/owner-resolver.js +384 -178
- package/dist/core/permission/ec-command-parser.js +129 -8
- package/dist/core/permission/tool-policy.js +35 -14
- package/dist/core/role/runtime-policy.js +64 -0
- package/dist/core/session/session-capsule.js +197 -0
- package/dist/core/session/session-manager.js +172 -18
- package/dist/core/session/session-mapper.js +2 -0
- package/dist/core/system-session/memory.js +3 -18
- package/dist/ecweb/basic-settings-service.js +709 -0
- package/dist/ecweb/providers-service.js +172 -0
- package/dist/index.js +95 -7
- package/dist/ipc.js +100 -19
- package/dist/stats/budget.js +1 -1
- package/dist/stats/db.js +48 -0
- package/dist/stats/index.js +3 -3
- package/dist/stats/price-resolver.js +304 -5
- package/dist/stats/query.js +328 -3
- package/dist/stats/writer.js +79 -6
- package/dist/trigger/application-service.js +12 -0
- package/dist/trigger/authorization.js +2 -2
- package/dist/trigger/feedback.js +18 -7
- package/dist/trigger/history.js +36 -0
- package/dist/trigger/manager.js +20 -3
- package/dist/trigger/parser.js +6 -3
- package/dist/trigger/patch.js +1 -1
- package/dist/trigger/scheduler.js +3 -0
- package/dist/trigger/system-definitions.js +43 -7
- package/dist/trigger/validation.js +13 -5
- package/dist/utils/ecweb-supervisor.js +31 -10
- package/dist/utils/error-utils.js +22 -4
- package/dist/utils/evolcore-version.js +3 -2
- package/dist/utils/host-info.js +52 -0
- package/dist/utils/npm-ops.js +2 -1
- package/dist/utils/package-version-info.js +1 -1
- package/dist/utils/upgrade-jobs.js +45 -5
- package/ecagent/dist/harness/agent-harness.js +4 -1
- package/kits/docs/INDEX.md +1 -1
- package/kits/docs/aun/ABILITY_CALLING.md +20 -2
- package/kits/docs/evolcore/INDEX.md +3 -2
- package/kits/docs/evolcore/agent-create.md +3 -2
- package/kits/docs/evolcore/agent.md +1 -1
- package/kits/docs/evolcore/aid.md +29 -12
- package/kits/docs/evolcore/config.md +9 -7
- package/kits/docs/evolcore/event.md +1 -0
- package/kits/docs/evolcore/fs.md +5 -0
- package/kits/docs/evolcore/memory-architecture.md +3 -4
- package/kits/docs/evolcore/memory-consolidation.md +28 -7
- package/kits/docs/evolcore/memory-tags.md +1 -1
- package/kits/docs/evolcore/memory.md +1 -1
- package/kits/docs/evolcore/menu-client.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +38 -0
- package/kits/docs/evolcore/msg.md +18 -2
- package/kits/docs/evolcore/session.md +14 -0
- package/kits/eck_manifest.json +3 -3
- package/kits/rules/04-relation.md +3 -2
- package/kits/schemas/agent-config.schema.13.json +20 -1
- package/kits/skills/aid-ability/SKILL.md +35 -6
- package/kits/templates/memory-consolidation/generalize.md +32 -4
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/promote.md +10 -2
- package/kits/templates/session-capsule/recovery.md +5 -0
- package/kits/templates/session-capsule/renew.md +5 -0
- package/kits/templates/system-fragments/baseagent.md +5 -0
- package/kits/templates/system-fragments/bootstrap.md +6 -6
- package/kits/templates/system-fragments/channel.md +1 -1
- package/kits/templates/system-fragments/memory.md +12 -3
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
- package/package.json +3 -3
- package/dist/stats/billing.js +0 -215
|
@@ -1,18 +1,317 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* price-resolver.ts —
|
|
3
|
-
*
|
|
2
|
+
* price-resolver.ts — 统一模型参数、价格表、网关价格缓存与计费逻辑。
|
|
3
|
+
* 供各基座、用量写入、查询和历史回填共用。
|
|
4
4
|
*/
|
|
5
|
-
import { resolvePriceRow, modelLookupKeys, BILLING_FNS } from './billing.js';
|
|
6
5
|
import fs from 'fs';
|
|
7
6
|
import path from 'path';
|
|
7
|
+
import { getPackageRoot } from '../paths.js';
|
|
8
|
+
import { parseModelId, stripContextWindowSuffix } from '../core/model/context-window-suffix.js';
|
|
9
|
+
import { logger } from '../utils/logger.js';
|
|
8
10
|
/** Keep wire/log metadata readable while preserving full precision in storage. */
|
|
9
11
|
export function roundCostForOutput(value) {
|
|
10
12
|
return Number.isFinite(value) ? Number(value.toFixed(4)) : value;
|
|
11
13
|
}
|
|
14
|
+
// 模型参数缓存(进程内,5 分钟 TTL)
|
|
15
|
+
let _parameterCache = null;
|
|
16
|
+
let _parameterCacheTs = 0;
|
|
17
|
+
let _priceCache = null;
|
|
18
|
+
let _priceCacheTs = 0;
|
|
19
|
+
const PRICE_CACHE_TTL = 5 * 60 * 1000;
|
|
20
|
+
/**
|
|
21
|
+
* 从包路径 + 用户路径合并读取 JSONL 文件。
|
|
22
|
+
* 包基线随构建产物发布在 dist/utils,源码运行时回退到 src/utils;
|
|
23
|
+
* 用户路径($EVOLCORE_HOME/data/stats/)为追加/覆盖。
|
|
24
|
+
* 两层合并(append),用户层行追加在包层之后——查价时 effective_from 越大越优先,天然正确。
|
|
25
|
+
*/
|
|
26
|
+
function _loadJsonlMerged(evolcoreHome, filename) {
|
|
27
|
+
const results = [];
|
|
28
|
+
// 1. 包路径(基线)
|
|
29
|
+
const packageRoot = getPackageRoot();
|
|
30
|
+
const pkgFile = [
|
|
31
|
+
path.join(packageRoot, 'dist', 'utils', filename),
|
|
32
|
+
path.join(packageRoot, 'src', 'utils', filename),
|
|
33
|
+
path.join(packageRoot, 'data', 'stats', filename),
|
|
34
|
+
].find(candidate => fs.existsSync(candidate));
|
|
35
|
+
if (pkgFile) {
|
|
36
|
+
try {
|
|
37
|
+
const lines = fs.readFileSync(pkgFile, 'utf-8').split('\n').filter(Boolean);
|
|
38
|
+
for (const l of lines)
|
|
39
|
+
results.push(JSON.parse(l));
|
|
40
|
+
}
|
|
41
|
+
catch { /* skip */ }
|
|
42
|
+
}
|
|
43
|
+
// 2. 用户路径(追加/覆盖)
|
|
44
|
+
const userFile = path.join(evolcoreHome, 'data', 'stats', filename);
|
|
45
|
+
if (fs.existsSync(userFile) && (!pkgFile || path.resolve(userFile) !== path.resolve(pkgFile))) {
|
|
46
|
+
try {
|
|
47
|
+
const lines = fs.readFileSync(userFile, 'utf-8').split('\n').filter(Boolean);
|
|
48
|
+
for (const l of lines)
|
|
49
|
+
results.push(JSON.parse(l));
|
|
50
|
+
}
|
|
51
|
+
catch { /* skip */ }
|
|
52
|
+
}
|
|
53
|
+
return results;
|
|
54
|
+
}
|
|
55
|
+
function loadModelParameters(evolcoreHome) {
|
|
56
|
+
if (_parameterCache && Date.now() - _parameterCacheTs < PRICE_CACHE_TTL)
|
|
57
|
+
return _parameterCache;
|
|
58
|
+
const params = _loadJsonlMerged(evolcoreHome, 'model-prices.jsonl');
|
|
59
|
+
_parameterCache = params;
|
|
60
|
+
_parameterCacheTs = Date.now();
|
|
61
|
+
return params;
|
|
62
|
+
}
|
|
63
|
+
let _aliasCache = null;
|
|
64
|
+
let _aliasCacheTs = 0;
|
|
65
|
+
function loadAliases(evolcoreHome) {
|
|
66
|
+
const now = Date.now();
|
|
67
|
+
if (_aliasCache && now - _aliasCacheTs < PRICE_CACHE_TTL)
|
|
68
|
+
return _aliasCache;
|
|
69
|
+
_aliasCache = _loadJsonlMerged(evolcoreHome, 'model-aliases.jsonl');
|
|
70
|
+
_aliasCacheTs = now;
|
|
71
|
+
return _aliasCache;
|
|
72
|
+
}
|
|
73
|
+
/** 解析模型 ID → 定价表规范 ID。精确匹配 alias 表,找不到返回原 ID。 */
|
|
74
|
+
export function resolveCanonicalModel(evolcoreHome, model) {
|
|
75
|
+
const aliases = loadAliases(evolcoreHome);
|
|
76
|
+
const entry = aliases.find(a => a.alias === model);
|
|
77
|
+
return entry ? entry.canonical : model;
|
|
78
|
+
}
|
|
79
|
+
function loadPrices(evolcoreHome) {
|
|
80
|
+
const now = Date.now();
|
|
81
|
+
if (_priceCache && now - _priceCacheTs < PRICE_CACHE_TTL)
|
|
82
|
+
return _priceCache;
|
|
83
|
+
_priceCache = loadModelParameters(evolcoreHome).filter((record) => (typeof record.billing_fn === 'string'
|
|
84
|
+
&& (record.currency === 'USD' || record.currency === 'CNY')));
|
|
85
|
+
_priceCacheTs = now;
|
|
86
|
+
return _priceCache;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* 按优先级列出一个模型 ID 的查表候选键。
|
|
90
|
+
*
|
|
91
|
+
* 上下文窗口变体(`claude-opus-5[1m]`)与基础模型同价,价表只需一条基础条目;
|
|
92
|
+
* 但仍先试精确匹配,好让用户能给某个变体单独定价。
|
|
93
|
+
*/
|
|
94
|
+
export function modelLookupKeys(evolcoreHome, model) {
|
|
95
|
+
const keys = [];
|
|
96
|
+
const push = (key) => { if (key && !keys.includes(key))
|
|
97
|
+
keys.push(key); };
|
|
98
|
+
push(model);
|
|
99
|
+
push(resolveCanonicalModel(evolcoreHome, model));
|
|
100
|
+
const base = stripContextWindowSuffix(model);
|
|
101
|
+
if (base !== model) {
|
|
102
|
+
push(base);
|
|
103
|
+
push(resolveCanonicalModel(evolcoreHome, base));
|
|
104
|
+
}
|
|
105
|
+
return keys;
|
|
106
|
+
}
|
|
107
|
+
/** 取 model 在 ts 时刻生效的价格行(effective_from <= ts 中最新的一条)。
|
|
108
|
+
* 精确匹配失败时,依次回落到 alias 规范 ID 和去掉窗口后缀的基础 ID。 */
|
|
109
|
+
export function resolvePriceRow(evolcoreHome, model, ts) {
|
|
110
|
+
const prices = loadPrices(evolcoreHome);
|
|
111
|
+
for (const key of modelLookupKeys(evolcoreHome, model)) {
|
|
112
|
+
const candidates = prices.filter(p => p.model === key && p.effective_from <= ts);
|
|
113
|
+
if (candidates.length) {
|
|
114
|
+
return candidates.reduce((a, b) => a.effective_from >= b.effective_from ? a : b);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
export const BILLING_FNS = {
|
|
120
|
+
// 通用 per-token(Claude / OpenAI 兼容 / Kimi / MiniMax)
|
|
121
|
+
per_token_v1: (e, p) => {
|
|
122
|
+
const tiers = Array.isArray(p.tiers)
|
|
123
|
+
? p.tiers
|
|
124
|
+
: [];
|
|
125
|
+
const promptTokens = e.input_tokens + e.cache_creation_tokens + e.cache_read_tokens;
|
|
126
|
+
const tier = tiers.find(t => t.up_to_input_tokens == null || promptTokens <= t.up_to_input_tokens);
|
|
127
|
+
const price = tier ?? p;
|
|
128
|
+
const r = (price.price_input ?? 0) * e.input_tokens / 1e6
|
|
129
|
+
+ (price.price_output ?? 0) * e.output_tokens / 1e6
|
|
130
|
+
+ (price.price_cache_creation ?? 0) * e.cache_creation_tokens / 1e6
|
|
131
|
+
+ (price.price_cache_read ?? 0) * e.cache_read_tokens / 1e6;
|
|
132
|
+
return p.currency === 'CNY' ? { cny: r } : { usd: r };
|
|
133
|
+
},
|
|
134
|
+
// DeepSeek cache_hit / cache_miss 口径
|
|
135
|
+
per_token_deepseek_v1: (e, p) => {
|
|
136
|
+
const r = (p.price_cache_hit ?? 0) * (e.cache_hit_tokens ?? 0) / 1e6
|
|
137
|
+
+ (p.price_cache_miss ?? 0) * (e.cache_miss_tokens ?? 0) / 1e6
|
|
138
|
+
+ (p.price_output ?? 0) * e.output_tokens / 1e6;
|
|
139
|
+
return { cny: r };
|
|
140
|
+
},
|
|
141
|
+
// Gemini 分档(按 total_context_tokens 确定所在档位)
|
|
142
|
+
per_token_tiered_v1: (e, p) => {
|
|
143
|
+
const tiers = p.tiers;
|
|
144
|
+
if (!Array.isArray(tiers))
|
|
145
|
+
return {};
|
|
146
|
+
const ctx = e.total_context_tokens ?? e.input_tokens;
|
|
147
|
+
const tier = tiers.find(t => t.up_to_tokens == null || ctx <= t.up_to_tokens) ?? tiers[tiers.length - 1];
|
|
148
|
+
const r = (tier.price_input ?? 0) * e.input_tokens / 1e6
|
|
149
|
+
+ (tier.price_output ?? 0) * e.output_tokens / 1e6
|
|
150
|
+
+ (tier.price_cache_read ?? 0) * e.cache_read_tokens / 1e6;
|
|
151
|
+
return p.currency === 'CNY' ? { cny: r } : { usd: r };
|
|
152
|
+
},
|
|
153
|
+
// 视觉模型(含 image_tokens 单独计费)
|
|
154
|
+
per_token_image_v1: (e, p) => {
|
|
155
|
+
const r = (p.price_input ?? 0) * e.input_tokens / 1e6
|
|
156
|
+
+ (p.price_output ?? 0) * e.output_tokens / 1e6
|
|
157
|
+
+ (p.price_image ?? 0) * (e.image_tokens ?? 0) / 1e6;
|
|
158
|
+
return p.currency === 'CNY' ? { cny: r } : { usd: r };
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
/** 注册新计费函数(扩展点)。 */
|
|
162
|
+
export function registerBillingFn(id, fn) {
|
|
163
|
+
BILLING_FNS[id] = fn;
|
|
164
|
+
}
|
|
165
|
+
/** 计算一条 usage_event 的费用。找不到价格行时返回 {}。 */
|
|
166
|
+
export function calcCost(evolcoreHome, event) {
|
|
167
|
+
const priceRow = resolvePriceRow(evolcoreHome, event.model, event.ts);
|
|
168
|
+
if (!priceRow)
|
|
169
|
+
return {};
|
|
170
|
+
const fn = BILLING_FNS[event.billing_fn] ?? BILLING_FNS[priceRow.billing_fn];
|
|
171
|
+
if (!fn)
|
|
172
|
+
return {};
|
|
173
|
+
return fn(event, priceRow);
|
|
174
|
+
}
|
|
175
|
+
// ── Model Specs ──────────────────────────────────────────────────────────────
|
|
176
|
+
let _specCache = null;
|
|
177
|
+
let _specCacheTs = 0;
|
|
178
|
+
function loadSpecs(evolcoreHome) {
|
|
179
|
+
const now = Date.now();
|
|
180
|
+
if (_specCache && now - _specCacheTs < PRICE_CACHE_TTL)
|
|
181
|
+
return _specCache;
|
|
182
|
+
_specCache = loadModelParameters(evolcoreHome).filter((record) => (typeof record.context_window === 'number'
|
|
183
|
+
&& typeof record.max_input_tokens === 'number'
|
|
184
|
+
&& typeof record.max_output_tokens === 'number'));
|
|
185
|
+
_specCacheTs = now;
|
|
186
|
+
return _specCache;
|
|
187
|
+
}
|
|
188
|
+
export function findModelSpec(evolcoreHome, model, ts = Date.now()) {
|
|
189
|
+
const specs = loadSpecs(evolcoreHome);
|
|
190
|
+
const suffixWindow = parseModelId(model).contextWindow;
|
|
191
|
+
for (const key of modelLookupKeys(evolcoreHome, model)) {
|
|
192
|
+
const candidates = specs.filter(spec => spec.model === key && spec.effective_from <= ts);
|
|
193
|
+
if (!candidates.length)
|
|
194
|
+
continue;
|
|
195
|
+
const row = candidates.reduce((a, b) => a.effective_from > b.effective_from ? a : b);
|
|
196
|
+
if (suffixWindow === undefined || suffixWindow === row.context_window)
|
|
197
|
+
return row;
|
|
198
|
+
// 后缀声明的窗口覆盖基础行,输入上限按原行的预留比例等比缩放。
|
|
199
|
+
const ratio = row.context_window > 0 ? row.max_input_tokens / row.context_window : 0.9;
|
|
200
|
+
return { ...row, model, context_window: suffixWindow, max_input_tokens: Math.floor(suffixWindow * ratio) };
|
|
201
|
+
}
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
/** 取模型在 ts 时刻的能力参数。找不到时返回 fallback 或默认值。
|
|
205
|
+
* 带窗口后缀的 ID 复用基础模型的参数行,但窗口由后缀决定(网关的权威声明)。 */
|
|
206
|
+
export function resolveModelSpec(evolcoreHome, model, ts, fallback) {
|
|
207
|
+
const spec = findModelSpec(evolcoreHome, model, ts);
|
|
208
|
+
if (spec)
|
|
209
|
+
return spec;
|
|
210
|
+
const suffixWindow = parseModelId(model).contextWindow;
|
|
211
|
+
// 默认值
|
|
212
|
+
const contextWindow = suffixWindow ?? fallback?.context_window ?? 200000;
|
|
213
|
+
return {
|
|
214
|
+
model,
|
|
215
|
+
effective_from: 0,
|
|
216
|
+
context_window: contextWindow,
|
|
217
|
+
max_input_tokens: Math.floor(contextWindow * 0.9),
|
|
218
|
+
max_output_tokens: fallback?.max_output_tokens ?? 8192,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
// ── 网关接口价格缓存 ──────────────────────────────────────────────────────────
|
|
222
|
+
const GATEWAY_PRICING_TTL_MS = 60 * 60 * 1000; // 1h
|
|
223
|
+
/** key: baseUrl */
|
|
224
|
+
const gatewayPricingCache = new Map();
|
|
225
|
+
/** 去重并发刷新 */
|
|
226
|
+
const gatewayPricingInFlight = new Set();
|
|
227
|
+
/**
|
|
228
|
+
* 把 /v1/models 单个 model 的价格对象转为 PriceQuad。
|
|
229
|
+
* 单位假设:接口价与 model-prices.jsonl 同口径(USD per 1M token),不做换算。
|
|
230
|
+
*/
|
|
231
|
+
export function apiPricingToQuad(p) {
|
|
232
|
+
if (!p || typeof p !== 'object')
|
|
233
|
+
return undefined;
|
|
234
|
+
const n = (v) => (typeof v === 'number' && isFinite(v) ? v : undefined);
|
|
235
|
+
const quad = {
|
|
236
|
+
input: n(p.input),
|
|
237
|
+
output: n(p.output),
|
|
238
|
+
cache_read: n(p.cache_read),
|
|
239
|
+
cache_write: n(p.cache_write),
|
|
240
|
+
};
|
|
241
|
+
// 全空则视为无价
|
|
242
|
+
if (quad.input === undefined && quad.output === undefined
|
|
243
|
+
&& quad.cache_read === undefined && quad.cache_write === undefined)
|
|
244
|
+
return undefined;
|
|
245
|
+
return quad;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* 拉取网关 /v1/models 的官方价(pricing) + 网关价(effective_pricing),写入缓存。
|
|
249
|
+
* 失败静默——保持回退到本地价表 / official。
|
|
250
|
+
*/
|
|
251
|
+
export async function refreshGatewayPricing(baseUrl, apiKey, requestHeaders) {
|
|
252
|
+
if (gatewayPricingInFlight.has(baseUrl))
|
|
253
|
+
return;
|
|
254
|
+
gatewayPricingInFlight.add(baseUrl);
|
|
255
|
+
try {
|
|
256
|
+
const url = `${baseUrl.replace(/\/+$/, '')}/v1/models`;
|
|
257
|
+
const controller = new AbortController();
|
|
258
|
+
const timer = setTimeout(() => controller.abort(), 5000);
|
|
259
|
+
const resp = await fetch(url, {
|
|
260
|
+
signal: controller.signal,
|
|
261
|
+
headers: {
|
|
262
|
+
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
|
263
|
+
...requestHeaders,
|
|
264
|
+
},
|
|
265
|
+
});
|
|
266
|
+
clearTimeout(timer);
|
|
267
|
+
if (!resp.ok)
|
|
268
|
+
return;
|
|
269
|
+
const json = await resp.json();
|
|
270
|
+
const arr = Array.isArray(json?.data) ? json.data
|
|
271
|
+
: Array.isArray(json?.models) ? json.models : [];
|
|
272
|
+
const official = new Map();
|
|
273
|
+
const gateway = new Map();
|
|
274
|
+
for (const m of arr) {
|
|
275
|
+
const id = typeof m === 'string' ? m : (m?.id || m?.name || m?.model);
|
|
276
|
+
if (!id || typeof m !== 'object')
|
|
277
|
+
continue;
|
|
278
|
+
const off = apiPricingToQuad(m.pricing);
|
|
279
|
+
if (off)
|
|
280
|
+
official.set(id, off);
|
|
281
|
+
const gw = apiPricingToQuad(m.effective_pricing);
|
|
282
|
+
if (gw)
|
|
283
|
+
gateway.set(id, gw);
|
|
284
|
+
}
|
|
285
|
+
// 汇率:接口 usd_to_cny,缺失则留空(计费层默认用 7)
|
|
286
|
+
const usdToCny = (typeof json?.usd_to_cny === 'number' && json.usd_to_cny > 0) ? json.usd_to_cny : undefined;
|
|
287
|
+
if (official.size > 0 || gateway.size > 0) {
|
|
288
|
+
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 ?? '(default 7)'}`);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
// 网络/解析失败:保持回退,不打断查询
|
|
294
|
+
}
|
|
295
|
+
finally {
|
|
296
|
+
gatewayPricingInFlight.delete(baseUrl);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* 读取某网关的价格缓存。缺失/过期时异步触发刷新,本轮先返回旧值或 undefined
|
|
301
|
+
* (调用方据此回退本地价表 / official)。
|
|
302
|
+
*/
|
|
303
|
+
export function getGatewayPricing(baseUrl, apiKey, requestHeaders) {
|
|
304
|
+
if (!baseUrl)
|
|
305
|
+
return undefined;
|
|
306
|
+
const entry = gatewayPricingCache.get(baseUrl);
|
|
307
|
+
if (!entry || Date.now() - entry.fetchedAt > GATEWAY_PRICING_TTL_MS) {
|
|
308
|
+
void refreshGatewayPricing(baseUrl, apiKey, requestHeaders); // 不 await,stale-while-revalidate
|
|
309
|
+
}
|
|
310
|
+
return entry?.cache;
|
|
311
|
+
}
|
|
12
312
|
// 网关价格表缓存(从用户覆盖层 model-prices-gateway.jsonl 读取)
|
|
13
313
|
let _gatewayPriceCache = null;
|
|
14
314
|
let _gatewayPriceCacheTs = 0;
|
|
15
|
-
const PRICE_CACHE_TTL = 5 * 60 * 1000;
|
|
16
315
|
/**
|
|
17
316
|
* 从用户覆盖层读取网关价格表(model-prices-gateway.jsonl)。
|
|
18
317
|
* 这是用户通过 ECWeb "改价" 功能手动设置的网关价格。
|
|
@@ -68,7 +367,7 @@ function pickGatewayQuad(evolcoreHome, map, model) {
|
|
|
68
367
|
return null;
|
|
69
368
|
}
|
|
70
369
|
/**
|
|
71
|
-
* 从 PriceQuad
|
|
370
|
+
* 从 PriceQuad 构造统一计费使用的 PriceRecord。
|
|
72
371
|
* 用于将网关接口返回的价格四元组转换为可用于 calcCost() 的格式。
|
|
73
372
|
*/
|
|
74
373
|
function priceQuadToRecord(model, ts, quad, billing_fn, currency = 'USD') {
|
package/dist/stats/query.js
CHANGED
|
@@ -3,7 +3,253 @@
|
|
|
3
3
|
* 支持跨年查询:自动附加归档库。
|
|
4
4
|
*/
|
|
5
5
|
import { openReadonlyDb, getDbPath, listArchivePaths } from './db.js';
|
|
6
|
-
import { calcCost } from './
|
|
6
|
+
import { calcCost } from './price-resolver.js'; // 保留用于尚未迁移的函数
|
|
7
|
+
function emptyStatusActivity() {
|
|
8
|
+
return {
|
|
9
|
+
received: null, sent: null, completed: null, errors: null, interrupts: null, avgResponseMs: null, modelCalls: null,
|
|
10
|
+
tokens: { input: null, output: null, cacheRead: null, cacheCreation: null, total: null },
|
|
11
|
+
cost: {
|
|
12
|
+
official: { usd: null, cny: null },
|
|
13
|
+
gateway: { usd: null, cny: null },
|
|
14
|
+
coverage: {
|
|
15
|
+
rows: 0,
|
|
16
|
+
official: { usdPricedRows: 0, cnyPricedRows: 0 },
|
|
17
|
+
gateway: { usdPricedRows: 0, cnyPricedRows: 0 },
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function statusCostValue(sum, rows, pricedRows) {
|
|
23
|
+
if (rows === 0)
|
|
24
|
+
return 0;
|
|
25
|
+
if (pricedRows === 0)
|
|
26
|
+
return null;
|
|
27
|
+
return Number(sum ?? 0);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Read the status activity window from the persisted stats database.
|
|
31
|
+
* Message and model-call counters are intentionally sourced from their
|
|
32
|
+
* dedicated tables; task lifecycle counters come from activity_events.
|
|
33
|
+
* A missing/unreadable database returns null-valued metrics rather than
|
|
34
|
+
* pretending that no activity occurred.
|
|
35
|
+
*/
|
|
36
|
+
export function queryStatusActivity(evolcoreHome, fromTs, toTs, agentAid) {
|
|
37
|
+
const result = emptyStatusActivity();
|
|
38
|
+
const db = openReadonlyDb(getDbPath(evolcoreHome));
|
|
39
|
+
if (!db)
|
|
40
|
+
return result;
|
|
41
|
+
const agentClause = agentAid ? ' AND agent_aid = ?' : '';
|
|
42
|
+
const params = agentAid ? [fromTs, toTs, agentAid] : [fromTs, toTs];
|
|
43
|
+
try {
|
|
44
|
+
const msg = db.prepare(`
|
|
45
|
+
SELECT
|
|
46
|
+
COALESCE(SUM(CASE WHEN direction = 'in' THEN 1 ELSE 0 END), 0) AS received,
|
|
47
|
+
COALESCE(SUM(CASE WHEN direction = 'out' THEN 1 ELSE 0 END), 0) AS sent
|
|
48
|
+
FROM message_events WHERE ts >= ? AND ts < ?${agentClause}
|
|
49
|
+
`).get(...params);
|
|
50
|
+
result.received = Number(msg?.received ?? 0);
|
|
51
|
+
result.sent = Number(msg?.sent ?? 0);
|
|
52
|
+
const calls = db.prepare(`
|
|
53
|
+
SELECT COUNT(*) AS calls
|
|
54
|
+
FROM model_calls WHERE ts >= ? AND ts < ?${agentClause}
|
|
55
|
+
`).get(...params);
|
|
56
|
+
result.modelCalls = Number(calls?.calls ?? 0);
|
|
57
|
+
const usage = db.prepare(`
|
|
58
|
+
SELECT
|
|
59
|
+
COUNT(*) AS rows,
|
|
60
|
+
COALESCE(SUM(input_tokens), 0) AS input,
|
|
61
|
+
COALESCE(SUM(output_tokens), 0) AS output,
|
|
62
|
+
COALESCE(SUM(cache_read_tokens), 0) AS cache_read,
|
|
63
|
+
COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation,
|
|
64
|
+
SUM(cost_official_usd) AS official_usd,
|
|
65
|
+
SUM(cost_official_cny) AS official_cny,
|
|
66
|
+
SUM(cost_gateway_usd) AS gateway_usd,
|
|
67
|
+
SUM(cost_gateway_cny) AS gateway_cny,
|
|
68
|
+
COUNT(cost_official_usd) AS official_usd_rows,
|
|
69
|
+
COUNT(cost_official_cny) AS official_cny_rows,
|
|
70
|
+
COUNT(cost_gateway_usd) AS gateway_usd_rows,
|
|
71
|
+
COUNT(cost_gateway_cny) AS gateway_cny_rows
|
|
72
|
+
FROM usage_events WHERE ts >= ? AND ts < ?${agentClause}
|
|
73
|
+
`).get(...params);
|
|
74
|
+
const rows = Number(usage?.rows ?? 0);
|
|
75
|
+
result.tokens = {
|
|
76
|
+
input: Number(usage?.input ?? 0),
|
|
77
|
+
output: Number(usage?.output ?? 0),
|
|
78
|
+
cacheRead: Number(usage?.cache_read ?? 0),
|
|
79
|
+
cacheCreation: Number(usage?.cache_creation ?? 0),
|
|
80
|
+
total: Number(usage?.input ?? 0) + Number(usage?.output ?? 0)
|
|
81
|
+
+ Number(usage?.cache_read ?? 0) + Number(usage?.cache_creation ?? 0),
|
|
82
|
+
};
|
|
83
|
+
result.cost = {
|
|
84
|
+
official: {
|
|
85
|
+
usd: statusCostValue(usage?.official_usd, rows, Number(usage?.official_usd_rows ?? 0)),
|
|
86
|
+
cny: statusCostValue(usage?.official_cny, rows, Number(usage?.official_cny_rows ?? 0)),
|
|
87
|
+
},
|
|
88
|
+
gateway: {
|
|
89
|
+
usd: statusCostValue(usage?.gateway_usd, rows, Number(usage?.gateway_usd_rows ?? 0)),
|
|
90
|
+
cny: statusCostValue(usage?.gateway_cny, rows, Number(usage?.gateway_cny_rows ?? 0)),
|
|
91
|
+
},
|
|
92
|
+
coverage: {
|
|
93
|
+
rows,
|
|
94
|
+
official: {
|
|
95
|
+
usdPricedRows: Number(usage?.official_usd_rows ?? 0),
|
|
96
|
+
cnyPricedRows: Number(usage?.official_cny_rows ?? 0),
|
|
97
|
+
},
|
|
98
|
+
gateway: {
|
|
99
|
+
usdPricedRows: Number(usage?.gateway_usd_rows ?? 0),
|
|
100
|
+
cnyPricedRows: Number(usage?.gateway_cny_rows ?? 0),
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
const startedAtRow = db.prepare(`SELECT value FROM activity_meta WHERE key = 'activity_events_started_at'`).get();
|
|
105
|
+
const activityStartedAt = Number(startedAtRow?.value);
|
|
106
|
+
if (!Number.isFinite(activityStartedAt) || fromTs < activityStartedAt) {
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
const activity = db.prepare(`
|
|
110
|
+
SELECT
|
|
111
|
+
SUM(CASE WHEN type = 'completed' THEN 1 ELSE 0 END) AS completed,
|
|
112
|
+
SUM(CASE WHEN type = 'error' THEN 1 ELSE 0 END) AS errors,
|
|
113
|
+
SUM(CASE WHEN type = 'interrupted' THEN 1 ELSE 0 END) AS interrupts,
|
|
114
|
+
AVG(CASE WHEN type = 'completed' THEN duration_ms END) AS avg_response
|
|
115
|
+
FROM activity_events WHERE ts >= ? AND ts < ?${agentClause}
|
|
116
|
+
`).get(...params);
|
|
117
|
+
result.completed = Number(activity?.completed ?? 0);
|
|
118
|
+
result.errors = Number(activity?.errors ?? 0);
|
|
119
|
+
result.interrupts = Number(activity?.interrupts ?? 0);
|
|
120
|
+
result.avgResponseMs = activity?.avg_response == null ? 0 : Number(activity.avg_response);
|
|
121
|
+
return result;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// Older databases may not have activity_events yet. Preserve metrics
|
|
125
|
+
// that can be read from established tables and leave lifecycle fields unknown.
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
db.close();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Batch status query for Agent rows; opens the stats DB once for all AIDs. */
|
|
133
|
+
export function queryStatusActivityByAgent(evolcoreHome, fromTs, toTs, agentAids) {
|
|
134
|
+
const output = new Map(agentAids.map(aid => [aid, emptyStatusActivity()]));
|
|
135
|
+
if (agentAids.length === 0)
|
|
136
|
+
return output;
|
|
137
|
+
const db = openReadonlyDb(getDbPath(evolcoreHome));
|
|
138
|
+
if (!db)
|
|
139
|
+
return output;
|
|
140
|
+
const placeholders = agentAids.map(() => '?').join(', ');
|
|
141
|
+
const params = [fromTs, toTs, ...agentAids];
|
|
142
|
+
const get = (aid) => output.get(aid);
|
|
143
|
+
try {
|
|
144
|
+
// An opened database can prove that an agent has no rows in the queried
|
|
145
|
+
// persistent tables. Keep lifecycle fields unknown until their coverage
|
|
146
|
+
// boundary is verified, but expose confirmed zeroes for message, model,
|
|
147
|
+
// token, and cost aggregates.
|
|
148
|
+
for (const item of output.values()) {
|
|
149
|
+
item.received = 0;
|
|
150
|
+
item.sent = 0;
|
|
151
|
+
item.modelCalls = 0;
|
|
152
|
+
item.tokens = { input: 0, output: 0, cacheRead: 0, cacheCreation: 0, total: 0 };
|
|
153
|
+
item.cost = {
|
|
154
|
+
official: { usd: 0, cny: 0 },
|
|
155
|
+
gateway: { usd: 0, cny: 0 },
|
|
156
|
+
coverage: {
|
|
157
|
+
rows: 0,
|
|
158
|
+
official: { usdPricedRows: 0, cnyPricedRows: 0 },
|
|
159
|
+
gateway: { usdPricedRows: 0, cnyPricedRows: 0 },
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
for (const row of db.prepare(`
|
|
164
|
+
SELECT agent_aid,
|
|
165
|
+
SUM(CASE WHEN direction = 'in' THEN 1 ELSE 0 END) AS received,
|
|
166
|
+
SUM(CASE WHEN direction = 'out' THEN 1 ELSE 0 END) AS sent
|
|
167
|
+
FROM message_events WHERE ts >= ? AND ts < ? AND agent_aid IN (${placeholders}) GROUP BY agent_aid
|
|
168
|
+
`).all(...params)) {
|
|
169
|
+
const item = get(row.agent_aid);
|
|
170
|
+
item.received = Number(row.received ?? 0);
|
|
171
|
+
item.sent = Number(row.sent ?? 0);
|
|
172
|
+
}
|
|
173
|
+
for (const row of db.prepare(`
|
|
174
|
+
SELECT agent_aid, COUNT(*) AS calls
|
|
175
|
+
FROM model_calls WHERE ts >= ? AND ts < ? AND agent_aid IN (${placeholders}) GROUP BY agent_aid
|
|
176
|
+
`).all(...params))
|
|
177
|
+
get(row.agent_aid).modelCalls = Number(row.calls ?? 0);
|
|
178
|
+
for (const row of db.prepare(`
|
|
179
|
+
SELECT agent_aid, COUNT(*) AS rows,
|
|
180
|
+
SUM(input_tokens) AS input, SUM(output_tokens) AS output,
|
|
181
|
+
SUM(cache_read_tokens) AS cache_read, SUM(cache_creation_tokens) AS cache_creation,
|
|
182
|
+
SUM(cost_official_usd) AS official_usd, SUM(cost_official_cny) AS official_cny,
|
|
183
|
+
SUM(cost_gateway_usd) AS gateway_usd, SUM(cost_gateway_cny) AS gateway_cny,
|
|
184
|
+
COUNT(cost_official_usd) AS official_usd_rows, COUNT(cost_official_cny) AS official_cny_rows,
|
|
185
|
+
COUNT(cost_gateway_usd) AS gateway_usd_rows, COUNT(cost_gateway_cny) AS gateway_cny_rows
|
|
186
|
+
FROM usage_events WHERE ts >= ? AND ts < ? AND agent_aid IN (${placeholders}) GROUP BY agent_aid
|
|
187
|
+
`).all(...params)) {
|
|
188
|
+
const item = get(row.agent_aid);
|
|
189
|
+
item.tokens = {
|
|
190
|
+
input: Number(row.input ?? 0), output: Number(row.output ?? 0),
|
|
191
|
+
cacheRead: Number(row.cache_read ?? 0), cacheCreation: Number(row.cache_creation ?? 0),
|
|
192
|
+
total: Number(row.input ?? 0) + Number(row.output ?? 0) + Number(row.cache_read ?? 0) + Number(row.cache_creation ?? 0),
|
|
193
|
+
};
|
|
194
|
+
const count = Number(row.rows ?? 0);
|
|
195
|
+
item.cost = {
|
|
196
|
+
official: {
|
|
197
|
+
usd: statusCostValue(row.official_usd, count, Number(row.official_usd_rows ?? 0)),
|
|
198
|
+
cny: statusCostValue(row.official_cny, count, Number(row.official_cny_rows ?? 0)),
|
|
199
|
+
},
|
|
200
|
+
gateway: {
|
|
201
|
+
usd: statusCostValue(row.gateway_usd, count, Number(row.gateway_usd_rows ?? 0)),
|
|
202
|
+
cny: statusCostValue(row.gateway_cny, count, Number(row.gateway_cny_rows ?? 0)),
|
|
203
|
+
},
|
|
204
|
+
coverage: {
|
|
205
|
+
rows: count,
|
|
206
|
+
official: {
|
|
207
|
+
usdPricedRows: Number(row.official_usd_rows ?? 0),
|
|
208
|
+
cnyPricedRows: Number(row.official_cny_rows ?? 0),
|
|
209
|
+
},
|
|
210
|
+
gateway: {
|
|
211
|
+
usdPricedRows: Number(row.gateway_usd_rows ?? 0),
|
|
212
|
+
cnyPricedRows: Number(row.gateway_cny_rows ?? 0),
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const startedAtRow = db.prepare(`SELECT value FROM activity_meta WHERE key = 'activity_events_started_at'`).get();
|
|
218
|
+
const activityStartedAt = Number(startedAtRow?.value);
|
|
219
|
+
if (Number.isFinite(activityStartedAt) && fromTs >= activityStartedAt) {
|
|
220
|
+
for (const row of db.prepare(`
|
|
221
|
+
SELECT agent_aid,
|
|
222
|
+
SUM(CASE WHEN type = 'completed' THEN 1 ELSE 0 END) AS completed,
|
|
223
|
+
SUM(CASE WHEN type = 'error' THEN 1 ELSE 0 END) AS errors,
|
|
224
|
+
SUM(CASE WHEN type = 'interrupted' THEN 1 ELSE 0 END) AS interrupts,
|
|
225
|
+
AVG(CASE WHEN type = 'completed' THEN duration_ms END) AS avg_response
|
|
226
|
+
FROM activity_events WHERE ts >= ? AND ts < ? AND agent_aid IN (${placeholders}) GROUP BY agent_aid
|
|
227
|
+
`).all(...params)) {
|
|
228
|
+
const item = get(row.agent_aid);
|
|
229
|
+
item.completed = Number(row.completed ?? 0);
|
|
230
|
+
item.errors = Number(row.errors ?? 0);
|
|
231
|
+
item.interrupts = Number(row.interrupts ?? 0);
|
|
232
|
+
item.avgResponseMs = row.avg_response == null ? 0 : Number(row.avg_response);
|
|
233
|
+
}
|
|
234
|
+
for (const item of output.values()) {
|
|
235
|
+
if (item.completed === null) {
|
|
236
|
+
item.completed = 0;
|
|
237
|
+
item.errors = 0;
|
|
238
|
+
item.interrupts = 0;
|
|
239
|
+
item.avgResponseMs = 0;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
// The status response can still report the other metric groups when a
|
|
246
|
+
// partially migrated database lacks an optional table.
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
db.close();
|
|
250
|
+
}
|
|
251
|
+
return output;
|
|
252
|
+
}
|
|
7
253
|
const GRAN_FMT = {
|
|
8
254
|
hour: '%Y-%m-%d %H:00',
|
|
9
255
|
day: '%Y-%m-%d',
|
|
@@ -625,7 +871,8 @@ export function queryTaskModelCalls(evolcoreHome, taskId) {
|
|
|
625
871
|
if (!db)
|
|
626
872
|
return [];
|
|
627
873
|
try {
|
|
628
|
-
|
|
874
|
+
// SELECT *:老库可能还没有 cost 列,显式列名会直接报错;缺失列由 _normalizeModelCall 补 null。
|
|
875
|
+
return db.prepare(`SELECT * FROM model_calls WHERE task_id = ? ORDER BY call_index`).all(taskId).map(_normalizeModelCall);
|
|
629
876
|
}
|
|
630
877
|
finally {
|
|
631
878
|
db.close();
|
|
@@ -637,12 +884,90 @@ export function querySessionModelCalls(evolcoreHome, sessionId) {
|
|
|
637
884
|
if (!db)
|
|
638
885
|
return [];
|
|
639
886
|
try {
|
|
640
|
-
return db.prepare(`SELECT * FROM model_calls WHERE session_id = ? ORDER BY ts, call_index`).all(sessionId);
|
|
887
|
+
return db.prepare(`SELECT * FROM model_calls WHERE session_id = ? ORDER BY ts, call_index`).all(sessionId).map(_normalizeModelCall);
|
|
641
888
|
}
|
|
642
889
|
finally {
|
|
643
890
|
db.close();
|
|
644
891
|
}
|
|
645
892
|
}
|
|
893
|
+
/** 补齐老库缺列(cost_* 为后加列)时的默认值。 */
|
|
894
|
+
function _normalizeModelCall(r) {
|
|
895
|
+
return {
|
|
896
|
+
...r,
|
|
897
|
+
cost_official_usd: r.cost_official_usd ?? null,
|
|
898
|
+
cost_official_cny: r.cost_official_cny ?? null,
|
|
899
|
+
cost_gateway_usd: r.cost_gateway_usd ?? null,
|
|
900
|
+
cost_gateway_cny: r.cost_gateway_cny ?? null,
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
/** 一个 task 的累计汇总(token + 官方价/网关价),单行。 */
|
|
904
|
+
export function queryTaskSummary(evolcoreHome, taskId) {
|
|
905
|
+
const empty = {
|
|
906
|
+
input_tokens: 0, output_tokens: 0, cache_creation_tokens: 0, cache_read_tokens: 0,
|
|
907
|
+
total_tokens: 0, calls: 0,
|
|
908
|
+
cost_official_usd: 0, cost_official_cny: 0, cost_gateway_usd: 0, cost_gateway_cny: 0,
|
|
909
|
+
usd: 0, cny: 0,
|
|
910
|
+
};
|
|
911
|
+
const sql = `
|
|
912
|
+
SELECT
|
|
913
|
+
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
914
|
+
COALESCE(SUM(output_tokens), 0) AS output_tokens,
|
|
915
|
+
COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation_tokens,
|
|
916
|
+
COALESCE(SUM(cache_read_tokens), 0) AS cache_read_tokens,
|
|
917
|
+
COUNT(*) AS calls,
|
|
918
|
+
COALESCE(SUM(cost_official_usd), 0) AS cost_official_usd,
|
|
919
|
+
COALESCE(SUM(cost_official_cny), 0) AS cost_official_cny,
|
|
920
|
+
COALESCE(SUM(cost_gateway_usd), 0) AS cost_gateway_usd,
|
|
921
|
+
COALESCE(SUM(cost_gateway_cny), 0) AS cost_gateway_cny
|
|
922
|
+
FROM model_calls WHERE task_id = ?`;
|
|
923
|
+
const acc = { ...empty };
|
|
924
|
+
for (const dbPath of _relevantDbs(evolcoreHome, {})) {
|
|
925
|
+
const db = openReadonlyDb(dbPath);
|
|
926
|
+
if (!db)
|
|
927
|
+
continue;
|
|
928
|
+
try {
|
|
929
|
+
const r = db.prepare(sql).get(taskId);
|
|
930
|
+
if (!r)
|
|
931
|
+
continue;
|
|
932
|
+
acc.input_tokens += r.input_tokens ?? 0;
|
|
933
|
+
acc.output_tokens += r.output_tokens ?? 0;
|
|
934
|
+
acc.cache_creation_tokens += r.cache_creation_tokens ?? 0;
|
|
935
|
+
acc.cache_read_tokens += r.cache_read_tokens ?? 0;
|
|
936
|
+
acc.calls += r.calls ?? 0;
|
|
937
|
+
acc.cost_official_usd += r.cost_official_usd ?? 0;
|
|
938
|
+
acc.cost_official_cny += r.cost_official_cny ?? 0;
|
|
939
|
+
acc.cost_gateway_usd += r.cost_gateway_usd ?? 0;
|
|
940
|
+
acc.cost_gateway_cny += r.cost_gateway_cny ?? 0;
|
|
941
|
+
}
|
|
942
|
+
catch {
|
|
943
|
+
// 老库无 cost 列:按零计,不阻塞 token 汇总
|
|
944
|
+
try {
|
|
945
|
+
const r = db.prepare(`SELECT
|
|
946
|
+
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
947
|
+
COALESCE(SUM(output_tokens), 0) AS output_tokens,
|
|
948
|
+
COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation_tokens,
|
|
949
|
+
COALESCE(SUM(cache_read_tokens), 0) AS cache_read_tokens,
|
|
950
|
+
COUNT(*) AS calls
|
|
951
|
+
FROM model_calls WHERE task_id = ?`).get(taskId);
|
|
952
|
+
if (!r)
|
|
953
|
+
continue;
|
|
954
|
+
acc.input_tokens += r.input_tokens ?? 0;
|
|
955
|
+
acc.output_tokens += r.output_tokens ?? 0;
|
|
956
|
+
acc.cache_creation_tokens += r.cache_creation_tokens ?? 0;
|
|
957
|
+
acc.cache_read_tokens += r.cache_read_tokens ?? 0;
|
|
958
|
+
acc.calls += r.calls ?? 0;
|
|
959
|
+
}
|
|
960
|
+
catch { /* 忽略该库 */ }
|
|
961
|
+
}
|
|
962
|
+
finally {
|
|
963
|
+
db.close();
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
acc.total_tokens = acc.input_tokens + acc.output_tokens + acc.cache_read_tokens + acc.cache_creation_tokens;
|
|
967
|
+
acc.usd = acc.cost_gateway_usd;
|
|
968
|
+
acc.cny = acc.cost_gateway_cny;
|
|
969
|
+
return acc;
|
|
970
|
+
}
|
|
646
971
|
function _enrichRow(evolcoreHome, r) {
|
|
647
972
|
const totalIn = (r.input_tokens ?? 0) + (r.cache_read_tokens ?? 0);
|
|
648
973
|
const cacheHitRate = totalIn > 0 ? (r.cache_read_tokens ?? 0) / totalIn : 0;
|