@ssamurias/dsh-fish 1.0.3 → 1.0.5
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/AGENTS.md +5 -3
- package/CHANGELOG.md +55 -0
- package/README.md +92 -8
- package/RELEASE-NOTES-1.0.4.md +106 -0
- package/RELEASE-NOTES-1.0.5.md +79 -0
- package/docs/composite-pressure-v0.1.md +23 -0
- package/docs/composite-pressure-v0.2.md +18 -0
- package/docs/pressure-backtest-v0.1.md +19 -0
- package/docs/session-capacity-advice-v0.1.md +17 -0
- package/docs/session-pressure-design-v1.1.md +1173 -0
- package/docs/session-pressure-ui-v0.3.md +28 -0
- package/docs/tool-retention-diagnostics-v2.md +13 -0
- package/lib/appoint.js +154 -25
- package/lib/ask.js +70 -7
- package/lib/autobackup.js +2 -1
- package/lib/backup.js +58 -6
- package/lib/browse.js +191 -19
- package/lib/capture.js +48 -10
- package/lib/client.js +2203 -37
- package/lib/cloudbackup.js +24 -1
- package/lib/clouddrive.js +4 -1
- package/lib/compact.js +28 -11
- package/lib/configstamp.js +25 -0
- package/lib/cue.js +114 -0
- package/lib/derive.js +66 -5
- package/lib/doing.js +11 -2
- package/lib/dreamtable.js +5 -4
- package/lib/drive.js +66 -11
- package/lib/generator.js +1 -1
- package/lib/handoff.js +34 -16
- package/lib/home.js +3 -1
- package/lib/identity.js +23 -4
- package/lib/index.js +6 -1
- package/lib/interest.js +38 -0
- package/lib/look.js +16 -2
- package/lib/note.js +182 -41
- package/lib/observe.js +198 -4
- package/lib/persona.js +37 -15
- package/lib/proactive.js +6 -1
- package/lib/refuse.js +42 -0
- package/lib/restrict.js +8 -2
- package/lib/sametopic.js +94 -0
- package/lib/say.js +36 -7
- package/lib/scheduler.js +445 -24
- package/lib/selfcheck.js +9 -9
- package/lib/selfpronoun.js +7 -2
- package/lib/session-pressure-analysis.js +296 -0
- package/lib/session-pressure-data.js +239 -0
- package/lib/session-pressure-formulas.js +280 -0
- package/lib/session-pressure-load.js +110 -0
- package/lib/session-pressure.js +714 -0
- package/lib/settings.js +4 -1
- package/lib/sleepfact.js +110 -0
- package/lib/stance.js +212 -16
- package/lib/store.js +4 -0
- package/lib/sub.js +9 -7
- package/lib/turns.js +8 -1
- package/lib/use.js +2 -0
- package/lib/video.js +3 -0
- package/lib/watch.js +149 -3
- package/lib/whatseen.js +24 -2
- package/lib/wiki.js +1753 -0
- package/lib/wikiserve.js +148 -0
- package/media/feedback-qr.jpg +0 -0
- package/media/principle-drive.svg +28 -24
- package/media/principle-memory.svg +1 -1
- package/package.json +1 -1
- package/scripts/sync-pressure-formulas.mjs +17 -0
package/lib/selfcheck.js
CHANGED
|
@@ -95,12 +95,12 @@ export async function runChecks(o = {}) {
|
|
|
95
95
|
// 插件本体是零依赖的,ffmpeg 是唯一的外部工具。
|
|
96
96
|
{
|
|
97
97
|
const ff = detectFfmpeg()
|
|
98
|
-
push('ffmpeg', '
|
|
98
|
+
push('ffmpeg', '看视频画面用的 ffmpeg', ff.ok
|
|
99
99
|
? { ok: true, detail: `${ff.bin}${ff.version ? ` · ${ff.version}` : ''}` }
|
|
100
100
|
: {
|
|
101
101
|
ok: false,
|
|
102
102
|
detail: ff.why,
|
|
103
|
-
fix: '要让她看视频画面才需要它。装法二选一:① winget install Gyan.FFmpeg ② 下载 https://www.gyan.dev/ffmpeg/builds/ 解压后把 bin 目录加进 PATH。装完重启 DSH
|
|
103
|
+
fix: '要让她看视频画面才需要它。装法二选一:① winget install Gyan.FFmpeg ② 下载 https://www.gyan.dev/ffmpeg/builds/ 解压后把 bin 目录加进 PATH。装完重启 DSH。不想装也行——把「看视频画面」关掉,她照样能读文字。',
|
|
104
104
|
})
|
|
105
105
|
}
|
|
106
106
|
|
|
@@ -336,24 +336,24 @@ export async function runChecks(o = {}) {
|
|
|
336
336
|
// 跟「手上的工具」用同一个判据:那边说它在她自己那一层、她照样看得见,这边就不能说查不准。
|
|
337
337
|
const ownLayerProved = applied && ownLayerNow.includes('read_image')
|
|
338
338
|
if (globalHasImage || restrictProved || ownLayerProved) {
|
|
339
|
-
push('read-image', '
|
|
339
|
+
push('read-image', '看图片', {
|
|
340
340
|
ok: true,
|
|
341
341
|
detail: globalHasImage
|
|
342
|
-
? '宿主给了 read_image
|
|
342
|
+
? '宿主给了 read_image,她能打开你发的图、本机图片和自己抽出来的帧(模型本身也得支持图像输入,否则还是会被拒)。'
|
|
343
343
|
: restrictProved
|
|
344
|
-
? '宿主认了 read_image
|
|
345
|
-
: '宿主给了 read_image
|
|
344
|
+
? '宿主认了 read_image:她能打开你发的图、本机图片和自己抽出来的帧(模型本身也得支持图像输入,否则还是会被拒)。'
|
|
345
|
+
: '宿主给了 read_image(在她自己那一层,收窄管不着):她能打开你发的图、本机图片和自己抽出来的帧(模型本身也得支持图像输入,否则还是会被拒)。',
|
|
346
346
|
})
|
|
347
347
|
} else if (o.attachments === false) {
|
|
348
|
-
push('read-image', '
|
|
348
|
+
push('read-image', '看图片', {
|
|
349
349
|
ok: false,
|
|
350
350
|
detail: '宿主没挂附件服务,read_image 注册不上:她能抽到视频帧,但打不开那张图。装不装 ffmpeg 都一样。',
|
|
351
351
|
fix: '① 给这个 profile 装上带图片能力的插件(官方附件/图片那类),让宿主把 attachments 与 read_image 注出来;② 或者换一个声明了图像输入的模型再用;③ 弄好后重启 DSH,这一项就不再是红的。',
|
|
352
352
|
})
|
|
353
353
|
} else {
|
|
354
|
-
push('read-image', '
|
|
354
|
+
push('read-image', '看图片', {
|
|
355
355
|
ok: true,
|
|
356
|
-
detail: '查不准(宿主把 read_image
|
|
356
|
+
detail: '查不准(宿主把 read_image 挂在会话那一层,这里看不见)。让她看一次图就知道:能把画面内容讲出来,就是好的。',
|
|
357
357
|
})
|
|
358
358
|
}
|
|
359
359
|
}
|
package/lib/selfpronoun.js
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
|
|
24
24
|
import { readFileSync, statSync } from 'node:fs'
|
|
25
25
|
import { paths } from './store.js'
|
|
26
|
+
import { configStamp } from './configstamp.js'
|
|
26
27
|
|
|
27
28
|
/** 允许的三个值。别加「它」「牠」这类——那是另一套指代,不在这个开关里。 */
|
|
28
29
|
export const SELF_PRONOUN_VALUES = Object.freeze(['他', '她', '祂'])
|
|
@@ -74,7 +75,9 @@ export function fillSelf(text, pronoun = lastKnown) {
|
|
|
74
75
|
}
|
|
75
76
|
|
|
76
77
|
// 给服务端「每轮渲染一次」用的同步读:只读 config.json,按 mtime 缓存。
|
|
77
|
-
|
|
78
|
+
// mtime 在 Windows 上只到毫秒,同一进程连写两次可能撞在同一个 mtime 上,
|
|
79
|
+
// 所以键里再加一个进程内版本号(`configstamp.js`,写配置时 +1)。
|
|
80
|
+
const cache = { file: '', mtimeMs: -1, stamp: -1, pronoun: DEFAULT_SELF_PRONOUN }
|
|
78
81
|
|
|
79
82
|
/**
|
|
80
83
|
* 按 root 现读配置里的代词(同步)。读不到、读坏都用默认值,永不抛。
|
|
@@ -85,11 +88,13 @@ export function selfPronounFor(root) {
|
|
|
85
88
|
try {
|
|
86
89
|
const file = paths(root).config
|
|
87
90
|
const st = statSync(file)
|
|
88
|
-
|
|
91
|
+
const stamp = configStamp()
|
|
92
|
+
if (cache.file !== file || cache.mtimeMs !== st.mtimeMs || cache.stamp !== stamp) {
|
|
89
93
|
const raw = JSON.parse(readFileSync(file, 'utf8'))
|
|
90
94
|
cache.pronoun = selfPronounOf(raw)
|
|
91
95
|
cache.file = file
|
|
92
96
|
cache.mtimeMs = st.mtimeMs
|
|
97
|
+
cache.stamp = stamp
|
|
93
98
|
}
|
|
94
99
|
lastKnown = cache.pronoun
|
|
95
100
|
return cache.pronoun
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { looksLikeSecret } from './guard.js'
|
|
2
|
+
|
|
3
|
+
const count = value => Number.isSafeInteger(value) && value >= 0 ? value : null
|
|
4
|
+
|
|
5
|
+
export function usageOf(usage) {
|
|
6
|
+
const uncached = count(usage?.inputTokens)
|
|
7
|
+
const cacheRead = count(usage?.cacheReadTokens)
|
|
8
|
+
const cacheWrite = count(usage?.cacheWriteTokens)
|
|
9
|
+
const input = uncached == null ? null : uncached + (cacheRead ?? 0) + (cacheWrite ?? 0)
|
|
10
|
+
const output = count(usage?.outputTokens)
|
|
11
|
+
const total = count(usage?.totalTokens) ?? (input != null && output != null ? input + output : null)
|
|
12
|
+
const comparable = input != null && output != null && total === input + output
|
|
13
|
+
return { input, output, total, comparable, cacheRead, cacheWrite, reasoning: count(usage?.reasoningTokens) }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function observedSum(requests, key) {
|
|
17
|
+
const values = requests.map(request => request[key]).filter(value => value != null)
|
|
18
|
+
return { value: values.length ? values.reduce((sum, value) => sum + value, 0) : null, reported: values.length }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Use the same block and role pricing as the DSH message meter.
|
|
22
|
+
function estimateContent(blocks) {
|
|
23
|
+
let tokens = 0
|
|
24
|
+
for (const block of blocks) {
|
|
25
|
+
if (block.type === 'text' || block.type === 'reasoning') tokens += Math.ceil((block.text?.length ?? 0) / 4) + 4
|
|
26
|
+
else if (block.type === 'tool-call') tokens += Math.ceil((block.name?.length ?? 0) / 4) + Math.ceil((block.arguments?.length ?? 0) / 4) + 4
|
|
27
|
+
else if (block.type === 'tool-result' && Array.isArray(block.content)) tokens += estimateContent(block.content) + 4
|
|
28
|
+
else tokens += Math.ceil(JSON.stringify(block).length / 4) + 4
|
|
29
|
+
}
|
|
30
|
+
return tokens
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function analyzePressureEvents(events, checkpoint = null, saveCheckpoint = false) {
|
|
34
|
+
const turns = new Map((checkpoint?.turns ?? []).map(turn => [turn.turn, {
|
|
35
|
+
...turn, steps: new Set(turn.steps), routes: new Set(turn.routes),
|
|
36
|
+
attemptsByStep: new Map(turn.attemptsByStep),
|
|
37
|
+
}]))
|
|
38
|
+
const callNames = new Map(checkpoint?.callNames)
|
|
39
|
+
const seen = new Set()
|
|
40
|
+
const surface = checkpoint?.surface ?? []
|
|
41
|
+
const activeTools = new Map(checkpoint?.activeTools)
|
|
42
|
+
const surfacePrices = new Map(checkpoint?.surfacePrices)
|
|
43
|
+
let surfaceTokens = checkpoint?.surfaceTokens ?? 0
|
|
44
|
+
let dispatch = checkpoint?.dispatch ?? null
|
|
45
|
+
const burden = new Map(checkpoint?.burden)
|
|
46
|
+
let route = checkpoint?.route
|
|
47
|
+
let envelope = checkpoint?.envelope ?? null
|
|
48
|
+
let toolSnapshot = checkpoint?.toolSnapshot ?? null
|
|
49
|
+
let requestEnvelope = checkpoint?.requestEnvelope ?? null
|
|
50
|
+
const compaction = checkpoint?.compaction ?? { summaries: 0, reported: 0, tokens: 0, shadowed: null }
|
|
51
|
+
const compactionEvents = checkpoint?.compactionEvents ?? { started: 0, succeeded: 0, failed: 0, summaries: 0, prunes: 0 }
|
|
52
|
+
const toolResults = new Map(checkpoint?.toolResults)
|
|
53
|
+
let surfaceKnown = checkpoint?.surfaceKnown ?? true
|
|
54
|
+
function measureRequest(turn, step, seq) {
|
|
55
|
+
if (!surfaceKnown || surfaceTokens <= 0) return { turn, step, seq, status: 'unavailable',
|
|
56
|
+
reason: surfaceKnown ? 'empty-request-surface' : 'incomplete-request-surface' }
|
|
57
|
+
const unique = new Map()
|
|
58
|
+
let duplicateTokens = 0
|
|
59
|
+
for (const [seq, tool] of activeTools) {
|
|
60
|
+
const key = tool.callKey ?? seq
|
|
61
|
+
duplicateTokens += unique.get(key)?.tokens ?? 0
|
|
62
|
+
unique.set(key, { ...tool, seq })
|
|
63
|
+
}
|
|
64
|
+
const tools = [...unique.values()]
|
|
65
|
+
const tokens = tools.reduce((sum, tool) => sum + tool.tokens, 0)
|
|
66
|
+
const inputTokens = surfaceTokens - duplicateTokens + (envelope?.systemTokens ?? 0) + (envelope?.toolTokens ?? 0)
|
|
67
|
+
return { turn, step, seq, status: tokens > inputTokens ? 'invalid' : 'estimated', inputTokens, tokens, tools }
|
|
68
|
+
}
|
|
69
|
+
for (const event of events) {
|
|
70
|
+
if (seen.has(event.seq)) continue
|
|
71
|
+
seen.add(event.seq)
|
|
72
|
+
const data = event.data ?? {}
|
|
73
|
+
if (event.type === 'request/context') {
|
|
74
|
+
const { provider, model, contextWindow } = data
|
|
75
|
+
route = { provider, model, contextWindow }
|
|
76
|
+
}
|
|
77
|
+
if (event.type === 'request/header' && data.header && typeof data.header === 'object') {
|
|
78
|
+
const { system, tools } = data.header
|
|
79
|
+
const systemChars = typeof system === 'string' ? system.length : system === undefined ? 0 : null
|
|
80
|
+
const toolChars = Array.isArray(tools) && tools.length ? JSON.stringify(tools).length
|
|
81
|
+
: tools === undefined || Array.isArray(tools) ? 0 : null
|
|
82
|
+
envelope = { systemChars, toolChars,
|
|
83
|
+
systemTokens: systemChars == null ? null : systemChars === 0 ? 0 : Math.ceil(systemChars / 4) + 4,
|
|
84
|
+
toolTokens: toolChars == null ? null : toolChars ? Math.ceil(toolChars / 4) + 4 : 0 }
|
|
85
|
+
}
|
|
86
|
+
if (event.type === 'assistant/message' && usageOf(data.usage).comparable) requestEnvelope = envelope
|
|
87
|
+
if (event.type === 'compaction/start') compactionEvents.started++
|
|
88
|
+
if (event.type === 'compaction/end') compactionEvents[data.error ? 'failed' : 'succeeded']++
|
|
89
|
+
if (event.type === 'compaction/prune') compactionEvents.prunes++
|
|
90
|
+
if (event.type === 'compaction/summary') {
|
|
91
|
+
compactionEvents.summaries++
|
|
92
|
+
const usage = usageOf(data.usage)
|
|
93
|
+
compaction.summaries++
|
|
94
|
+
if (usage.total != null) { compaction.reported++; compaction.tokens += usage.total }
|
|
95
|
+
compaction.shadowed = count(data.shadowedTokenCount)
|
|
96
|
+
}
|
|
97
|
+
const turnId = count(data.turn)
|
|
98
|
+
if (event.type === 'assistant/chunk' && turnId != null && (dispatch?.turn !== turnId || dispatch?.step !== data.step)) {
|
|
99
|
+
dispatch = measureRequest(turnId, data.step, event.seq)
|
|
100
|
+
}
|
|
101
|
+
let turn
|
|
102
|
+
if (turnId != null && /^(turn\/(?:start|end)|step\/start|assistant\/(?:message|attempt)|tool\/(?:call|result))$/.test(event.type)) {
|
|
103
|
+
turn = turns.get(turnId) ?? { turn: turnId, steps: new Set(), attempts: 0, attemptsByStep: new Map(), attemptUsage: [], retries: 0, requests: [],
|
|
104
|
+
tools: 0, toolErrors: 0, ended: false, failed: false, routes: new Set(), toolLoad: 0, surfaceKnown: true }
|
|
105
|
+
turns.set(turnId, turn)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (event.type === 'assistant/message' && turn) {
|
|
109
|
+
const key = route?.provider && route?.model && count(route.contextWindow) > 0
|
|
110
|
+
? JSON.stringify([route.provider, route.model, route.contextWindow]) : null
|
|
111
|
+
turn.routes.add(key)
|
|
112
|
+
const usage = usageOf(data.usage)
|
|
113
|
+
turn.requests.push(usage)
|
|
114
|
+
turn.requestWindow = count(route?.contextWindow)
|
|
115
|
+
turn.requestSeq = event.seq
|
|
116
|
+
turn.requestTools = null
|
|
117
|
+
const matchedDispatch = dispatch?.turn === turnId && dispatch?.step === data.step
|
|
118
|
+
const requestSurface = matchedDispatch ? dispatch : measureRequest(turnId, data.step, event.seq)
|
|
119
|
+
dispatch = null
|
|
120
|
+
if (requestSurface.status === 'estimated') {
|
|
121
|
+
const { tokens, tools } = requestSurface
|
|
122
|
+
let carried = 0
|
|
123
|
+
let oldestTurn = null
|
|
124
|
+
const ages = new Map()
|
|
125
|
+
for (const tool of tools) {
|
|
126
|
+
const age = turnId - tool.turn
|
|
127
|
+
ages.set(age, (ages.get(age) ?? 0) + tool.tokens)
|
|
128
|
+
if (tool.turn < turnId) carried += tool.tokens
|
|
129
|
+
oldestTurn = oldestTurn == null ? tool.turn : Math.min(oldestTurn, tool.turn)
|
|
130
|
+
const result = toolResults.get(tool.seq)
|
|
131
|
+
if (result && tool.turn < turnId) result.carried++
|
|
132
|
+
if (tool.turn < turnId) {
|
|
133
|
+
const row = burden.get(tool.name) ?? { name: tool.name, exposures: 0, tokensAcrossRequests: 0 }
|
|
134
|
+
row.exposures++
|
|
135
|
+
row.tokensAcrossRequests += tool.tokens
|
|
136
|
+
burden.set(tool.name, row)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (Number.isFinite(usage.input) && Number.isFinite(usage.output)) {
|
|
140
|
+
toolSnapshot = { seq: event.seq, dispatchSeq: requestSurface.seq, matchedDispatch, tokens,
|
|
141
|
+
inputTokens: requestSurface.inputTokens, status: 'estimated', ages: [...ages].sort(([a], [b]) => a - b) }
|
|
142
|
+
}
|
|
143
|
+
if (requestSurface.inputTokens > 0) {
|
|
144
|
+
turn.pairedToolInput = (turn.pairedToolInput ?? 0) + requestSurface.inputTokens
|
|
145
|
+
turn.pairedCarry = (turn.pairedCarry ?? 0) + carried
|
|
146
|
+
turn.pairedToolRequests = (turn.pairedToolRequests ?? 0) + 1
|
|
147
|
+
}
|
|
148
|
+
turn.requestTools = { count: tools.length, tokens, oldestTurn }
|
|
149
|
+
turn.toolLoad += tokens
|
|
150
|
+
turn.carriedTokens = (turn.carriedTokens ?? 0) + carried
|
|
151
|
+
} else {
|
|
152
|
+
if (requestSurface.status === 'invalid') turn.invalidToolRequests = (turn.invalidToolRequests ?? 0) + 1
|
|
153
|
+
if (Number.isFinite(usage.input) && Number.isFinite(usage.output)) {
|
|
154
|
+
toolSnapshot = { seq: event.seq, dispatchSeq: requestSurface.seq, matchedDispatch,
|
|
155
|
+
status: requestSurface.status, reason: requestSurface.reason, tokens: requestSurface.tokens,
|
|
156
|
+
inputTokens: requestSurface.inputTokens, ages: [] }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (turn.attemptsByStep.has(data.step)) {
|
|
160
|
+
const recovered = turn.attemptsByStep.get(data.step)
|
|
161
|
+
turn.retries += recovered.length
|
|
162
|
+
turn.recoveredAttempts = [...(turn.recoveredAttempts ?? []), ...recovered]
|
|
163
|
+
turn.attemptsByStep.delete(data.step)
|
|
164
|
+
}
|
|
165
|
+
turn.surfaceKnown &&= requestSurface.status === 'estimated'
|
|
166
|
+
} else if (event.type === 'assistant/attempt' && turn) {
|
|
167
|
+
dispatch = null
|
|
168
|
+
turn.attempts++
|
|
169
|
+
const chunks = Array.isArray(data.stream) ? data.stream : []
|
|
170
|
+
const usage = chunks.findLast(record => record.type === 'chunk' && record.chunk?.type === 'usage')?.chunk.usage
|
|
171
|
+
turn.attemptUsage.push(usageOf(usage).total)
|
|
172
|
+
|
|
173
|
+
if (count(data.step) != null) turn.attemptsByStep.set(data.step, [...(turn.attemptsByStep.get(data.step) ?? []), usageOf(usage).total])
|
|
174
|
+
} else if (event.type === 'step/start' && turn && count(data.step) != null) {
|
|
175
|
+
turn.steps.add(data.step)
|
|
176
|
+
} else if (event.type === 'turn/end' && turn) {
|
|
177
|
+
turn.ended = true
|
|
178
|
+
turn.surfaceKnown &&= surfaceKnown
|
|
179
|
+
turn.failed = data.reason?.kind === 'error'
|
|
180
|
+
turn.completed = data.reason?.kind === 'completed'
|
|
181
|
+
} else if (event.type === 'tool/call' && turn) {
|
|
182
|
+
turn.tools++
|
|
183
|
+
if (typeof data.callId === 'string' && typeof data.name === 'string' && !looksLikeSecret(data.name).hit) {
|
|
184
|
+
callNames.set(data.callId, data.name)
|
|
185
|
+
}
|
|
186
|
+
} else if (event.type === 'tool/result' && turn && (data.message?.isError || data.error)) {
|
|
187
|
+
turn.toolErrors++
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (!surfaceKnown) continue
|
|
191
|
+
const op = event.surfaceOp
|
|
192
|
+
if (op?.op === 'replace') {
|
|
193
|
+
const start = surface.indexOf(op.startSeq ?? op.start)
|
|
194
|
+
const end = surface.indexOf(op.endSeq ?? op.end)
|
|
195
|
+
if (start < 0 || end < start) {
|
|
196
|
+
surfaceKnown = false
|
|
197
|
+
continue
|
|
198
|
+
}
|
|
199
|
+
for (const seq of surface.splice(start, end - start + 1, event.seq)) {
|
|
200
|
+
activeTools.delete(seq)
|
|
201
|
+
surfaceTokens -= surfacePrices.get(seq) ?? 0
|
|
202
|
+
surfacePrices.delete(seq)
|
|
203
|
+
}
|
|
204
|
+
} else if (op === 'append' || op?.op === 'append') {
|
|
205
|
+
surface.push(event.seq)
|
|
206
|
+
} else {
|
|
207
|
+
if (op != null) surfaceKnown = false
|
|
208
|
+
continue
|
|
209
|
+
}
|
|
210
|
+
const message = event.type === 'user/message' ? (data.message ?? data)
|
|
211
|
+
: ['assistant/message', 'tool/result'].includes(event.type) ? data.message : null
|
|
212
|
+
if ((event.type === 'tool/result' && !turn) || (['user/message', 'assistant/message', 'tool/result'].includes(event.type)
|
|
213
|
+
&& !Array.isArray(message?.content))) {
|
|
214
|
+
surfaceKnown = false
|
|
215
|
+
continue
|
|
216
|
+
}
|
|
217
|
+
const tokens = Array.isArray(message?.content) && (message.content.length || event.type !== 'assistant/message')
|
|
218
|
+
? estimateContent(message.content) + 4 : 0
|
|
219
|
+
surfacePrices.set(event.seq, tokens)
|
|
220
|
+
surfaceTokens += tokens
|
|
221
|
+
if (event.type === 'tool/result' && turn) {
|
|
222
|
+
const callId = data.message?.toolCallId
|
|
223
|
+
const name = callNames.get(callId) ?? '未知工具'
|
|
224
|
+
const callKey = typeof callId === 'string' ? JSON.stringify([turnId, callId]) : null
|
|
225
|
+
activeTools.set(event.seq, { name, tokens, turn: turnId, callKey })
|
|
226
|
+
toolResults.set(event.seq, { seq: event.seq, name, tokens, turn: turnId, carried: 0 })
|
|
227
|
+
if (toolResults.size > 200) toolResults.delete(toolResults.keys().next().value)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const rows = [...turns.values()].filter(turn => turn.ended).map(turn => {
|
|
232
|
+
const requests = turn.requests
|
|
233
|
+
const total = observedSum(requests, 'total')
|
|
234
|
+
const cached = requests.filter(row => row.input != null && row.input > 0 && row.cacheRead != null)
|
|
235
|
+
const cacheInput = cached.reduce((sum, row) => sum + row.input, 0)
|
|
236
|
+
const cacheRead = cached.reduce((sum, row) => sum + row.cacheRead, 0)
|
|
237
|
+
const openingInput = requests[0]?.input
|
|
238
|
+
const usageBreakdownMismatch = requests.some(row => row.input != null && row.output != null && !row.comparable)
|
|
239
|
+
const reportedAttempts = turn.attemptUsage.filter(Number.isFinite)
|
|
240
|
+
const attemptTokens = reportedAttempts.reduce((sum, n) => sum + n, 0)
|
|
241
|
+
if (reportedAttempts.length) {
|
|
242
|
+
total.value = (total.value ?? 0) + attemptTokens
|
|
243
|
+
total.reported += reportedAttempts.length
|
|
244
|
+
}
|
|
245
|
+
const completeUsage = total.reported === requests.length + turn.attempts && total.reported > 0
|
|
246
|
+
const subsequent = requests.slice(1)
|
|
247
|
+
const knownSubsequent = subsequent.filter(row => row.comparable)
|
|
248
|
+
const repeatedInput = knownSubsequent.reduce((sum, row) => sum + row.input, 0)
|
|
249
|
+
const uncachedInput = cacheInput - cacheRead
|
|
250
|
+
const allAttemptsAttributed = turn.attempts === turn.retries || turn.failed
|
|
251
|
+
return {
|
|
252
|
+
metrics: {
|
|
253
|
+
firstInput: openingInput ?? null, lastInput: requests.at(-1)?.input ?? null,
|
|
254
|
+
window: turn.requestWindow ?? null, requestSeq: turn.requestSeq, cacheInput, cachedInput: cacheRead, cacheReports: cached.length,
|
|
255
|
+
tools: turn.requestTools ?? null, carry: turn.surfaceKnown && turn.attempts === 0 && requests.length ? turn.carriedTokens : null,
|
|
256
|
+
pairedToolInput: turn.pairedToolInput ?? 0, pairedCarry: turn.pairedCarry ?? 0,
|
|
257
|
+
pairedToolRequests: turn.pairedToolRequests ?? 0, invalidToolRequests: turn.invalidToolRequests ?? 0,
|
|
258
|
+
attemptReports: reportedAttempts.length,
|
|
259
|
+
retryTokens: (turn.recoveredAttempts ?? []).every(Number.isFinite)
|
|
260
|
+
? (turn.recoveredAttempts ?? []).reduce((sum, number) => sum + number, 0) : null,
|
|
261
|
+
},
|
|
262
|
+
turn: turn.turn, steps: turn.steps.size, requests: requests.length, attempts: turn.attempts, retries: turn.retries,
|
|
263
|
+
tools: turn.tools, toolErrors: turn.toolErrors, failed: turn.failed, completed: turn.completed,
|
|
264
|
+
route: turn.routes.size === 1 ? [...turn.routes][0] : null,
|
|
265
|
+
load: {
|
|
266
|
+
U: completeUsage ? total.value : null,
|
|
267
|
+
A: turn.attempts === 0 && requests.length > 0 && knownSubsequent.length === subsequent.length ? repeatedInput : null,
|
|
268
|
+
T: turn.surfaceKnown && turn.attempts === 0 && requests.length ? turn.toolLoad : null,
|
|
269
|
+
K: turn.attempts === 0 && requests.length > 0 && cached.length === requests.length ? uncachedInput : null,
|
|
270
|
+
E: turn.attempts > 0
|
|
271
|
+
? (allAttemptsAttributed && reportedAttempts.length === turn.attempts ? attemptTokens : null)
|
|
272
|
+
: (!turn.failed && !turn.toolErrors && turn.completed ? 0 : null),
|
|
273
|
+
},
|
|
274
|
+
observedLoad: {
|
|
275
|
+
U: total.value,
|
|
276
|
+
A: knownSubsequent.length ? repeatedInput : null,
|
|
277
|
+
K: cached.length ? uncachedInput : null,
|
|
278
|
+
E: allAttemptsAttributed && reportedAttempts.length ? attemptTokens : null,
|
|
279
|
+
},
|
|
280
|
+
total, completeUsage, usageBreakdownMismatch, input: observedSum(requests, 'input'), output: observedSum(requests, 'output'),
|
|
281
|
+
cacheWrite: observedSum(requests, 'cacheWrite'), reasoning: observedSum(requests, 'reasoning'),
|
|
282
|
+
cache: cacheInput ? { ratio: cacheRead / cacheInput, reported: cached.length } : null,
|
|
283
|
+
amplification: completeUsage && turn.attempts === 0 && requests.every(row => row.comparable) && openingInput > 0 ? total.value / openingInput : null,
|
|
284
|
+
}
|
|
285
|
+
}).sort((a, b) => a.turn - b.turn)
|
|
286
|
+
return { rows, requestEnvelope, toolSnapshot, compaction, compactionEvents, toolResults: [...toolResults.values()].map(tool => ({
|
|
287
|
+
...tool, retained: surfaceKnown ? activeTools.has(tool.seq) : null, carried: surfaceKnown ? tool.carried : null,
|
|
288
|
+
})), latest: rows.at(-1) ?? null, retentionComplete: surfaceKnown,
|
|
289
|
+
burden: [...burden.values()].sort((a, b) => b.tokensAcrossRequests - a.tokensAcrossRequests),
|
|
290
|
+
...(saveCheckpoint ? { checkpoint: {
|
|
291
|
+
turns: [...turns.values()].map(turn => ({ ...turn, steps: [...turn.steps], routes: [...turn.routes],
|
|
292
|
+
attemptsByStep: [...turn.attemptsByStep] })),
|
|
293
|
+
callNames: [...callNames], surface, activeTools: [...activeTools], surfacePrices: [...surfacePrices], surfaceTokens, dispatch,
|
|
294
|
+
burden: [...burden], route, surfaceKnown, envelope, requestEnvelope, toolSnapshot, compaction, compactionEvents, toolResults: [...toolResults],
|
|
295
|
+
} } : {}) }
|
|
296
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
const finite = Number.isFinite
|
|
2
|
+
const total = values => values.length && values.every(finite) ? values.reduce((a, b) => a + b, 0) : null
|
|
3
|
+
const ratio = (a, b) => finite(a) && finite(b) && b > 0 ? a / b : null
|
|
4
|
+
|
|
5
|
+
export function pressureDataDictionary(rounds, samples, request, details = {}, compactionPair, historical = false) {
|
|
6
|
+
const last = rounds.at(-1)
|
|
7
|
+
const m = last?.metrics
|
|
8
|
+
const row = (label, source, raw_value, value, unit, scope, formula, confidence = '精确统计') => ({
|
|
9
|
+
label, source, raw_value, value, unit, scope, formula,
|
|
10
|
+
availability: value == null ? '暂不可获取' : formula === '原值' ? '直接获取' : '可推导',
|
|
11
|
+
confidence: value == null ? '未知' : confidence,
|
|
12
|
+
})
|
|
13
|
+
const missing = (label, source, unit, scope, formula) => row(label, source, null, null, unit, scope, formula)
|
|
14
|
+
const meta = rounds.map(r => r.metrics)
|
|
15
|
+
const requests = total(rounds.map(r => r.requests))
|
|
16
|
+
const attempts = total(rounds.map(r => r.attempts))
|
|
17
|
+
const input = total(rounds.map(r => r.input.reported === r.requests ? r.input.value : null))
|
|
18
|
+
const output = total(rounds.map(r => r.output.reported === r.requests ? r.output.value : null))
|
|
19
|
+
const inOut = total([input, output])
|
|
20
|
+
const completedTotal = rounds.every(r => r.completeUsage) ? total(rounds.map(r => r.total.value)) : null
|
|
21
|
+
const lastInput = request?.input ?? null
|
|
22
|
+
const window = request?.contextWindow ?? null
|
|
23
|
+
const usageScope = '已完成轮 · 成功请求'
|
|
24
|
+
const requestSamples = historical ? new Map(rounds.filter(row => row.completed && finite(row.metrics?.lastInput)
|
|
25
|
+
&& row.metrics.window > 0).map(row => [row.turn, { tokens: row.metrics.lastInput, contextWindow: row.metrics.window }])) : null
|
|
26
|
+
const growth = n => {
|
|
27
|
+
const end = last?.turn
|
|
28
|
+
const byTurn = new Map(samples.map(sample => [sample.turn, sample]))
|
|
29
|
+
const changes = []
|
|
30
|
+
let requestPairs = 0
|
|
31
|
+
if (Number.isSafeInteger(end)) for (let turn = Math.max(2, end - n + 1); turn <= end; turn++) {
|
|
32
|
+
let a = byTurn.get(turn - 1), b = byTurn.get(turn)
|
|
33
|
+
if (historical && (!(a?.contextWindow > 0) || !(b?.contextWindow > 0))) {
|
|
34
|
+
a = requestSamples.get(turn - 1)
|
|
35
|
+
b = requestSamples.get(turn)
|
|
36
|
+
if (a && b) requestPairs++
|
|
37
|
+
}
|
|
38
|
+
if (!a || !b || !(a.contextWindow > 0) || !(b.contextWindow > 0)) continue
|
|
39
|
+
if (!historical && (a.route !== b.route || a.contextWindow !== b.contextWindow)) continue
|
|
40
|
+
changes.push(a.contextWindow === b.contextWindow ? (b.tokens - a.tokens) / b.contextWindow
|
|
41
|
+
: b.tokens / b.contextWindow - a.tokens / a.contextWindow)
|
|
42
|
+
}
|
|
43
|
+
return { changes: changes.length, requestPairs,
|
|
44
|
+
compacted: Number.isSafeInteger(end) && samples.some(sample =>
|
|
45
|
+
sample.compacted && sample.turn > end - n && sample.turn <= end),
|
|
46
|
+
net: changes.length ? changes.reduce((a, b) => a + b, 0) / changes.length : null,
|
|
47
|
+
positive: changes.length ? changes.reduce((a, b) => a + Math.max(0, b), 0) : null }
|
|
48
|
+
}
|
|
49
|
+
const lastSample = samples.findLast(sample => sample.turn === last?.turn)
|
|
50
|
+
const previousSample = samples.findLast(sample => sample.turn === last?.turn - 1)
|
|
51
|
+
const lastDelta = lastSample && previousSample && lastSample.route === previousSample.route
|
|
52
|
+
&& lastSample.contextWindow === previousSample.contextWindow && lastSample.contextWindow > 0
|
|
53
|
+
? (lastSample.tokens - previousSample.tokens) / lastSample.contextWindow : null
|
|
54
|
+
const growthWindows = [5, 10, 20].map(n => [n, growth(n)])
|
|
55
|
+
const cache = (items, scope) => {
|
|
56
|
+
const metadata = items.map(item => item.metrics)
|
|
57
|
+
const eligible = total(items.map(item => item.requests))
|
|
58
|
+
const reported = items.length ? metadata.reduce((sum, item) => sum + (item?.cacheReports ?? 0), 0) : null
|
|
59
|
+
const covered = metadata.filter(item => item?.cacheReports > 0)
|
|
60
|
+
const i = total(covered.map(item => item.cacheInput))
|
|
61
|
+
const hit = total(covered.map(item => item.cachedInput))
|
|
62
|
+
const missed = finite(i) && finite(hit) ? i - hit : null
|
|
63
|
+
return [row('缓存统计覆盖率', '完成轮成功请求与有效缓存报告', { reported, eligible },
|
|
64
|
+
ratio(reported, eligible), '%', scope, '有有效缓存报告的请求数 ÷ 成功请求数'),
|
|
65
|
+
row('未命中比例', 'DSH 请求 usage.cacheReadTokens', { input: i, hit, reports: total(covered.map(item => item.cacheReports)) },
|
|
66
|
+
ratio(missed, i), '%', scope, '1 − 缓存命中 Token ÷ 有缓存报告的输入 Token')]
|
|
67
|
+
}
|
|
68
|
+
const retained = Number.isSafeInteger(request?.seq) && request.seq === details.toolSnapshot?.seq ? details.toolSnapshot : null
|
|
69
|
+
const retainedTokens = retained?.tokens ?? null
|
|
70
|
+
const retainedShare = requestToolShare(retained)
|
|
71
|
+
const failed = total(rounds.map(r => r.attempts))
|
|
72
|
+
const toolErrors = total(rounds.map(r => r.toolErrors))
|
|
73
|
+
const toolCalls = total(rounds.map(r => r.tools))
|
|
74
|
+
const retry = rounds.length && rounds.every(r => r.attempts === 0 || finite(r.load.E))
|
|
75
|
+
? total(rounds.map(r => r.attempts === 0 ? 0 : r.load.E)) : null
|
|
76
|
+
const matchedRetry = total(meta.map(item => item?.retryTokens))
|
|
77
|
+
return [
|
|
78
|
+
{ id: 'C', title: '上下文容量', rows: [
|
|
79
|
+
row('请求输入', 'DSH 最新有用量的模型请求', lastInput, lastInput, 'Token', '最新有用量的请求', '原值'),
|
|
80
|
+
row('有效窗口', 'DSH request/context.contextWindow', window, window, 'Token', '同一次请求', '原值'),
|
|
81
|
+
row('窗口占用率', '同一请求的输入用量与模型窗口', { input: lastInput, window }, ratio(lastInput, window), '%', '最新有用量的请求', '请求输入 Token ÷ 窗口 Token', '估算'),
|
|
82
|
+
row('剩余容量', '同一请求的输入用量与模型窗口', { input: lastInput, window }, finite(lastInput) && window > 0 ? window - lastInput : null, 'Token', '同一次请求', '窗口 − 输入 Token', '估算'),
|
|
83
|
+
...[['系统消息占用', 'systemChars', 'systemTokens'], ['工具定义占用', 'toolChars', 'toolTokens']].map(([label, chars, tokens]) =>
|
|
84
|
+
row(label, 'DSH request/header(宿主 token-meter 估算法)', { chars: details.requestEnvelope?.[chars], headerRecorded: details.requestEnvelope != null },
|
|
85
|
+
details.requestEnvelope?.[tokens], 'Token', '最新有用量的请求', '已记录请求头中该字段为空或缺省时为 0;未采到请求头为未知;非空按字符数 ÷ 4 向上取整 + 4', '估算')),
|
|
86
|
+
...[['压缩前占用', 'before'], ['压缩后占用', 'after']].map(([label, key]) =>
|
|
87
|
+
row(label, 'DSH tokenMeter · 同一压缩 ID 的开始 / 结束事件', compactionPair?.[key],
|
|
88
|
+
compactionPair?.[key], 'Token', '最近一次有效配对', '原值', '估算')),
|
|
89
|
+
row('压缩占用减少量', 'DSH tokenMeter 压缩边界采样', compactionPair,
|
|
90
|
+
compactionPair ? compactionPair.before - compactionPair.after : null, 'Token',
|
|
91
|
+
'最近一次有效配对', '压缩前占用 − 压缩后占用', '估算'),
|
|
92
|
+
] },
|
|
93
|
+
{ id: 'G', title: '增长负担', rows: [
|
|
94
|
+
row('逐轮净变化', '相邻轮末 tokenMeter 采样', { previous: previousSample?.tokens, current: lastSample?.tokens,
|
|
95
|
+
window: lastSample?.contextWindow, compacted: lastSample?.compacted }, lastDelta, '百分点',
|
|
96
|
+
'最新完成轮', '本轮结束占用率 − 上一轮结束占用率'),
|
|
97
|
+
row('当前轮请求数', 'assistant/message 与 assistant/attempt', { requests: last?.requests, attempts: last?.attempts },
|
|
98
|
+
total([last?.requests, last?.attempts]), '次', '最新完成轮', '成功请求数 + 失败尝试数'),
|
|
99
|
+
...growthWindows.flatMap(([n, g]) => [
|
|
100
|
+
row('平均净增长', historical && g.requestPairs
|
|
101
|
+
? (g.requestPairs === g.changes ? '相邻轮请求实报输入与当轮窗口' : '轮末 tokenMeter 与相邻轮请求实报占用率')
|
|
102
|
+
: 'Fish turn/end 的 tokenMeter 采样', { comparablePairs: g.changes, compacted: g.compacted,
|
|
103
|
+
...(historical ? { requestPairs: g.requestPairs } : {}) }, g.net, '百分点', '最近 ' + n + ' 轮', '相邻可比轮占用率差之和 ÷ 可比差值数 × 100'),
|
|
104
|
+
row('正向增长', 'Fish turn/end 的 tokenMeter 采样', { comparablePairs: g.changes }, g.positive, '百分点', '最近 ' + n + ' 轮', 'Σ max(0, 本轮占用率 − 上轮占用率) × 100'),
|
|
105
|
+
]),
|
|
106
|
+
row('短期减中期平均增长', '相同轮末采样', growthWindows.map(([, g]) => g.net),
|
|
107
|
+
growthWindows[0][1].changes >= 5 && growthWindows[1][1].changes >= 10
|
|
108
|
+
? growthWindows[0][1].net - growthWindows[1][1].net : null, '百分点', '最近 5 / 10 轮', '5 轮平均净增长 − 10 轮平均净增长'),
|
|
109
|
+
...[['压缩开始', 'started'], ['压缩成功结束', 'succeeded'], ['压缩错误结束', 'failed'],
|
|
110
|
+
['压缩摘要', 'summaries'], ['工具结果裁剪', 'prunes']].map(([label, key]) =>
|
|
111
|
+
row(label, 'DSH compaction/start, end, summary, prune', details.compactionEvents?.[key],
|
|
112
|
+
details.compactionEvents?.[key], '次', '已扫描会话事件', '计数:对应事件')),
|
|
113
|
+
row('记录到的压缩轮', 'Fish 轮末采样 compaction/end', samples.length ? samples.filter(s => s.compacted).length : null,
|
|
114
|
+
samples.length ? samples.filter(s => s.compacted).length : null, '轮', '已采样轮', '有压缩标记的轮数'),
|
|
115
|
+
] },
|
|
116
|
+
{ id: 'U', title: 'Token 总消耗', rows: [
|
|
117
|
+
row('累计请求输入(含缓存)', 'DSH 模型请求 usage.inputTokens', input, input, 'Token', usageScope, 'Σ 输入 Token'),
|
|
118
|
+
row('累计请求输出', 'DSH 模型请求 usage.outputTokens', output, output, 'Token', usageScope, 'Σ 输出 Token'),
|
|
119
|
+
row('成功请求总用量', 'DSH 模型请求 usage', { input, output }, inOut, 'Token', usageScope, '累计输入 + 累计输出'),
|
|
120
|
+
row('常规模型请求总用量(含失败尝试)', 'assistant/message 与 assistant/attempt 的 usage', completedTotal,
|
|
121
|
+
completedTotal, 'Token', '已完成轮 · 不含独立压缩调用', 'Σ 每轮成功请求及失败尝试 Token;要求用量齐全'),
|
|
122
|
+
row('平均每轮消耗', 'DSH 模型请求 usage', { total: inOut, turns: rounds.length }, ratio(inOut, rounds.length), 'Token / 轮', usageScope, '累计输入与输出 ÷ 轮数'),
|
|
123
|
+
row('累计请求数(含尝试)', 'assistant/message 与 assistant/attempt', { requests, attempts }, total([requests, attempts]), '次', '已完成轮', '成功请求数 + 失败尝试数'),
|
|
124
|
+
row('压缩请求消耗', 'DSH compaction/summary.usage',
|
|
125
|
+
{ reported: details.compaction?.reported, summaries: details.compaction?.summaries },
|
|
126
|
+
details.compaction?.reported ? details.compaction.tokens : null, 'Token', '会话 · 已报告的压缩调用', 'Σ 已报告的压缩输入与输出 Token'),
|
|
127
|
+
row('最近一次压缩替换的原文规模', 'DSH compaction/summary.shadowedTokenCount', details.compaction?.shadowed,
|
|
128
|
+
details.compaction?.shadowed, 'Token', '最近一次压缩摘要', '原值', '估算'),
|
|
129
|
+
] },
|
|
130
|
+
{ id: 'A', title: '请求放大', rows: [
|
|
131
|
+
row('模型请求数(含尝试)', 'assistant/message 与 assistant/attempt', { requests: last?.requests, attempts: last?.attempts }, total([last?.requests, last?.attempts]), '次', '最新完成轮', '成功请求数 + 失败尝试数'),
|
|
132
|
+
row('首个成功请求输入', 'DSH 模型请求 usage.inputTokens', m?.firstInput, m?.firstInput, 'Token', '最新完成轮', '原值'),
|
|
133
|
+
row('追加请求输入', 'DSH 模型请求 usage.inputTokens', last?.load.A, last?.load.A, 'Token', '最新完成轮', 'Σ 第 2 次起的请求输入 Token'),
|
|
134
|
+
row('输入放大率', '本轮首个请求及后续请求输入', { first: m?.firstInput, extra: last?.load.A }, ratio(last?.load.A, m?.firstInput), '%', '最新完成轮', '追加请求输入 ÷ 首次输入'),
|
|
135
|
+
missing('工具后继续推理次数', '未建立请求与工具结果的可靠因果关联', '次', '最新完成轮', '按明确关联的请求计数'),
|
|
136
|
+
] },
|
|
137
|
+
{ id: 'T', title: '工具结果残留', rows: [
|
|
138
|
+
row('工具结果残留', 'DSH 请求边界的可见上下文', retained?.dispatchSeq, retainedTokens, 'Token', '最新有用量的请求', '同一套估算器统计去重后的可见工具结果', '估算'),
|
|
139
|
+
row('残留占比', '同一请求上下文、同一估算口径', { retainedTokens, estimatedInput: retained?.inputTokens,
|
|
140
|
+
status: retained?.status ?? 'unavailable', reason: retained?.reason ?? null },
|
|
141
|
+
retainedShare, '%', '同一次请求', '估算工具结果 Token ÷ 估算请求输入 Token', '估算'),
|
|
142
|
+
row('累计携带', '请求时的工具 surface', rounds.filter(r => finite(r.load.T)).length,
|
|
143
|
+
total(rounds.map(r => r.load.T)), 'Token·次', '已完成轮', 'Σ 每次成功请求中全部可见工具结果 Token,含本轮生成的结果;缺覆盖的轮次保留未知', '估算'),
|
|
144
|
+
row('跨轮重复携带', '请求时的工具 surface 与结果产生轮', meta.map(item => item?.carry ?? null).filter(finite).length,
|
|
145
|
+
total(meta.map(item => item?.carry)), 'Token·次', '已完成轮', 'Σ 每次成功请求中仅早于请求轮生成的可见工具结果 Token;属于累计携带的子集', '估算'),
|
|
146
|
+
row('当前最早残留年龄', '工具结果产生轮、请求轮', null, retained?.ages?.at(-1)?.[0] ?? null, '轮', '同一次请求', '当前轮 − 最早残留结果所在轮', '估算'),
|
|
147
|
+
...(details.toolResults ?? []).slice(-30).reverse().flatMap(tool => [
|
|
148
|
+
row(tool.name + ' · 结果大小', 'DSH tool/result 与 surfaceOp', { seq: tool.seq, retained: tool.retained },
|
|
149
|
+
tool.tokens, 'Token', '第 ' + tool.turn + ' 轮', 'DSH 消息及内容块估算', '估算'),
|
|
150
|
+
row(tool.name + ' · 后续轮携带', 'DSH 请求与工具结果的 surface 历史', { seq: tool.seq, retained: tool.retained },
|
|
151
|
+
tool.carried, '次', '第 ' + tool.turn + ' 轮的结果', '计数:该结果在后续轮成功请求中出现'),
|
|
152
|
+
]),
|
|
153
|
+
] },
|
|
154
|
+
{ id: 'K', title: '缓存复用负担', rows: [
|
|
155
|
+
row('未缓存输入', 'DSH 请求 usage', meta.filter(item => item?.cacheReports > 0).length,
|
|
156
|
+
total(meta.filter(item => item?.cacheReports > 0).map(item => item.cacheInput - item.cachedInput)),
|
|
157
|
+
'Token', '已完成轮 · 有缓存报告的请求', 'Σ(输入 − 缓存命中)'),
|
|
158
|
+
...cache(rounds, '已完成轮'), ...cache(rounds.slice(-5), '最近 5 个完成轮'), ...cache(rounds.slice(-10), '最近 10 个完成轮'),
|
|
159
|
+
...[['有缓存记录的输入', 'cacheInput'], ['缓存命中输入', 'cachedInput']].map(([label, key]) => {
|
|
160
|
+
const value = total(meta.filter(item => item?.cacheReports > 0).map(item => item[key]))
|
|
161
|
+
return row(label, 'DSH 模型请求 usage', value, value, 'Token', '已完成轮 · 有缓存报告的请求', 'Σ 对应输入')
|
|
162
|
+
}),
|
|
163
|
+
] },
|
|
164
|
+
{ id: 'E', title: '失败与恢复', rows: [
|
|
165
|
+
row('模型失败尝试', 'DSH assistant/attempt', failed, failed, '次', '已完成轮', 'Σ 失败尝试事件'),
|
|
166
|
+
row('模型失败率', 'DSH assistant/attempt 与 assistant/message', { failed, requests }, ratio(failed, total([failed, requests])), '%', '已完成轮', '失败尝试数 ÷ 总请求数'),
|
|
167
|
+
row('显式工具失败', 'DSH tool/result 错误标记', toolErrors, toolErrors, '次', '已完成轮', 'Σ 标记失败的工具结果'),
|
|
168
|
+
row('工具失败率', 'DSH tool/call 与 tool/result', { toolErrors, toolCalls }, ratio(toolErrors, toolCalls), '%', '已完成轮', '工具失败数 ÷ 工具调用数'),
|
|
169
|
+
row('已归因尝试耗用', 'assistant/attempt 的用量和重试关联', retry, retry, 'Token', '已完成轮', 'Σ 明确归因的失败尝试 Token'),
|
|
170
|
+
row('重试负担占比', '失败尝试与请求用量', { retry: matchedRetry, total: completedTotal }, ratio(matchedRetry, completedTotal), '%', '已完成轮', '有同轮同步骤后续成功的失败尝试 Token ÷ 常规模型请求总用量'),
|
|
171
|
+
row('有同轮同步骤后续成功的失败尝试', '同轮同 step 的 assistant/attempt → assistant/message',
|
|
172
|
+
total(rounds.map(r => r.retries)), total(rounds.map(r => r.retries)), '次', '已完成轮', '计数:失败尝试之后有同一步成功请求'),
|
|
173
|
+
row('匹配到后续成功的失败尝试用量', 'assistant/attempt.usage + 同轮同 step 关联',
|
|
174
|
+
null, total(meta.map(item => item?.retryTokens)), 'Token', '已完成轮', 'Σ 匹配到后续成功的失败尝试自身 Token'),
|
|
175
|
+
missing('恢复请求、错误分类与语义失败', '缺少可靠的恢复归因和标准分类', 'Token / 次', '会话', '按明确错误类型及恢复关联统计'),
|
|
176
|
+
] },
|
|
177
|
+
]
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function requestBurdenInputs(rounds, window) {
|
|
181
|
+
const completed = rounds.filter(round => round.completed === true)
|
|
182
|
+
function summarize(items) {
|
|
183
|
+
const input = total(items.map(round => round.requests === 0 ? 0
|
|
184
|
+
: round.input.reported === round.requests ? round.input.value : null))
|
|
185
|
+
const output = total(items.map(round => round.requests === 0 ? 0
|
|
186
|
+
: round.output.reported === round.requests ? round.output.value : null))
|
|
187
|
+
const coveredInput = items.reduce((sum, round) => sum + (round.metrics?.cacheInput ?? 0), 0)
|
|
188
|
+
const cached = items.reduce((sum, round) => sum + (round.metrics?.cachedInput ?? 0), 0)
|
|
189
|
+
return { rounds: items.length, input, output, cached, knownMiss: coveredInput - cached,
|
|
190
|
+
unknownInput: input != null && input >= coveredInput ? input - coveredInput : null,
|
|
191
|
+
requests: items.reduce((sum, round) => sum + round.requests, 0),
|
|
192
|
+
cacheReports: items.reduce((sum, round) => sum + (round.metrics?.cacheReports ?? 0), 0) }
|
|
193
|
+
}
|
|
194
|
+
return { window, all: summarize(completed), recent: summarize(completed.slice(-10)) }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function requestToolShare(snapshot) {
|
|
198
|
+
if (snapshot?.status !== 'estimated' || snapshot.tokens > snapshot.inputTokens) return null
|
|
199
|
+
return ratio(snapshot.tokens, snapshot.inputTokens)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function structurePressureInputs(details) {
|
|
203
|
+
const rounds = details.rows ?? []
|
|
204
|
+
const request = details.lastRequest
|
|
205
|
+
const snapshot = details.toolSnapshot?.seq === request?.seq ? details.toolSnapshot : null
|
|
206
|
+
const pairedInput = rounds.reduce((sum, row) => sum + (row.metrics?.pairedToolInput ?? 0), 0)
|
|
207
|
+
const pairedCarry = rounds.reduce((sum, row) => sum + (row.metrics?.pairedCarry ?? 0), 0)
|
|
208
|
+
const pairedRequests = rounds.reduce((sum, row) => sum + (row.metrics?.pairedToolRequests ?? 0), 0)
|
|
209
|
+
const requestCount = rounds.reduce((sum, row) => sum + row.requests, 0)
|
|
210
|
+
const invalidRequests = rounds.reduce((sum, row) => sum + (row.metrics?.invalidToolRequests ?? 0), 0)
|
|
211
|
+
const invalid = snapshot?.status === 'invalid' || (finite(snapshot?.tokens) && finite(snapshot?.inputTokens)
|
|
212
|
+
&& snapshot.tokens > snapshot.inputTokens) || pairedCarry > pairedInput || invalidRequests > 0
|
|
213
|
+
const currentShare = requestToolShare(snapshot)
|
|
214
|
+
const retryTokens = total(rounds.map(row => row.metrics?.retryTokens))
|
|
215
|
+
const regularTokens = rounds.every(row => row.completeUsage) ? total(rounds.map(row => row.total.value)) : null
|
|
216
|
+
let cumulative = 0
|
|
217
|
+
const median = snapshot?.tokens > 0 ? snapshot.ages.find(([, tokens]) => {
|
|
218
|
+
cumulative += tokens
|
|
219
|
+
return cumulative >= snapshot.tokens / 2
|
|
220
|
+
})?.[0] ?? null : null
|
|
221
|
+
return {
|
|
222
|
+
currentShare: invalid ? null : currentShare,
|
|
223
|
+
repeatedShare: invalid ? null : ratio(pairedCarry, pairedInput),
|
|
224
|
+
retryShare: ratio(retryTokens, regularTokens),
|
|
225
|
+
retainedTokens: snapshot?.tokens ?? null, currentInput: snapshot?.inputTokens ?? null, reportedInput: request?.input ?? null,
|
|
226
|
+
measurementStatus: invalid ? 'invalid' : snapshot?.status ?? 'unavailable', dispatchSeq: snapshot?.dispatchSeq ?? null,
|
|
227
|
+
measurementReason: snapshot?.reason ?? null,
|
|
228
|
+
matchedDispatch: snapshot?.matchedDispatch ?? false, invalidRequests,
|
|
229
|
+
pairedInput, pairedCarry, pairedRequests, requestCount, retryTokens, regularTokens,
|
|
230
|
+
modelFailureRate: ratio(total(rounds.map(row => row.attempts)), total(rounds.map(row => row.attempts + row.requests))),
|
|
231
|
+
toolFailureRate: ratio(total(rounds.map(row => row.toolErrors)), total(rounds.map(row => row.tools))),
|
|
232
|
+
ages: {
|
|
233
|
+
mean: snapshot?.tokens > 0 ? snapshot.ages.reduce((sum, [age, tokens]) => sum + age * tokens, 0) / snapshot.tokens : null,
|
|
234
|
+
median,
|
|
235
|
+
older: [10, 20, 40].map(rounds => ({ rounds, share: snapshot?.tokens > 0
|
|
236
|
+
? snapshot.ages.reduce((sum, [age, tokens]) => sum + (age > rounds ? tokens : 0), 0) / snapshot.tokens : null })),
|
|
237
|
+
},
|
|
238
|
+
}
|
|
239
|
+
}
|