evolcore 0.0.40 → 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.
Files changed (100) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/claude-runner.js +21 -106
  5. package/dist/agents/codex-runner.js +451 -231
  6. package/dist/agents/ecagent-runner.js +30 -11
  7. package/dist/agents/gemini-runner.js +26 -6
  8. package/dist/agents/runner-types.js +11 -3
  9. package/dist/aun/ability-device-routing.js +26 -0
  10. package/dist/aun/aid/client.js +1 -1
  11. package/dist/aun/group/identity.js +8 -0
  12. package/dist/aun/msg/managed-operation.js +4 -4
  13. package/dist/aun/msg/p2p.js +27 -7
  14. package/dist/aun/storage/download.js +30 -0
  15. package/dist/aun/storage/index.js +14 -6
  16. package/dist/channels/aun.js +33 -4
  17. package/dist/channels/daemon.js +24 -4
  18. package/dist/cli/agent-command.js +2 -0
  19. package/dist/cli/agent-create.js +98 -19
  20. package/dist/cli/agent.js +10 -3
  21. package/dist/cli/aun-commands.js +82 -22
  22. package/dist/cli/daemon-commands.js +19 -10
  23. package/dist/cli/index.js +1 -1
  24. package/dist/cli/restart-monitor.js +17 -0
  25. package/dist/cli/session-command.js +128 -13
  26. package/dist/cli/stats.js +60 -4
  27. package/dist/cli/trigger-command.js +2 -2
  28. package/dist/config/access-policy.js +2 -0
  29. package/dist/config/config-operation-service.js +17 -6
  30. package/dist/config/gateway-config.js +1 -1
  31. package/dist/config/peer-role-resolver.js +10 -8
  32. package/dist/core/agent-application-service.js +11 -1
  33. package/dist/core/agent-ipc-registration.js +4 -0
  34. package/dist/core/auth/agent-delegation.js +80 -5
  35. package/dist/core/auth/authorization-audit.js +20 -3
  36. package/dist/core/auth/operation-catalog.js +8 -0
  37. package/dist/core/command/agent-control.js +91 -12
  38. package/dist/core/command/command-handler.js +57 -46
  39. package/dist/core/command/connect-menu.js +23 -2
  40. package/dist/core/command/menu-catalog.js +1 -0
  41. package/dist/core/command/menu-handler.js +38 -101
  42. package/dist/core/command/menu-protocol.js +9 -2
  43. package/dist/core/command/role-menu.js +7 -6
  44. package/dist/core/command/slash-gate.js +13 -10
  45. package/dist/core/command/slash-handler.js +34 -98
  46. package/dist/core/event-catalog.js +15 -0
  47. package/dist/core/ipc-registration.js +18 -1
  48. package/dist/core/memory/consolidation-trigger.js +1 -1
  49. package/dist/core/message/aun-ipc-sender.js +26 -5
  50. package/dist/core/message/aun-request-registry.js +97 -3
  51. package/dist/core/message/im-renderer.js +4 -0
  52. package/dist/core/message/message-admission.js +8 -4
  53. package/dist/core/message/message-bridge.js +40 -6
  54. package/dist/core/message/message-log.js +55 -0
  55. package/dist/core/message/message-queue.js +5 -5
  56. package/dist/core/message/response-engine.js +310 -136
  57. package/dist/core/model/model-catalog.js +7 -6
  58. package/dist/core/ownership/owner-resolver.js +2 -2
  59. package/dist/core/permission/ec-command-parser.js +110 -5
  60. package/dist/core/permission/tool-policy.js +28 -7
  61. package/dist/core/session/session-capsule.js +197 -0
  62. package/dist/core/session/session-manager.js +148 -14
  63. package/dist/core/session/session-mapper.js +2 -0
  64. package/dist/index.js +3 -3
  65. package/dist/ipc.js +22 -8
  66. package/dist/stats/budget.js +1 -1
  67. package/dist/stats/db.js +15 -0
  68. package/dist/stats/index.js +2 -2
  69. package/dist/stats/price-resolver.js +304 -5
  70. package/dist/stats/query.js +82 -3
  71. package/dist/stats/writer.js +38 -5
  72. package/dist/trigger/feedback.js +18 -7
  73. package/dist/trigger/manager.js +20 -3
  74. package/dist/trigger/parser.js +6 -3
  75. package/dist/trigger/patch.js +1 -1
  76. package/dist/trigger/system-definitions.js +43 -7
  77. package/dist/trigger/validation.js +13 -5
  78. package/dist/utils/error-utils.js +14 -0
  79. package/dist/utils/npm-ops.js +2 -1
  80. package/dist/utils/package-version-info.js +1 -1
  81. package/dist/utils/upgrade-jobs.js +45 -5
  82. package/kits/docs/INDEX.md +1 -1
  83. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  84. package/kits/docs/evolcore/INDEX.md +2 -1
  85. package/kits/docs/evolcore/agent-create.md +3 -2
  86. package/kits/docs/evolcore/agent.md +1 -1
  87. package/kits/docs/evolcore/config.md +1 -1
  88. package/kits/docs/evolcore/event.md +1 -0
  89. package/kits/docs/evolcore/fs.md +5 -0
  90. package/kits/docs/evolcore/menu-protocol.md +32 -0
  91. package/kits/docs/evolcore/msg.md +17 -1
  92. package/kits/docs/evolcore/session.md +14 -0
  93. package/kits/schemas/agent-config.schema.13.json +15 -0
  94. package/kits/skills/aid-ability/SKILL.md +35 -6
  95. package/kits/templates/session-capsule/recovery.md +5 -0
  96. package/kits/templates/session-capsule/renew.md +5 -0
  97. package/kits/templates/system-fragments/bootstrap.md +6 -6
  98. package/kits/templates/system-fragments/channel.md +1 -1
  99. package/package.json +3 -3
  100. package/dist/stats/billing.js +0 -215
@@ -1,18 +1,317 @@
1
1
  /**
2
- * price-resolver.ts — 统一价格解析逻辑,支持官方价格和网关价格。
3
- * 供 writer.ts 写入时调用,供 rebuild 命令回填历史数据。
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 构造一个符合 billing.ts 规范的 PriceRecord。
370
+ * 从 PriceQuad 构造统一计费使用的 PriceRecord。
72
371
  * 用于将网关接口返回的价格四元组转换为可用于 calcCost() 的格式。
73
372
  */
74
373
  function priceQuadToRecord(model, ts, quad, billing_fn, currency = 'USD') {
@@ -3,7 +3,7 @@
3
3
  * 支持跨年查询:自动附加归档库。
4
4
  */
5
5
  import { openReadonlyDb, getDbPath, listArchivePaths } from './db.js';
6
- import { calcCost } from './billing.js'; // 保留用于尚未迁移的函数
6
+ import { calcCost } from './price-resolver.js'; // 保留用于尚未迁移的函数
7
7
  function emptyStatusActivity() {
8
8
  return {
9
9
  received: null, sent: null, completed: null, errors: null, interrupts: null, avgResponseMs: null, modelCalls: null,
@@ -871,7 +871,8 @@ export function queryTaskModelCalls(evolcoreHome, taskId) {
871
871
  if (!db)
872
872
  return [];
873
873
  try {
874
- return db.prepare(`SELECT * FROM model_calls WHERE task_id = ? ORDER BY call_index`).all(taskId);
874
+ // SELECT *:老库可能还没有 cost 列,显式列名会直接报错;缺失列由 _normalizeModelCall 补 null。
875
+ return db.prepare(`SELECT * FROM model_calls WHERE task_id = ? ORDER BY call_index`).all(taskId).map(_normalizeModelCall);
875
876
  }
876
877
  finally {
877
878
  db.close();
@@ -883,12 +884,90 @@ export function querySessionModelCalls(evolcoreHome, sessionId) {
883
884
  if (!db)
884
885
  return [];
885
886
  try {
886
- 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);
887
888
  }
888
889
  finally {
889
890
  db.close();
890
891
  }
891
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
+ }
892
971
  function _enrichRow(evolcoreHome, r) {
893
972
  const totalIn = (r.input_tokens ?? 0) + (r.cache_read_tokens ?? 0);
894
973
  const cacheHitRate = totalIn > 0 ? (r.cache_read_tokens ?? 0) / totalIn : 0;
@@ -206,8 +206,29 @@ export function insertMessageEvent(evolcoreHome, event) {
206
206
  import('../utils/logger.js').then(({ logger }) => logger.warn(`[StatsWriter] insertMessageEvent failed: ${e}`));
207
207
  }
208
208
  }
209
+ /**
210
+ * 为单次大模型调用算价。
211
+ * 复用 usage_events 的同一套口径(normalizeUsage 推断 billing_fn + resolvePrices 取价),
212
+ * 保证明细行的金额与同轮 usage_events 的费用可对账。
213
+ */
214
+ function resolveCallPrices(evolcoreHome, r, gatewayPricing) {
215
+ const event = normalizeUsage({
216
+ input_tokens: r.input_tokens,
217
+ output_tokens: r.output_tokens,
218
+ cache_creation_input_tokens: r.cache_creation_tokens,
219
+ cache_read_input_tokens: r.cache_read_tokens,
220
+ }, {
221
+ ts: r.ts,
222
+ agent_aid: r.agent_aid,
223
+ peer_key: r.peer_key,
224
+ session_id: r.session_id,
225
+ model: r.model || 'unknown',
226
+ turns: 1,
227
+ });
228
+ return resolvePrices(evolcoreHome, event, gatewayPricing);
229
+ }
209
230
  /** 批量写入大模型调用明细。单事务;失败不影响主流程。 */
210
- export function insertModelCalls(evolcoreHome, rows) {
231
+ export function insertModelCalls(evolcoreHome, rows, gatewayPricing) {
211
232
  if (!rows.length)
212
233
  return;
213
234
  const db = getDb(evolcoreHome);
@@ -218,12 +239,24 @@ export function insertModelCalls(evolcoreHome, rows) {
218
239
  INSERT INTO model_calls
219
240
  (ts, task_id, session_id, agent_session_id, agent_aid, peer_key, call_index, model,
220
241
  source, provider_thread_id, request_id, message_id, input_tokens, output_tokens, cache_creation_tokens,
221
- cache_read_tokens, context_tokens, max_tokens, auto_compact_tokens, degraded)
222
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
242
+ cache_read_tokens, context_tokens, max_tokens, auto_compact_tokens, degraded,
243
+ cost_official_usd, cost_official_cny, cost_gateway_usd, cost_gateway_cny)
244
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
223
245
  `);
246
+ // 价格解析在读事务外算好:resolvePrices 可能读价格表文件,避免拖长写锁。
247
+ const priced = rows.map(r => {
248
+ let prices = { official: null, gateway: null };
249
+ try {
250
+ prices = resolveCallPrices(evolcoreHome, r, gatewayPricing);
251
+ }
252
+ catch {
253
+ // 单行算价失败不影响其它行落库,金额留空
254
+ }
255
+ return { r, prices };
256
+ });
224
257
  db.exec('BEGIN');
225
- for (const r of rows) {
226
- 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);
258
+ 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);
227
260
  }
228
261
  db.exec('COMMIT');
229
262
  }
@@ -543,7 +543,10 @@ export class TriggerFeedbackDispatcher {
543
543
  try {
544
544
  if (cancellation.signal.aborted)
545
545
  return { effects, error: cancellation.error() };
546
- if (this.deps.tryHandoff) {
546
+ // Successful feedback may use the cross-session handoff path. Final
547
+ // failures must stay on the structured adapter path so the receiver
548
+ // gets one `result.error` payload instead of a plain text handoff.
549
+ if (this.deps.tryHandoff && (input.reply.outcome === 'success' || input.reply.outcome === 'noop')) {
547
550
  const startedAt = Date.now();
548
551
  try {
549
552
  const routed = await raceWithAbort(this.deps.tryHandoff({ ...input, signal: cancellation.signal }, text, target, binding), cancellation.signal);
@@ -597,12 +600,7 @@ export class TriggerFeedbackDispatcher {
597
600
  ? replyContextWithCausation(target, input.causation)
598
601
  : replyContextFromTarget(target),
599
602
  causation: isAunTarget ? input.causation : undefined,
600
- }), {
601
- kind: 'result.text',
602
- text,
603
- isFinal: true,
604
- format: 'plain',
605
- }), cancellation.signal);
603
+ }), feedbackPayload(input.reply, text)), cancellation.signal);
606
604
  const common = {
607
605
  type: 'message.send',
608
606
  channelKey: target.channelKey,
@@ -865,6 +863,19 @@ function errorFromReply(reply) {
865
863
  ...(reply.error?.recoverable !== undefined ? { recoverable: reply.error.recoverable } : {}),
866
864
  };
867
865
  }
866
+ function feedbackPayload(reply, text) {
867
+ if (reply.outcome === 'success' || reply.outcome === 'noop') {
868
+ return { kind: 'result.text', text, isFinal: true, format: 'plain' };
869
+ }
870
+ return {
871
+ kind: 'result.error',
872
+ text,
873
+ reason: reply.error?.reason ?? reply.outcome,
874
+ subtype: reply.error?.subtype ?? reply.error?.reason ?? reply.outcome,
875
+ ...(reply.error?.raw ? { raw: reply.error.raw } : {}),
876
+ ...(reply.error?.recoverable !== undefined ? { recoverable: reply.error.recoverable } : {}),
877
+ };
878
+ }
868
879
  function originAsTarget(origin) {
869
880
  return {
870
881
  channelKey: origin.channelKey,
@@ -36,12 +36,19 @@ export class TriggerDefinitionManager {
36
36
  if (!fs.existsSync(file))
37
37
  return undefined;
38
38
  const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
39
- const definition = normalizeTriggerDefinition(raw);
39
+ const definition = normalizeTriggerDefinition(raw, { allowLegacyZeroRetryAttempts: true });
40
+ const migrations = [];
40
41
  if (legacyFeedbackTargetNeedsMigration(raw, definition)) {
41
42
  definition.feedback.target.chatType ??= 'private';
43
+ migrations.push('legacy-aun-target-chat-type');
44
+ }
45
+ if (legacyRetryAttemptsNeedMigration(raw)) {
46
+ migrations.push('legacy-retry-attempts-default-one');
47
+ }
48
+ if (migrations.length > 0) {
42
49
  definition.updatedAt = Date.now();
43
50
  this.writeDefinition(definition);
44
- this.history.recordDefinition('trigger.updated', definition, { reason: 'legacy-aun-target-chat-type' });
51
+ this.history.recordDefinition('trigger.updated', definition, { reason: migrations.join(',') });
45
52
  }
46
53
  return definition;
47
54
  }
@@ -186,7 +193,7 @@ export class TriggerDefinitionManager {
186
193
  const sourceDir = stat.isDirectory() ? inputPath : path.dirname(inputPath);
187
194
  const triggerJson = stat.isDirectory() ? path.join(inputPath, 'trigger.json') : inputPath;
188
195
  const definitionRaw = JSON.parse(fs.readFileSync(triggerJson, 'utf-8'));
189
- const definition = normalizeTriggerDefinition(definitionRaw);
196
+ const definition = normalizeTriggerDefinition(definitionRaw, { allowLegacyZeroRetryAttempts: true });
190
197
  const files = [];
191
198
  if (definition.execution.type === 'script') {
192
199
  const scriptAbs = resolveScriptPath(sourceDir, definition.execution.script.path);
@@ -495,6 +502,16 @@ function legacyFeedbackTargetNeedsMigration(raw, definition) {
495
502
  const channelKey = optionalString(target.channelKey);
496
503
  return !!channelKey && (channelKey === 'aun' || channelKey.startsWith('aun#'));
497
504
  }
505
+ function legacyRetryAttemptsNeedMigration(raw) {
506
+ if (!isRecord(raw))
507
+ return false;
508
+ const reliability = isRecord(raw.reliability) ? raw.reliability : undefined;
509
+ const retry = reliability && isRecord(reliability.retry) ? reliability.retry : undefined;
510
+ if (retry?.maxAttempts === 0)
511
+ return true;
512
+ const execution = isRecord(raw.execution) ? raw.execution : undefined;
513
+ return execution?.onError === 'retry' && retry?.maxAttempts === undefined;
514
+ }
498
515
  function mergeOrigin(existing, incoming) {
499
516
  if (existing?.channelKey && existing.channelId)
500
517
  return existing;
@@ -810,9 +810,12 @@ function parseTriggerUpdateFlags(nameOrId, flags, opts = {}) {
810
810
  if ('error' in retryAttempts)
811
811
  return { ok: false, error: retryAttempts.error };
812
812
  if (retryAttempts.value !== undefined) {
813
- if (!/^\d+$/.test(retryAttempts.value))
814
- return { ok: false, error: '--retry-attempts 必须是非负整数' };
815
- update.retryAttempts = Number(retryAttempts.value);
813
+ if (!/^[1-9]\d*$/.test(retryAttempts.value))
814
+ return { ok: false, error: '--retry-attempts 必须是正整数(1 到 20)' };
815
+ const parsedAttempts = Number(retryAttempts.value);
816
+ if (parsedAttempts > 20)
817
+ return { ok: false, error: '--retry-attempts 必须是 1 到 20 的整数' };
818
+ update.retryAttempts = parsedAttempts;
816
819
  }
817
820
  const retryBackoff = optionalFlagString(flags, 'retry-backoff');
818
821
  if ('error' in retryBackoff)
@@ -146,7 +146,7 @@ export function applyTriggerPatch(definition, input, opts = {}) {
146
146
  if (patch.retryAttempts !== undefined || patch.retryBackoff !== undefined) {
147
147
  const retry = { ...updated.reliability.retry };
148
148
  if (patch.retryAttempts !== undefined)
149
- retry.maxAttempts = patch.retryAttempts ?? 0;
149
+ retry.maxAttempts = patch.retryAttempts ?? 1;
150
150
  if (patch.retryBackoff !== undefined)
151
151
  retry.backoffMs = patch.retryBackoff ?? 30_000;
152
152
  updated.reliability = { ...updated.reliability, retry };