@narumitw/pi-analytics 0.49.9 → 0.49.10

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/src/menu.ts CHANGED
@@ -2,418 +2,400 @@ import { stripVTControlCharacters } from "node:util";
2
2
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
3
  import type { MenuDefinition } from "@narumitw/pi-tui-kit";
4
4
  import type { ClearAnalyticsResult } from "./storage/files.js";
5
- import type {
6
- AnalyticsSnapshot,
7
- SkillStats,
8
- TimeRange,
9
- TimeRangeId,
10
- ToolStats,
11
- } from "./storage/queries.js";
5
+ import type { AnalyticsSnapshot, SkillStats, TimeRange, TimeRangeId, ToolStats } from "./storage/queries.js";
12
6
  import { resolveTimeRange } from "./storage/queries.js";
13
7
 
14
8
  export type AnalyticsLoadResult =
15
- | { kind: "ready"; snapshot: AnalyticsSnapshot }
16
- | { kind: "unavailable"; message: string };
9
+ | { kind: "ready"; snapshot: AnalyticsSnapshot }
10
+ | { kind: "unavailable"; message: string };
17
11
 
18
12
  export interface AnalyticsMenuDataSource {
19
- path: string;
20
- load(range: TimeRange, signal: AbortSignal): Promise<AnalyticsLoadResult>;
21
- clearAll(signal: AbortSignal): Promise<ClearAnalyticsResult>;
13
+ path: string;
14
+ load(range: TimeRange, signal: AbortSignal): Promise<AnalyticsLoadResult>;
15
+ clearAll(signal: AbortSignal): Promise<ClearAnalyticsResult>;
22
16
  }
23
17
 
24
18
  export interface AnalyticsMenuState {
25
- rangeId: TimeRangeId;
26
- range: TimeRange;
27
- path: string;
28
- result: AnalyticsLoadResult;
19
+ rangeId: TimeRangeId;
20
+ range: TimeRange;
21
+ path: string;
22
+ result: AnalyticsLoadResult;
29
23
  }
30
24
 
31
25
  export interface AnalyticsMenuOptions {
32
- runConfirmation: typeof import("@narumitw/pi-tui-kit")["runConfirmation"];
33
- isCurrent(): boolean;
26
+ runConfirmation: typeof import("@narumitw/pi-tui-kit")["runConfirmation"];
27
+ isCurrent(): boolean;
34
28
  }
35
29
 
36
30
  type Screen = "main" | "range" | "skills" | "tools" | "reliability" | "responses" | "privacy";
37
31
  type Action = "setRange" | "clearData";
38
32
 
39
33
  const RANGE_LABELS: Record<TimeRangeId, string> = {
40
- today: "Today",
41
- "7d": "Last 7 days",
42
- "30d": "Last 30 days",
43
- all: "All time",
34
+ today: "Today",
35
+ "7d": "Last 7 days",
36
+ "30d": "Last 30 days",
37
+ all: "All time",
44
38
  };
45
39
 
46
40
  export function createAnalyticsMenu(
47
- source: AnalyticsMenuDataSource,
48
- now: () => number = Date.now,
49
- options?: AnalyticsMenuOptions,
41
+ source: AnalyticsMenuDataSource,
42
+ now: () => number = Date.now,
43
+ options?: AnalyticsMenuOptions,
50
44
  ) {
51
- let rangeId: TimeRangeId = "7d";
52
- let cachedState: AnalyticsMenuState | undefined;
53
- const loadState = async (signal: AbortSignal): Promise<AnalyticsMenuState> => {
54
- if (cachedState?.rangeId === rangeId) return cachedState;
55
- const range = resolveTimeRange(rangeId, now());
56
- const loaded = { rangeId, range, path: source.path, result: await source.load(range, signal) };
57
- if (!signal.aborted && rangeId === loaded.rangeId) cachedState = loaded;
58
- return loaded;
59
- };
60
- const getState = ({ signal }: { signal: AbortSignal }): Promise<AnalyticsMenuState> =>
61
- loadState(signal);
62
- const menu: MenuDefinition<AnalyticsMenuState, Screen, Action> = {
63
- start: "main",
64
- screens: {
65
- main: ({ state }) => ({
66
- kind: "actions",
67
- title: `Analytics · ${RANGE_LABELS[state.rangeId]}`,
68
- lines: overviewLines(state.result),
69
- items: [
70
- { id: "range", label: "Change time range", to: "range" },
71
- { id: "skills", label: "Skills", to: "skills" },
72
- { id: "tools", label: "Tools", to: "tools" },
73
- { id: "reliability", label: "Provider reliability", to: "reliability" },
74
- { id: "responses", label: "Response cycles", to: "responses" },
75
- { id: "privacy", label: "Data & privacy", to: "privacy" },
76
- { id: "close", label: "Close", close: true },
77
- ],
78
- hint: "close",
79
- }),
80
- range: ({ state }) => ({
81
- kind: "choice",
82
- title: "Analytics time range",
83
- items: (Object.keys(RANGE_LABELS) as TimeRangeId[]).map((id) => ({
84
- id,
85
- label: RANGE_LABELS[id],
86
- })),
87
- action: "setRange",
88
- currentItemId: state.rangeId,
89
- initialItemId: state.rangeId,
90
- hint: "back",
91
- }),
92
- skills: ({ state }) => skillsScreen(state.result),
93
- tools: ({ state }) => toolsScreen(state.result),
94
- reliability: ({ state }) => ({
95
- kind: "detail",
96
- title: `Provider reliability · ${RANGE_LABELS[state.rangeId]}`,
97
- lines: reliabilityLines(state.result),
98
- hint: "back",
99
- }),
100
- responses: ({ state }) => ({
101
- kind: "detail",
102
- title: `Response cycles · ${RANGE_LABELS[state.rangeId]}`,
103
- lines: responseLines(state.result),
104
- hint: "back",
105
- }),
106
- privacy: ({ state }) => ({
107
- kind: "actions",
108
- title: "Analytics data & privacy",
109
- lines: privacyLines(state),
110
- items: [
111
- {
112
- id: "clear",
113
- label: "Clear analytics data…",
114
- action: "clearData",
115
- disabled: state.result.kind !== "ready",
116
- },
117
- ],
118
- hint: "back",
119
- }),
120
- },
121
- actions: {
122
- setRange: async ({ itemId, signal }) => {
123
- if (!isRangeId(itemId)) return { kind: "rejected", error: new Error("Unknown range") };
124
- rangeId = itemId;
125
- cachedState = undefined;
126
- await loadState(signal);
127
- return signal.aborted ? { kind: "close" } : { kind: "to", screen: "main" };
128
- },
129
- clearData: async ({ ctx, state, signal }) => {
130
- if (state.result.kind !== "ready") return { kind: "stay" };
131
- if (!options) throw new Error("Analytics confirmation is unavailable");
132
- const count = state.result.snapshot.overview.responseCycles;
133
- const confirmation = await options.runConfirmation(ctx, {
134
- title: "Delete analytics data?",
135
- message: `This will clear all local analytics history from:\n\n${safeDisplayText(state.path)}\n\nThe selected range currently shows ${count} response cycles. Other running Pi processes may add new records afterward.`,
136
- confirmLabel: "Delete data",
137
- cancelLabel: "Keep data",
138
- signal,
139
- isCurrent: options.isCurrent,
140
- // Keep the dashboard's existing domain-level error route as the only notifier.
141
- onError: () => undefined,
142
- });
143
- if (signal.aborted || !options.isCurrent()) return { kind: "close" };
144
- if (confirmation.kind === "closed") {
145
- return confirmation.reason === "close" ? { kind: "close" } : { kind: "stay" };
146
- }
147
- if (confirmation.kind === "stale") return { kind: "close" };
148
- if (confirmation.kind === "unsupported") {
149
- throw new Error(`Analytics confirmation is unavailable in ${confirmation.mode} mode`);
150
- }
151
- if (confirmation.kind === "error") throw confirmation.error;
45
+ let rangeId: TimeRangeId = "7d";
46
+ let cachedState: AnalyticsMenuState | undefined;
47
+ const loadState = async (signal: AbortSignal): Promise<AnalyticsMenuState> => {
48
+ if (cachedState?.rangeId === rangeId) return cachedState;
49
+ const range = resolveTimeRange(rangeId, now());
50
+ const loaded = { rangeId, range, path: source.path, result: await source.load(range, signal) };
51
+ if (!signal.aborted && rangeId === loaded.rangeId) cachedState = loaded;
52
+ return loaded;
53
+ };
54
+ const getState = ({ signal }: { signal: AbortSignal }): Promise<AnalyticsMenuState> => loadState(signal);
55
+ const menu: MenuDefinition<AnalyticsMenuState, Screen, Action> = {
56
+ start: "main",
57
+ screens: {
58
+ main: ({ state }) => ({
59
+ kind: "actions",
60
+ title: `Analytics · ${RANGE_LABELS[state.rangeId]}`,
61
+ lines: overviewLines(state.result),
62
+ items: [
63
+ { id: "range", label: "Change time range", to: "range" },
64
+ { id: "skills", label: "Skills", to: "skills" },
65
+ { id: "tools", label: "Tools", to: "tools" },
66
+ { id: "reliability", label: "Provider reliability", to: "reliability" },
67
+ { id: "responses", label: "Response cycles", to: "responses" },
68
+ { id: "privacy", label: "Data & privacy", to: "privacy" },
69
+ { id: "close", label: "Close", close: true },
70
+ ],
71
+ hint: "close",
72
+ }),
73
+ range: ({ state }) => ({
74
+ kind: "choice",
75
+ title: "Analytics time range",
76
+ items: (Object.keys(RANGE_LABELS) as TimeRangeId[]).map((id) => ({
77
+ id,
78
+ label: RANGE_LABELS[id],
79
+ })),
80
+ action: "setRange",
81
+ currentItemId: state.rangeId,
82
+ initialItemId: state.rangeId,
83
+ hint: "back",
84
+ }),
85
+ skills: ({ state }) => skillsScreen(state.result),
86
+ tools: ({ state }) => toolsScreen(state.result),
87
+ reliability: ({ state }) => ({
88
+ kind: "detail",
89
+ title: `Provider reliability · ${RANGE_LABELS[state.rangeId]}`,
90
+ lines: reliabilityLines(state.result),
91
+ hint: "back",
92
+ }),
93
+ responses: ({ state }) => ({
94
+ kind: "detail",
95
+ title: `Response cycles · ${RANGE_LABELS[state.rangeId]}`,
96
+ lines: responseLines(state.result),
97
+ hint: "back",
98
+ }),
99
+ privacy: ({ state }) => ({
100
+ kind: "actions",
101
+ title: "Analytics data & privacy",
102
+ lines: privacyLines(state),
103
+ items: [
104
+ {
105
+ id: "clear",
106
+ label: "Clear analytics data…",
107
+ action: "clearData",
108
+ disabled: state.result.kind !== "ready",
109
+ },
110
+ ],
111
+ hint: "back",
112
+ }),
113
+ },
114
+ actions: {
115
+ setRange: async ({ itemId, signal }) => {
116
+ if (!isRangeId(itemId)) return { kind: "rejected", error: new Error("Unknown range") };
117
+ rangeId = itemId;
118
+ cachedState = undefined;
119
+ await loadState(signal);
120
+ return signal.aborted ? { kind: "close" } : { kind: "to", screen: "main" };
121
+ },
122
+ clearData: async ({ ctx, state, signal }) => {
123
+ if (state.result.kind !== "ready") return { kind: "stay" };
124
+ if (!options) throw new Error("Analytics confirmation is unavailable");
125
+ const count = state.result.snapshot.overview.responseCycles;
126
+ const confirmation = await options.runConfirmation(ctx, {
127
+ title: "Delete analytics data?",
128
+ message: `This will clear all local analytics history from:\n\n${safeDisplayText(state.path)}\n\nThe selected range currently shows ${count} response cycles. Other running Pi processes may add new records afterward.`,
129
+ confirmLabel: "Delete data",
130
+ cancelLabel: "Keep data",
131
+ signal,
132
+ isCurrent: options.isCurrent,
133
+ // Keep the dashboard's existing domain-level error route as the only notifier.
134
+ onError: () => undefined,
135
+ });
136
+ if (signal.aborted || !options.isCurrent()) return { kind: "close" };
137
+ if (confirmation.kind === "closed") {
138
+ return confirmation.reason === "close" ? { kind: "close" } : { kind: "stay" };
139
+ }
140
+ if (confirmation.kind === "stale") return { kind: "close" };
141
+ if (confirmation.kind === "unsupported") {
142
+ throw new Error(`Analytics confirmation is unavailable in ${confirmation.mode} mode`);
143
+ }
144
+ if (confirmation.kind === "error") throw confirmation.error;
152
145
 
153
- const result = await source.clearAll(signal);
154
- cachedState = undefined;
155
- const isCurrent = options.isCurrent();
156
- if (isCurrent) {
157
- try {
158
- ctx.ui.notify("Cleared local analytics data.", "info");
159
- if (result.cleanupIncomplete) {
160
- ctx.ui.notify(
161
- "Some obsolete analytics files are still in use. Stop other Pi processes and clear again to remove them.",
162
- "warning",
163
- );
164
- }
165
- } catch {
166
- // The host can dispose the current UI after the ownership check.
167
- }
168
- }
169
- return signal.aborted || !isCurrent ? { kind: "close" } : { kind: "to", screen: "main" };
170
- },
171
- },
172
- };
173
- return {
174
- menu,
175
- getState,
176
- preload: (signal: AbortSignal) => loadState(signal),
177
- get rangeId() {
178
- return rangeId;
179
- },
180
- };
146
+ const result = await source.clearAll(signal);
147
+ cachedState = undefined;
148
+ const isCurrent = options.isCurrent();
149
+ if (isCurrent) {
150
+ try {
151
+ ctx.ui.notify("Cleared local analytics data.", "info");
152
+ if (result.cleanupIncomplete) {
153
+ ctx.ui.notify(
154
+ "Some obsolete analytics files are still in use. Stop other Pi processes and clear again to remove them.",
155
+ "warning",
156
+ );
157
+ }
158
+ } catch {
159
+ // The host can dispose the current UI after the ownership check.
160
+ }
161
+ }
162
+ return signal.aborted || !isCurrent ? { kind: "close" } : { kind: "to", screen: "main" };
163
+ },
164
+ },
165
+ };
166
+ return {
167
+ menu,
168
+ getState,
169
+ preload: (signal: AbortSignal) => loadState(signal),
170
+ get rangeId() {
171
+ return rangeId;
172
+ },
173
+ };
181
174
  }
182
175
 
183
176
  export async function showAnalyticsMenu(
184
- ctx: ExtensionCommandContext,
185
- source: AnalyticsMenuDataSource,
186
- options: { signal: AbortSignal; isCurrent: () => boolean },
177
+ ctx: ExtensionCommandContext,
178
+ source: AnalyticsMenuDataSource,
179
+ options: { signal: AbortSignal; isCurrent: () => boolean },
187
180
  ): Promise<void> {
188
- const { runConfirmation, runMenu, runTask } = await import("@narumitw/pi-tui-kit");
189
- if (options.signal.aborted || !options.isCurrent()) return;
190
- const controller = createAnalyticsMenu(source, Date.now, {
191
- runConfirmation,
192
- isCurrent: options.isCurrent,
193
- });
194
- const loading = await runTask(ctx, {
195
- label: "Loading local analytics…",
196
- signal: options.signal,
197
- isCurrent: options.isCurrent,
198
- task: ({ signal }) => controller.preload(signal),
199
- onError: () => undefined,
200
- });
201
- if (loading.kind !== "completed") {
202
- if (loading.kind === "error") {
203
- ctx.ui.notify(
204
- "Analytics failed: The local analytics query could not be completed. Existing data was not changed.",
205
- "error",
206
- );
207
- }
208
- return;
209
- }
210
- await runMenu(ctx, controller.menu, {
211
- getState: controller.getState,
212
- signal: options.signal,
213
- isCurrent: options.isCurrent,
214
- onError: (_ctx, error) => {
215
- ctx.ui.notify(`Analytics failed: ${safeErrorMessage(error)}`, "error");
216
- },
217
- });
181
+ const { runConfirmation, runMenu, runTask } = await import("@narumitw/pi-tui-kit");
182
+ if (options.signal.aborted || !options.isCurrent()) return;
183
+ const controller = createAnalyticsMenu(source, Date.now, {
184
+ runConfirmation,
185
+ isCurrent: options.isCurrent,
186
+ });
187
+ const loading = await runTask(ctx, {
188
+ label: "Loading local analytics…",
189
+ signal: options.signal,
190
+ isCurrent: options.isCurrent,
191
+ task: ({ signal }) => controller.preload(signal),
192
+ onError: () => undefined,
193
+ });
194
+ if (loading.kind !== "completed") {
195
+ if (loading.kind === "error") {
196
+ ctx.ui.notify(
197
+ "Analytics failed: The local analytics query could not be completed. Existing data was not changed.",
198
+ "error",
199
+ );
200
+ }
201
+ return;
202
+ }
203
+ await runMenu(ctx, controller.menu, {
204
+ getState: controller.getState,
205
+ signal: options.signal,
206
+ isCurrent: options.isCurrent,
207
+ onError: (_ctx, error) => {
208
+ ctx.ui.notify(`Analytics failed: ${safeErrorMessage(error)}`, "error");
209
+ },
210
+ });
218
211
  }
219
212
 
220
213
  function overviewLines(result: AnalyticsLoadResult): string[] {
221
- if (result.kind === "unavailable") {
222
- return [result.message, "", "No analytics are being collected."];
223
- }
224
- const stats = result.snapshot.overview;
225
- if (stats.responseCycles === 0) {
226
- return [
227
- "No analytics yet.",
228
- "Collection is active. Complete one Pi response cycle, then open /analytics again.",
229
- "",
230
- "Includes settled response cycles only.",
231
- ];
232
- }
233
- return [
234
- metric("Response cycles", stats.responseCycles),
235
- metric("LLM calls", stats.llmCalls),
236
- metric(
237
- "Calls per response",
238
- `${formatDecimal(stats.callsPerResponse)} · P95 ${stats.p95CallsPerResponse}`,
239
- ),
240
- metric("Tool calls", stats.toolCalls),
241
- metric("Tool errors", stats.toolErrors),
242
- metric("Skill activations", stats.skillActivations),
243
- metric("Provider errors", stats.providerErrors),
244
- metric("Recovered errors", stats.recoveredErrors),
245
- "",
246
- "Includes settled response cycles only.",
247
- ];
214
+ if (result.kind === "unavailable") {
215
+ return [result.message, "", "No analytics are being collected."];
216
+ }
217
+ const stats = result.snapshot.overview;
218
+ if (stats.responseCycles === 0) {
219
+ return [
220
+ "No analytics yet.",
221
+ "Collection is active. Complete one Pi response cycle, then open /analytics again.",
222
+ "",
223
+ "Includes settled response cycles only.",
224
+ ];
225
+ }
226
+ return [
227
+ metric("Response cycles", stats.responseCycles),
228
+ metric("LLM calls", stats.llmCalls),
229
+ metric("Calls per response", `${formatDecimal(stats.callsPerResponse)} · P95 ${stats.p95CallsPerResponse}`),
230
+ metric("Tool calls", stats.toolCalls),
231
+ metric("Tool errors", stats.toolErrors),
232
+ metric("Skill activations", stats.skillActivations),
233
+ metric("Provider errors", stats.providerErrors),
234
+ metric("Recovered errors", stats.recoveredErrors),
235
+ "",
236
+ "Includes settled response cycles only.",
237
+ ];
248
238
  }
249
239
 
250
240
  function skillsScreen(result: AnalyticsLoadResult) {
251
- if (result.kind === "unavailable") {
252
- return {
253
- kind: "browse" as const,
254
- title: "Skills",
255
- lines: [result.message],
256
- items: [],
257
- hint: "back" as const,
258
- };
259
- }
260
- return {
261
- kind: "browse" as const,
262
- title: "Skills",
263
- lines:
264
- result.snapshot.skills.length === 0
265
- ? ["No skill activations detected in this time range."]
266
- : undefined,
267
- items: result.snapshot.skills.map(skillItem),
268
- viewportSize: "adaptive" as const,
269
- hint: "back" as const,
270
- };
241
+ if (result.kind === "unavailable") {
242
+ return {
243
+ kind: "browse" as const,
244
+ title: "Skills",
245
+ lines: [result.message],
246
+ items: [],
247
+ hint: "back" as const,
248
+ };
249
+ }
250
+ return {
251
+ kind: "browse" as const,
252
+ title: "Skills",
253
+ lines: result.snapshot.skills.length === 0 ? ["No skill activations detected in this time range."] : undefined,
254
+ items: result.snapshot.skills.map(skillItem),
255
+ viewportSize: "adaptive" as const,
256
+ hint: "back" as const,
257
+ };
271
258
  }
272
259
 
273
260
  function skillItem(skill: SkillStats) {
274
- return {
275
- id: skill.name,
276
- label: safeDisplayText(skill.name),
277
- statusText: `${skill.count} · ${skill.modelInitiated} model / ${skill.userInitiated} user`,
278
- searchText: skill.models.map(modelLabel).join(" "),
279
- details: [
280
- metric("Activations", skill.count),
281
- metric("Model initiated", skill.modelInitiated),
282
- metric("User initiated", skill.userInitiated),
283
- "",
284
- "By model",
285
- ...skill.models.map((model) => `${modelLabel(model)}: ${model.count}`),
286
- "",
287
- `Last detected: ${formatTimestamp(skill.lastOccurredAtMs)}`,
288
- ],
289
- };
261
+ return {
262
+ id: skill.name,
263
+ label: safeDisplayText(skill.name),
264
+ statusText: `${skill.count} · ${skill.modelInitiated} model / ${skill.userInitiated} user`,
265
+ searchText: skill.models.map(modelLabel).join(" "),
266
+ details: [
267
+ metric("Activations", skill.count),
268
+ metric("Model initiated", skill.modelInitiated),
269
+ metric("User initiated", skill.userInitiated),
270
+ "",
271
+ "By model",
272
+ ...skill.models.map((model) => `${modelLabel(model)}: ${model.count}`),
273
+ "",
274
+ `Last detected: ${formatTimestamp(skill.lastOccurredAtMs)}`,
275
+ ],
276
+ };
290
277
  }
291
278
 
292
279
  function toolsScreen(result: AnalyticsLoadResult) {
293
- if (result.kind === "unavailable") {
294
- return {
295
- kind: "browse" as const,
296
- title: "Tools",
297
- lines: [result.message],
298
- items: [],
299
- hint: "back" as const,
300
- };
301
- }
302
- return {
303
- kind: "browse" as const,
304
- title: "Tools",
305
- lines:
306
- result.snapshot.tools.length === 0
307
- ? ["No tool calls detected in this time range."]
308
- : undefined,
309
- items: result.snapshot.tools.map(toolItem),
310
- viewportSize: "adaptive" as const,
311
- hint: "back" as const,
312
- };
280
+ if (result.kind === "unavailable") {
281
+ return {
282
+ kind: "browse" as const,
283
+ title: "Tools",
284
+ lines: [result.message],
285
+ items: [],
286
+ hint: "back" as const,
287
+ };
288
+ }
289
+ return {
290
+ kind: "browse" as const,
291
+ title: "Tools",
292
+ lines: result.snapshot.tools.length === 0 ? ["No tool calls detected in this time range."] : undefined,
293
+ items: result.snapshot.tools.map(toolItem),
294
+ viewportSize: "adaptive" as const,
295
+ hint: "back" as const,
296
+ };
313
297
  }
314
298
 
315
299
  function toolItem(tool: ToolStats) {
316
- return {
317
- id: tool.name,
318
- label: safeDisplayText(tool.name),
319
- statusText: `${tool.count} · ${tool.errors} errors`,
320
- searchText: tool.models.map(modelLabel).join(" "),
321
- details: [
322
- metric("Calls", tool.count),
323
- metric("Errors", tool.errors),
324
- `Average duration: ${formatDecimal(tool.averageDurationMs)} ms`,
325
- "",
326
- "By model",
327
- ...tool.models.map((model) => `${modelLabel(model)}: ${model.count}`),
328
- "",
329
- `Last detected: ${formatTimestamp(tool.lastOccurredAtMs)}`,
330
- ],
331
- };
300
+ return {
301
+ id: tool.name,
302
+ label: safeDisplayText(tool.name),
303
+ statusText: `${tool.count} · ${tool.errors} errors`,
304
+ searchText: tool.models.map(modelLabel).join(" "),
305
+ details: [
306
+ metric("Calls", tool.count),
307
+ metric("Errors", tool.errors),
308
+ `Average duration: ${formatDecimal(tool.averageDurationMs)} ms`,
309
+ "",
310
+ "By model",
311
+ ...tool.models.map((model) => `${modelLabel(model)}: ${model.count}`),
312
+ "",
313
+ `Last detected: ${formatTimestamp(tool.lastOccurredAtMs)}`,
314
+ ],
315
+ };
332
316
  }
333
317
 
334
318
  function reliabilityLines(result: AnalyticsLoadResult): string[] {
335
- if (result.kind === "unavailable") return [result.message];
336
- const value = result.snapshot.reliability;
337
- return [
338
- "Observed provider errors only; provider-internal failures may be invisible.",
339
- "",
340
- metric("HTTP 429", value.http429),
341
- metric("HTTP 5xx", value.http5xx),
342
- metric("DNS", value.categories.dns),
343
- metric("Connection timeout", value.categories.timeout),
344
- metric("Connection refused", value.categories.connection_refused),
345
- metric("Connection reset", value.categories.connection_reset),
346
- metric("TLS", value.categories.tls),
347
- metric("Other network", value.categories.network_other),
348
- metric("Other provider", value.categories.provider_other),
349
- "",
350
- metric("Recovered", value.recovered),
351
- metric("Terminal failures", value.terminal),
352
- ];
319
+ if (result.kind === "unavailable") return [result.message];
320
+ const value = result.snapshot.reliability;
321
+ return [
322
+ "Observed provider errors only; provider-internal failures may be invisible.",
323
+ "",
324
+ metric("HTTP 429", value.http429),
325
+ metric("HTTP 5xx", value.http5xx),
326
+ metric("DNS", value.categories.dns),
327
+ metric("Connection timeout", value.categories.timeout),
328
+ metric("Connection refused", value.categories.connection_refused),
329
+ metric("Connection reset", value.categories.connection_reset),
330
+ metric("TLS", value.categories.tls),
331
+ metric("Other network", value.categories.network_other),
332
+ metric("Other provider", value.categories.provider_other),
333
+ "",
334
+ metric("Recovered", value.recovered),
335
+ metric("Terminal failures", value.terminal),
336
+ ];
353
337
  }
354
338
 
355
339
  function responseLines(result: AnalyticsLoadResult): string[] {
356
- if (result.kind === "unavailable") return [result.message];
357
- const value = result.snapshot.responses;
358
- return [
359
- metric("Cycles", value.count),
360
- metric("LLM calls", value.llmCalls),
361
- metric("Average", formatDecimal(value.average)),
362
- metric("Median", formatDecimal(value.median)),
363
- metric("P95", value.p95),
364
- metric("Maximum", value.maximum),
365
- "",
366
- "Calls per response",
367
- metric("1 call", value.distribution.one),
368
- metric("2–3 calls", value.distribution.twoToThree),
369
- metric("4–6 calls", value.distribution.fourToSix),
370
- metric("7+ calls", value.distribution.sevenPlus),
371
- ];
340
+ if (result.kind === "unavailable") return [result.message];
341
+ const value = result.snapshot.responses;
342
+ return [
343
+ metric("Cycles", value.count),
344
+ metric("LLM calls", value.llmCalls),
345
+ metric("Average", formatDecimal(value.average)),
346
+ metric("Median", formatDecimal(value.median)),
347
+ metric("P95", value.p95),
348
+ metric("Maximum", value.maximum),
349
+ "",
350
+ "Calls per response",
351
+ metric("1 call", value.distribution.one),
352
+ metric("2–3 calls", value.distribution.twoToThree),
353
+ metric("4–6 calls", value.distribution.fourToSix),
354
+ metric("7+ calls", value.distribution.sevenPlus),
355
+ ];
372
356
  }
373
357
 
374
358
  function privacyLines(state: AnalyticsMenuState): string[] {
375
- return [
376
- "Local analytics files:",
377
- safeDisplayText(state.path),
378
- "",
379
- "Stored: timestamps, extension-generated record IDs, model/provider IDs, thinking level, tool and skill names, durations, counts, HTTP statuses, and classified errors.",
380
- "Not stored: prompts, responses, thinking, tool arguments/results, raw errors, headers, cwd/file paths, session identity, or credentials.",
381
- "",
382
- "No database server, cloud connection, or other remote telemetry is used.",
383
- "Analytics are non-critical derived metadata; a failed local write may be dropped.",
384
- ];
359
+ return [
360
+ "Local analytics files:",
361
+ safeDisplayText(state.path),
362
+ "",
363
+ "Stored: timestamps, extension-generated record IDs, model/provider IDs, thinking level, tool and skill names, durations, counts, HTTP statuses, and classified errors.",
364
+ "Not stored: prompts, responses, thinking, tool arguments/results, raw errors, headers, cwd/file paths, session identity, or credentials.",
365
+ "",
366
+ "No database server, cloud connection, or other remote telemetry is used.",
367
+ "Analytics are non-critical derived metadata; a failed local write may be dropped.",
368
+ ];
385
369
  }
386
370
 
387
371
  function metric(label: string, value: string | number): string {
388
- return `${label.padEnd(24)} ${value}`;
372
+ return `${label.padEnd(24)} ${value}`;
389
373
  }
390
374
 
391
375
  function formatDecimal(value: number): string {
392
- return Number.isInteger(value)
393
- ? String(value)
394
- : value.toFixed(2).replace(/0+$/u, "").replace(/\.$/u, "");
376
+ return Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/0+$/u, "").replace(/\.$/u, "");
395
377
  }
396
378
 
397
379
  function formatTimestamp(value: number): string {
398
- return new Date(value).toLocaleString();
380
+ return new Date(value).toLocaleString();
399
381
  }
400
382
 
401
383
  function modelLabel(model: { provider?: string; model?: string }): string {
402
- if (!model.provider && !model.model) return "unknown";
403
- return safeDisplayText(`${model.provider ?? "unknown"}/${model.model ?? "unknown"}`);
384
+ if (!model.provider && !model.model) return "unknown";
385
+ return safeDisplayText(`${model.provider ?? "unknown"}/${model.model ?? "unknown"}`);
404
386
  }
405
387
 
406
388
  function safeDisplayText(value: unknown): string {
407
- return Array.from(stripVTControlCharacters(String(value)), (character) => {
408
- const codePoint = character.codePointAt(0) ?? 0;
409
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
410
- }).join("");
389
+ return Array.from(stripVTControlCharacters(String(value)), (character) => {
390
+ const codePoint = character.codePointAt(0) ?? 0;
391
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
392
+ }).join("");
411
393
  }
412
394
 
413
395
  function isRangeId(value: string): value is TimeRangeId {
414
- return value === "today" || value === "7d" || value === "30d" || value === "all";
396
+ return value === "today" || value === "7d" || value === "30d" || value === "all";
415
397
  }
416
398
 
417
399
  function safeErrorMessage(_error: unknown): string {
418
- return "The local analytics query could not be completed. Try again; existing data was not changed.";
400
+ return "The local analytics query could not be completed. Try again; existing data was not changed.";
419
401
  }