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,208 @@
1
+ import { basename, dirname, join } from 'node:path';
2
+ import { normalizeContentText } from '../../report/content/redact.js';
3
+ import { contentExcluded, DeferredContent, textParts } from './content.js';
4
+ import { arr, count, defineAdapter, fileSession, hasCounts, obj, segments, str, timestamp, tokens } from './shared.js';
5
+ const contentKey = (convo, id) => JSON.stringify([convo.session, id]);
6
+ function updateMessage(convo, row, fallback) {
7
+ const id = str(row.id, fallback);
8
+ if (!id)
9
+ return;
10
+ const previous = convo.messages.get(id);
11
+ if (convo.content) {
12
+ const content = row.content ?? row.parts;
13
+ if (contentExcluded(row))
14
+ convo.content.set(contentKey(convo, id), undefined);
15
+ else if (content !== undefined) {
16
+ const text = textParts(content);
17
+ const expansion = typeof text === 'string' && /\bcontent from referenced files\b/i.test(normalizeContentText(text));
18
+ convo.content.set(contentKey(convo, id), expansion ? undefined : text);
19
+ }
20
+ }
21
+ const tools = previous?.tools ?? new Map();
22
+ for (const [index, raw] of arr(row.toolCalls).entries()) {
23
+ const call = obj(raw);
24
+ convo.identifiers?.(call.args);
25
+ const callId = str(call.id, call.callId) ?? String(index);
26
+ const old = tools.get(callId);
27
+ tools.set(callId, {
28
+ id: callId, name: str(call.name, old?.name), ts: timestamp(call.timestamp, old?.ts),
29
+ error: call.status === 'error' || call.isError === true ? true :
30
+ call.status === 'success' || call.status === 'completed' ? false : old?.error ?? null,
31
+ });
32
+ }
33
+ const usage = obj(row.tokens);
34
+ convo.messages.set(id, {
35
+ ts: timestamp(row.timestamp, previous?.ts), kind: str(row.type, row.role, previous?.kind),
36
+ model: str(row.model, previous?.model), generated: Boolean(row.isSynthetic ?? row.isMeta ?? previous?.generated),
37
+ ...(convo.content ? { excludedFromContent: contentExcluded(row) || previous?.excludedFromContent } : {}),
38
+ tokens: Object.fromEntries(['input', 'output', 'cached', 'thoughts'].flatMap(key => {
39
+ const value = usage[key] ?? previous?.tokens[key];
40
+ return typeof value === 'number' ? [[key, value]] : [];
41
+ })),
42
+ tools,
43
+ });
44
+ }
45
+ function updateMetadata(convo, row) {
46
+ convo.project = str(row.cwd, row.projectHash, convo.project);
47
+ convo.parent = str(row.parentSessionId, convo.parent);
48
+ convo.child ||= row.kind === 'subagent' || Boolean(convo.parent);
49
+ convo.start = timestamp(row.startTime, convo.start);
50
+ convo.end = timestamp(row.lastUpdated, convo.end);
51
+ }
52
+ function setMessages(convo, rows, replace) {
53
+ const previous = new Set(replace ? convo.messages.keys() : []);
54
+ for (const [i, raw] of rows.entries()) {
55
+ const row = obj(raw);
56
+ const id = str(row.id) ?? `index-${i}`;
57
+ updateMessage(convo, row, id);
58
+ previous.delete(id);
59
+ }
60
+ for (const id of previous) {
61
+ convo.messages.delete(id);
62
+ convo.content?.take(contentKey(convo, id));
63
+ }
64
+ if (replace)
65
+ reorder(convo, rows.map((row, i) => str(obj(row).id) ?? `index-${i}`));
66
+ }
67
+ function reorder(convo, order) {
68
+ const suffix = new Map();
69
+ for (const id of order) {
70
+ if (typeof id !== 'string')
71
+ continue;
72
+ const found = convo.messages.get(id);
73
+ if (found)
74
+ suffix.set(id, found);
75
+ }
76
+ for (const id of suffix.keys())
77
+ convo.messages.delete(id);
78
+ for (const [id, message] of suffix)
79
+ convo.messages.set(id, message);
80
+ }
81
+ export const geminiCliAdapter = defineAdapter({
82
+ id: 'gemini-cli', displayName: 'Gemini CLI', tier: 1, defaultRetentionDays: 30,
83
+ roots: ({ env, homeDir, platform }) => env.GEMINI_CLI_HOME
84
+ ? [join(env.GEMINI_CLI_HOME, '.gemini', 'tmp'), join(env.GEMINI_CLI_HOME, 'tmp')]
85
+ : [join(homeDir, '.gemini', 'tmp'), ...(platform === 'darwin' ? [join(homeDir, '.cache', '.gemini', 'tmp')] : [])],
86
+ matches(path) {
87
+ const parts = segments(path);
88
+ const chats = parts.lastIndexOf('chats');
89
+ return chats >= 0 && ((chats === parts.length - 2 && /^session-.*\.jsonl?$/i.test(basename(path))) ||
90
+ (chats === parts.length - 3 && /\.jsonl$/i.test(path)));
91
+ },
92
+ async parse(state, files) {
93
+ const conversations = new Map();
94
+ const twins = new Map();
95
+ const content = state.ctx.content && new DeferredContent(() => state.ctx.content?.skip());
96
+ const conversation = (session, path) => {
97
+ let convo = conversations.get(session);
98
+ if (!convo) {
99
+ const folder = basename(dirname(path));
100
+ const parent = folder !== 'chats' ? folder : undefined;
101
+ convo = { session, parent, child: Boolean(parent), messages: new Map(),
102
+ ...(content ? { content, identifiers: (value) => state.identifiers(value) } : {}) };
103
+ conversations.set(session, convo);
104
+ }
105
+ return convo;
106
+ };
107
+ for (const path of files.filter(path => /\.json$/i.test(path))) {
108
+ await state.json(path, value => {
109
+ const row = obj(value);
110
+ const name = path.slice(0, -5);
111
+ const session = str(row.sessionId) ?? name;
112
+ twins.set(name, session);
113
+ const convo = conversation(session, path);
114
+ updateMetadata(convo, row);
115
+ setMessages(convo, arr(row.messages), false);
116
+ });
117
+ }
118
+ for (const path of files.filter(path => /\.jsonl$/i.test(path))) {
119
+ const name = path.slice(0, -6);
120
+ let session = twins.get(name) ?? fileSession(path);
121
+ await state.jsonl(path, (row, ordinal) => {
122
+ session = str(row.sessionId, obj(row.$set).sessionId, session);
123
+ const convo = conversation(session, path);
124
+ if (typeof row.$rewindTo === 'string') {
125
+ if (!convo.messages.has(row.$rewindTo)) {
126
+ for (const id of convo.messages.keys())
127
+ convo.content?.take(contentKey(convo, id));
128
+ convo.messages.clear();
129
+ return;
130
+ }
131
+ let remove = false;
132
+ for (const id of convo.messages.keys()) {
133
+ remove ||= id === row.$rewindTo;
134
+ if (remove) {
135
+ convo.messages.delete(id);
136
+ convo.content?.take(contentKey(convo, id));
137
+ }
138
+ }
139
+ return;
140
+ }
141
+ if (row.$patch) {
142
+ const patch = obj(row.$patch);
143
+ for (const update of [patch, ...arr(patch.updates).map(obj)]) {
144
+ if (typeof update.id === 'string' && convo.messages.has(update.id))
145
+ updateMessage(convo, update);
146
+ }
147
+ for (const id of arr(patch.removeIds))
148
+ if (typeof id === 'string') {
149
+ convo.messages.delete(id);
150
+ convo.content?.take(contentKey(convo, id));
151
+ }
152
+ if (Array.isArray(patch.orderIds))
153
+ reorder(convo, patch.orderIds);
154
+ return;
155
+ }
156
+ if (row.$set) {
157
+ const set = obj(row.$set);
158
+ updateMetadata(convo, set);
159
+ if (Array.isArray(set.messages))
160
+ setMessages(convo, set.messages, true);
161
+ return;
162
+ }
163
+ if (row.sessionId && !row.id) {
164
+ updateMetadata(convo, row);
165
+ if (Array.isArray(row.messages))
166
+ setMessages(convo, row.messages, false);
167
+ return;
168
+ }
169
+ if (row.id || row.type)
170
+ updateMessage(convo, row, `line-${ordinal}`);
171
+ });
172
+ }
173
+ for (const convo of conversations.values()) {
174
+ const { session, project, parent, child, start, end, messages, content: texts } = convo;
175
+ state.session(session, start, project, child, parent);
176
+ state.session(session, end, project, child, parent);
177
+ for (const [id, message] of messages) {
178
+ const { ts, kind, model, tokens: usage, tools } = message;
179
+ if (ts === undefined)
180
+ continue;
181
+ state.session(session, ts, project, child, parent);
182
+ const text = texts?.take(contentKey(convo, id));
183
+ if (kind === 'user' && !child && !message.generated) {
184
+ state.prompt(session, ts, id);
185
+ if (!message.excludedFromContent)
186
+ state.content('user', session, ts, id, text);
187
+ }
188
+ if (kind === 'gemini' || kind === 'assistant' || kind === 'model') {
189
+ if (!message.generated && !message.excludedFromContent)
190
+ state.content('agent', session, ts, id, text);
191
+ if (hasCounts(usage, ['input', 'output', 'thoughts'])) {
192
+ const cache = Math.min(count(usage.input), count(usage.cached));
193
+ const thoughts = count(usage.thoughts);
194
+ state.request(session, ts, JSON.stringify([session, id]), tokens(count(usage.input) - cache, count(usage.output) + thoughts, cache, 0, 0, thoughts), {
195
+ model, provider: 'google', cache: hasCounts(usage, ['cached']), reasoning: hasCounts(usage, ['thoughts']),
196
+ });
197
+ }
198
+ for (const tool of tools.values()) {
199
+ if (tool.name)
200
+ state.tool(session, tool.ts ?? ts, tool.id, tool.name, tool.error);
201
+ }
202
+ }
203
+ if (kind === 'compaction')
204
+ state.compact(session, ts, id, 'unknown');
205
+ }
206
+ }
207
+ },
208
+ });
@@ -0,0 +1,18 @@
1
+ import { aiderAdapter } from './aider.js';
2
+ import { claudeCodeAdapter } from './claude-code.js';
3
+ import { clineAdapter, rooCodeAdapter } from './cline-roo.js';
4
+ import { codexCliAdapter } from './codex-cli.js';
5
+ import { cursorIdeAdapter } from './cursor-ide.js';
6
+ import { geminiCliAdapter } from './gemini-cli.js';
7
+ import { openCodeAdapter } from './opencode.js';
8
+ import { piAgentAdapter } from './pi-agent.js';
9
+ export const ALL_ADAPTERS = [
10
+ claudeCodeAdapter, codexCliAdapter, openCodeAdapter, geminiCliAdapter, cursorIdeAdapter,
11
+ clineAdapter, rooCodeAdapter, piAgentAdapter, aiderAdapter,
12
+ ];
13
+ export function getAdapter(id) {
14
+ const adapter = ALL_ADAPTERS.find(adapter => adapter.id === id);
15
+ if (!adapter)
16
+ throw new RangeError('UNKNOWN_HARNESS');
17
+ return adapter;
18
+ }
@@ -0,0 +1,203 @@
1
+ import { basename, dirname, join, relative } from 'node:path';
2
+ import { openCodeColumns as schemas, openHardenedSqlite } from '../sqlite-stage.js';
3
+ import { contentExcluded, DeferredContent, textParts } from './content.js';
4
+ import { arr, count, defineAdapter, fileSession, hasCounts, obj, parseJson, segments, str, timestamp, tokens } from './shared.js';
5
+ function* rows(db, table) {
6
+ const present = [];
7
+ for (const column of schemas[table]) {
8
+ try {
9
+ db.prepare(`SELECT "${column}" FROM "${table}" LIMIT 0`);
10
+ present.push(column);
11
+ }
12
+ catch (error) {
13
+ const message = error.message ?? '';
14
+ if (message.includes('no such table:'))
15
+ return;
16
+ if (!message.includes('no such column:'))
17
+ throw error;
18
+ }
19
+ }
20
+ if (present.length)
21
+ yield* db.prepare(`SELECT ${present.map(column => `"${column}"`).join(', ')} FROM "${table}"`).iterate();
22
+ }
23
+ function usageOf(value) {
24
+ const usage = obj(value);
25
+ if (!hasCounts(usage, ['input', 'output', 'reasoning']))
26
+ return;
27
+ const cache = obj(usage.cache);
28
+ return {
29
+ input: count(usage.input), output: count(usage.output), read: count(cache.read),
30
+ write: count(cache.write), reasoning: count(usage.reasoning),
31
+ hasCache: hasCounts(cache, ['read', 'write']), hasReasoning: hasCounts(usage, ['reasoning']),
32
+ };
33
+ }
34
+ export const openCodeAdapter = defineAdapter({
35
+ id: 'opencode', displayName: 'OpenCode', tier: 1, defaultRetentionDays: null,
36
+ roots: ({ env, homeDir }) => {
37
+ const data = join(env.XDG_DATA_HOME || join(homeDir, '.local', 'share'), 'opencode');
38
+ return env.OPENCODE_DB ? [env.OPENCODE_DB, join(data, 'storage')] : [data];
39
+ },
40
+ configuredMatch: (path, root, { env }) => Boolean(env.OPENCODE_DB && root === env.OPENCODE_DB && !relative(root, path)),
41
+ matches(path, root) {
42
+ const parts = segments(path);
43
+ return /^opencode(?:-[\w.-]+)?\.db$/i.test(basename(path)) ||
44
+ (!relative(root, path) && /\.(?:db|sqlite|sqlite3)$/i.test(path)) ||
45
+ (/\.json$/i.test(path) && ['session', 'message', 'part', 'project'].includes(parts.at(-3) ?? '') &&
46
+ parts.includes('storage')) || (/\.json$/i.test(path) && parts.at(-2) === 'project' && parts.at(-3) === 'storage');
47
+ },
48
+ async parse(state, files) {
49
+ const sessions = new Map();
50
+ const projects = new Map();
51
+ const messages = new Map();
52
+ const text = state.ctx.content && new DeferredContent(() => state.ctx.content?.skip());
53
+ const parts = new Map();
54
+ const addPart = (value, row, rank, messageHint, index) => {
55
+ const message = str(row.message_id, value.messageID, value.messageId, messageHint);
56
+ const kind = str(value.type, row.type);
57
+ const id = (kind === 'tool' ? str(row.call_id, value.callID, value.callId, row.id, value.id) : str(row.id, value.id)) ??
58
+ (typeof row.ordinal === 'number' ? String(row.ordinal) : index === undefined ? undefined : String(index));
59
+ if (!message || !id)
60
+ return;
61
+ const key = JSON.stringify([message, id]);
62
+ if ((parts.get(key)?.rank ?? -1) > rank)
63
+ return;
64
+ if (text)
65
+ text.set(key, kind === 'text' && !contentExcluded(value, row) && !value.synthetic &&
66
+ !value.ignored && typeof value.text === 'string' ? value.text : undefined);
67
+ const status = obj(value.state);
68
+ if (text && kind === 'tool')
69
+ state.identifiers(status.input);
70
+ parts.set(key, {
71
+ message, id, rank, kind, name: str(value.tool, value.name),
72
+ error: status.status === 'error' ? true : status.status === 'completed' ? false : null,
73
+ ts: timestamp(obj(status.time).start, row.time_created, obj(value.time).created, value.timestamp),
74
+ usage: usageOf(value.tokens ?? value.usage),
75
+ });
76
+ };
77
+ const add = (kind, value, row, rank) => {
78
+ const id = str(row.id, value.id);
79
+ const time = obj(value.time);
80
+ if (kind === 'part' || kind === 'session_part') {
81
+ addPart(value, row, rank);
82
+ }
83
+ else if (kind === 'project' && id) {
84
+ const cwd = str(row.worktree, value.worktree);
85
+ if (cwd)
86
+ projects.set(id, cwd);
87
+ }
88
+ else if ((kind === 'session' || kind === 'session_v2') && id) {
89
+ const prior = sessions.get(id);
90
+ sessions.set(id, {
91
+ cwd: str(row.directory, value.directory, value.cwd, prior?.cwd),
92
+ parent: str(row.parent_id, value.parentID, value.parentId, prior?.parent),
93
+ project: str(row.project_id, value.projectID, value.projectId, prior?.project),
94
+ start: timestamp(row.time_created, time.created, value.createdAt, prior?.start),
95
+ end: timestamp(row.time_updated, time.updated, value.updatedAt, prior?.end),
96
+ });
97
+ }
98
+ else if ((kind === 'message' || kind === 'session_message') && id) {
99
+ const session = str(row.session_id, value.sessionID, value.sessionId);
100
+ if (!session)
101
+ return;
102
+ const model = obj(value.model);
103
+ const prior = messages.get(id);
104
+ if (!prior || rank >= prior.rank)
105
+ messages.set(id, {
106
+ session, rank, ts: timestamp(time.created, row.time_created, value.timestamp, prior?.ts),
107
+ end: timestamp(time.completed, row.time_updated, prior?.end), kind: str(value.role, value.type, row.type, row.role, prior?.kind),
108
+ model: str(value.modelID, value.modelId, model.id, model.modelID, value.model, prior?.model),
109
+ provider: str(value.providerID, model.providerID, model.providerId, prior?.provider),
110
+ ...(text ? { excludedFromContent: contentExcluded(value, row) || prior?.excludedFromContent } : {}),
111
+ usage: usageOf(value.tokens ?? value.usage) ?? prior?.usage,
112
+ });
113
+ for (const [index, part] of arr(value.parts ?? (Array.isArray(value.content) ? value.content : undefined)).entries()) {
114
+ addPart(obj(part), {}, rank, id, index);
115
+ }
116
+ }
117
+ };
118
+ for (const path of files.filter(path => /\.json$/i.test(path))) {
119
+ await state.json(path, raw => {
120
+ const value = obj(raw);
121
+ const folder = basename(dirname(path));
122
+ const kind = folder === 'project' ? folder : basename(dirname(dirname(path)));
123
+ add(kind, value, {
124
+ id: str(value.id) ?? fileSession(path),
125
+ session_id: kind === 'message' ? str(value.sessionID, value.sessionId, folder) : undefined,
126
+ message_id: kind === 'part' ? str(value.messageID, value.messageId, folder) : undefined,
127
+ }, 0);
128
+ });
129
+ }
130
+ for (const path of files.filter(path => !/\.json$/i.test(path))) {
131
+ await state.sqlite(path, snapshot => {
132
+ const tables = Object.keys(schemas);
133
+ const db = openHardenedSqlite(snapshot, tables);
134
+ try {
135
+ for (const table of tables) {
136
+ state.ctx.signal?.throwIfAborted();
137
+ if (table.endsWith('_v2') || table.includes('_')) {
138
+ for (const row of rows(db, table))
139
+ add(table, obj(parseJson(row.data)), row, 2);
140
+ }
141
+ else {
142
+ for (const row of rows(db, table))
143
+ add(table, obj(parseJson(row.data)), row, 1);
144
+ }
145
+ }
146
+ }
147
+ finally {
148
+ db.close();
149
+ }
150
+ });
151
+ }
152
+ for (const [id, session] of sessions) {
153
+ const cwd = session.cwd ?? projects.get(session.project ?? '');
154
+ state.session(id, session.start, cwd, Boolean(session.parent), session.parent);
155
+ state.session(id, session.end, cwd, Boolean(session.parent), session.parent);
156
+ }
157
+ const byMessage = new Map();
158
+ for (const part of parts.values()) {
159
+ const group = byMessage.get(part.message) ?? [];
160
+ group.push(part);
161
+ byMessage.set(part.message, group);
162
+ }
163
+ for (const [id, message] of messages) {
164
+ const { session, ts, end, kind, model, provider, usage } = message;
165
+ if (ts === undefined)
166
+ continue;
167
+ const meta = sessions.get(session);
168
+ state.session(session, ts, meta?.cwd, Boolean(meta?.parent), meta?.parent);
169
+ state.session(session, end);
170
+ if (kind === 'user' && !meta?.parent)
171
+ state.prompt(session, ts, id);
172
+ if (kind === 'compaction')
173
+ state.compact(session, ts, id, 'unknown');
174
+ const emit = (key, at, data) => state.request(session, at, key, tokens(data.input, data.output + data.reasoning, data.read, data.write, 0, data.reasoning), { model, provider, cache: data.hasCache, reasoning: data.hasReasoning, quality: message.rank, coverageGroup: id });
175
+ const related = byMessage.get(id) ?? [];
176
+ if (text && !message.excludedFromContent && (kind === 'assistant' || kind === 'user' && meta && !meta.parent)) {
177
+ const prose = related.filter(part => part.kind === 'text').map(part => text.take(JSON.stringify([id, part.id])));
178
+ state.content(kind === 'user' ? 'user' : 'agent', session, ts, id, textParts(prose));
179
+ }
180
+ const usageParts = related.filter(part => part.kind === 'step-finish' && part.usage);
181
+ const latestPartRank = usageParts.reduce((rank, part) => Math.max(rank, part.rank), -1);
182
+ const steps = usageParts.filter(part => part.rank === latestPartRank);
183
+ const axes = ['input', 'output', 'read', 'write', 'reasoning'];
184
+ const hasPositiveUsage = (data) => Boolean(data && axes.some(axis => data[axis] > 0));
185
+ if (kind === 'assistant' || kind === 'compaction') {
186
+ if (steps.length && (steps.some(part => hasPositiveUsage(part.usage)) || !hasPositiveUsage(usage))) {
187
+ for (const part of steps)
188
+ emit(JSON.stringify([id, part.id]), part.ts ?? ts, part.usage);
189
+ }
190
+ else if (usage) {
191
+ emit(id, ts, usage);
192
+ }
193
+ }
194
+ const seenTools = new Set();
195
+ for (const part of related.sort((a, b) => b.rank - a.rank)) {
196
+ if (part.kind === 'tool' && part.name && !seenTools.has(part.id)) {
197
+ seenTools.add(part.id);
198
+ state.tool(session, part.ts ?? ts, JSON.stringify([id, part.id]), part.name, part.error);
199
+ }
200
+ }
201
+ }
202
+ },
203
+ });
@@ -0,0 +1,85 @@
1
+ import { basename, join, resolve } from 'node:path';
2
+ import { contentExcluded, textParts } from './content.js';
3
+ import { arr, count, defineAdapter, fileSession, hasCounts, obj, segments, str, timestamp, tokens } from './shared.js';
4
+ export const piAgentAdapter = defineAdapter({
5
+ id: 'pi-agent', displayName: 'Pi', tier: 2, defaultRetentionDays: null,
6
+ roots: ({ env, homeDir }) => [env.PI_CODING_AGENT_SESSION_DIR || join(homeDir, '.pi', 'agent', 'sessions')],
7
+ matches(path) {
8
+ const parts = segments(path);
9
+ const sessions = parts.lastIndexOf('sessions');
10
+ const layout = sessions >= 0 && (parts[sessions - 1] === 'agent' ||
11
+ parts.slice(0, sessions).some(part => ['.pi', 'pi', 'pi-agent'].includes(part)));
12
+ return layout && /\.jsonl$/i.test(path) && !/^rollout[-_]/i.test(basename(path));
13
+ },
14
+ configuredMatch: (path, root, { env }) => Boolean(env.PI_CODING_AGENT_SESSION_DIR) &&
15
+ resolve(root) === resolve(env.PI_CODING_AGENT_SESSION_DIR) && /\.jsonl$/i.test(path),
16
+ async parse(state, files) {
17
+ const usedEntries = new Set();
18
+ for (const path of files) {
19
+ let session = fileSession(path);
20
+ let cwd;
21
+ let recognized = false;
22
+ let child = false;
23
+ const calls = new Map();
24
+ const outcomes = new Map();
25
+ await state.jsonl(path, (row, ordinal) => {
26
+ if (row.type === 'session') {
27
+ session = str(row.id, row.sessionId, session);
28
+ cwd = str(row.cwd);
29
+ recognized = true;
30
+ if (state.ctx.content)
31
+ child = Boolean(row.parentSessionId || row.isSubagent || segments(path).includes('subagents'));
32
+ state.session(session, timestamp(row.timestamp), cwd);
33
+ return;
34
+ }
35
+ if (!recognized)
36
+ return;
37
+ const message = obj(row.message);
38
+ const ts = timestamp(message.timestamp, row.timestamp);
39
+ if (ts === undefined)
40
+ return;
41
+ const identity = typeof row.id === 'string' ? JSON.stringify([row.id, str(row.parentId) ?? null, ts]) : JSON.stringify([session, ordinal]);
42
+ if (usedEntries.has(identity))
43
+ return;
44
+ usedEntries.add(identity);
45
+ state.session(session, ts, cwd);
46
+ if (row.type === 'compaction')
47
+ state.compact(session, ts, identity, 'unknown');
48
+ if (row.type !== 'message')
49
+ return;
50
+ if (message.role === 'user' && !message.isSynthetic) {
51
+ state.prompt(session, ts, identity);
52
+ if (state.ctx.content && !child && !contentExcluded(row, message)) {
53
+ state.content('user', session, ts, identity, textParts(message.content, 'text'));
54
+ }
55
+ }
56
+ if (message.role === 'toolResult') {
57
+ const id = str(message.toolCallId);
58
+ if (id && typeof message.isError === 'boolean')
59
+ outcomes.set(id, message.isError);
60
+ }
61
+ if (message.role !== 'assistant')
62
+ return;
63
+ if (state.ctx.content && !contentExcluded(row, message) && Array.isArray(message.content)) {
64
+ state.content('agent', session, ts, identity, textParts(message.content, 'text'));
65
+ }
66
+ if (message.stopReason === 'aborted')
67
+ state.interrupt(session, ts, identity);
68
+ const usage = obj(message.usage);
69
+ if (hasCounts(usage, ['input', 'output'])) {
70
+ state.request(session, ts, identity, tokens(count(usage.input), count(usage.output), count(usage.cacheRead), count(usage.cacheWrite)), { model: message.model, provider: message.provider, cache: hasCounts(usage, ['cacheRead', 'cacheWrite']) });
71
+ }
72
+ for (const [index, raw] of arr(message.content).entries()) {
73
+ const block = obj(raw);
74
+ const name = str(block.name);
75
+ if (block.type === 'toolCall' && state.ctx.content)
76
+ state.identifiers(block.arguments);
77
+ if (block.type === 'toolCall' && name)
78
+ calls.set(str(block.id) ?? JSON.stringify([identity, index]), { ts, name });
79
+ }
80
+ });
81
+ for (const [id, call] of calls)
82
+ state.tool(session, call.ts, id, call.name, outcomes.get(id) ?? null);
83
+ }
84
+ },
85
+ });