coauthored 0.0.0-stage → 1.0.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.
Files changed (130) hide show
  1. package/LICENSE +21 -0
  2. package/PRIVACY.md +107 -0
  3. package/README.md +113 -3
  4. package/THIRD_PARTY_LICENSES.md +105 -0
  5. package/dist/cli/analytics/anchors.js +39 -0
  6. package/dist/cli/analytics/archetypes.js +193 -0
  7. package/dist/cli/analytics/content/analyzer.js +945 -0
  8. package/dist/cli/analytics/content/classify.js +115 -0
  9. package/dist/cli/analytics/content/demo-corpus.js +301 -0
  10. package/dist/cli/analytics/content/sketch.js +54 -0
  11. package/dist/cli/analytics/dataset.js +321 -0
  12. package/dist/cli/analytics/demo-fixtures.js +531 -0
  13. package/dist/cli/analytics/fdr.js +183 -0
  14. package/dist/cli/analytics/helicorder.js +66 -0
  15. package/dist/cli/analytics/insights.js +589 -0
  16. package/dist/cli/analytics/models.js +75 -0
  17. package/dist/cli/analytics/pricing.js +121 -0
  18. package/dist/cli/analytics/probable-cause.js +115 -0
  19. package/dist/cli/analytics/report-builder.js +162 -0
  20. package/dist/cli/analytics/statistics.js +91 -0
  21. package/dist/cli/analytics/time.js +252 -0
  22. package/dist/cli/cli/args.js +105 -0
  23. package/dist/cli/cli/browser.js +71 -0
  24. package/dist/cli/cli/index.js +20 -0
  25. package/dist/cli/cli/main.js +520 -0
  26. package/dist/cli/cli/phrase-review.js +78 -0
  27. package/dist/cli/cli/server.js +481 -0
  28. package/dist/cli/cli/terminal.js +363 -0
  29. package/dist/cli/ingest/adapters/aider.js +116 -0
  30. package/dist/cli/ingest/adapters/claude-code.js +139 -0
  31. package/dist/cli/ingest/adapters/cline-roo.js +89 -0
  32. package/dist/cli/ingest/adapters/codex-cli.js +240 -0
  33. package/dist/cli/ingest/adapters/content.js +99 -0
  34. package/dist/cli/ingest/adapters/cursor-ide.js +149 -0
  35. package/dist/cli/ingest/adapters/gemini-cli.js +208 -0
  36. package/dist/cli/ingest/adapters/index.js +18 -0
  37. package/dist/cli/ingest/adapters/opencode.js +203 -0
  38. package/dist/cli/ingest/adapters/pi-agent.js +85 -0
  39. package/dist/cli/ingest/adapters/shared.js +484 -0
  40. package/dist/cli/ingest/content-sink.js +31 -0
  41. package/dist/cli/ingest/discovery.js +50 -0
  42. package/dist/cli/ingest/message-digests.js +61 -0
  43. package/dist/cli/ingest/pipeline.js +155 -0
  44. package/dist/cli/ingest/safe-fs.js +284 -0
  45. package/dist/cli/ingest/sqlite-stage.js +139 -0
  46. package/dist/cli/ingest/time-window.js +34 -0
  47. package/dist/cli/ingest/tool-map.js +24 -0
  48. package/dist/cli/ingest/types.js +1 -0
  49. package/dist/cli/ingest/worker.js +97 -0
  50. package/dist/cli/report/content/emoji-names.js +3956 -0
  51. package/dist/cli/report/content/insights.js +41 -0
  52. package/dist/cli/report/content/lexicons.js +112 -0
  53. package/dist/cli/report/content/policy.js +77 -0
  54. package/dist/cli/report/content/redact.js +164 -0
  55. package/dist/cli/report/content/stopwords.js +8848 -0
  56. package/dist/cli/report/content/suppression.js +2617 -0
  57. package/dist/cli/report/content/validate.js +152 -0
  58. package/dist/cli/report/copy-lint.js +105 -0
  59. package/dist/cli/report/share.js +132 -0
  60. package/dist/cli/report/types.js +1 -0
  61. package/dist/cli/report/validators.js +334 -0
  62. package/dist/web/assets/Archivo-VF-BohoA-Sn.woff2 +0 -0
  63. package/dist/web/assets/DelaGothicOne-subset-CpoJGhTq.woff2 +0 -0
  64. package/dist/web/assets/Film-Dq8Xxn7U.css +1 -0
  65. package/dist/web/assets/MartianMono-VF-CmJ1nXx9.woff2 +0 -0
  66. package/dist/web/assets/app-DEQgytaq.js +38 -0
  67. package/dist/web/assets/bricolage-grotesque-latin-700-normal-gtcctNPv.woff2 +0 -0
  68. package/dist/web/assets/bricolage-grotesque-latin-800-normal-J50vIsBe.woff2 +0 -0
  69. package/dist/web/assets/chorus-D7bfON5Z.ogg +0 -0
  70. package/dist/web/assets/chorus-bass-CBTKpMv_.ogg +0 -0
  71. package/dist/web/assets/chorus-drums-BOzgLSoq.ogg +0 -0
  72. package/dist/web/assets/chorus-harmony-DnJYs_tp.ogg +0 -0
  73. package/dist/web/assets/chorus-lead-CFpg5DC1.ogg +0 -0
  74. package/dist/web/assets/chunk-BNfsY4o8.js +1 -0
  75. package/dist/web/assets/chunk-BSm8IhPY.js +1 -0
  76. package/dist/web/assets/chunk-Bi6EQAkf.js +1 -0
  77. package/dist/web/assets/chunk-BmDwUWlX.js +1 -0
  78. package/dist/web/assets/chunk-Ds4joAI5.js +46 -0
  79. package/dist/web/assets/chunk-V3YGpFIw.js +1 -0
  80. package/dist/web/assets/chunk-XGhNFWse.js +1 -0
  81. package/dist/web/assets/dialogue-card-A5zmbNhu.ogg +0 -0
  82. package/dist/web/assets/groove-bass-BFNelLKi.ogg +0 -0
  83. package/dist/web/assets/groove-drums-BY1SBntR.ogg +0 -0
  84. package/dist/web/assets/groove-harmony-C0CrBzu3.ogg +0 -0
  85. package/dist/web/assets/groove-lead-CEYPzm5U.ogg +0 -0
  86. package/dist/web/assets/groove-ln-zQmTb.ogg +0 -0
  87. package/dist/web/assets/guess-high-CL6mF18x.ogg +0 -0
  88. package/dist/web/assets/guess-low-C3UnKayZ.ogg +0 -0
  89. package/dist/web/assets/higher-BevsMIWl.ogg +0 -0
  90. package/dist/web/assets/identity-0EPS3msD.ogg +0 -0
  91. package/dist/web/assets/index-DpT0dtHc.css +1 -0
  92. package/dist/web/assets/intro-DeRh6kUx.ogg +0 -0
  93. package/dist/web/assets/intro-bass-D63IPU0H.ogg +0 -0
  94. package/dist/web/assets/intro-drums-Dt9QO534.ogg +0 -0
  95. package/dist/web/assets/intro-harmony-DBsMG9jJ.ogg +0 -0
  96. package/dist/web/assets/intro-lead-DWcWS1ia.ogg +0 -0
  97. package/dist/web/assets/jar-coin-rtCvspuq.ogg +0 -0
  98. package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  99. package/dist/web/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  100. package/dist/web/assets/ledger-tick-C1rQgQGX.ogg +0 -0
  101. package/dist/web/assets/night-B_bMOZcf.ogg +0 -0
  102. package/dist/web/assets/night-bass-B-7Ay9ME.ogg +0 -0
  103. package/dist/web/assets/night-drums-zEtqWXX3.ogg +0 -0
  104. package/dist/web/assets/night-harmony-C5Ix2yce.ogg +0 -0
  105. package/dist/web/assets/night-lead-B7KMlRyj.ogg +0 -0
  106. package/dist/web/assets/ourturn-DX78hTEz.ogg +0 -0
  107. package/dist/web/assets/plus-jakarta-sans-latin-400-normal-Dhut76fR.woff2 +0 -0
  108. package/dist/web/assets/plus-jakarta-sans-latin-500-normal-Bf-nb4oT.woff2 +0 -0
  109. package/dist/web/assets/plus-jakarta-sans-latin-600-normal-DLTa1BUW.woff2 +0 -0
  110. package/dist/web/assets/plus-jakarta-sans-latin-700-normal-CfpNZvy6.woff2 +0 -0
  111. package/dist/web/assets/reveal-BmWAGHih.ogg +0 -0
  112. package/dist/web/assets/review-split-Dac4zagw.ogg +0 -0
  113. package/dist/web/assets/shutter-uhz2Y9S9.ogg +0 -0
  114. package/dist/web/assets/soclose-CiUFR5St.ogg +0 -0
  115. package/dist/web/assets/stinger-TnnzHAMN.ogg +0 -0
  116. package/dist/web/assets/stomp-mzIk4cGm.ogg +0 -0
  117. package/dist/web/assets/syne-latin-700-normal-AF3Rs61n.woff2 +0 -0
  118. package/dist/web/assets/syne-latin-800-normal-EehdNYzx.woff2 +0 -0
  119. package/dist/web/assets/tension-BHvWG5ru.ogg +0 -0
  120. package/dist/web/assets/tension-bass-4G-2qA9W.ogg +0 -0
  121. package/dist/web/assets/tension-drums-D7sdehJr.ogg +0 -0
  122. package/dist/web/assets/tension-harmony-FyPldmLb.ogg +0 -0
  123. package/dist/web/assets/tension-lead-C5uoFMR8.ogg +0 -0
  124. package/dist/web/assets/why-clock-Dzs1A_ym.ogg +0 -0
  125. package/dist/web/favicon.svg +1 -0
  126. package/dist/web/index.html +16 -0
  127. package/dist/web/licenses/OFL-Archivo.txt +93 -0
  128. package/dist/web/licenses/OFL-DelaGothic.txt +93 -0
  129. package/dist/web/licenses/OFL-MartianMono.txt +93 -0
  130. package/package.json +63 -6
@@ -0,0 +1,89 @@
1
+ import { basename, dirname, join, resolve } from 'node:path';
2
+ import { contentExcluded } from './content.js';
3
+ import { arr, count, defineAdapter, hasCounts, ideUserRoot, obj, parseJson, segments, str, timestamp, tokens } from './shared.js';
4
+ const fields = ['tokensIn', 'tokensOut', 'cacheWrites', 'cacheReads'];
5
+ function extensionAdapter(id, displayName, extensionId, directory) {
6
+ return defineAdapter({
7
+ id, displayName, tier: 2, defaultRetentionDays: null,
8
+ roots(options) {
9
+ const { homeDir, env } = options;
10
+ const custom = id === 'roo-code' ? env.ROO_CODE_STORAGE_PATH : undefined;
11
+ return [
12
+ ...(custom ? [join(custom, 'tasks')] : []),
13
+ ...['Code', 'Code - Insiders', 'VSCodium'].map(product => join(ideUserRoot(product, options), 'globalStorage', extensionId, 'tasks')),
14
+ ...['.vscode-server', '.vscode-server-insiders'].map(product => join(homeDir, product, 'data', 'User', 'globalStorage', extensionId, 'tasks')),
15
+ ];
16
+ },
17
+ matches(path) {
18
+ const parts = segments(path);
19
+ return basename(path) === 'ui_messages.json' && parts.at(-3) === 'tasks' &&
20
+ (parts.includes(extensionId) || parts.includes(directory) || (id === 'roo-code' && parts.includes('roo')));
21
+ },
22
+ configuredMatch: (path, root, { env }) => id === 'roo-code' && Boolean(env.ROO_CODE_STORAGE_PATH) &&
23
+ resolve(root) === resolve(env.ROO_CODE_STORAGE_PATH, 'tasks') &&
24
+ basename(path) === 'ui_messages.json' && segments(path).at(-3) === 'tasks',
25
+ async parse(state, files) {
26
+ for (const path of files) {
27
+ const session = basename(dirname(path));
28
+ await state.json(path, value => {
29
+ let pending;
30
+ const emit = (request) => {
31
+ const { ts, id: requestId, usage } = request;
32
+ if (!hasCounts(usage, fields))
33
+ return;
34
+ state.request(session, ts, JSON.stringify([session, requestId]), tokens(count(usage.tokensIn), count(usage.tokensOut), count(usage.cacheReads), count(usage.cacheWrites)), { model: str(usage.modelId, usage.model), provider: usage.provider, cache: hasCounts(usage, ['cacheWrites', 'cacheReads']) });
35
+ };
36
+ const entries = arr(value);
37
+ const child = state.ctx.content && entries.some(raw => {
38
+ const row = obj(raw);
39
+ return Boolean(row.parentTaskId || row.rootTaskId && row.rootTaskId !== session || row.isSubtask || row.isSubagent);
40
+ });
41
+ for (const [index, raw] of entries.entries()) {
42
+ const row = obj(raw);
43
+ const ts = timestamp(row.ts, row.timestamp);
44
+ if (ts === undefined)
45
+ continue;
46
+ state.session(session, ts);
47
+ const action = str(row.say, row.ask);
48
+ const event = str(row.id) ?? JSON.stringify([ts, index]);
49
+ if (action === 'task' || action === 'user_feedback' || action === 'user_message' ||
50
+ (index === 0 && row.type === 'say' && action === 'text'))
51
+ state.prompt(session, ts, event);
52
+ if (state.ctx.content && (action === 'tool' || action === 'command') && typeof row.text === 'string') {
53
+ state.identifiers(row.text);
54
+ }
55
+ if (state.ctx.content && !contentExcluded(row) && typeof row.text === 'string') {
56
+ // A task header can be a delegation. Some logs carry no lineage on the UI rows.
57
+ const rootTask = row.rootTaskId === session || row.parentTaskId === null || row.isSubtask === false;
58
+ if (!child && (action === 'task' && rootTask || action === 'user_feedback' || action === 'user_message')) {
59
+ state.content('user', session, ts, event, row.text);
60
+ }
61
+ else if (index > 0 && row.type === 'say' && row.say === 'text' && row.partial !== true) {
62
+ state.content('agent', session, ts, event, row.text);
63
+ }
64
+ }
65
+ if (action === 'api_req_started') {
66
+ if (pending)
67
+ emit(pending);
68
+ pending = { ts, id: event, usage: obj(parseJson(row.text ?? row.usage)) };
69
+ }
70
+ else if (action === 'api_req_finished') {
71
+ const usage = obj(parseJson(row.text ?? row.usage));
72
+ if (pending) {
73
+ emit({ ...pending, usage: { ...pending.usage, ...usage } });
74
+ pending = undefined;
75
+ }
76
+ else {
77
+ emit({ ts, id: event, usage });
78
+ }
79
+ }
80
+ }
81
+ if (pending)
82
+ emit(pending);
83
+ });
84
+ }
85
+ },
86
+ });
87
+ }
88
+ export const clineAdapter = extensionAdapter('cline', 'Cline', 'saoudrizwan.claude-dev', 'cline');
89
+ export const rooCodeAdapter = extensionAdapter('roo-code', 'Roo Code', 'rooveterinaryinc.roo-cline', 'roo-code');
@@ -0,0 +1,240 @@
1
+ import { basename, join } from 'node:path';
2
+ import { contentExcluded, DeferredContent, textParts } from './content.js';
3
+ import { count, defineAdapter, fileSession, hasCounts, obj, parseJson, str, timestamp, tokens } from './shared.js';
4
+ const axes = ['input_tokens', 'cached_input_tokens', 'cache_write_input_tokens', 'output_tokens', 'reasoning_output_tokens'];
5
+ const isUsage = (value) => hasCounts(value, ['input_tokens', 'output_tokens']);
6
+ const values = (row) => axes.map(axis => count(row[axis]));
7
+ const equals = (a, b) => a.every((value, i) => value === b[i]);
8
+ export const codexCliAdapter = defineAdapter({
9
+ id: 'codex-cli', displayName: 'Codex CLI', tier: 1, defaultRetentionDays: null,
10
+ roots: ({ env, homeDir }) => {
11
+ const home = env.CODEX_HOME || join(homeDir, '.codex');
12
+ return [join(home, 'sessions'), join(home, 'archived_sessions')];
13
+ },
14
+ matches(path) {
15
+ return /^rollout[-_].*\.jsonl$/i.test(basename(path));
16
+ },
17
+ async parse(state, files) {
18
+ for (const path of files) {
19
+ let session = fileSession(path);
20
+ let model;
21
+ let provider;
22
+ let cwd;
23
+ let parent;
24
+ let fork;
25
+ let child = false;
26
+ let cutoff;
27
+ let turn;
28
+ let baseline;
29
+ const native = [];
30
+ const legacy = [];
31
+ const prompts = new Map();
32
+ const text = state.ctx.content && new DeferredContent(() => state.ctx.content?.skip());
33
+ const outcomes = new Map();
34
+ const calls = new Map();
35
+ await state.jsonl(path, (row, ordinal) => {
36
+ const p = obj(row.payload);
37
+ const ts = timestamp(row.timestamp, p.timestamp);
38
+ if (row.type === 'session_meta') {
39
+ session = str(p.id, p.session_id, p.thread_id, session);
40
+ cwd = str(p.cwd);
41
+ provider = p.model_provider;
42
+ model = p.model;
43
+ const source = obj(p.source);
44
+ const subagent = obj(source.subagent);
45
+ const spawn = obj(subagent.thread_spawn);
46
+ parent = str(spawn.parent_thread_id, p.parent_thread_id, p.parent_session_id);
47
+ child = Boolean(source.subagent || parent);
48
+ fork = str(p.forked_from_id, obj(p.forked_from).id);
49
+ const boundary = p.forked_from_ordinal_exclusive ?? obj(p.forked_from).ordinal_exclusive;
50
+ if (typeof boundary === 'number' && Number.isSafeInteger(boundary))
51
+ cutoff = boundary;
52
+ state.session(session, ts, cwd, child, parent);
53
+ return;
54
+ }
55
+ const at = typeof row.ordinal === 'number' ? row.ordinal : typeof p.ordinal === 'number' ? p.ordinal : ordinal - 1;
56
+ const origin = str(p.origin_thread_id, p.source_thread_id, row.origin_thread_id);
57
+ const owner = str(p.thread_id, p.session_id);
58
+ const replay = Boolean(fork && ((cutoff !== undefined && at < cutoff) || origin === fork || owner === fork));
59
+ if (row.type === 'turn_context') {
60
+ model = p.model ?? model;
61
+ turn = str(p.turn_id, p.id);
62
+ }
63
+ if (ts === undefined)
64
+ return;
65
+ if (!replay)
66
+ state.session(session, ts, cwd, child, parent);
67
+ const eventId = str(p.id, row.id) ?? JSON.stringify([ts, at]);
68
+ if (row.type === 'token_usage_record' || (row.type === 'event_msg' && p.type === 'token_usage_record')) {
69
+ const data = obj(p.usage);
70
+ if (!replay && isUsage(data))
71
+ native.push({
72
+ ts, data, id: str(p.response_id), turn: str(p.turn_id, turn), model: p.model ?? model, provider: p.model_provider ?? provider,
73
+ scope: str(p.origin_thread_id, p.thread_id, session),
74
+ });
75
+ return;
76
+ }
77
+ if (row.type === 'event_msg' && p.type === 'token_count') {
78
+ const info = obj(p.info);
79
+ const total = obj(info.total_token_usage);
80
+ const last = obj(info.last_token_usage);
81
+ if (!isUsage(total) || p.fill_to_context_window || info.fill_to_context_window)
82
+ return;
83
+ const current = values(total);
84
+ const previous = baseline;
85
+ baseline = current;
86
+ if (replay)
87
+ return;
88
+ if (previous && equals(previous, current))
89
+ return;
90
+ const monotone = previous && current.every((value, i) => value >= previous[i]);
91
+ let delta;
92
+ if (monotone)
93
+ delta = current.map((value, i) => value - previous[i]);
94
+ else if (isUsage(last))
95
+ delta = values(last);
96
+ else if (!previous && current.some(Boolean))
97
+ delta = current;
98
+ else
99
+ return;
100
+ if (delta.some(Boolean))
101
+ legacy.push({
102
+ ts, id: str(p.response_id, info.response_id), turn: str(p.turn_id, turn), model,
103
+ data: Object.fromEntries(axes.map((axis, i) => [axis, delta[i]])),
104
+ cache: hasCounts(total, ['cached_input_tokens', 'cache_write_input_tokens']),
105
+ reasoning: hasCounts(total, ['reasoning_output_tokens']),
106
+ });
107
+ return;
108
+ }
109
+ if (replay)
110
+ return;
111
+ if (!child && !p.is_automated && !p.is_meta &&
112
+ ((row.type === 'event_msg' && p.type === 'user_message') ||
113
+ (row.type === 'response_item' && p.type === 'message' && p.role === 'user'))) {
114
+ const explicit = row.type === 'event_msg';
115
+ // Legacy logs often emit both the response item and the user event for a single turn.
116
+ const key = str(p.turn_id, turn) ?? eventId;
117
+ if (!prompts.has(key) || explicit) {
118
+ prompts.set(key, { ts, explicit, turn: str(p.turn_id, turn) });
119
+ if (text)
120
+ text.set(key, !contentExcluded(row, p) && (!fork || origin === session || owner === session || cutoff !== undefined)
121
+ ? explicit ? (typeof p.message === 'string' ? p.message : undefined)
122
+ : Array.isArray(p.content) ? textParts(p.content, 'input_text') : undefined
123
+ : undefined);
124
+ }
125
+ }
126
+ if (row.type === 'compacted' || (row.type === 'event_msg' && p.type === 'context_compacted')) {
127
+ state.compact(session, ts, eventId, p.trigger);
128
+ }
129
+ if (row.type === 'event_msg' && (p.type === 'turn_aborted' || p.type === 'turn_interrupted'))
130
+ state.interrupt(session, ts, eventId);
131
+ if (row.type === 'response_item') {
132
+ if (state.ctx.content && p.type === 'message' && p.role === 'assistant' && Array.isArray(p.content) &&
133
+ !contentExcluded(row, p) && (!fork || origin === session || owner === session || cutoff !== undefined)) {
134
+ state.content('agent', session, ts, eventId, textParts(p.content, 'output_text'));
135
+ }
136
+ if (['function_call', 'custom_tool_call', 'local_shell_call', 'web_search_call'].includes(String(p.type))) {
137
+ if (state.ctx.content)
138
+ state.identifiers([p.arguments, p.input, p.action]);
139
+ const name = str(p.name, p.type === 'local_shell_call' ? 'shell_command' : p.type === 'web_search_call' ? 'web_search' : undefined);
140
+ if (name)
141
+ calls.set(str(p.call_id) ?? eventId, { ts, name });
142
+ }
143
+ else if (['function_call_output', 'custom_tool_call_output'].includes(String(p.type))) {
144
+ const callId = str(p.call_id);
145
+ if (callId) {
146
+ const parsed = obj(parseJson(p.output));
147
+ const meta = obj(parsed.metadata);
148
+ const exitCode = typeof parsed.exit_code === 'number' ? parsed.exit_code
149
+ : typeof meta.exit_code === 'number' ? meta.exit_code : undefined;
150
+ if (typeof parsed.success === 'boolean') {
151
+ outcomes.set(callId, !parsed.success);
152
+ }
153
+ else if (exitCode !== undefined && Number.isFinite(exitCode)) {
154
+ outcomes.set(callId, exitCode !== 0);
155
+ }
156
+ else if (typeof p.output === 'string') {
157
+ const match = /(?:^|[\r\n])(?:Process exited with code|Exit code:?)\s*(-?\d+)\b/i.exec(p.output);
158
+ if (match)
159
+ outcomes.set(callId, Number(match[1]) !== 0);
160
+ }
161
+ }
162
+ }
163
+ }
164
+ });
165
+ const hasSubmissionEvents = [...prompts.values()].some(prompt => prompt.explicit);
166
+ for (const [key, prompt] of prompts) {
167
+ if (prompt.explicit || !hasSubmissionEvents) {
168
+ state.prompt(session, prompt.ts, key);
169
+ if (text)
170
+ state.content('user', session, prompt.ts, key, text.take(key));
171
+ }
172
+ }
173
+ for (const [id, call] of calls)
174
+ state.tool(session, call.ts, id, call.name, outcomes.get(id) ?? null);
175
+ const nativeByTurn = new Map();
176
+ const uniqueNative = new Map();
177
+ for (const usage of native) {
178
+ const key = JSON.stringify([usage.provider ?? null, usage.scope, usage.id ?? [usage.turn, usage.ts, values(usage.data)]]);
179
+ const prior = uniqueNative.get(key);
180
+ if (!prior || count(usage.data.output_tokens) > count(prior.data.output_tokens))
181
+ uniqueNative.set(key, usage);
182
+ }
183
+ const emit = (usage, key, quality) => {
184
+ const [input = 0, cached = 0, written = 0, output = 0, reasoning = 0] = values(usage.data);
185
+ const cacheRead = Math.min(input, cached);
186
+ const cacheWrite = Math.min(input - cacheRead, written);
187
+ state.request(session, usage.ts, key, tokens(input - cacheRead - cacheWrite, output, cacheRead, cacheWrite, 0, Math.min(reasoning, output)), {
188
+ model: usage.model, provider: usage.provider ?? provider, quality, contextFill: quality === 2,
189
+ cache: usage.cache ?? hasCounts(usage.data, ['cached_input_tokens', 'cache_write_input_tokens']),
190
+ reasoning: usage.reasoning ?? hasCounts(usage.data, ['reasoning_output_tokens']),
191
+ });
192
+ };
193
+ for (const [key, usage] of uniqueNative) {
194
+ if (usage.turn) {
195
+ const group = nativeByTurn.get(usage.turn) ?? [];
196
+ group.push(usage);
197
+ nativeByTurn.set(usage.turn, group);
198
+ }
199
+ emit(usage, key, 2);
200
+ }
201
+ const nativeIds = new Set([...uniqueNative.values()].map(usage => usage.id).filter(Boolean));
202
+ const matchingLegacy = new Map();
203
+ for (const usage of legacy) {
204
+ if (!usage.turn || (usage.id && nativeIds.has(usage.id)))
205
+ continue;
206
+ const group = matchingLegacy.get(usage.turn) ?? [];
207
+ group.push(usage);
208
+ matchingLegacy.set(usage.turn, group);
209
+ }
210
+ const coveredIds = new Set(legacy.map(usage => usage.id).filter(Boolean));
211
+ const remaining = new Map(legacy.map(usage => [usage, values(usage.data)]));
212
+ for (const [key, group] of nativeByTurn) {
213
+ const matches = matchingLegacy.get(key) ?? [];
214
+ for (const nativeUsage of group) {
215
+ if (nativeUsage.id && coveredIds.has(nativeUsage.id))
216
+ continue;
217
+ const amount = values(nativeUsage.data);
218
+ const cover = matches.find(usage => equals(remaining.get(usage), amount)) ??
219
+ (matches.length === 1 && remaining.get(matches[0]).every((value, i) => value >= amount[i]) ? matches[0] : undefined);
220
+ if (cover)
221
+ remaining.set(cover, remaining.get(cover).map((value, i) => value - amount[i]));
222
+ }
223
+ }
224
+ const nativeSignatures = new Set();
225
+ for (const usage of uniqueNative.values()) {
226
+ nativeSignatures.add(JSON.stringify([usage.ts, values(usage.data)]));
227
+ }
228
+ for (const usage of legacy) {
229
+ if (usage.id && nativeIds.has(usage.id))
230
+ continue;
231
+ const delta = remaining.get(usage);
232
+ if (!delta.some(Boolean))
233
+ continue;
234
+ if (!usage.turn && nativeSignatures.has(JSON.stringify([usage.ts, delta])))
235
+ continue;
236
+ emit({ ...usage, data: Object.fromEntries(axes.map((axis, i) => [axis, delta[i]])) }, JSON.stringify([provider ?? null, session, usage.id ?? [usage.ts, delta]]), 1);
237
+ }
238
+ }
239
+ },
240
+ });
@@ -0,0 +1,99 @@
1
+ import { obj } from './shared.js';
2
+ import { MAX_MESSAGE_BYTES } from '../../report/content/policy.js';
3
+ export { MAX_MESSAGE_BYTES };
4
+ const DEFERRED_BYTES = 16 * 1024 * 1024;
5
+ export function textParts(value, type) {
6
+ if (typeof value === 'string')
7
+ return value;
8
+ if (!Array.isArray(value))
9
+ value = [value];
10
+ const lines = [];
11
+ let bytes = 0;
12
+ for (const item of value) {
13
+ const part = obj(item);
14
+ if (part.thought || part.isMeta || part.synthetic || part.ignored ||
15
+ (type ? part.type !== type :
16
+ (Array.isArray(item) || (part.type !== undefined && part.type !== 'text'))))
17
+ continue;
18
+ const text = typeof item === 'string' && !type ? item : part.text;
19
+ if (typeof text !== 'string' || !text)
20
+ continue;
21
+ bytes += Buffer.byteLength(text) + Number(lines.length > 0);
22
+ if (bytes > MAX_MESSAGE_BYTES)
23
+ return null;
24
+ lines.push(text);
25
+ }
26
+ return lines.length ? lines.join('\n') : undefined;
27
+ }
28
+ export function contentExcluded(...rows) {
29
+ return rows.some(row => row.isMeta === true || row.is_meta === true || row.isSynthetic === true ||
30
+ row.isCompactSummary === true || row.isVisibleInTranscriptOnly === true || row.isSummary === true ||
31
+ row.summary === true || row.isReplay === true ||
32
+ row.is_replay === true || row.is_automated === true || row.isSubagent === true || row.isSubtask === true);
33
+ }
34
+ // R2: tool arguments are read only to feed the open-vocabulary veto with path, file, host and address words. Fields
35
+ // whose name says they hold a path are taken whole (spaces included); other strings are scanned for path-shaped parts.
36
+ // Bodies (file contents, patches, prompts) are skipped, and every call is bounded.
37
+ const PATH_KEY = /path|file|dir|cwd|folder|root|target|dest|source|url|uri|host|cd$/i;
38
+ const BODY_KEY = /^(?:content|contents|new_?str(?:ing)?|old_?str(?:ing)?|text|body|data|code|prompt|description|message|edits?)$/i;
39
+ const TOOL_ARGUMENT_BUDGET = 64 * 1024;
40
+ export function toolArgumentText(value, visit) {
41
+ let budget = TOOL_ARGUMENT_BUDGET;
42
+ const walk = (node, key, depth) => {
43
+ if (budget <= 0 || depth > 6 || node === null || node === undefined)
44
+ return;
45
+ if (typeof node === 'string') {
46
+ if (!node || BODY_KEY.test(key))
47
+ return;
48
+ const trimmed = node.trimStart();
49
+ if ((trimmed.startsWith('{') || trimmed.startsWith('[')) && node.length <= TOOL_ARGUMENT_BUDGET) {
50
+ try {
51
+ walk(JSON.parse(node), key, depth + 1);
52
+ return;
53
+ }
54
+ catch { /* not JSON: scan it as text */ }
55
+ }
56
+ const text = node.length > budget ? node.slice(0, budget) : node;
57
+ budget -= text.length;
58
+ visit(text, PATH_KEY.test(key) ? 'path' : 'text');
59
+ }
60
+ else if (Array.isArray(node)) {
61
+ for (const item of node)
62
+ walk(item, key, depth + 1);
63
+ }
64
+ else if (typeof node === 'object') {
65
+ for (const [name, item] of Object.entries(node))
66
+ walk(item, name, depth + 1);
67
+ }
68
+ };
69
+ walk(value, '', 0);
70
+ }
71
+ // Some formats reconcile patches, message roles or snapshots after reading. Hold only selected text
72
+ // under a fixed byte and entry cap until that adapter resolves the final message. Never spill.
73
+ export class DeferredContent {
74
+ onSkip;
75
+ pending = new Map();
76
+ bytes = 0;
77
+ constructor(onSkip) {
78
+ this.onSkip = onSkip;
79
+ }
80
+ set(key, text) {
81
+ const old = this.pending.get(key);
82
+ this.bytes -= old?.bytes ?? 0;
83
+ this.pending.delete(key);
84
+ const bytes = typeof text === 'string' ? Buffer.byteLength(text) : 0;
85
+ if (text === null || bytes > MAX_MESSAGE_BYTES || this.bytes + bytes > DEFERRED_BYTES || this.pending.size >= 32_768) {
86
+ this.onSkip();
87
+ return;
88
+ }
89
+ if (text) {
90
+ this.pending.set(key, { text, bytes });
91
+ this.bytes += bytes;
92
+ }
93
+ }
94
+ take(key) {
95
+ const value = this.pending.get(key);
96
+ this.set(key, undefined);
97
+ return value?.text;
98
+ }
99
+ }
@@ -0,0 +1,149 @@
1
+ import { basename, dirname, join, relative } from 'node:path';
2
+ import { openHardenedSqlite } from '../sqlite-stage.js';
3
+ import { contentExcluded, DeferredContent } from './content.js';
4
+ import { arr, count, defineAdapter, hasCounts, ideUserRoot, obj, parseJson, segments, str, timestamp, tokens } from './shared.js';
5
+ const tables = ['cursorDiskKV', 'ItemTable'];
6
+ function* query(db, table, predicate, ...args) {
7
+ let rows;
8
+ try {
9
+ rows = db.prepare(`SELECT key, value FROM ${table} WHERE ${predicate}`);
10
+ }
11
+ catch (error) {
12
+ if (error.message.includes('no such table:'))
13
+ return;
14
+ throw error;
15
+ }
16
+ yield* rows.iterate(...args);
17
+ }
18
+ export const cursorIdeAdapter = defineAdapter({
19
+ id: 'cursor-ide', displayName: 'Cursor IDE', tier: 2, defaultRetentionDays: null,
20
+ roots: options => [join(ideUserRoot('Cursor', options), 'globalStorage', 'state.vscdb')],
21
+ matches: (path, root) => {
22
+ const parts = segments(path);
23
+ if (basename(path).toLowerCase() !== 'state.vscdb')
24
+ return false;
25
+ if (!relative(root, path))
26
+ return true;
27
+ if (parts.includes('workspacestorage'))
28
+ return false;
29
+ return parts.includes('cursor') ||
30
+ (basename(dirname(path)).toLowerCase() === 'globalstorage' && !parts.some(part => part === 'code' || part === 'vscodium'));
31
+ },
32
+ async parse(state, files) {
33
+ const text = state.ctx.content && new DeferredContent(() => state.ctx.content?.skip());
34
+ const composers = new Map();
35
+ const bubbles = new Map();
36
+ const usageFields = ['inputTokens', 'outputTokens', 'input_tokens', 'output_tokens'];
37
+ const bubble = (session, id, row) => {
38
+ const group = bubbles.get(session) ?? new Map();
39
+ const previous = group.get(id);
40
+ const role = row.type ?? row.role;
41
+ const timing = obj(row.timingInfo);
42
+ if (text && (typeof row.text === 'string' || contentExcluded(row) || row.isSimulatedMsg === true)) {
43
+ text.set(JSON.stringify([session, id]), contentExcluded(row) || row.isSimulatedMsg === true || typeof row.text !== 'string'
44
+ ? undefined : row.text);
45
+ }
46
+ if (text && row.toolFormerData !== undefined)
47
+ state.identifiers(row.toolFormerData);
48
+ const usage = [row.tokenUsage, row.tokenCount, row.usage].map(obj).find(u => hasCounts(u, usageFields)) ?? previous?.usage ?? {};
49
+ group.set(id, {
50
+ ts: timestamp(row.createdAt, row.timestamp, timing.clientRpcSendTime, timing.clientStartTime, previous?.ts),
51
+ user: role === 1 || role === 'user' || (role === undefined && Boolean(previous?.user)),
52
+ assistant: role === 2 || role === 'assistant' || (role === undefined && Boolean(previous?.assistant)),
53
+ simulated: row.isSimulatedMsg === true || previous?.simulated === true,
54
+ model: str(row.model, row.modelName, obj(row.modelConfig).modelName, previous?.model),
55
+ usage,
56
+ });
57
+ bubbles.set(session, group);
58
+ };
59
+ const composer = (row, fallback) => {
60
+ const id = str(row.composerId, row.id, fallback);
61
+ if (!id)
62
+ return;
63
+ const old = composers.get(id);
64
+ composers.set(id, {
65
+ start: timestamp(row.createdAt, old?.start), end: timestamp(row.lastUpdatedAt, row.lastUpdated, old?.end),
66
+ cwd: str(row.cwd, row.workspacePath, old?.cwd), parent: str(row.parentComposerId, old?.parent),
67
+ model: str(obj(row.modelConfig).modelName, row.modelName, old?.model),
68
+ });
69
+ for (const header of arr(row.fullConversationHeadersOnly).map(obj)) {
70
+ const key = str(header.bubbleId, header.id);
71
+ if (key)
72
+ bubble(id, key, header);
73
+ }
74
+ for (const [key, raw] of Object.entries(obj(row.conversationMap)))
75
+ bubble(id, key, obj(raw));
76
+ for (const [index, raw] of arr(row.conversation).entries()) {
77
+ const message = obj(raw);
78
+ bubble(id, str(message.bubbleId, message.id) ?? String(index), message);
79
+ }
80
+ };
81
+ for (const path of files) {
82
+ await state.sqlite(path, staged => {
83
+ const db = openHardenedSqlite(staged, tables);
84
+ try {
85
+ for (const table of tables) {
86
+ for (const row of query(db, table, 'key >= ? AND key < ?', 'composerData:', 'composerData;')) {
87
+ state.ctx.signal?.throwIfAborted();
88
+ if (typeof row.key === 'string')
89
+ composer(obj(parseJson(row.value)), row.key.slice('composerData:'.length));
90
+ }
91
+ for (const row of query(db, table, 'key >= ? AND key < ?', 'bubbleId:', 'bubbleId;')) {
92
+ state.ctx.signal?.throwIfAborted();
93
+ if (typeof row.key !== 'string')
94
+ continue;
95
+ const [session, ...rest] = row.key.slice('bubbleId:'.length).split(':');
96
+ if (session && rest.length)
97
+ bubble(session, rest.join(':'), obj(parseJson(row.value)));
98
+ }
99
+ }
100
+ for (const row of query(db, 'ItemTable', 'key IN (?, ?)', 'composer.composerData', 'composer.composerHeaders')) {
101
+ const value = parseJson(row.value);
102
+ for (const entry of arr(obj(value).allComposers ?? obj(value).headers ?? value))
103
+ composer(obj(entry));
104
+ }
105
+ }
106
+ finally {
107
+ db.close();
108
+ }
109
+ });
110
+ }
111
+ for (const [session, meta] of composers) {
112
+ const child = Boolean(meta.parent) || session.startsWith('task-toolu_');
113
+ state.session(session, meta.start, meta.cwd, child, meta.parent);
114
+ state.session(session, meta.end, meta.cwd, child, meta.parent);
115
+ }
116
+ let unmetered = false;
117
+ for (const [session, group] of bubbles) {
118
+ const meta = composers.get(session);
119
+ const child = Boolean(meta?.parent) || session.startsWith('task-toolu_');
120
+ for (const [id, row] of group) {
121
+ const ts = row.ts ?? meta?.start;
122
+ if (row.simulated || ts === undefined || (!row.user && !row.assistant))
123
+ continue;
124
+ state.session(session, ts, meta?.cwd, child, meta?.parent);
125
+ if (row.user && !child)
126
+ state.prompt(session, ts, id);
127
+ const prose = text ? text.take(JSON.stringify([session, id])) : undefined;
128
+ if (row.user && meta && !child)
129
+ state.content('user', session, ts, id, prose);
130
+ if (row.assistant)
131
+ state.content('agent', session, ts, id, prose);
132
+ if (row.assistant) {
133
+ const usage = row.usage;
134
+ if (!hasCounts(usage, usageFields)) {
135
+ unmetered ||= state.observed(ts);
136
+ continue;
137
+ }
138
+ state.request(session, ts, JSON.stringify([session, id]), tokens(count(usage.inputTokens ?? usage.input_tokens), count(usage.outputTokens ?? usage.output_tokens)), { model: row.model ?? meta?.model });
139
+ }
140
+ }
141
+ }
142
+ if (unmetered) {
143
+ if (state.capabilities.agentRequestTimestamps === 'present')
144
+ state.capabilities.agentRequestTimestamps = 'partial';
145
+ if (state.capabilities.tokenBreakdown === 'present')
146
+ state.capabilities.tokenBreakdown = 'partial';
147
+ }
148
+ },
149
+ });