@agy-daddy/plugin-context 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/NOTICE +7 -0
- package/README.md +13 -2
- package/agy-plugin.json +59 -0
- package/baseline.json +10 -0
- package/locales/en.json +10 -0
- package/locales/zh-CN.json +10 -0
- package/native/mcp-server.js +140 -0
- package/native/mcp.json +8 -0
- package/native/skills/context-governance/SKILL.md +10 -0
- package/package.json +31 -4
- package/settings.schema.json +84 -0
- package/src/attachment-audit.js +171 -0
- package/src/context-analyzer.js +1036 -0
- package/src/node.js +506 -0
- package/src/panel-styles.js +274 -0
- package/src/pulse-capsule.js +484 -0
- package/src/renderer.js +995 -0
- package/src/stream-speed-tracker.js +143 -0
|
@@ -0,0 +1,1036 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const COMPRESSION_MIN_DROP = 5000;
|
|
4
|
+
const DEFAULT_CONTEXT_LIMIT = 256000;
|
|
5
|
+
const GPT_OSS_LIMIT = 131072;
|
|
6
|
+
const CLAUDE_55_LIMIT = 1000000;
|
|
7
|
+
const GEMINI_4_LIMIT = 1048576;
|
|
8
|
+
|
|
9
|
+
function safeNum(value) {
|
|
10
|
+
return value !== undefined && value !== null && Number.isFinite(Number(value)) && Number(value) >= 0
|
|
11
|
+
? Number(value)
|
|
12
|
+
: null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function toPositiveIntLimit(v) {
|
|
16
|
+
if (v === null || v === undefined || v === '') return 0;
|
|
17
|
+
const n = Number(v);
|
|
18
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function parseDurationSec(value) {
|
|
22
|
+
if (value === undefined || value === null) return null;
|
|
23
|
+
if (typeof value === 'number') return Number.isFinite(value) && value >= 0 ? value : null;
|
|
24
|
+
const match = String(value).trim().match(/^([\d.]+)\s*s?$/i);
|
|
25
|
+
if (!match) return null;
|
|
26
|
+
const num = parseFloat(match[1]);
|
|
27
|
+
return Number.isFinite(num) && num >= 0 ? num : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function parseTimestampMs(val) {
|
|
31
|
+
if (!val) return 0;
|
|
32
|
+
if (typeof val === 'number') {
|
|
33
|
+
const ms = val < 1e11 ? val * 1000 : val;
|
|
34
|
+
return Number.isFinite(ms) && ms > 946684800000 ? ms : 0;
|
|
35
|
+
}
|
|
36
|
+
if (typeof val === 'string') {
|
|
37
|
+
const t = val.trim();
|
|
38
|
+
if (!t || t.startsWith('1970-01-01') || t.startsWith('0001-01-01')) return 0;
|
|
39
|
+
const ms = Date.parse(t.replace(/(\.\d{3})\d+(Z|[+-]\d{2}:?\d{2})$/, '$1$2'));
|
|
40
|
+
return Number.isFinite(ms) && ms > 946684800000 ? ms : 0;
|
|
41
|
+
}
|
|
42
|
+
return 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function measure(text, outAcc = null) {
|
|
46
|
+
const s = String(text || '');
|
|
47
|
+
const len = s.length;
|
|
48
|
+
let chars = 0;
|
|
49
|
+
let bytes = 0;
|
|
50
|
+
let cjk = 0;
|
|
51
|
+
for (let i = 0; i < len; i++) {
|
|
52
|
+
const c = s.charCodeAt(i);
|
|
53
|
+
if (c <= 127) {
|
|
54
|
+
chars++;
|
|
55
|
+
bytes++;
|
|
56
|
+
} else if (c <= 2047) {
|
|
57
|
+
chars++;
|
|
58
|
+
bytes += 2;
|
|
59
|
+
} else if (c >= 0xD800 && c <= 0xDBFF && i + 1 < len) {
|
|
60
|
+
const c2 = s.charCodeAt(i + 1);
|
|
61
|
+
if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
|
|
62
|
+
i++;
|
|
63
|
+
chars++;
|
|
64
|
+
bytes += 4;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
chars++;
|
|
68
|
+
bytes += 3;
|
|
69
|
+
} else {
|
|
70
|
+
chars++;
|
|
71
|
+
bytes += 3;
|
|
72
|
+
if ((c >= 0x2e80 && c <= 0x9fff) || (c >= 0xf900 && c <= 0xfaff)) cjk++;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (outAcc) {
|
|
76
|
+
outAcc.chars += chars;
|
|
77
|
+
outAcc.bytes += bytes;
|
|
78
|
+
outAcc.cjk += cjk;
|
|
79
|
+
return outAcc;
|
|
80
|
+
}
|
|
81
|
+
const middle = (chars - cjk) / 4 + cjk * 1.2;
|
|
82
|
+
return {
|
|
83
|
+
chars,
|
|
84
|
+
bytes,
|
|
85
|
+
low: Math.ceil(middle * 0.7),
|
|
86
|
+
high: Math.ceil(Math.max(middle * 1.6, bytes / 2))
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function parseThresholdSpec(raw, fallbackTokens = 240000) {
|
|
91
|
+
const fb = Number(fallbackTokens) > 0 ? Math.round(Number(fallbackTokens)) : 240000;
|
|
92
|
+
const fbLabel = formatTokensShort(fb).toUpperCase();
|
|
93
|
+
if (typeof raw === 'number') {
|
|
94
|
+
if (Number.isFinite(raw) && raw > 0) {
|
|
95
|
+
const val = Math.round(raw);
|
|
96
|
+
return { kind: 'tokens', value: val, label: formatTokensShort(val).toUpperCase() };
|
|
97
|
+
}
|
|
98
|
+
return { kind: 'tokens', value: fb, label: fbLabel };
|
|
99
|
+
}
|
|
100
|
+
const s = String(raw || '').trim();
|
|
101
|
+
if (!s) return { kind: 'tokens', value: fb, label: fbLabel };
|
|
102
|
+
|
|
103
|
+
const pctMatch = s.match(/^(\d+(?:\.\d+)?)\s*%$/);
|
|
104
|
+
if (pctMatch) {
|
|
105
|
+
const pct = Math.max(1, Math.min(99, Number(pctMatch[1])));
|
|
106
|
+
const cleanPct = Number(pct.toFixed(1));
|
|
107
|
+
return { kind: 'percent', value: cleanPct, label: `${cleanPct}%` };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const mMatch = s.match(/^(\d+(?:\.\d+)?)\s*m$/i);
|
|
111
|
+
if (mMatch) {
|
|
112
|
+
const num = Number(mMatch[1]);
|
|
113
|
+
if (Number.isFinite(num) && num > 0) {
|
|
114
|
+
const val = Math.round(num * 1000000);
|
|
115
|
+
return { kind: 'tokens', value: val, label: formatTokensShort(val).toUpperCase() };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const kMatch = s.match(/^(\d+(?:\.\d+)?)\s*k$/i);
|
|
120
|
+
if (kMatch) {
|
|
121
|
+
const num = Number(kMatch[1]);
|
|
122
|
+
if (Number.isFinite(num) && num > 0) {
|
|
123
|
+
const val = Math.round(num * 1000);
|
|
124
|
+
return { kind: 'tokens', value: val, label: formatTokensShort(val).toUpperCase() };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const numMatch = s.match(/^(\d+(?:\.\d+)?)$/);
|
|
129
|
+
if (numMatch) {
|
|
130
|
+
const num = Number(numMatch[1]);
|
|
131
|
+
if (Number.isFinite(num) && num > 0) {
|
|
132
|
+
const val = Math.round(num);
|
|
133
|
+
return { kind: 'tokens', value: val, label: formatTokensShort(val).toUpperCase() };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return { kind: 'tokens', value: fb, label: fbLabel };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function resolveThresholdTokens(raw, budget, fallbackTokens = 240000) {
|
|
141
|
+
const spec = parseThresholdSpec(raw, fallbackTokens);
|
|
142
|
+
if (spec.kind === 'percent') {
|
|
143
|
+
const b = Number(budget);
|
|
144
|
+
if (Number.isFinite(b) && b > 0) {
|
|
145
|
+
return Math.max(1000, Math.round((spec.value / 100) * b));
|
|
146
|
+
}
|
|
147
|
+
return Number(fallbackTokens) > 0 ? Math.round(Number(fallbackTokens)) : 240000;
|
|
148
|
+
}
|
|
149
|
+
return spec.value;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function formatThresholdLabel(raw, budget, fallbackTokens = 240000) {
|
|
153
|
+
const spec = parseThresholdSpec(raw, fallbackTokens);
|
|
154
|
+
const tokens = resolveThresholdTokens(raw, budget, fallbackTokens);
|
|
155
|
+
return {
|
|
156
|
+
spec,
|
|
157
|
+
tokens,
|
|
158
|
+
shortLabel: spec.kind === 'percent' ? `${spec.value}%` : formatTokensShort(tokens).toUpperCase()
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function emptyGroup() {
|
|
163
|
+
return { chars: 0, bytes: 0, low: 0, high: 0 };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function addGroup(a, b) {
|
|
167
|
+
for (const k of ['chars', 'bytes', 'low', 'high']) a[k] += b[k] || 0;
|
|
168
|
+
return a;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function formatTokensShort(value) {
|
|
172
|
+
if (value === null || value === undefined || !Number.isFinite(Number(value))) return '—';
|
|
173
|
+
const safe = Math.max(0, Number(value));
|
|
174
|
+
if (safe >= 1000000) return `${(safe / 1000000).toFixed(safe >= 10000000 ? 1 : 2).replace(/\.?0+$/, '')}M`;
|
|
175
|
+
if (safe >= 1000) return `${(safe / 1000).toFixed(safe >= 100000 ? 0 : 1).replace(/\.0$/, '')}k`;
|
|
176
|
+
return String(Math.round(safe));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function normalizeModelId(raw) {
|
|
180
|
+
if (!raw || typeof raw !== 'string') return null;
|
|
181
|
+
const str = raw.trim().toLowerCase().replace(/^word\//, '');
|
|
182
|
+
if (str.includes('3.8-flash') || str.includes('3.8 flash') || str.includes('flash-n')) return 'gemini-3.8-flash';
|
|
183
|
+
if (str.includes('3.7-flash') || str.includes('3.7 flash')) return 'gemini-3.7-flash';
|
|
184
|
+
if (str.includes('3.6-flash') || str.includes('3.6 flash')) return 'gemini-3.6-flash';
|
|
185
|
+
if (str.includes('3.5-flash-lite') || str.includes('3.5 flash-lite') || str.includes('flash-lite')) {
|
|
186
|
+
if (str.includes('3.1')) return 'gemini-3.1-flash-lite';
|
|
187
|
+
if (str.includes('2.5')) return 'gemini-2.5-flash-lite';
|
|
188
|
+
return 'gemini-3.5-flash-lite';
|
|
189
|
+
}
|
|
190
|
+
if (str.includes('3.1-flash-lite') || str.includes('3.1 flash-lite')) return 'gemini-3.1-flash-lite';
|
|
191
|
+
if (str.includes('2.5-flash-lite') || str.includes('2.5 flash-lite')) return 'gemini-2.5-flash-lite';
|
|
192
|
+
if (str.includes('2.5-flash') || str.includes('2.5 flash')) return 'gemini-2.5-flash';
|
|
193
|
+
if ((str.includes('3.5-flash') || str.includes('3.5 flash')) && !str.includes('flash-lite')) return 'gemini-3.5-flash';
|
|
194
|
+
if (/\bgemini-3-flash(?:-[a-z0-9]+)?\b/.test(str) || str.includes('3 flash')) return 'gemini-3-flash';
|
|
195
|
+
if (str.includes('4-hydrogen') || str.includes('4 hydrogen') || str.includes('hydrogen')) return 'gemini-4-hydrogen';
|
|
196
|
+
if (str.includes('4-carbon') || str.includes('4 carbon') || str.includes('carbon') || str.includes('m670')) return 'gemini-4-carbon';
|
|
197
|
+
if (str.includes('4-neon') || str.includes('4 neon') || /\bneon\b/.test(str) || str.includes('m532')) return 'gemini-4-neon';
|
|
198
|
+
if (str.includes('4-argon') || str.includes('4 argon') || str.includes('argon') || /\bgemini-pro-orchestrator(?:-(?:argon|g1(?:-pro)?))?(?![a-z0-9-])/.test(str) || str.includes('m668')) {
|
|
199
|
+
return 'gemini-4-argon';
|
|
200
|
+
}
|
|
201
|
+
if (str.includes('3.1-pro') || str.includes('3.1 pro')) return 'gemini-3.1-pro-preview';
|
|
202
|
+
if (str.includes('2.5-pro') || str.includes('2.5 pro')) return 'gemini-2.5-pro';
|
|
203
|
+
if (/(?:opus[-_ ]5[._-]5|5[._-]5[-_ ]opus)/.test(str)) return 'claude-opus-5-5';
|
|
204
|
+
if (/(?:sonnet[-_ ]5[._-]5|5[._-]5[-_ ]sonnet)/.test(str)) return 'claude-sonnet-5-5';
|
|
205
|
+
if (/(?:opus[-_ ]4[._-]6|4[._-]6[-_ ]opus)/.test(str)) return 'claude-opus-4-6';
|
|
206
|
+
if (/(?:sonnet[-_ ]4[._-]6|4[._-]6[-_ ]sonnet)/.test(str)) return 'claude-sonnet-4-6';
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function getModelCandidateKeys(modelId, label) {
|
|
211
|
+
const keys = [];
|
|
212
|
+
const pushKey = (raw) => {
|
|
213
|
+
const k = String(raw || '').trim().toLowerCase();
|
|
214
|
+
if (!k) return;
|
|
215
|
+
if (!keys.includes(k)) keys.push(k);
|
|
216
|
+
const stripped = k.replace(/^model_placeholder_/, '').replace(/^model_/, '');
|
|
217
|
+
if (stripped && !keys.includes(stripped)) keys.push(stripped);
|
|
218
|
+
const mTag = k.match(/\b(m\d{2,4})\b/);
|
|
219
|
+
if (mTag && !keys.includes(mTag[1])) keys.push(mTag[1]);
|
|
220
|
+
};
|
|
221
|
+
pushKey(modelId);
|
|
222
|
+
pushKey(label);
|
|
223
|
+
return keys;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function getContextLimitForModel(modelId, label = '', options = {}) {
|
|
227
|
+
const rtBudget = toPositiveIntLimit(options.runtimeBudget);
|
|
228
|
+
if (rtBudget > 0) return rtBudget;
|
|
229
|
+
|
|
230
|
+
const modelMax = toPositiveIntLimit(options.modelMaxTokens);
|
|
231
|
+
if (modelMax > 0) return modelMax;
|
|
232
|
+
|
|
233
|
+
const candKeys = getModelCandidateKeys(modelId, label);
|
|
234
|
+
if (options.availableModels instanceof Map) {
|
|
235
|
+
for (const k of candKeys) {
|
|
236
|
+
const info = options.availableModels.get(k);
|
|
237
|
+
if (info && toPositiveIntLimit(info.maxTokens) > 0) return toPositiveIntLimit(info.maxTokens);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const combined = `${modelId || ''} ${label || ''}`.toUpperCase();
|
|
242
|
+
if (combined.includes('GPT_OSS') || combined.includes('GPT-OSS') || combined.includes('120B')) {
|
|
243
|
+
return GPT_OSS_LIMIT;
|
|
244
|
+
}
|
|
245
|
+
if (combined.includes('CLAUDE') || combined.includes('OPUS') || combined.includes('SONNET')) {
|
|
246
|
+
if (/5[._-]5|M400|M401|M402|M403|M404|M405/.test(combined)) return CLAUDE_55_LIMIT;
|
|
247
|
+
return 200000;
|
|
248
|
+
}
|
|
249
|
+
if (combined.includes('GEMINI') || combined.includes('CARBON') || combined.includes('ARGON') || combined.includes('HYDROGEN') || combined.includes('NEON') || combined.includes('M532') || combined.includes('M668') || combined.includes('M670') || combined.includes('ORCHESTRATOR') || combined.includes('FLASH')) {
|
|
250
|
+
return GEMINI_4_LIMIT;
|
|
251
|
+
}
|
|
252
|
+
return DEFAULT_CONTEXT_LIMIT;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function isShadowOrImageModel(modelId) {
|
|
256
|
+
if (!modelId) return false;
|
|
257
|
+
const s = String(modelId).toUpperCase();
|
|
258
|
+
return s.includes('_M50') || s === 'M50' || s.includes('FLASH_LITE') || s.includes('_M21') || s === 'M21' || s.includes('BANANA');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function formatResetTimeZh(isoStr) {
|
|
262
|
+
if (!isoStr) return '';
|
|
263
|
+
try {
|
|
264
|
+
const d = new Date(isoStr);
|
|
265
|
+
if (Number.isNaN(d.getTime())) return String(isoStr);
|
|
266
|
+
return `${d.getMonth() + 1}月${d.getDate()}日 ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
|
|
267
|
+
} catch {
|
|
268
|
+
return String(isoStr);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function classifyRequestError(input, options = {}) {
|
|
273
|
+
const error = typeof input === 'string' ? input : String(input?.error || input?.message || '');
|
|
274
|
+
const currentModel = options.currentModel || '';
|
|
275
|
+
|
|
276
|
+
if (!error) {
|
|
277
|
+
return {
|
|
278
|
+
kind: 'none',
|
|
279
|
+
title: '正常',
|
|
280
|
+
badgeText: '正常',
|
|
281
|
+
detail: '',
|
|
282
|
+
serviceLimit: null,
|
|
283
|
+
retryAfterSec: null,
|
|
284
|
+
modelOrPool: currentModel || null,
|
|
285
|
+
diagnostic: ''
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
let diagnostic = error.replace(/https?:\/\/[^\s"']+/g, '<API>').trim();
|
|
290
|
+
if (diagnostic.length > 120) diagnostic = diagnostic.slice(0, 117) + '...';
|
|
291
|
+
|
|
292
|
+
// 1. 上下文超限(明确排除 Go context.DeadlineExceeded)
|
|
293
|
+
const isDeadlineTimeout = /context deadline exceeded|deadline exceeded|stream idle timeout/i.test(error);
|
|
294
|
+
const overflowMatch = !isDeadlineTimeout && /input token count exceeds|context\s*(?:window|length|tokens?|limit|size|capacity)?.{0,35}(?:exceed|too long)|maximum context length|prompt exceeds maximum context length|max_tokens exceeded/i.test(error);
|
|
295
|
+
if (overflowMatch) {
|
|
296
|
+
const rawLimit = error.match(/(?:allowed|limit(?:\s+of)?|length(?:\s+is|\s+of)?)\s*[:=]?\s*([\d,]+)/i)?.[1];
|
|
297
|
+
const serviceLimit = rawLimit ? safeNum(rawLimit.replaceAll(',', '')) : null;
|
|
298
|
+
return {
|
|
299
|
+
kind: 'context_overflow',
|
|
300
|
+
title: '超限告警',
|
|
301
|
+
badgeText: '超限',
|
|
302
|
+
detail: `输入超出模型容量上限${serviceLimit ? `(${serviceLimit} tokens)` : ''},请精简上下文或压缩会话`,
|
|
303
|
+
serviceLimit,
|
|
304
|
+
retryAfterSec: null,
|
|
305
|
+
modelOrPool: currentModel || null,
|
|
306
|
+
diagnostic
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// 2. 配额耗尽
|
|
311
|
+
if (/(?:quota\s*(?:exceeded|reached|limit|exhausted)|out\s+of\s+quota|exhausted.*(?:capacity|quota)|resource_exhausted.*(?:quota|capacity|billing)|daily\s+quota|weekly\s+quota)/i.test(error)) {
|
|
312
|
+
const resetTimeZh = options.resetTime ? formatResetTimeZh(options.resetTime) : null;
|
|
313
|
+
return {
|
|
314
|
+
kind: 'quota_exhausted',
|
|
315
|
+
title: '额度耗尽',
|
|
316
|
+
badgeText: '额度耗尽',
|
|
317
|
+
detail: `${currentModel || '当前模型'}配额已用尽${resetTimeZh ? `,预计 ${resetTimeZh} 重置` : ''}`,
|
|
318
|
+
serviceLimit: null,
|
|
319
|
+
retryAfterSec: null,
|
|
320
|
+
modelOrPool: currentModel || null,
|
|
321
|
+
diagnostic
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// 3. 频率限制
|
|
326
|
+
if (/(?:rate\s*limit|too\s*many\s*requests|\b429\b|RateLimitError|RESOURCE_EXHAUSTED.*rate)/i.test(error)) {
|
|
327
|
+
const retryMatch = error.match(/(?:retry\s+in|retry-after|wait)\s*[:=]?\s*([\d.]+)/i);
|
|
328
|
+
const retryAfterSec = retryMatch ? parseFloat(retryMatch[1]) : null;
|
|
329
|
+
return {
|
|
330
|
+
kind: 'rate_limited',
|
|
331
|
+
title: '请求限流',
|
|
332
|
+
badgeText: '限流',
|
|
333
|
+
detail: `触发频率限制 (429)${retryAfterSec ? `,建议等待 ${retryAfterSec}s` : ''}`,
|
|
334
|
+
serviceLimit: null,
|
|
335
|
+
retryAfterSec,
|
|
336
|
+
modelOrPool: currentModel || null,
|
|
337
|
+
diagnostic
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// 4. 用户取消
|
|
342
|
+
if (/(?:context canceled by user|user cancelled|request was aborted|AbortError)/i.test(error)) {
|
|
343
|
+
return {
|
|
344
|
+
kind: 'canceled',
|
|
345
|
+
title: '已取消',
|
|
346
|
+
badgeText: '已取消',
|
|
347
|
+
detail: '生成请求已取消',
|
|
348
|
+
serviceLimit: null,
|
|
349
|
+
retryAfterSec: null,
|
|
350
|
+
modelOrPool: currentModel || null,
|
|
351
|
+
diagnostic
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// 5. 认证与权限
|
|
356
|
+
if (/(?:UNAUTHENTICATED|PERMISSION_DENIED|\b401\b|\b403\b|invalid api key|credentials expired|permission denied)/i.test(error)) {
|
|
357
|
+
return {
|
|
358
|
+
kind: 'auth_error',
|
|
359
|
+
title: '认证异常',
|
|
360
|
+
badgeText: '认证',
|
|
361
|
+
detail: '身份认证失败或缺少权限,请检查登录态或订阅级别',
|
|
362
|
+
serviceLimit: null,
|
|
363
|
+
retryAfterSec: null,
|
|
364
|
+
modelOrPool: currentModel || null,
|
|
365
|
+
diagnostic
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// 6. 服务端暂不可用
|
|
370
|
+
if (/(?:UNAVAILABLE|\b503\b|\b502\b|\b504\b|server overloaded|high demand|Bad Gateway|Service Unavailable)/i.test(error)) {
|
|
371
|
+
return {
|
|
372
|
+
kind: 'service_unavailable',
|
|
373
|
+
title: '服务受限',
|
|
374
|
+
badgeText: '服务异常',
|
|
375
|
+
detail: '模型服务暂时过载或不可用,请稍后重试',
|
|
376
|
+
serviceLimit: null,
|
|
377
|
+
retryAfterSec: null,
|
|
378
|
+
modelOrPool: currentModel || null,
|
|
379
|
+
diagnostic
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// 7. 网络连接或超时
|
|
384
|
+
if (/(?:\bEOF\b|idle timeout|deadline exceeded|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|socket hang up|fetch failed|Failed to fetch|NetworkError)/i.test(error)) {
|
|
385
|
+
return {
|
|
386
|
+
kind: 'network_error',
|
|
387
|
+
title: '网络故障',
|
|
388
|
+
badgeText: '网络',
|
|
389
|
+
detail: '网络连接异常或超时,请检查代理网关连通性',
|
|
390
|
+
serviceLimit: null,
|
|
391
|
+
retryAfterSec: null,
|
|
392
|
+
modelOrPool: currentModel || null,
|
|
393
|
+
diagnostic
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// 8. 兜底未知
|
|
398
|
+
return {
|
|
399
|
+
kind: 'unknown',
|
|
400
|
+
title: '原因待确认',
|
|
401
|
+
badgeText: '待确认',
|
|
402
|
+
detail: `请求失败 (${diagnostic})`,
|
|
403
|
+
serviceLimit: null,
|
|
404
|
+
retryAfterSec: null,
|
|
405
|
+
modelOrPool: currentModel || null,
|
|
406
|
+
diagnostic
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function summarizeMetadata(metadata, options = {}) {
|
|
411
|
+
const m = metadata?.chatModel;
|
|
412
|
+
if (!m) return null;
|
|
413
|
+
const lastRetry = (m.retryInfos || []).at(-1);
|
|
414
|
+
const error = String(lastRetry?.error || m.error || '');
|
|
415
|
+
const model = m.modelDisplayName || m.responseModel || m.model || options.currentModel || '';
|
|
416
|
+
const modelRaw = String(m.model || m.modelOrAlias?.model || m.responseModel || m.modelDisplayName || options.currentModel || '').trim();
|
|
417
|
+
|
|
418
|
+
const classification = error ? classifyRequestError(error, { currentModel: model }) : { kind: 'none' };
|
|
419
|
+
const exceeded = classification.kind === 'context_overflow';
|
|
420
|
+
const network = classification.kind === 'network_error';
|
|
421
|
+
|
|
422
|
+
const usage = lastRetry ? lastRetry.usage : m.usage;
|
|
423
|
+
const input = safeNum(usage?.inputTokens);
|
|
424
|
+
const cached = safeNum(usage?.cacheReadTokens);
|
|
425
|
+
const output = safeNum(usage?.outputTokens);
|
|
426
|
+
const thinking = safeNum(usage?.thinkingOutputTokens);
|
|
427
|
+
const responseTokens = safeNum(usage?.responseOutputTokens);
|
|
428
|
+
const hasInput = (input || 0) + (cached || 0) > 0;
|
|
429
|
+
|
|
430
|
+
const prevContext = options.previousValidContext || null;
|
|
431
|
+
const totalInputTokens = (input || 0) + (cached || 0);
|
|
432
|
+
const actualCached = hasInput ? (cached || 0) : (prevContext?.cached || 0);
|
|
433
|
+
const uncachedInput = hasInput ? (input || 0) : (prevContext?.uncachedInput ?? null);
|
|
434
|
+
const cacheHitRate = hasInput && totalInputTokens > 0
|
|
435
|
+
? Number(((actualCached / totalInputTokens) * 100).toFixed(1))
|
|
436
|
+
: (prevContext?.cacheHitRate ?? null);
|
|
437
|
+
|
|
438
|
+
let actual = hasInput && !error ? (input || 0) + (cached || 0) + (output || 0) : null;
|
|
439
|
+
if (actual === null && prevContext && prevContext.actual != null && !exceeded) {
|
|
440
|
+
actual = prevContext.actual;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const context = m.chatStartMetadata?.contextWindowMetadata;
|
|
444
|
+
const estimate = safeNum(context?.estimatedTokensUsed) || prevContext?.estimate || null;
|
|
445
|
+
const budget = safeNum(context?.maxContextTokens) || prevContext?.budget || getContextLimitForModel(modelRaw, model, options);
|
|
446
|
+
|
|
447
|
+
const ttft = parseDurationSec(m.timeToFirstToken);
|
|
448
|
+
const streamingSec = parseDurationSec(m.streamingDuration);
|
|
449
|
+
const duration = (ttft !== null && streamingSec !== null) ? (ttft + streamingSec) : (ttft ?? streamingSec ?? null);
|
|
450
|
+
const tps = (output && duration && duration > 0) ? Number((output / duration).toFixed(1)) : null;
|
|
451
|
+
const streamingTps = (output && streamingSec && streamingSec > 0.05) ? Number((output / streamingSec).toFixed(1)) : null;
|
|
452
|
+
|
|
453
|
+
const speed = (tps !== null || duration !== null || output !== null) ? {
|
|
454
|
+
tps,
|
|
455
|
+
streamingTps,
|
|
456
|
+
duration: duration !== null ? Number(duration.toFixed(2)) : null,
|
|
457
|
+
ttft: ttft !== null ? Number(ttft.toFixed(2)) : null,
|
|
458
|
+
streamingSec: streamingSec !== null ? Number(streamingSec.toFixed(2)) : null,
|
|
459
|
+
outputTokens: output ?? 0,
|
|
460
|
+
thinkingTokens: thinking ?? 0,
|
|
461
|
+
responseTokens: responseTokens ?? (output ?? 0)
|
|
462
|
+
} : null;
|
|
463
|
+
|
|
464
|
+
let status = 'pending';
|
|
465
|
+
if (exceeded) status = 'exceeded';
|
|
466
|
+
else if (network) status = 'network';
|
|
467
|
+
else if (classification.kind === 'quota_exhausted') status = 'quota_exhausted';
|
|
468
|
+
else if (classification.kind === 'rate_limited') status = 'rate_limited';
|
|
469
|
+
else if (classification.kind === 'auth_error') status = 'auth_error';
|
|
470
|
+
else if (classification.kind === 'service_unavailable') status = 'service_unavailable';
|
|
471
|
+
else if (classification.kind === 'canceled') status = 'canceled';
|
|
472
|
+
else if (error) status = 'failed';
|
|
473
|
+
else if (actual !== null) status = 'reported';
|
|
474
|
+
else if (estimate > 0) status = 'estimated';
|
|
475
|
+
|
|
476
|
+
const usedVal = actual ?? (estimate > 0 ? estimate : null);
|
|
477
|
+
const percentVal = usedVal !== null && budget > 0 && !exceeded ? Number(((usedVal / budget) * 100).toFixed(1)) : null;
|
|
478
|
+
|
|
479
|
+
return {
|
|
480
|
+
used: usedVal,
|
|
481
|
+
actual,
|
|
482
|
+
estimate: estimate > 0 ? estimate : null,
|
|
483
|
+
budget: budget > 0 ? budget : null,
|
|
484
|
+
serviceLimit: classification.serviceLimit || null,
|
|
485
|
+
exceeded,
|
|
486
|
+
network,
|
|
487
|
+
error,
|
|
488
|
+
errorClassification: classification,
|
|
489
|
+
estimated: actual === null,
|
|
490
|
+
input: hasInput ? totalInputTokens : (prevContext?.input || null),
|
|
491
|
+
cached: actualCached,
|
|
492
|
+
uncachedInput,
|
|
493
|
+
cacheHitRate,
|
|
494
|
+
output: output ?? (prevContext?.output ?? null),
|
|
495
|
+
percent: percentVal,
|
|
496
|
+
model,
|
|
497
|
+
modelRaw,
|
|
498
|
+
status,
|
|
499
|
+
speed
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function analyzeTrajectorySteps(steps, options = {}) {
|
|
504
|
+
const groups = {
|
|
505
|
+
user: emptyGroup(),
|
|
506
|
+
assistant: emptyGroup(),
|
|
507
|
+
thinking: emptyGroup(),
|
|
508
|
+
tools: emptyGroup(),
|
|
509
|
+
summaries: emptyGroup()
|
|
510
|
+
};
|
|
511
|
+
const media = new Map();
|
|
512
|
+
let userMessages = 0;
|
|
513
|
+
let assistantMessages = 0;
|
|
514
|
+
let prevCacheInclusiveInput = 0;
|
|
515
|
+
let maxPriorCacheRead = 0;
|
|
516
|
+
let compressionDetected = false;
|
|
517
|
+
let compressionBefore = 0;
|
|
518
|
+
let compressionAfter = 0;
|
|
519
|
+
let compressionDrop = 0;
|
|
520
|
+
let latestCacheRead = 0;
|
|
521
|
+
let latestInput = 0;
|
|
522
|
+
let latestOutput = 0;
|
|
523
|
+
let hasPreciseUsage = false;
|
|
524
|
+
let activeModelId = options.preferredModelId || '';
|
|
525
|
+
let observedBudget = toPositiveIntLimit(options.runtimeBudget);
|
|
526
|
+
|
|
527
|
+
const skip = new Set(['metadata', 'userConfig', 'lastUserConfig', 'userAgentSpec', 'activeUserState', 'thinkingSignature', 'thumbnail', 'inlineData', 'media', 'modelUsage', 'tokenUsage', 'mendelExperimentIds']);
|
|
528
|
+
const toolAcc = { chars: 0, bytes: 0, cjk: 0 };
|
|
529
|
+
|
|
530
|
+
function accumulateContent(value, acc) {
|
|
531
|
+
if (typeof value === 'string') { measure(value, acc); return; }
|
|
532
|
+
if (typeof value === 'number' || typeof value === 'boolean') { measure(String(value), acc); return; }
|
|
533
|
+
if (!value) return;
|
|
534
|
+
if (Array.isArray(value)) {
|
|
535
|
+
for (let i = 0; i < value.length; i++) {
|
|
536
|
+
if (i > 0) { acc.chars += 1; acc.bytes += 1; }
|
|
537
|
+
accumulateContent(value[i], acc);
|
|
538
|
+
}
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
const keys = Object.keys(value);
|
|
542
|
+
let wrote = false;
|
|
543
|
+
for (const key of keys) {
|
|
544
|
+
if (skip.has(key)) continue;
|
|
545
|
+
if (wrote) { acc.chars += 1; acc.bytes += 1; }
|
|
546
|
+
wrote = true;
|
|
547
|
+
measure(key, acc);
|
|
548
|
+
acc.chars += 2;
|
|
549
|
+
acc.bytes += 2;
|
|
550
|
+
accumulateContent(value[key], acc);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function collectAttachments(value, source, withinStep = new Set()) {
|
|
555
|
+
if (!value || typeof value !== 'object') return;
|
|
556
|
+
if (Array.isArray(value)) {
|
|
557
|
+
for (const v of value) collectAttachments(v, source, withinStep);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
if (value.uri && (value.mimeType || value.inlineData !== undefined)) {
|
|
561
|
+
const key = String(value.uri);
|
|
562
|
+
if (!withinStep.has(key)) {
|
|
563
|
+
withinStep.add(key);
|
|
564
|
+
const prior = media.get(key);
|
|
565
|
+
if (prior) {
|
|
566
|
+
prior.references++;
|
|
567
|
+
} else {
|
|
568
|
+
media.set(key, {
|
|
569
|
+
uri: key,
|
|
570
|
+
name: String(value.description || key.split(/[\\/]/).pop()),
|
|
571
|
+
mime: String(value.mimeType || ''),
|
|
572
|
+
references: 1,
|
|
573
|
+
source
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
} else if (value.inlineData && !value.uri) {
|
|
578
|
+
const key = `inline-${media.size}`;
|
|
579
|
+
const mime = String(value.mimeType || value.inlineData.mimeType || '');
|
|
580
|
+
if (!withinStep.has(key)) {
|
|
581
|
+
withinStep.add(key);
|
|
582
|
+
media.set(key, {
|
|
583
|
+
uri: `inline:${key}`,
|
|
584
|
+
name: String(value.description || (mime.startsWith('image/') ? '内嵌图像' : '内嵌附件')),
|
|
585
|
+
mime,
|
|
586
|
+
references: 1,
|
|
587
|
+
source
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
for (const [key, v] of Object.entries(value)) {
|
|
592
|
+
if (!skip.has(key) || key === 'media') collectAttachments(v, source, withinStep);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const list = Array.isArray(steps) ? steps : [];
|
|
597
|
+
for (let i = 0; i < list.length; i++) {
|
|
598
|
+
const s = list[i];
|
|
599
|
+
if (!s || typeof s !== 'object') continue;
|
|
600
|
+
const meta = s.metadata || s;
|
|
601
|
+
const mu = meta.modelUsage || s.modelUsage || s.checkpoint?.modelUsage || s.usage || null;
|
|
602
|
+
const stepModel = (mu && (mu.model || mu.modelId)) || meta.generatorModel || s.model || '';
|
|
603
|
+
const stepBudget = toPositiveIntLimit(meta.chatStartMetadata?.contextWindowMetadata?.maxContextTokens ?? meta.modelInfo?.maxTokens);
|
|
604
|
+
if (stepBudget > 0 && (!stepModel || !isShadowOrImageModel(stepModel))) {
|
|
605
|
+
observedBudget = stepBudget;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (mu && (mu.inputTokens !== undefined || mu.outputTokens !== undefined || mu.cacheReadTokens !== undefined || mu.promptTokens !== undefined)) {
|
|
609
|
+
if (!isShadowOrImageModel(stepModel)) {
|
|
610
|
+
const inTok = Math.max(0, Number(mu.inputTokens ?? mu.promptTokens ?? 0) || 0);
|
|
611
|
+
const cacheRead = Math.max(0, Number(mu.cacheReadTokens ?? mu.cachedTokens ?? 0) || 0);
|
|
612
|
+
const outTok = Math.max(0, Number(mu.outputTokens ?? mu.completionTokens ?? 0) || 0);
|
|
613
|
+
const cacheInclusive = inTok + cacheRead;
|
|
614
|
+
if (cacheInclusive + outTok > 0) {
|
|
615
|
+
if (prevCacheInclusiveInput > 0 && (prevCacheInclusiveInput - cacheInclusive) > COMPRESSION_MIN_DROP) {
|
|
616
|
+
compressionDetected = true;
|
|
617
|
+
compressionBefore = prevCacheInclusiveInput;
|
|
618
|
+
compressionAfter = cacheInclusive;
|
|
619
|
+
compressionDrop = prevCacheInclusiveInput - cacheInclusive;
|
|
620
|
+
}
|
|
621
|
+
if (hasPreciseUsage) {
|
|
622
|
+
maxPriorCacheRead = Math.max(maxPriorCacheRead, latestCacheRead);
|
|
623
|
+
}
|
|
624
|
+
prevCacheInclusiveInput = cacheInclusive;
|
|
625
|
+
latestInput = inTok;
|
|
626
|
+
latestCacheRead = cacheRead;
|
|
627
|
+
latestOutput = outTok;
|
|
628
|
+
hasPreciseUsage = true;
|
|
629
|
+
if (stepModel && !activeModelId) activeModelId = stepModel;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
if (s.userInput) {
|
|
635
|
+
userMessages++;
|
|
636
|
+
const u = s.userInput;
|
|
637
|
+
addGroup(groups.user, measure(u.userResponse || (u.items || []).map((it) => it.text || '').join('\n')));
|
|
638
|
+
collectAttachments(u.media?.length ? u.media : u.items, 'user');
|
|
639
|
+
} else if (s.plannerResponse) {
|
|
640
|
+
assistantMessages++;
|
|
641
|
+
addGroup(groups.assistant, measure(s.plannerResponse.modifiedResponse || s.plannerResponse.response || ''));
|
|
642
|
+
addGroup(groups.thinking, measure(s.plannerResponse.thinking || ''));
|
|
643
|
+
collectAttachments(s.plannerResponse, 'assistant');
|
|
644
|
+
} else if (s.checkpoint) {
|
|
645
|
+
addGroup(groups.summaries, measure(s.checkpoint.sessionSummary || ''));
|
|
646
|
+
} else {
|
|
647
|
+
toolAcc.chars = 0;
|
|
648
|
+
toolAcc.bytes = 0;
|
|
649
|
+
toolAcc.cjk = 0;
|
|
650
|
+
let wroteStep = false;
|
|
651
|
+
const withinToolStep = new Set();
|
|
652
|
+
for (const k of Object.keys(s)) {
|
|
653
|
+
if (k === 'type' || k === 'status' || k === 'metadata' || k === 'error') continue;
|
|
654
|
+
if (!skip.has(k)) {
|
|
655
|
+
if (wroteStep) { toolAcc.chars += 1; toolAcc.bytes += 1; }
|
|
656
|
+
wroteStep = true;
|
|
657
|
+
measure(k, toolAcc);
|
|
658
|
+
toolAcc.chars += 2;
|
|
659
|
+
toolAcc.bytes += 2;
|
|
660
|
+
accumulateContent(s[k], toolAcc);
|
|
661
|
+
}
|
|
662
|
+
if (!skip.has(k) || k === 'media') {
|
|
663
|
+
collectAttachments(s[k], 'assistant', withinToolStep);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
if (toolAcc.chars > 0 || toolAcc.bytes > 0) {
|
|
667
|
+
const middle = (toolAcc.chars - toolAcc.cjk) / 4 + toolAcc.cjk * 1.2;
|
|
668
|
+
addGroup(groups.tools, {
|
|
669
|
+
chars: toolAcc.chars,
|
|
670
|
+
bytes: toolAcc.bytes,
|
|
671
|
+
low: Math.ceil(middle * 0.7),
|
|
672
|
+
high: Math.ceil(Math.max(middle * 1.6, toolAcc.bytes / 2))
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const totalTextGroup = Object.values(groups).reduce(addGroup, emptyGroup());
|
|
679
|
+
const budget = getContextLimitForModel(activeModelId, options.preferredModelLabel, { runtimeBudget: observedBudget });
|
|
680
|
+
const preciseUsed = hasPreciseUsage ? (latestInput + latestCacheRead + latestOutput) : null;
|
|
681
|
+
const totalInputWithCache = latestInput + latestCacheRead;
|
|
682
|
+
const cacheHitRate = totalInputWithCache > 0 ? Number(((latestCacheRead / totalInputWithCache) * 100).toFixed(1)) : 0;
|
|
683
|
+
|
|
684
|
+
const warnThreshold = resolveThresholdTokens(options.warnThreshold ?? options.warnThresholdTokens, budget, 240000);
|
|
685
|
+
const cliffThreshold = resolveThresholdTokens(options.cliffThreshold ?? options.cliffThresholdTokens, budget, 328000);
|
|
686
|
+
const effectiveUsed = preciseUsed ?? totalTextGroup.high;
|
|
687
|
+
|
|
688
|
+
const cacheDropDetected = Boolean(
|
|
689
|
+
hasPreciseUsage &&
|
|
690
|
+
totalInputWithCache >= 150000 &&
|
|
691
|
+
cacheHitRate < 25 &&
|
|
692
|
+
(maxPriorCacheRead >= 50000 || latestInput >= warnThreshold)
|
|
693
|
+
);
|
|
694
|
+
const cacheCliffRisk = effectiveUsed >= cliffThreshold ? 'critical' : (effectiveUsed >= warnThreshold ? 'warn' : 'none');
|
|
695
|
+
|
|
696
|
+
return {
|
|
697
|
+
groups,
|
|
698
|
+
total: totalTextGroup,
|
|
699
|
+
media: Array.from(media.values()),
|
|
700
|
+
steps: list.length,
|
|
701
|
+
userMessages,
|
|
702
|
+
assistantMessages,
|
|
703
|
+
preciseUsed,
|
|
704
|
+
budget,
|
|
705
|
+
inputTokens: latestInput,
|
|
706
|
+
cacheReadTokens: latestCacheRead,
|
|
707
|
+
outputTokens: latestOutput,
|
|
708
|
+
cacheHitRate,
|
|
709
|
+
hasPreciseUsage,
|
|
710
|
+
cacheDropDetected,
|
|
711
|
+
cacheCliffRisk,
|
|
712
|
+
compressionDetected,
|
|
713
|
+
compressionBefore,
|
|
714
|
+
compressionAfter,
|
|
715
|
+
compressionDrop,
|
|
716
|
+
modelId: activeModelId
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function extractCallId(row, cascadeId = null, fallbackStepIndex = null) {
|
|
721
|
+
if (!row || typeof row !== 'object') return '';
|
|
722
|
+
const u = row.chatModel?.usage || row.usage || {};
|
|
723
|
+
const explicit =
|
|
724
|
+
u.responseId ||
|
|
725
|
+
u.response_id ||
|
|
726
|
+
row.response_id ||
|
|
727
|
+
row.responseId ||
|
|
728
|
+
u.messageId ||
|
|
729
|
+
u.message_id ||
|
|
730
|
+
row.message_id ||
|
|
731
|
+
row.messageId ||
|
|
732
|
+
row.callId ||
|
|
733
|
+
row.call_id ||
|
|
734
|
+
'';
|
|
735
|
+
if (explicit) return String(explicit);
|
|
736
|
+
const stepIdx = row.stepIndices?.[0] ?? row.stepIndex ?? row.step_index ?? fallbackStepIndex;
|
|
737
|
+
if (cascadeId && stepIdx !== null && stepIdx !== undefined) {
|
|
738
|
+
return `${cascadeId}#${stepIdx}`;
|
|
739
|
+
}
|
|
740
|
+
return '';
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
function formatLocalDateStr(dt) {
|
|
744
|
+
return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function extractStepTimestampsFromTrajectory(steps = []) {
|
|
748
|
+
const map = new Map();
|
|
749
|
+
const list = Array.isArray(steps) ? steps : [];
|
|
750
|
+
for (let i = 0; i < list.length; i++) {
|
|
751
|
+
const s = list[i];
|
|
752
|
+
if (!s || typeof s !== 'object') continue;
|
|
753
|
+
const rawStep = s.stepIndex ?? s.step_index ?? s.metadata?.stepIndex ?? i;
|
|
754
|
+
const parsedStep = Number(rawStep);
|
|
755
|
+
if (!Number.isInteger(parsedStep) || parsedStep < 0) continue;
|
|
756
|
+
const ts = parseTimestampMs(
|
|
757
|
+
s.metadata?.createdAt ||
|
|
758
|
+
s.metadata?.timestamp ||
|
|
759
|
+
s.createdAt ||
|
|
760
|
+
s.created_at ||
|
|
761
|
+
s.timestamp ||
|
|
762
|
+
s.plannerResponse?.createdAt ||
|
|
763
|
+
s.userInput?.createdAt
|
|
764
|
+
);
|
|
765
|
+
if (ts > 0 && !map.has(parsedStep)) {
|
|
766
|
+
map.set(parsedStep, ts);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
return map;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function resolveTimestampFromStepMap(stepIndex, stepTimestamps) {
|
|
773
|
+
if (!stepTimestamps) return 0;
|
|
774
|
+
if (typeof stepTimestamps.resolve === 'function') {
|
|
775
|
+
return Number(stepTimestamps.resolve(stepIndex)) || 0;
|
|
776
|
+
}
|
|
777
|
+
if (!(stepTimestamps instanceof Map) || stepTimestamps.size === 0) return 0;
|
|
778
|
+
const hasValidStep = Number.isInteger(stepIndex) && stepIndex >= 0;
|
|
779
|
+
if (hasValidStep && stepTimestamps.has(stepIndex)) {
|
|
780
|
+
return Number(stepTimestamps.get(stepIndex)) || 0;
|
|
781
|
+
}
|
|
782
|
+
let bestStep = -1;
|
|
783
|
+
let bestTs = 0;
|
|
784
|
+
let earliestStep = Infinity;
|
|
785
|
+
let earliestTs = 0;
|
|
786
|
+
for (const [s, ts] of stepTimestamps.entries()) {
|
|
787
|
+
if (!Number.isFinite(ts) || ts <= 946684800000) continue;
|
|
788
|
+
if (s < earliestStep) {
|
|
789
|
+
earliestStep = s;
|
|
790
|
+
earliestTs = ts;
|
|
791
|
+
}
|
|
792
|
+
if (hasValidStep && s <= stepIndex && s > bestStep) {
|
|
793
|
+
bestStep = s;
|
|
794
|
+
bestTs = ts;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
if (bestTs > 0) return bestTs;
|
|
798
|
+
return earliestTs > 0 ? earliestTs : 0;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function parseGeneratorCall(row, cascadeId = null, source = 'desktop', fallbackIndex = 0, options = {}) {
|
|
802
|
+
if (!row || typeof row !== 'object') return null;
|
|
803
|
+
const cm = row.chatModel || {};
|
|
804
|
+
const u = cm.usage || row.usage || {};
|
|
805
|
+
const model = cm.modelDisplayName || cm.responseModel || cm.model || row.model || row.modelId || '';
|
|
806
|
+
const modelKey = normalizeModelId(model);
|
|
807
|
+
|
|
808
|
+
const inputTokens = Number(u.inputTokens ?? row.inputTokens ?? row.input_tokens ?? 0);
|
|
809
|
+
const cacheTokens = Number(u.cacheReadTokens ?? row.cacheTokens ?? row.cacheReadTokens ?? row.cache_read_tokens ?? 0);
|
|
810
|
+
const outputTokens = Number(u.outputTokens ?? row.outputTokens ?? row.output_tokens ?? 0);
|
|
811
|
+
const thinkingTokens = Number(u.thinkingOutputTokens ?? row.thinkingTokens ?? row.thinking_output_tokens ?? 0);
|
|
812
|
+
const responseTokens = Number(u.responseOutputTokens ?? row.responseTokens ?? Math.max(0, outputTokens - thinkingTokens));
|
|
813
|
+
const totalTokens = inputTokens + cacheTokens + outputTokens;
|
|
814
|
+
|
|
815
|
+
const rawStepIdx = row.stepIndices?.[0] ?? row.stepIndex ?? row.step_index ?? fallbackIndex;
|
|
816
|
+
const parsedIdx = rawStepIdx !== undefined && rawStepIdx !== null && rawStepIdx !== '' ? Number(rawStepIdx) : NaN;
|
|
817
|
+
const stepIndex = Number.isInteger(parsedIdx) && parsedIdx >= 0 ? parsedIdx : null;
|
|
818
|
+
|
|
819
|
+
const callId = extractCallId(row, cascadeId, stepIndex ?? fallbackIndex);
|
|
820
|
+
if (!callId) return null;
|
|
821
|
+
|
|
822
|
+
const hasExplicitFinish = Boolean(
|
|
823
|
+
row.status === 'final' ||
|
|
824
|
+
row.status === 'completed' ||
|
|
825
|
+
cm.finishReason ||
|
|
826
|
+
row.finishReason ||
|
|
827
|
+
row.done === true ||
|
|
828
|
+
(cm.streamingDuration != null && cm.timeToFirstToken != null)
|
|
829
|
+
);
|
|
830
|
+
const status = hasExplicitFinish || (totalTokens > 0 && !row.isStreaming && row.status !== 'streaming')
|
|
831
|
+
? 'final'
|
|
832
|
+
: 'streaming';
|
|
833
|
+
const isEstimated = totalTokens <= 0 || outputTokens === 0;
|
|
834
|
+
|
|
835
|
+
const rawCreatedAt = row.created_at || row.createdAt || row.timestamp || cm.chatStartMetadata?.createdAt || cm.createdAt;
|
|
836
|
+
let timestamp = parseTimestampMs(rawCreatedAt);
|
|
837
|
+
let date = null;
|
|
838
|
+
let dateIsProvisional = false;
|
|
839
|
+
if (timestamp > 0) {
|
|
840
|
+
date = formatLocalDateStr(new Date(timestamp));
|
|
841
|
+
} else {
|
|
842
|
+
const stepTs = resolveTimestampFromStepMap(stepIndex, options?.stepTimestamps);
|
|
843
|
+
const fallbackMs = Number(options?.fallbackTimestampMs) || 0;
|
|
844
|
+
if (stepTs > 0) {
|
|
845
|
+
timestamp = stepTs;
|
|
846
|
+
date = formatLocalDateStr(new Date(timestamp));
|
|
847
|
+
dateIsProvisional = false;
|
|
848
|
+
} else if (row.date && /^\d{4}-\d{2}-\d{2}/.test(String(row.date))) {
|
|
849
|
+
date = String(row.date).slice(0, 10);
|
|
850
|
+
timestamp = Date.parse(date);
|
|
851
|
+
dateIsProvisional = Boolean(row.dateIsProvisional);
|
|
852
|
+
} else if (Number.isFinite(fallbackMs) && fallbackMs > 946684800000) {
|
|
853
|
+
timestamp = fallbackMs;
|
|
854
|
+
date = formatLocalDateStr(new Date(timestamp));
|
|
855
|
+
dateIsProvisional = true;
|
|
856
|
+
} else {
|
|
857
|
+
timestamp = Date.now();
|
|
858
|
+
date = formatLocalDateStr(new Date(timestamp));
|
|
859
|
+
dateIsProvisional = true;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
const ttftSec = parseDurationSec(cm.timeToFirstToken) ?? safeNum(row.ttftSec);
|
|
864
|
+
const streamingSec = parseDurationSec(cm.streamingDuration) ?? safeNum(row.streamingSec);
|
|
865
|
+
const durationSec = (ttftSec !== null && streamingSec !== null)
|
|
866
|
+
? Number((ttftSec + streamingSec).toFixed(2))
|
|
867
|
+
: (ttftSec ?? streamingSec ?? safeNum(row.durationSec));
|
|
868
|
+
const tps = (status === 'final' && !isEstimated && outputTokens > 0 && durationSec && durationSec > 0)
|
|
869
|
+
? Number((outputTokens / durationSec).toFixed(1))
|
|
870
|
+
: null;
|
|
871
|
+
|
|
872
|
+
return {
|
|
873
|
+
callId,
|
|
874
|
+
source,
|
|
875
|
+
cascadeId,
|
|
876
|
+
stepIndex,
|
|
877
|
+
model,
|
|
878
|
+
modelKey,
|
|
879
|
+
inputTokens,
|
|
880
|
+
cacheTokens,
|
|
881
|
+
cacheReadTokens: cacheTokens,
|
|
882
|
+
outputTokens,
|
|
883
|
+
thinkingTokens,
|
|
884
|
+
responseTokens,
|
|
885
|
+
totalTokens,
|
|
886
|
+
status,
|
|
887
|
+
isEstimated,
|
|
888
|
+
date,
|
|
889
|
+
dateIsProvisional,
|
|
890
|
+
timestamp,
|
|
891
|
+
ttftSec,
|
|
892
|
+
streamingSec,
|
|
893
|
+
durationSec,
|
|
894
|
+
tps
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
function summarizeSessionGeneratorCalls(gmRows, options = {}) {
|
|
899
|
+
const rows = Array.isArray(gmRows) ? gmRows : [];
|
|
900
|
+
const cascadeId = options.cascadeId || null;
|
|
901
|
+
const deduped = [];
|
|
902
|
+
const byCallId = new Map();
|
|
903
|
+
|
|
904
|
+
for (let i = 0; i < rows.length; i++) {
|
|
905
|
+
const row = rows[i];
|
|
906
|
+
if (!row || typeof row !== 'object') continue;
|
|
907
|
+
const cm = row.chatModel || {};
|
|
908
|
+
const u = cm.usage || row.usage || {};
|
|
909
|
+
const modelRaw = String(cm.model || cm.modelOrAlias?.model || cm.responseModel || cm.modelDisplayName || row.model || row.modelId || '').trim();
|
|
910
|
+
if (isShadowOrImageModel(modelRaw)) continue;
|
|
911
|
+
|
|
912
|
+
const inputTokens = Math.max(0, Number(u.inputTokens ?? row.inputTokens ?? row.input_tokens ?? 0) || 0);
|
|
913
|
+
const cachedTokens = Math.max(0, Number(u.cacheReadTokens ?? row.cacheTokens ?? row.cacheReadTokens ?? row.cache_read_tokens ?? 0) || 0);
|
|
914
|
+
const outputTokens = Math.max(0, Number(u.outputTokens ?? row.outputTokens ?? row.output_tokens ?? 0) || 0);
|
|
915
|
+
const thinkingTokens = Math.max(0, Number(u.thinkingOutputTokens ?? row.thinkingTokens ?? row.thinking_output_tokens ?? 0) || 0);
|
|
916
|
+
const rawResponseTokens = u.responseOutputTokens ?? row.responseTokens;
|
|
917
|
+
const responseTokens = rawResponseTokens !== undefined && rawResponseTokens !== null
|
|
918
|
+
? Math.max(0, Number(rawResponseTokens) || 0)
|
|
919
|
+
: Math.max(0, outputTokens - thinkingTokens);
|
|
920
|
+
|
|
921
|
+
if (inputTokens + cachedTokens + outputTokens <= 0) continue;
|
|
922
|
+
|
|
923
|
+
const ttftSec = parseDurationSec(cm.timeToFirstToken) ?? safeNum(row.ttftSec);
|
|
924
|
+
const streamingSec = parseDurationSec(cm.streamingDuration) ?? safeNum(row.streamingSec);
|
|
925
|
+
const durationSec = (ttftSec !== null && streamingSec !== null)
|
|
926
|
+
? (ttftSec + streamingSec)
|
|
927
|
+
: (ttftSec ?? streamingSec ?? safeNum(row.durationSec));
|
|
928
|
+
|
|
929
|
+
const entry = {
|
|
930
|
+
inputTokens,
|
|
931
|
+
cachedTokens,
|
|
932
|
+
outputTokens,
|
|
933
|
+
thinkingTokens,
|
|
934
|
+
responseTokens,
|
|
935
|
+
ttftSec,
|
|
936
|
+
streamingSec,
|
|
937
|
+
durationSec
|
|
938
|
+
};
|
|
939
|
+
|
|
940
|
+
const explicitId = String(
|
|
941
|
+
u.responseId || u.response_id || row.response_id || row.responseId
|
|
942
|
+
|| u.messageId || u.message_id || row.message_id || row.messageId
|
|
943
|
+
|| row.callId || row.call_id || ''
|
|
944
|
+
);
|
|
945
|
+
const callKey = explicitId || extractCallId(row, cascadeId, i);
|
|
946
|
+
if (callKey) {
|
|
947
|
+
if (byCallId.has(callKey)) {
|
|
948
|
+
deduped[byCallId.get(callKey)] = entry;
|
|
949
|
+
} else {
|
|
950
|
+
byCallId.set(callKey, deduped.length);
|
|
951
|
+
deduped.push(entry);
|
|
952
|
+
}
|
|
953
|
+
} else {
|
|
954
|
+
deduped.push(entry);
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
let inputTokens = 0;
|
|
959
|
+
let cachedTokens = 0;
|
|
960
|
+
let outputTokens = 0;
|
|
961
|
+
let thinkingTokens = 0;
|
|
962
|
+
let responseTokens = 0;
|
|
963
|
+
let timedOutput = 0;
|
|
964
|
+
let timedDuration = 0;
|
|
965
|
+
let streamOutput = 0;
|
|
966
|
+
let streamDuration = 0;
|
|
967
|
+
|
|
968
|
+
for (const c of deduped) {
|
|
969
|
+
inputTokens += c.inputTokens;
|
|
970
|
+
cachedTokens += c.cachedTokens;
|
|
971
|
+
outputTokens += c.outputTokens;
|
|
972
|
+
thinkingTokens += c.thinkingTokens;
|
|
973
|
+
responseTokens += c.responseTokens;
|
|
974
|
+
if (c.outputTokens > 0 && c.durationSec !== null && c.durationSec > 0) {
|
|
975
|
+
timedOutput += c.outputTokens;
|
|
976
|
+
timedDuration += c.durationSec;
|
|
977
|
+
}
|
|
978
|
+
if (c.outputTokens > 0 && c.streamingSec !== null && c.streamingSec > 0.05) {
|
|
979
|
+
streamOutput += c.outputTokens;
|
|
980
|
+
streamDuration += c.streamingSec;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
const totalInputTokens = inputTokens + cachedTokens;
|
|
985
|
+
const totalTokens = totalInputTokens + outputTokens;
|
|
986
|
+
|
|
987
|
+
return {
|
|
988
|
+
callsCount: deduped.length,
|
|
989
|
+
inputTokens,
|
|
990
|
+
cachedTokens,
|
|
991
|
+
totalInputTokens,
|
|
992
|
+
outputTokens,
|
|
993
|
+
thinkingTokens,
|
|
994
|
+
responseTokens,
|
|
995
|
+
totalTokens,
|
|
996
|
+
avgTps: timedDuration > 0 ? Number((timedOutput / timedDuration).toFixed(1)) : null,
|
|
997
|
+
avgStreamingTps: streamDuration > 0.05 ? Number((streamOutput / streamDuration).toFixed(1)) : null
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function getRingAccentToken(usagePercent, cacheAlert = {}) {
|
|
1002
|
+
if (cacheAlert.isCacheDrop || Number(usagePercent) >= 80) {
|
|
1003
|
+
return 'var(--ag-ring-danger, #ef4444)';
|
|
1004
|
+
}
|
|
1005
|
+
if (cacheAlert.isCliff328k || cacheAlert.isWarn240k || Number(usagePercent) >= 50) {
|
|
1006
|
+
return 'var(--ag-ring-warn, #f59e0b)';
|
|
1007
|
+
}
|
|
1008
|
+
return 'var(--ag-custom-token-accent, var(--ag-token-accent-default, #71717a))';
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
module.exports = {
|
|
1012
|
+
COMPRESSION_MIN_DROP,
|
|
1013
|
+
DEFAULT_CONTEXT_LIMIT,
|
|
1014
|
+
GPT_OSS_LIMIT,
|
|
1015
|
+
CLAUDE_55_LIMIT,
|
|
1016
|
+
GEMINI_4_LIMIT,
|
|
1017
|
+
measure,
|
|
1018
|
+
parseTimestampMs,
|
|
1019
|
+
parseDurationSec,
|
|
1020
|
+
formatTokensShort,
|
|
1021
|
+
parseThresholdSpec,
|
|
1022
|
+
resolveThresholdTokens,
|
|
1023
|
+
formatThresholdLabel,
|
|
1024
|
+
normalizeModelId,
|
|
1025
|
+
getModelCandidateKeys,
|
|
1026
|
+
getContextLimitForModel,
|
|
1027
|
+
isShadowOrImageModel,
|
|
1028
|
+
classifyRequestError,
|
|
1029
|
+
summarizeMetadata,
|
|
1030
|
+
analyzeTrajectorySteps,
|
|
1031
|
+
extractStepTimestampsFromTrajectory,
|
|
1032
|
+
extractCallId,
|
|
1033
|
+
parseGeneratorCall,
|
|
1034
|
+
summarizeSessionGeneratorCalls,
|
|
1035
|
+
getRingAccentToken
|
|
1036
|
+
};
|