wrapt-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,277 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { cleanCopilotPrompt, normalizeTool, stripVendor } from "./tools.js";
5
+ /** Default VS Code user dirs per platform (stable + Insiders). */
6
+ export function vscodeUserDirs() {
7
+ const home = os.homedir();
8
+ const apps = ["Code", "Code - Insiders"];
9
+ if (process.platform === "darwin")
10
+ return apps.map((a) => path.join(home, "Library/Application Support", a, "User"));
11
+ if (process.platform === "win32") {
12
+ const appData = process.env.APPDATA ?? path.join(home, "AppData/Roaming");
13
+ return apps.map((a) => path.join(appData, a, "User"));
14
+ }
15
+ return apps.map((a) => path.join(process.env.XDG_CONFIG_HOME ?? path.join(home, ".config"), a, "User"));
16
+ }
17
+ function setAt(obj, keys, v) {
18
+ let o = obj;
19
+ for (let i = 0; i < keys.length - 1; i++) {
20
+ const k = keys[i];
21
+ if (o[k] === null || typeof o[k] !== "object")
22
+ o[k] = typeof keys[i + 1] === "number" ? [] : {};
23
+ o = o[k];
24
+ }
25
+ o[keys[keys.length - 1]] = v;
26
+ }
27
+ function getAt(obj, keys) {
28
+ let o = obj;
29
+ for (const k of keys) {
30
+ if (o === null || typeof o !== "object")
31
+ return undefined;
32
+ o = o[k];
33
+ }
34
+ return o;
35
+ }
36
+ /** Replay an op-log (or read a legacy JSON snapshot). Returns null if nothing usable. */
37
+ export function replaySession(text, report) {
38
+ const trimmed = text.trimStart();
39
+ if (trimmed.startsWith("{") && !trimmed.includes("\n{")) {
40
+ // Legacy single-object JSON file, or a one-line op log.
41
+ try {
42
+ const j = JSON.parse(trimmed);
43
+ report.lines++;
44
+ if (typeof j.kind === "number" && "v" in j)
45
+ return j.kind === 0 ? j.v : null;
46
+ return j;
47
+ }
48
+ catch {
49
+ /* fall through to line mode */
50
+ }
51
+ }
52
+ let state = null;
53
+ for (const line of text.split("\n")) {
54
+ if (!line.trim())
55
+ continue;
56
+ report.lines++;
57
+ let op;
58
+ try {
59
+ op = JSON.parse(line);
60
+ }
61
+ catch {
62
+ report.malformed++;
63
+ continue;
64
+ }
65
+ if (op.kind === 0 && op.v && typeof op.v === "object") {
66
+ state = op.v;
67
+ continue;
68
+ }
69
+ if (!state || !Array.isArray(op.k)) {
70
+ report.malformed++;
71
+ continue;
72
+ }
73
+ const keys = op.k;
74
+ if (op.kind === 1)
75
+ setAt(state, keys, op.v);
76
+ else if (op.kind === 2) {
77
+ const arr = getAt(state, keys);
78
+ const items = Array.isArray(op.v) ? op.v : [];
79
+ if (Array.isArray(arr)) {
80
+ if (typeof op.i === "number")
81
+ arr.splice(op.i, arr.length - op.i, ...items);
82
+ else
83
+ arr.push(...items);
84
+ }
85
+ else
86
+ setAt(state, keys, items);
87
+ }
88
+ else
89
+ report.malformed++;
90
+ }
91
+ return state;
92
+ }
93
+ function workspaceInfo(storageDir) {
94
+ try {
95
+ const wj = JSON.parse(fs.readFileSync(path.join(storageDir, "workspace.json"), "utf8"));
96
+ if (wj.folder) {
97
+ const p = decodeURIComponent(new URL(wj.folder).pathname);
98
+ return { folders: [p], fallback: path.basename(p) || "untitled workspace" };
99
+ }
100
+ if (wj.workspace) {
101
+ const wsFile = decodeURIComponent(new URL(wj.workspace).pathname);
102
+ const named = path.basename(wsFile).replace(/\.code-workspace$/, "");
103
+ try {
104
+ const w = JSON.parse(fs.readFileSync(wsFile, "utf8"));
105
+ const folders = (w.folders ?? [])
106
+ .map((f) => f.path)
107
+ .filter((p) => !!p)
108
+ .map((p) => (path.isAbsolute(p) ? p : path.resolve(path.dirname(wsFile), p)));
109
+ // Untitled workspaces live in Code/Workspaces/<id>/workspace.json: name them by their first folder.
110
+ const untitled = /^workspace(\.json)?$/.test(named);
111
+ return { folders, fallback: untitled ? path.basename(folders[0] ?? "") || "untitled workspace" : named };
112
+ }
113
+ catch {
114
+ return { folders: [], fallback: /^workspace(\.json)?$/.test(named) ? "untitled workspace" : named };
115
+ }
116
+ }
117
+ }
118
+ catch {
119
+ /* no workspace.json */
120
+ }
121
+ return { folders: [], fallback: "untitled workspace" };
122
+ }
123
+ const gitRootCache = new Map();
124
+ /** Nearest ancestor directory of `file` that contains `.git`, or null. */
125
+ export function gitRoot(file) {
126
+ let dir = path.dirname(file);
127
+ const visited = [];
128
+ while (true) {
129
+ const cached = gitRootCache.get(dir);
130
+ if (cached !== undefined) {
131
+ visited.forEach((d) => gitRootCache.set(d, cached));
132
+ return cached;
133
+ }
134
+ visited.push(dir);
135
+ if (fs.existsSync(path.join(dir, ".git"))) {
136
+ visited.forEach((d) => gitRootCache.set(d, dir));
137
+ return dir;
138
+ }
139
+ const up = path.dirname(dir);
140
+ if (up === dir) {
141
+ visited.forEach((d) => gitRootCache.set(d, null));
142
+ return null;
143
+ }
144
+ dir = up;
145
+ }
146
+ }
147
+ /** Most common git repo among the files a session touched. */
148
+ function repoFromFiles(files) {
149
+ const counts = new Map();
150
+ for (const f of files) {
151
+ const root = gitRoot(f);
152
+ if (root)
153
+ counts.set(root, (counts.get(root) ?? 0) + 1);
154
+ }
155
+ const best = [...counts.entries()].sort((a, b) => b[1] - a[1])[0];
156
+ return best ? path.basename(best[0]) : null;
157
+ }
158
+ /**
159
+ * Project for a session: the single workspace folder; in a multi-root workspace the folder
160
+ * holding most touched files; when the workspace is unknown, the git repo of those files.
161
+ */
162
+ function projectFor(ws, files) {
163
+ if (!ws.folders.length)
164
+ return (files.length && repoFromFiles(files)) || ws.fallback;
165
+ if (ws.folders.length === 1 || !files.length)
166
+ return ws.fallback;
167
+ const counts = new Map();
168
+ for (const f of files) {
169
+ const hit = ws.folders.filter((d) => f.startsWith(d.endsWith("/") ? d : d + "/")).sort((a, b) => b.length - a.length)[0];
170
+ if (hit)
171
+ counts.set(hit, (counts.get(hit) ?? 0) + 1);
172
+ }
173
+ const best = [...counts.entries()].sort((a, b) => b[1] - a[1])[0];
174
+ return best ? path.basename(best[0]) : ws.fallback;
175
+ }
176
+ const uriPath = (u) => u?.fsPath ?? u?.path;
177
+ function sessionFiles(userDir) {
178
+ const out = [];
179
+ const wsRoot = path.join(userDir, "workspaceStorage");
180
+ for (const hash of safeReaddir(wsRoot)) {
181
+ const dir = path.join(wsRoot, hash, "chatSessions");
182
+ const names = safeReaddir(dir).filter((n) => n.endsWith(".jsonl") || n.endsWith(".json"));
183
+ if (!names.length)
184
+ continue;
185
+ const ws = workspaceInfo(path.join(wsRoot, hash));
186
+ for (const n of names)
187
+ out.push({ file: path.join(dir, n), ws });
188
+ }
189
+ const empty = path.join(userDir, "globalStorage", "emptyWindowChatSessions");
190
+ for (const n of safeReaddir(empty).filter((n) => n.endsWith(".jsonl") || n.endsWith(".json"))) {
191
+ out.push({ file: path.join(empty, n), ws: { folders: [], fallback: "no folder" } });
192
+ }
193
+ return out;
194
+ }
195
+ function safeReaddir(dir) {
196
+ try {
197
+ return fs.readdirSync(dir).sort();
198
+ }
199
+ catch {
200
+ return [];
201
+ }
202
+ }
203
+ export function hasCopilotVscode(userDirs = vscodeUserDirs()) {
204
+ return userDirs.some((d) => sessionFiles(d).length > 0);
205
+ }
206
+ export async function* readCopilotVscode(report, userDirs = vscodeUserDirs()) {
207
+ const seen = new Set();
208
+ for (const userDir of userDirs) {
209
+ for (const { file, ws } of sessionFiles(userDir)) {
210
+ report.files++;
211
+ let state;
212
+ try {
213
+ state = replaySession(fs.readFileSync(file, "utf8"), report);
214
+ }
215
+ catch {
216
+ report.malformed++;
217
+ continue;
218
+ }
219
+ if (!state || !Array.isArray(state.requests))
220
+ continue;
221
+ const sessionId = `vscode:${state.sessionId ?? path.basename(file).replace(/\.jsonl?$/, "")}`;
222
+ // First pass: every file the session edited, to attribute multi-root workspaces.
223
+ const perRequestFiles = state.requests.map((r) => {
224
+ const files = new Set();
225
+ for (const p of r.response ?? [])
226
+ if (p.kind === "textEditGroup")
227
+ files.add(uriPath(p.uri) ?? "");
228
+ for (const e of r.editedFileEvents ?? [])
229
+ files.add(uriPath(e.uri) ?? "");
230
+ files.delete("");
231
+ return [...files];
232
+ });
233
+ const project = projectFor(ws, perRequestFiles.flat());
234
+ for (const [i, r] of state.requests.entries()) {
235
+ if (typeof r.timestamp !== "number") {
236
+ report.malformed++;
237
+ continue;
238
+ }
239
+ const id = r.requestId ?? `${sessionId}:${i}`;
240
+ if (seen.has(id)) {
241
+ report.duplicates++;
242
+ continue;
243
+ }
244
+ seen.add(id);
245
+ const ts = new Date(r.timestamp);
246
+ const base = { sessionId, project, source: "copilot-vscode" };
247
+ const rawText = r.message?.text ?? "";
248
+ const text = cleanCopilotPrompt(rawText);
249
+ if (r.isSystemInitiated)
250
+ report.excludedUser["copilot:system-initiated"] = (report.excludedUser["copilot:system-initiated"] ?? 0) + 1;
251
+ else if (r.slashCommand || rawText.trimStart().startsWith("/"))
252
+ report.excludedUser["copilot:slash-command"] = (report.excludedUser["copilot:slash-command"] ?? 0) + 1;
253
+ else if (!rawText.trim())
254
+ report.excludedUser["copilot:empty"] = (report.excludedUser["copilot:empty"] ?? 0) + 1;
255
+ else
256
+ yield { kind: "prompt", ts, text, ...base };
257
+ const tools = [];
258
+ for (const p of r.response ?? []) {
259
+ if (p.kind === "toolInvocationSerialized" && p.toolId)
260
+ tools.push({ name: normalizeTool(p.toolId), input: {} });
261
+ }
262
+ const end = r.responseTimestamp ?? (typeof r.elapsedMs === "number" ? r.timestamp + r.elapsedMs : r.timestamp);
263
+ yield {
264
+ kind: "assistant",
265
+ ts: new Date(end),
266
+ messageId: `vscode:${id}`,
267
+ model: stripVendor(r.modelId),
268
+ // VS Code reports the whole prompt (cache hits included) as promptTokens: no cache split.
269
+ usage: { input_tokens: r.promptTokens ?? 0, output_tokens: r.completionTokens ?? 0 },
270
+ tools,
271
+ files: perRequestFiles[i],
272
+ ...base,
273
+ };
274
+ }
275
+ }
276
+ }
277
+ }
@@ -0,0 +1,41 @@
1
+ import { readEvents } from "../parse/reader.js";
2
+ import { copilotHome, hasCopilotCli, readCopilotCli } from "./copilot-cli.js";
3
+ import { hasCopilotVscode, readCopilotVscode, vscodeUserDirs } from "./copilot-vscode.js";
4
+ import fs from "node:fs";
5
+ export const SOURCES = [
6
+ {
7
+ id: "claude",
8
+ name: "Claude Code",
9
+ detect: (p) => fs.existsSync(p.claudeProjects),
10
+ read: (p, r) => readEvents(p.claudeProjects, r),
11
+ },
12
+ {
13
+ id: "copilot-vscode",
14
+ name: "Copilot Chat (VS Code)",
15
+ detect: (p) => hasCopilotVscode(p.vscodeUserDirs ?? vscodeUserDirs()),
16
+ read: (p, r) => readCopilotVscode(r, p.vscodeUserDirs ?? vscodeUserDirs()),
17
+ },
18
+ {
19
+ id: "copilot-cli",
20
+ name: "Copilot CLI",
21
+ detect: (p) => hasCopilotCli(p.copilotHome ?? copilotHome()),
22
+ read: (p, r) => readCopilotCli(r, p.copilotHome ?? copilotHome()),
23
+ },
24
+ ];
25
+ /** `--source` aliases: "all", "claude", "copilot" (both Copilot sources), or exact ids, comma-separated. */
26
+ export function resolveSources(spec, paths) {
27
+ const want = (spec ?? "all").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
28
+ const ids = new Set();
29
+ for (const w of want) {
30
+ if (w === "all" || w === "auto")
31
+ SOURCES.forEach((s) => ids.add(s.id));
32
+ else if (w === "copilot")
33
+ ["copilot-vscode", "copilot-cli"].forEach((id) => ids.add(id));
34
+ else if (SOURCES.some((s) => s.id === w))
35
+ ids.add(w);
36
+ else
37
+ throw new Error(`Unknown --source "${w}". Use all, claude, copilot, copilot-vscode or copilot-cli.`);
38
+ }
39
+ const explicit = !want.includes("all") && !want.includes("auto");
40
+ return SOURCES.filter((s) => ids.has(s.id) && (explicit || s.detect(paths)));
41
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Copilot tool names mapped onto Claude Code's, so the Stack card compares
3
+ * like with like across sources. Unknown names pass through unchanged.
4
+ * Names seen in real VS Code Copilot Chat and Copilot CLI logs (2026).
5
+ */
6
+ const MAP = {
7
+ // read
8
+ copilot_readFile: "Read",
9
+ read_file: "Read",
10
+ view: "Read",
11
+ // edit
12
+ copilot_replaceString: "Edit",
13
+ copilot_multiReplaceString: "Edit",
14
+ copilot_applyPatch: "Edit",
15
+ copilot_insertEdit: "Edit",
16
+ replace_string_in_file: "Edit",
17
+ insert_edit_into_file: "Edit",
18
+ apply_patch: "Edit",
19
+ edit: "Edit",
20
+ str_replace_editor: "Edit",
21
+ // write
22
+ copilot_createFile: "Write",
23
+ create_file: "Write",
24
+ create: "Write",
25
+ // shell
26
+ run_in_terminal: "Bash",
27
+ bash: "Bash",
28
+ get_terminal_output: "BashOutput",
29
+ // search
30
+ copilot_findTextInFiles: "Grep",
31
+ grep_search: "Grep",
32
+ rg: "Grep",
33
+ grep: "Grep",
34
+ copilot_findFiles: "Glob",
35
+ file_search: "Glob",
36
+ glob: "Glob",
37
+ copilot_listDirectory: "LS",
38
+ list_dir: "LS",
39
+ copilot_searchCodebase: "CodebaseSearch",
40
+ semantic_search: "CodebaseSearch",
41
+ // web
42
+ copilot_fetchWebPage: "WebFetch",
43
+ vscode_fetchWebPage_internal: "WebFetch",
44
+ fetch_webpage: "WebFetch",
45
+ // misc
46
+ manage_todo_list: "TodoWrite",
47
+ copilot_memory: "Memory",
48
+ copilot_getErrors: "Diagnostics",
49
+ get_errors: "Diagnostics",
50
+ copilot_createDirectory: "Mkdir",
51
+ vscode_askQuestions: "AskUserQuestion",
52
+ ask_user: "AskUserQuestion",
53
+ tool_search: "ToolSearch",
54
+ tool_search_tool: "ToolSearch",
55
+ rename_chat: "RenameChat",
56
+ };
57
+ export function normalizeTool(name) {
58
+ return MAP[name] ?? name;
59
+ }
60
+ /** Paths named in an apply_patch body ("*** Update File: src/a.ts"). */
61
+ export function patchPaths(patch) {
62
+ const out = [];
63
+ for (const m of patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))
64
+ out.push(m[1].trim());
65
+ return out;
66
+ }
67
+ /** "copilot/claude-haiku-4.5" -> "claude-haiku-4.5". */
68
+ export function stripVendor(model) {
69
+ if (!model)
70
+ return undefined;
71
+ return model.includes("/") ? model.slice(model.lastIndexOf("/") + 1) : model;
72
+ }
73
+ /**
74
+ * Copilot Chat prompt text includes UI syntax: a leading "@agent" participant, "#file:x" /
75
+ * "#attachment:pasted text #1" variables, and the "Continue to iterate?" button, which sends
76
+ * `@agent Continue: "Continue to iterate?"`. Return what the human actually said.
77
+ */
78
+ export function cleanCopilotPrompt(text) {
79
+ let t = text.trim();
80
+ if (/^(@\w+\s+)?continue:\s*"?continue to iterate\??"?$/i.test(t))
81
+ return "continue";
82
+ t = t.replace(/^@[\w-]+\s*/, "");
83
+ t = t.replace(/#attachment:[^#\n]*?#\d+/gi, " ");
84
+ t = t.replace(/#(?:file|attachment|selection|codebase|terminalSelection|terminalLastCommand|editor|sym|fetch|problems|changes|githubRepo|searchResults|testFailure)(?::\S+)?/g, " ");
85
+ return t.replace(/[ \t]{2,}/g, " ").trim();
86
+ }
@@ -0,0 +1,285 @@
1
+ import { FILE_TOOLS, languageForPath } from "./languages.js";
2
+ import { SOURCE_NAMES } from "./schema.js";
3
+ import { extractWords, machineWords, normalizeShortPrompt, redactSecrets, truncate } from "./words.js";
4
+ export const SESSION_GAP_MS = 30 * 60 * 1000;
5
+ export const SAMPLE_SIZE = 300;
6
+ export const SAMPLE_CHARS = 300;
7
+ /** A single prompt adds at most this many to any one word, so a pasted log can't win the year. */
8
+ export const MAX_WORD_HITS_PER_PROMPT = 3;
9
+ /**
10
+ * Rhythm label thresholds (share of prompts). The label whose share beats its
11
+ * threshold by the largest ratio wins; if none does, you're a 9-to-5er.
12
+ * Night Owl: 22:00–03:59 >= 25%
13
+ * Early Bird: 05:00–08:59 >= 20%
14
+ * Weekend Warrior: Sat + Sun >= 40%
15
+ */
16
+ export const RHYTHM_THRESHOLDS = { night: 0.25, early: 0.2, weekend: 0.4 };
17
+ const NIGHT_HOURS = new Set([22, 23, 0, 1, 2, 3]);
18
+ const EARLY_HOURS = new Set([5, 6, 7, 8]);
19
+ /** Local calendar date as YYYY-MM-DD. */
20
+ export function localDate(d) {
21
+ const y = d.getFullYear();
22
+ const m = String(d.getMonth() + 1).padStart(2, "0");
23
+ const day = String(d.getDate()).padStart(2, "0");
24
+ return `${y}-${m}-${day}`;
25
+ }
26
+ /** One id per model across tools: "claude-opus-5-5" / "claude-opus-5.5-20260101" -> "claude-opus-5.5". */
27
+ export function canonicalModel(id) {
28
+ const m = /^(claude-[a-z]+-\d+)[-.](\d{1,2})(?:-\d{8})?$/.exec(id);
29
+ if (m)
30
+ return `${m[1]}.${m[2]}`;
31
+ return id.replace(/-\d{8}$/, "");
32
+ }
33
+ function topN(map, n) {
34
+ return [...map.entries()]
35
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
36
+ .slice(0, n)
37
+ .map(([name, count]) => ({ name, count }));
38
+ }
39
+ function bump(map, key, by = 1) {
40
+ map.set(key, (map.get(key) ?? 0) + by);
41
+ }
42
+ export class StatsEngine {
43
+ year;
44
+ random;
45
+ now;
46
+ excludeWords;
47
+ prompts = 0;
48
+ sessions = new Set();
49
+ sessionTimes = new Map();
50
+ messages = new Map();
51
+ hours = new Array(24).fill(0);
52
+ weekdays = new Array(7).fill(0); // Monday first
53
+ days = new Map();
54
+ afterMidnight = 0;
55
+ projects = new Map();
56
+ tools = new Map();
57
+ languages = new Map();
58
+ words = new Map();
59
+ repeats = new Map();
60
+ samples = [];
61
+ bySource = new Map();
62
+ first = null;
63
+ last = null;
64
+ constructor(opts) {
65
+ this.year = opts.year;
66
+ this.random = opts.random ?? Math.random;
67
+ this.now = opts.now ?? new Date();
68
+ this.excludeWords = opts.excludeWords ?? machineWords();
69
+ }
70
+ add(e) {
71
+ if (e.ts.getFullYear() !== this.year)
72
+ return;
73
+ const t = e.ts.getTime();
74
+ if (!this.first || t < this.first.getTime())
75
+ this.first = e.ts;
76
+ if (!this.last || t > this.last.getTime())
77
+ this.last = e.ts;
78
+ const times = this.sessionTimes.get(e.sessionId) ?? [];
79
+ times.push(t);
80
+ this.sessionTimes.set(e.sessionId, times);
81
+ const src = this.source(e.source ?? "claude");
82
+ if (e.kind === "prompt") {
83
+ src.prompts++;
84
+ src.sessions.add(e.sessionId);
85
+ this.addPrompt(e.ts, e.sessionId, e.project, e.text);
86
+ }
87
+ else if (e.kind === "assistant") {
88
+ src.sessions.add(e.sessionId);
89
+ src.turns.add(e.messageId);
90
+ this.addAssistant(e);
91
+ }
92
+ else if (e.kind === "tool") {
93
+ this.addTools(e.tools, e.files);
94
+ }
95
+ }
96
+ source(id) {
97
+ let s = this.bySource.get(id);
98
+ if (!s)
99
+ this.bySource.set(id, (s = { prompts: 0, sessions: new Set(), turns: new Set() }));
100
+ return s;
101
+ }
102
+ addTools(tools, files) {
103
+ for (const call of tools) {
104
+ bump(this.tools, call.name);
105
+ for (const key of FILE_TOOLS[call.name] ?? []) {
106
+ const p = call.input[key];
107
+ if (typeof p === "string") {
108
+ const lang = languageForPath(p);
109
+ if (lang)
110
+ bump(this.languages, lang);
111
+ }
112
+ }
113
+ }
114
+ for (const f of files ?? []) {
115
+ const lang = languageForPath(f);
116
+ if (lang)
117
+ bump(this.languages, lang);
118
+ }
119
+ }
120
+ addPrompt(ts, sessionId, project, text) {
121
+ this.prompts++;
122
+ this.sessions.add(sessionId);
123
+ const h = ts.getHours();
124
+ this.hours[h]++;
125
+ this.weekdays[(ts.getDay() + 6) % 7]++;
126
+ bump(this.days, localDate(ts));
127
+ if (h < 5)
128
+ this.afterMidnight++;
129
+ bump(this.projects, project);
130
+ const perPrompt = new Map();
131
+ for (const w of extractWords(text, this.excludeWords))
132
+ bump(perPrompt, w);
133
+ for (const [w, n] of perPrompt)
134
+ bump(this.words, w, Math.min(n, MAX_WORD_HITS_PER_PROMPT));
135
+ const short = normalizeShortPrompt(text);
136
+ if (short)
137
+ bump(this.repeats, short);
138
+ // Reservoir sampling (Algorithm R) so samples are uniform over the year.
139
+ const clean = text.trim();
140
+ if (clean) {
141
+ const sample = { text: truncate(redactSecrets(clean), SAMPLE_CHARS) };
142
+ if (this.samples.length < SAMPLE_SIZE)
143
+ this.samples.push(sample);
144
+ else {
145
+ const j = Math.floor(this.random() * this.prompts);
146
+ if (j < SAMPLE_SIZE)
147
+ this.samples[j] = sample;
148
+ }
149
+ }
150
+ }
151
+ addAssistant(e) {
152
+ this.sessions.add(e.sessionId);
153
+ // Each content block of one API message is its own line with the same usage: keep the max.
154
+ const acc = this.messages.get(e.messageId) ?? { input: 0, output: 0, cacheCreation: 0, cacheRead: 0, model: e.model };
155
+ const u = e.usage;
156
+ if (u) {
157
+ acc.input = Math.max(acc.input, u.input_tokens ?? 0);
158
+ acc.output = Math.max(acc.output, u.output_tokens ?? 0);
159
+ acc.cacheCreation = Math.max(acc.cacheCreation, u.cache_creation_input_tokens ?? 0);
160
+ acc.cacheRead = Math.max(acc.cacheRead, u.cache_read_input_tokens ?? 0);
161
+ }
162
+ acc.model ??= e.model;
163
+ this.messages.set(e.messageId, acc);
164
+ this.addTools(e.tools, e.files);
165
+ }
166
+ estimateHours() {
167
+ let ms = 0;
168
+ for (const times of this.sessionTimes.values()) {
169
+ times.sort((a, b) => a - b);
170
+ let start = times[0];
171
+ let prev = start;
172
+ for (const t of times.slice(1)) {
173
+ if (t - prev > SESSION_GAP_MS) {
174
+ ms += prev - start;
175
+ start = t;
176
+ }
177
+ prev = t;
178
+ }
179
+ ms += prev - start;
180
+ }
181
+ return Math.round((ms / 3_600_000) * 10) / 10;
182
+ }
183
+ streak() {
184
+ const dates = [...this.days.keys()].sort();
185
+ let best = { days: 0, start: null, end: null };
186
+ let runStart = "";
187
+ let run = 0;
188
+ let prev = null;
189
+ for (const d of dates) {
190
+ const cur = new Date(`${d}T12:00:00`);
191
+ const consecutive = prev && Math.round((cur.getTime() - prev.getTime()) / 86_400_000) === 1;
192
+ if (consecutive)
193
+ run++;
194
+ else {
195
+ run = 1;
196
+ runStart = d;
197
+ }
198
+ if (run > best.days)
199
+ best = { days: run, start: runStart, end: d };
200
+ prev = cur;
201
+ }
202
+ return best;
203
+ }
204
+ label(shares) {
205
+ const candidates = [
206
+ ["Night Owl", shares.night / RHYTHM_THRESHOLDS.night],
207
+ ["Early Bird", shares.early / RHYTHM_THRESHOLDS.early],
208
+ ["Weekend Warrior", shares.weekend / RHYTHM_THRESHOLDS.weekend],
209
+ ];
210
+ const best = candidates.sort((a, b) => b[1] - a[1])[0];
211
+ return best[1] >= 1 ? best[0] : "9-to-5er";
212
+ }
213
+ finish(parse) {
214
+ const tokens = { input: 0, output: 0, cacheCreation: 0, cacheRead: 0, total: 0 };
215
+ const models = new Map();
216
+ for (const m of this.messages.values()) {
217
+ tokens.input += m.input;
218
+ tokens.output += m.output;
219
+ tokens.cacheCreation += m.cacheCreation;
220
+ tokens.cacheRead += m.cacheRead;
221
+ if (m.model && m.model !== "<synthetic>")
222
+ bump(models, canonicalModel(m.model));
223
+ }
224
+ tokens.total = tokens.input + tokens.output + tokens.cacheCreation + tokens.cacheRead;
225
+ const modelTotal = [...models.values()].reduce((a, b) => a + b, 0) || 1;
226
+ const p = this.prompts || 1;
227
+ let night = 0;
228
+ let early = 0;
229
+ this.hours.forEach((n, h) => {
230
+ if (NIGHT_HOURS.has(h))
231
+ night += n;
232
+ if (EARLY_HOURS.has(h))
233
+ early += n;
234
+ });
235
+ const weekend = this.weekdays[5] + this.weekdays[6];
236
+ const round3 = (x) => Math.round(x * 1000) / 1000;
237
+ const shares = { night: round3(night / p), early: round3(early / p), weekend: round3(weekend / p) };
238
+ const busiest = topN(this.days, 1)[0];
239
+ const topWords = topN(this.words, 10);
240
+ const stats = {
241
+ version: 1,
242
+ year: this.year,
243
+ generatedAt: this.now.toISOString(),
244
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
245
+ range: { first: this.first?.toISOString() ?? null, last: this.last?.toISOString() ?? null },
246
+ totals: {
247
+ sessions: this.sessions.size,
248
+ prompts: this.prompts,
249
+ assistantTurns: this.messages.size,
250
+ tokens,
251
+ activeDays: this.days.size,
252
+ hours: this.estimateHours(),
253
+ },
254
+ rhythm: {
255
+ hours: this.hours,
256
+ weekdays: this.weekdays,
257
+ longestStreak: this.streak(),
258
+ busiestDay: busiest ? { date: busiest.name, prompts: busiest.count } : null,
259
+ afterMidnight: this.afterMidnight,
260
+ label: this.prompts ? this.label(shares) : "9-to-5er",
261
+ shares,
262
+ },
263
+ stack: {
264
+ projects: topN(this.projects, 5),
265
+ tools: topN(this.tools, 10),
266
+ models: topN(models, 10).map((m) => ({ ...m, pct: Math.round((m.count / modelTotal) * 1000) / 10 })),
267
+ languages: topN(this.languages, 8),
268
+ },
269
+ words: {
270
+ wordOfYear: topWords[0] ?? null,
271
+ topWords,
272
+ repeatPrompts: topN(this.repeats, 50)
273
+ .filter((r) => r.count >= 2)
274
+ .slice(0, 5)
275
+ .map((r) => ({ text: r.name, count: r.count })),
276
+ },
277
+ sources: [...this.bySource.entries()]
278
+ .filter(([, v]) => v.prompts > 0 || v.turns.size > 0)
279
+ .sort((a, b) => b[1].prompts - a[1].prompts)
280
+ .map(([id, v]) => ({ id, name: SOURCE_NAMES[id], prompts: v.prompts, sessions: v.sessions.size, assistantTurns: v.turns.size })),
281
+ parse,
282
+ };
283
+ return { stats, samples: this.samples };
284
+ }
285
+ }