dsh-last-response-stats 0.0.0-stage → 1.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Borivoje Latinovic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # Last Response Stats
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small DeepSeek Harness bundle that shows the average output speed,
4
+ prompt-cache hit, and time to first token of the most recent Chat response —
5
+ for example `42 tok/s · 87% cache hit · 0.4s TTFT` — directly under that
6
+ response in the conversation flow.
7
+
8
+ ## What it computes
9
+
10
+ ```text
11
+ tok/s = provider output tokens / (message settlement - first token)
12
+ cache hit = cache-read tokens / (uncached input + cache-read + cache-write)
13
+ TTFT = first token - step start
14
+ total = message settlement - step start
15
+ ```
16
+
17
+ The first-token timestamp comes from the durable `assistant/message` stream
18
+ and the step start from its preceding `step/start`, so the readings survive a
19
+ page reload. Only content-bearing assistant messages count as a response;
20
+ reasoning-only and tool-call-only messages are skipped. Each part is hidden
21
+ when its inputs are missing: no output-token usage or first token means no
22
+ speed, and no cache-read/cache-write report means no cache hit. Hovering the
23
+ reading shows the output and prompt token counts plus the total response
24
+ time.
25
+
26
+ ## Where it appears
27
+
28
+ `conversation.chat.turnTail` — the small footer area under a completed Turn,
29
+ before the message action row. The Host projection carries the Turn of the
30
+ latest response, so only that Turn renders the reading.
31
+
32
+ ## Install
33
+
34
+ The Harness plugin manager installs through `pnpm`; make sure `pnpm` is on the
35
+ PATH of the process running `dsh web`. If the profile already has a dependency
36
+ tree, match the pnpm major to its store (pnpm reports a store mismatch when the
37
+ major does not match).
38
+
39
+ ### Published package or repository
40
+
41
+ In the Harness Web UI, open **Settings → Plugins → Add plugin** and enter either:
42
+
43
+ - the npm package name `dsh-last-response-stats`, once published; or
44
+ - the public repository URL, for example
45
+ `https://github.com/latinovicb/dsh-last-response-stats`.
46
+
47
+ Install, then reload the page.
48
+
49
+ ### Local checkout
50
+
51
+ 1. Open **Settings → Plugins**.
52
+ 2. Choose **Add plugin** and enter this directory's absolute path.
53
+ 3. Install, then reload the page.
54
+
55
+ You can also ask a Harness agent to install the bundle with the same path
56
+ through the plugin-manager bundle install action.
57
+
58
+ After installation, the bundle should appear under **Installed**. If it is
59
+ disabled, enable it and reload. A running `dsh web` process may need a restart
60
+ if the Host plugin does not activate live.
61
+
62
+ The package declares DSH compatibility `>=0.2.1-rc.2 <0.3.0`.
63
+
64
+ ## Files
65
+
66
+ - `index.js` — Host half: the `lastResponseStats` session projection.
67
+ - `client.js` — Web UI half: the turn-tail pill, locale dictionaries, styles.
68
+ - `cordis.patch.yml` — inserts the bundle row.
69
+ - `locale/en.json`, `locale/zh.json` — plugin title and description.
70
+ - `icon.svg` — plugin inventory artwork.
package/client.js ADDED
@@ -0,0 +1,243 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-last-response-stats',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const NS = 'last-response-stats';
7
+
8
+ const EN = {
9
+ label: '{value} tok/s',
10
+ title: 'Average generation speed for the last response',
11
+ detail: '{tokens} output tokens over {seconds} s',
12
+ cacheLabel: '{percent}% cache hit',
13
+ cacheTitle: 'Prompt cache hit for the last response',
14
+ cacheDetail: '{cached} of {prompt} prompt tokens served from cache',
15
+ ttftLabel: 'TTFT {value}s',
16
+ ttftTitle: 'Time to first token',
17
+ ttftDetail: '{value}s from request start to first token',
18
+ totalTitle: 'Total response time',
19
+ totalDetail: '{value}s from request start to completion',
20
+ };
21
+ const ZH = {
22
+ label: '{value} tok/s',
23
+ title: '最近一次回复的平均生成速度',
24
+ detail: '最近一次回复:{tokens} 个输出 token,用时 {seconds} 秒',
25
+ cacheLabel: '{percent}% 缓存命中',
26
+ cacheTitle: '最近一次回复的提示词缓存命中',
27
+ cacheDetail: '提示词缓存命中 {cached}/{prompt} 个 token',
28
+ ttftLabel: 'TTFT {value}s',
29
+ ttftTitle: '首 token 延迟',
30
+ ttftDetail: '从请求开始到首 token:{value} 秒',
31
+ totalTitle: '总响应时间',
32
+ totalDetail: '从请求开始到完成:{value} 秒',
33
+ };
34
+
35
+ const CSS = [
36
+ '.dshLastResponseSpeed {',
37
+ ' display: inline-flex;',
38
+ ' align-items: center;',
39
+ ' gap: 6px;',
40
+ ' min-width: 0;',
41
+ ' max-width: 100%;',
42
+ ' color: var(--dsw-alias-label-tertiary);',
43
+ ' font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px);',
44
+ ' line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px));',
45
+ ' font-variant-numeric: tabular-nums;',
46
+ ' white-space: nowrap;',
47
+ ' user-select: none;',
48
+ '}',
49
+ '.dshLastResponseSpeedIcon { flex: none; width: 14px; height: 14px; }',
50
+ '.dshLastResponseSpeedLabel { overflow: hidden; text-overflow: ellipsis; }',
51
+ ].join('\n');
52
+
53
+ function formatSpeed(tokensPerSecond) {
54
+ const clamped = Math.max(0, tokensPerSecond);
55
+ return clamped >= 10
56
+ ? String(Math.round(clamped))
57
+ : String(Math.round(clamped * 10) / 10);
58
+ }
59
+
60
+ function formatCount(value) {
61
+ try {
62
+ return Math.round(value).toLocaleString();
63
+ } catch {
64
+ return String(Math.round(value));
65
+ }
66
+ }
67
+
68
+ function formatSeconds(milliseconds) {
69
+ return (milliseconds / 1000).toFixed(1);
70
+ }
71
+
72
+ function formatCacheHitPercent(cacheReadTokens, promptTokens) {
73
+ if (promptTokens <= 0 || cacheReadTokens < 0 || cacheReadTokens > promptTokens) {
74
+ return null;
75
+ }
76
+ if (cacheReadTokens === promptTokens) return '100';
77
+ const percent = (cacheReadTokens / promptTokens) * 100;
78
+ if (percent >= 99) return String(Math.floor(percent * 10) / 10);
79
+ if (percent >= 10) return String(Math.round(percent));
80
+ return String(Math.round(percent * 10) / 10);
81
+ }
82
+
83
+ function cacheHitReading(stats) {
84
+ const inputTokens = stats.inputTokens;
85
+ const cacheReadTokens = stats.cacheReadTokens;
86
+ if (typeof inputTokens !== 'number' || typeof cacheReadTokens !== 'number') {
87
+ return null;
88
+ }
89
+ const cacheWriteTokens = typeof stats.cacheWriteTokens === 'number' ? stats.cacheWriteTokens : 0;
90
+ const promptTokens = inputTokens + cacheReadTokens + cacheWriteTokens;
91
+ const percent = formatCacheHitPercent(cacheReadTokens, promptTokens);
92
+ if (percent === null) return null;
93
+ return { percent, cachedTokens: cacheReadTokens, promptTokens };
94
+ }
95
+
96
+ function GaugeIcon() {
97
+ return h(
98
+ 'svg',
99
+ {
100
+ className: 'dshLastResponseSpeedIcon',
101
+ viewBox: '0 0 24 24',
102
+ width: 14,
103
+ height: 14,
104
+ 'aria-hidden': true,
105
+ focusable: 'false',
106
+ fill: 'none',
107
+ stroke: 'currentColor',
108
+ strokeWidth: 1.7,
109
+ strokeLinecap: 'round',
110
+ strokeLinejoin: 'round',
111
+ },
112
+ h('path', { d: 'M4.5 17.5a7.5 7.5 0 0 1 15 0' }),
113
+ h('path', { d: 'M12 17.5l4-6' }),
114
+ h('circle', { cx: 12, cy: 17.5, r: 1.2, fill: 'currentColor', stroke: 'none' }),
115
+ );
116
+ }
117
+
118
+ /**
119
+ * Quiet reading under one completed Turn. The projection carries the
120
+ * latest response's Turn, so only that Turn's tail renders a value.
121
+ */
122
+ function LastResponseSpeed({ turn, useProjection, t }) {
123
+ const stats = useProjection('lastResponseStats');
124
+ const turnNumber =
125
+ typeof turn === 'number'
126
+ ? turn
127
+ : turn !== null && typeof turn === 'object'
128
+ ? turn.turn
129
+ : undefined;
130
+ if (stats === undefined || turnNumber === undefined || stats.turn !== turnNumber) {
131
+ return null;
132
+ }
133
+
134
+ const outputTokens = stats.outputTokens;
135
+ const decodeMs = stats.decodeMs;
136
+ const hasSpeed =
137
+ typeof outputTokens === 'number' &&
138
+ outputTokens > 0 &&
139
+ typeof decodeMs === 'number' &&
140
+ decodeMs > 0;
141
+ const tokensPerSecond = hasSpeed ? outputTokens / (decodeMs / 1000) : null;
142
+ const hasFiniteSpeed =
143
+ tokensPerSecond !== null && Number.isFinite(tokensPerSecond) && tokensPerSecond > 0;
144
+ const ttftMs = stats.ttftMs;
145
+ const totalMs = stats.totalMs;
146
+ const hasTtft = typeof ttftMs === 'number' && ttftMs >= 0;
147
+ const hasTotal = typeof totalMs === 'number' && totalMs >= 0;
148
+ const cache = cacheHitReading(stats);
149
+ if (!hasFiniteSpeed && cache === null && !hasTtft) return null;
150
+
151
+ const speedLabel = hasFiniteSpeed
152
+ ? t('label', { value: formatSpeed(tokensPerSecond) })
153
+ : null;
154
+ const cacheLabel = cache !== null ? t('cacheLabel', { percent: cache.percent }) : null;
155
+ const ttftLabel = hasTtft ? t('ttftLabel', { value: formatSeconds(ttftMs) }) : null;
156
+ const label = [speedLabel, cacheLabel, ttftLabel].filter(Boolean).join(' · ');
157
+
158
+ const titleParts = [];
159
+ if (speedLabel !== null) {
160
+ titleParts.push(
161
+ `${t('title')} · ${t('detail', {
162
+ tokens: formatCount(outputTokens),
163
+ seconds: formatSeconds(decodeMs),
164
+ })}`,
165
+ );
166
+ }
167
+ if (cache !== null) {
168
+ titleParts.push(
169
+ `${t('cacheTitle')} · ${t('cacheDetail', {
170
+ cached: formatCount(cache.cachedTokens),
171
+ prompt: formatCount(cache.promptTokens),
172
+ })}`,
173
+ );
174
+ }
175
+ if (hasTtft) {
176
+ titleParts.push(
177
+ `${t('ttftTitle')} · ${t('ttftDetail', { value: formatSeconds(ttftMs) })}`,
178
+ );
179
+ }
180
+ if (hasTotal) {
181
+ titleParts.push(
182
+ `${t('totalTitle')} · ${t('totalDetail', { value: formatSeconds(totalMs) })}`,
183
+ );
184
+ }
185
+
186
+ const data = {};
187
+ if (speedLabel !== null) {
188
+ data['data-output-tokens'] = outputTokens;
189
+ data['data-decode-ms'] = decodeMs;
190
+ }
191
+ if (cache !== null) {
192
+ data['data-cache-hit-percent'] = cache.percent;
193
+ data['data-cache-read-tokens'] = cache.cachedTokens;
194
+ data['data-prompt-tokens'] = cache.promptTokens;
195
+ }
196
+ if (hasTtft) data['data-ttft-ms'] = ttftMs;
197
+ if (hasTotal) data['data-total-ms'] = totalMs;
198
+
199
+ return h(
200
+ 'span',
201
+ {
202
+ className: 'dshLastResponseSpeed',
203
+ 'data-last-response-speed': true,
204
+ ...data,
205
+ title: titleParts.join(' · '),
206
+ 'aria-label': label,
207
+ },
208
+ h(GaugeIcon),
209
+ h('span', { className: 'dshLastResponseSpeedLabel' }, label),
210
+ );
211
+ }
212
+
213
+ return {
214
+ inject: ['slots', 'locale'],
215
+ apply(ctx) {
216
+ ctx.effect(
217
+ () => ctx.locale.register(NS, { en: EN, zh: ZH }),
218
+ 'dsh-last-response-stats: dictionaries',
219
+ );
220
+
221
+ ctx.effect(() => {
222
+ const tag = document.createElement('style');
223
+ tag.dataset.lastResponseStats = 'dsh-last-response-stats';
224
+ tag.textContent = CSS;
225
+ document.head.append(tag);
226
+ return () => tag.remove();
227
+ }, 'dsh-last-response-stats: styles');
228
+
229
+ ctx.slots.inject('conversation.chat.turnTail', () =>
230
+ ctx.slots.register(
231
+ {
232
+ name: 'conversation.chat.turnTail',
233
+ id: 'dsh-last-response-stats',
234
+ order: 20,
235
+ locale: NS,
236
+ },
237
+ LastResponseSpeed,
238
+ ),
239
+ );
240
+ },
241
+ };
242
+ },
243
+ });
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: last-response-stats
3
+ name: 'dsh-last-response-stats'
4
+ config: {}
package/icon.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Last Response Stats">
2
+ <rect width="64" height="64" rx="14" fill="#10243b"/>
3
+ <path d="M15 45a17 17 0 0 1 34 0" fill="none" stroke="#6fd3ff" stroke-width="4" stroke-linecap="round"/>
4
+ <path d="M32 45l9.5-14" fill="none" stroke="#ffffff" stroke-width="3.5" stroke-linecap="round"/>
5
+ <circle cx="32" cy="45" r="3.2" fill="#ffffff"/>
6
+ <path d="M32 20v4M17 28l2.8 2.8M47 28l-2.8 2.8" fill="none" stroke="#6fd3ff" stroke-width="3" stroke-linecap="round"/>
7
+ </svg>
package/index.js ADDED
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Host half of the Last Response Stats bundle.
3
+ *
4
+ * `lastResponseStats` is a per-Session projection over the durable log: the
5
+ * most recent content-bearing assistant message, its provider token usage
6
+ * (output and prompt-cache buckets), and its first-token, decode, and total
7
+ * latency. The Client reads the whole value through
8
+ * `useProjection('lastResponseStats')`; no Client-side event folding is
9
+ * involved.
10
+ */
11
+
12
+ const EMPTY_STATE = Object.freeze({
13
+ /** Seq of the projected assistant/message, or -1 before the first response. */
14
+ seq: -1,
15
+ /** Turn and step of that response; null before the first response. */
16
+ turn: null,
17
+ step: null,
18
+ /** Provider-reported output tokens, or null when the provider reported none. */
19
+ outputTokens: null,
20
+ /** Prompt-side token buckets; null when the provider did not report them. */
21
+ inputTokens: null,
22
+ cacheReadTokens: null,
23
+ cacheWriteTokens: null,
24
+ /** completedTime - firstTokenTime in milliseconds, or null when undecidable. */
25
+ decodeMs: null,
26
+ /** firstTokenTime - stepStartTime in milliseconds, or null without a step start. */
27
+ ttftMs: null,
28
+ /** completedTime - stepStartTime in milliseconds, or null without a step start. */
29
+ totalMs: null,
30
+ /** Start boundary of the step currently being folded. */
31
+ stepStartTime: null,
32
+ stepStartTurn: null,
33
+ stepStartStep: null,
34
+ /** First token delta timestamp, or null when the stream records none. */
35
+ firstTokenTime: null,
36
+ /** assistant/message settlement timestamp, or null before the first response. */
37
+ completedTime: null,
38
+ });
39
+
40
+ function isFiniteNumber(value) {
41
+ return typeof value === 'number' && Number.isFinite(value);
42
+ }
43
+
44
+ function isCount(value) {
45
+ return Number.isSafeInteger(value) && value >= 0;
46
+ }
47
+
48
+ function isNullableCount(value) {
49
+ return value === null || isCount(value);
50
+ }
51
+
52
+ function isNullableNumber(value) {
53
+ return value === null || isFiniteNumber(value);
54
+ }
55
+
56
+ /**
57
+ * Validate one projection state/view value. The registry calls only `parse`
58
+ * on these schemas; the structural checks keep a malformed persisted-cache
59
+ * row from seeding a fold.
60
+ * @param {unknown} value
61
+ * @returns {{ seq: number, turn: number | null, step: number | null, outputTokens: number | null, inputTokens: number | null, cacheReadTokens: number | null, cacheWriteTokens: number | null, decodeMs: number | null, ttftMs: number | null, totalMs: number | null, stepStartTime: number | null, stepStartTurn: number | null, stepStartStep: number | null, firstTokenTime: number | null, completedTime: number | null }}
62
+ */
63
+ function parseState(value) {
64
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
65
+ throw new TypeError('lastResponseStats state must be an object');
66
+ }
67
+ const {
68
+ seq,
69
+ turn,
70
+ step,
71
+ outputTokens,
72
+ inputTokens,
73
+ cacheReadTokens,
74
+ cacheWriteTokens,
75
+ decodeMs,
76
+ ttftMs,
77
+ totalMs,
78
+ stepStartTime,
79
+ stepStartTurn,
80
+ stepStartStep,
81
+ firstTokenTime,
82
+ completedTime,
83
+ } = value;
84
+ if (!Number.isSafeInteger(seq) || seq < -1) {
85
+ throw new TypeError('lastResponseStats seq must be an integer >= -1');
86
+ }
87
+ if (!(turn === null || (Number.isSafeInteger(turn) && turn >= 0))) {
88
+ throw new TypeError('lastResponseStats turn must be a non-negative integer or null');
89
+ }
90
+ if (!(step === null || (Number.isSafeInteger(step) && step >= 0))) {
91
+ throw new TypeError('lastResponseStats step must be a non-negative integer or null');
92
+ }
93
+ if (!isNullableCount(outputTokens)) {
94
+ throw new TypeError('lastResponseStats outputTokens must be a non-negative integer or null');
95
+ }
96
+ if (!isNullableCount(inputTokens)) {
97
+ throw new TypeError('lastResponseStats inputTokens must be a non-negative integer or null');
98
+ }
99
+ if (!isNullableCount(cacheReadTokens)) {
100
+ throw new TypeError('lastResponseStats cacheReadTokens must be a non-negative integer or null');
101
+ }
102
+ if (!isNullableCount(cacheWriteTokens)) {
103
+ throw new TypeError('lastResponseStats cacheWriteTokens must be a non-negative integer or null');
104
+ }
105
+ if (!isNullableCount(decodeMs)) {
106
+ throw new TypeError('lastResponseStats decodeMs must be a non-negative integer or null');
107
+ }
108
+ if (!isNullableCount(ttftMs)) {
109
+ throw new TypeError('lastResponseStats ttftMs must be a non-negative integer or null');
110
+ }
111
+ if (!isNullableCount(totalMs)) {
112
+ throw new TypeError('lastResponseStats totalMs must be a non-negative integer or null');
113
+ }
114
+ if (!isNullableNumber(stepStartTime)) {
115
+ throw new TypeError('lastResponseStats stepStartTime must be a finite number or null');
116
+ }
117
+ if (!(stepStartTurn === null || (Number.isSafeInteger(stepStartTurn) && stepStartTurn >= 0))) {
118
+ throw new TypeError('lastResponseStats stepStartTurn must be a non-negative integer or null');
119
+ }
120
+ if (!(stepStartStep === null || (Number.isSafeInteger(stepStartStep) && stepStartStep >= 0))) {
121
+ throw new TypeError('lastResponseStats stepStartStep must be a non-negative integer or null');
122
+ }
123
+ if (!isNullableNumber(firstTokenTime)) {
124
+ throw new TypeError('lastResponseStats firstTokenTime must be a finite number or null');
125
+ }
126
+ if (!isNullableNumber(completedTime)) {
127
+ throw new TypeError('lastResponseStats completedTime must be a finite number or null');
128
+ }
129
+ return {
130
+ seq,
131
+ turn,
132
+ step,
133
+ outputTokens,
134
+ inputTokens,
135
+ cacheReadTokens,
136
+ cacheWriteTokens,
137
+ decodeMs,
138
+ ttftMs,
139
+ totalMs,
140
+ stepStartTime,
141
+ stepStartTurn,
142
+ stepStartStep,
143
+ firstTokenTime,
144
+ completedTime,
145
+ };
146
+ }
147
+
148
+ const stateSchema = { parse: parseState };
149
+ const viewSchema = { parse: parseState };
150
+
151
+ /**
152
+ * Whether one assistant message carries a visible reply. This mirrors the
153
+ * Chat target's closing-response rule: reasoning-only and tool-call-only
154
+ * messages are protocol material, not a response.
155
+ * @param {unknown} content
156
+ * @returns {boolean}
157
+ */
158
+ function hasVisibleReply(content) {
159
+ if (!Array.isArray(content)) return false;
160
+ for (const block of content) {
161
+ if (block === null || typeof block !== 'object') continue;
162
+ if (block.type === 'reasoning' || block.type === 'tool-call') continue;
163
+ if (block.type === 'text') {
164
+ if (typeof block.text === 'string' && block.text.trim() !== '') return true;
165
+ continue;
166
+ }
167
+ return true;
168
+ }
169
+ return false;
170
+ }
171
+
172
+ /**
173
+ * Whether one stream chunk is the first output token for latency purposes.
174
+ * @param {unknown} chunk
175
+ * @returns {boolean}
176
+ */
177
+ function isTokenChunk(chunk) {
178
+ if (chunk === null || typeof chunk !== 'object') return false;
179
+ switch (chunk.type) {
180
+ case 'text-delta':
181
+ case 'reasoning-delta':
182
+ return typeof chunk.text === 'string' && chunk.text !== '';
183
+ case 'tool-call-delta':
184
+ return (
185
+ (typeof chunk.argumentsDelta === 'string' && chunk.argumentsDelta !== '') ||
186
+ chunk.name !== undefined
187
+ );
188
+ default:
189
+ return false;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Reconstruct the first token time from the durable compact stream records,
195
+ * matching `assistantStreamFirstTokenTime` semantics.
196
+ * @param {unknown} stream
197
+ * @returns {number | null}
198
+ */
199
+ function firstTokenTimeOfStream(stream) {
200
+ if (!Array.isArray(stream)) return null;
201
+ for (const record of stream) {
202
+ if (record === null || typeof record !== 'object') continue;
203
+ if (record.type === 'chunk') {
204
+ if (isTokenChunk(record.chunk) && isFiniteNumber(record.time)) return record.time;
205
+ continue;
206
+ }
207
+ if (
208
+ record.type !== 'text-chunks' &&
209
+ record.type !== 'reasoning-chunks' &&
210
+ record.type !== 'tool-call-chunks'
211
+ ) {
212
+ continue;
213
+ }
214
+ if (!isFiniteNumber(record.time0)) continue;
215
+ if (record.type === 'tool-call-chunks' && record.name !== undefined) return record.time0;
216
+ const members = record.type === 'tool-call-chunks' ? record.args : record.texts;
217
+ const dt = record.dt;
218
+ if (!Array.isArray(members) || !Array.isArray(dt)) continue;
219
+ let time = record.time0;
220
+ for (let index = 0; index < members.length; index += 1) {
221
+ if (index > 0) {
222
+ const delta = dt[index - 1];
223
+ if (!isFiniteNumber(delta)) {
224
+ time = null;
225
+ break;
226
+ }
227
+ time += delta;
228
+ }
229
+ const member = members[index];
230
+ if (typeof member === 'string' && member !== '') return time;
231
+ }
232
+ }
233
+ return null;
234
+ }
235
+
236
+ /**
237
+ * Provider token usage for one assistant/message, preferring the event's
238
+ * usage and falling back to the final usage chunk in its embedded stream.
239
+ * @param {any} event
240
+ * @returns {{ outputTokens: number, inputTokens?: number, cacheReadTokens?: number, cacheWriteTokens?: number } | null}
241
+ */
242
+ function usageOf(event) {
243
+ const usage = event.data.usage;
244
+ if (usage !== null && typeof usage === 'object' && isCount(usage.outputTokens)) {
245
+ return usage;
246
+ }
247
+ const stream = event.data.stream;
248
+ if (!Array.isArray(stream)) return null;
249
+ for (let index = stream.length - 1; index >= 0; index -= 1) {
250
+ const record = stream[index];
251
+ if (record === null || typeof record !== 'object' || record.type !== 'chunk') continue;
252
+ const chunk = record.chunk;
253
+ if (chunk === null || typeof chunk !== 'object' || chunk.type !== 'usage') continue;
254
+ const streamed = chunk.usage;
255
+ if (streamed !== null && typeof streamed === 'object' && isCount(streamed.outputTokens)) {
256
+ return streamed;
257
+ }
258
+ }
259
+ return null;
260
+ }
261
+
262
+ /**
263
+ * Pure projection transition. Unrelated events return the same state
264
+ * reference so the registry's Object.is gate stays quiet.
265
+ * @param {typeof EMPTY_STATE} state
266
+ * @param {any} event
267
+ * @returns {typeof EMPTY_STATE}
268
+ */
269
+ function fold(state, event) {
270
+ if (event.type === 'step/start') {
271
+ if (!isFiniteNumber(event.time)) return state;
272
+ const turn = event.data.turn;
273
+ const step = event.data.step;
274
+ if (!Number.isSafeInteger(turn) || turn < 0 || !Number.isSafeInteger(step) || step < 0) {
275
+ return state;
276
+ }
277
+ return {
278
+ ...state,
279
+ stepStartTime: event.time,
280
+ stepStartTurn: turn,
281
+ stepStartStep: step,
282
+ };
283
+ }
284
+ if (event.type !== 'assistant/message' || event.surfaceOp !== 'append') return state;
285
+ if (event.seq <= state.seq) return state;
286
+ const message = event.data.message;
287
+ if (message === null || typeof message !== 'object' || !hasVisibleReply(message.content)) {
288
+ return state;
289
+ }
290
+ const completedTime = event.time;
291
+ if (!isFiniteNumber(completedTime)) return state;
292
+ const firstTokenTime = firstTokenTimeOfStream(event.data.stream);
293
+ const usage = usageOf(event);
294
+ const outputTokens = usage !== null && isCount(usage.outputTokens) ? usage.outputTokens : null;
295
+ const inputTokens = usage !== null && isCount(usage.inputTokens) ? usage.inputTokens : null;
296
+ const cacheReadTokens = usage !== null && isCount(usage.cacheReadTokens) ? usage.cacheReadTokens : null;
297
+ const cacheWriteTokens = usage !== null && isCount(usage.cacheWriteTokens) ? usage.cacheWriteTokens : null;
298
+ const decodeMs =
299
+ firstTokenTime !== null && completedTime > firstTokenTime
300
+ ? completedTime - firstTokenTime
301
+ : null;
302
+ const hasStepStart =
303
+ state.stepStartTime !== null &&
304
+ state.stepStartTurn === event.data.turn &&
305
+ state.stepStartStep === event.data.step;
306
+ const ttftMs =
307
+ hasStepStart && firstTokenTime !== null && firstTokenTime >= state.stepStartTime
308
+ ? firstTokenTime - state.stepStartTime
309
+ : null;
310
+ const totalMs =
311
+ hasStepStart && completedTime >= state.stepStartTime
312
+ ? completedTime - state.stepStartTime
313
+ : null;
314
+ return {
315
+ ...state,
316
+ seq: event.seq,
317
+ turn: event.data.turn,
318
+ step: event.data.step,
319
+ outputTokens,
320
+ inputTokens,
321
+ cacheReadTokens,
322
+ cacheWriteTokens,
323
+ decodeMs,
324
+ ttftMs,
325
+ totalMs,
326
+ firstTokenTime,
327
+ completedTime,
328
+ };
329
+ }
330
+
331
+ export const inject = ['sessionProjections'];
332
+
333
+ /**
334
+ * Register the per-Session projection unit.
335
+ * @param {any} ctx - owning Host plugin context.
336
+ */
337
+ export function apply(ctx) {
338
+ ctx.sessionProjections.register({
339
+ key: 'lastResponseStats',
340
+ stateSchema,
341
+ stateVersion: 3,
342
+ init: () => EMPTY_STATE,
343
+ apply: fold,
344
+ wire: {
345
+ viewSchema,
346
+ view: (state) => state,
347
+ },
348
+ });
349
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Last Response Stats",
4
+ "description": "Adds output tok/s, prompt-cache hit, and TTFT under the most recent Chat response."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "最近回复统计",
4
+ "description": "在聊天中最近一次回复下方显示输出 tok/s、提示词缓存命中率和首 token 延迟。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "dsh-last-response-stats",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.0",
4
+ "type": "module",
5
+ "description": "Shows output speed, prompt-cache hit, and time to first token for the most recent Chat response.",
6
+ "author": "Borivoje Latinovic",
7
+ "license": "MIT",
8
+ "keywords": [
9
+ "dsh",
10
+ "deepseek-harness",
11
+ "dsh-plugin",
12
+ "tokens-per-second",
13
+ "prompt-cache",
14
+ "ttft"
15
+ ],
16
+ "engines": {
17
+ "dsh": ">=0.2.1-rc.2 <0.3.0"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/latinovicb/dsh-last-response-stats.git"
22
+ },
23
+ "homepage": "https://github.com/latinovicb/dsh-last-response-stats#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/latinovicb/dsh-last-response-stats/issues"
26
+ },
27
+ "exports": {
28
+ ".": "./index.js",
29
+ "./client": "./client.js",
30
+ "./locale/*.json": "./locale/*.json",
31
+ "./icon": "./icon.svg"
32
+ },
33
+ "files": [
34
+ "README.md",
35
+ "LICENSE",
36
+ "index.js",
37
+ "client.js",
38
+ "cordis.patch.yml",
39
+ "locale/*.json",
40
+ "icon.svg"
41
+ ],
42
+ "dsh": {
43
+ "bundle": {
44
+ "patch": "./cordis.patch.yml"
45
+ },
46
+ "client": {
47
+ "platform": "web",
48
+ "immediately": true,
49
+ "inject": [
50
+ "@deepseek-ai/dsh-client-locale",
51
+ "@deepseek-ai/dsh-client-ui-chat"
52
+ ]
53
+ }
54
+ }
55
+ }