coauthored 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/PRIVACY.md +107 -0
- package/README.md +113 -3
- package/THIRD_PARTY_LICENSES.md +105 -0
- package/dist/cli/analytics/anchors.js +39 -0
- package/dist/cli/analytics/archetypes.js +193 -0
- package/dist/cli/analytics/content/analyzer.js +945 -0
- package/dist/cli/analytics/content/classify.js +115 -0
- package/dist/cli/analytics/content/demo-corpus.js +301 -0
- package/dist/cli/analytics/content/sketch.js +54 -0
- package/dist/cli/analytics/dataset.js +321 -0
- package/dist/cli/analytics/demo-fixtures.js +531 -0
- package/dist/cli/analytics/fdr.js +183 -0
- package/dist/cli/analytics/helicorder.js +66 -0
- package/dist/cli/analytics/insights.js +589 -0
- package/dist/cli/analytics/models.js +75 -0
- package/dist/cli/analytics/pricing.js +121 -0
- package/dist/cli/analytics/probable-cause.js +115 -0
- package/dist/cli/analytics/report-builder.js +162 -0
- package/dist/cli/analytics/statistics.js +91 -0
- package/dist/cli/analytics/time.js +252 -0
- package/dist/cli/cli/args.js +105 -0
- package/dist/cli/cli/browser.js +71 -0
- package/dist/cli/cli/index.js +20 -0
- package/dist/cli/cli/main.js +520 -0
- package/dist/cli/cli/phrase-review.js +78 -0
- package/dist/cli/cli/server.js +481 -0
- package/dist/cli/cli/terminal.js +363 -0
- package/dist/cli/ingest/adapters/aider.js +116 -0
- package/dist/cli/ingest/adapters/claude-code.js +139 -0
- package/dist/cli/ingest/adapters/cline-roo.js +89 -0
- package/dist/cli/ingest/adapters/codex-cli.js +240 -0
- package/dist/cli/ingest/adapters/content.js +99 -0
- package/dist/cli/ingest/adapters/cursor-ide.js +149 -0
- package/dist/cli/ingest/adapters/gemini-cli.js +208 -0
- package/dist/cli/ingest/adapters/index.js +18 -0
- package/dist/cli/ingest/adapters/opencode.js +203 -0
- package/dist/cli/ingest/adapters/pi-agent.js +85 -0
- package/dist/cli/ingest/adapters/shared.js +484 -0
- package/dist/cli/ingest/content-sink.js +31 -0
- package/dist/cli/ingest/discovery.js +50 -0
- package/dist/cli/ingest/message-digests.js +61 -0
- package/dist/cli/ingest/pipeline.js +155 -0
- package/dist/cli/ingest/safe-fs.js +284 -0
- package/dist/cli/ingest/sqlite-stage.js +139 -0
- package/dist/cli/ingest/time-window.js +34 -0
- package/dist/cli/ingest/tool-map.js +24 -0
- package/dist/cli/ingest/types.js +1 -0
- package/dist/cli/ingest/worker.js +97 -0
- package/dist/cli/report/content/emoji-names.js +3956 -0
- package/dist/cli/report/content/insights.js +41 -0
- package/dist/cli/report/content/lexicons.js +112 -0
- package/dist/cli/report/content/policy.js +77 -0
- package/dist/cli/report/content/redact.js +164 -0
- package/dist/cli/report/content/stopwords.js +8848 -0
- package/dist/cli/report/content/suppression.js +2617 -0
- package/dist/cli/report/content/validate.js +152 -0
- package/dist/cli/report/copy-lint.js +105 -0
- package/dist/cli/report/share.js +132 -0
- package/dist/cli/report/types.js +1 -0
- package/dist/cli/report/validators.js +334 -0
- package/dist/web/assets/Archivo-VF-BohoA-Sn.woff2 +0 -0
- package/dist/web/assets/DelaGothicOne-subset-CpoJGhTq.woff2 +0 -0
- package/dist/web/assets/Film-BkhZFxG9.css +1 -0
- package/dist/web/assets/MartianMono-VF-CmJ1nXx9.woff2 +0 -0
- package/dist/web/assets/app-Dw1a5h5V.js +38 -0
- package/dist/web/assets/bricolage-grotesque-latin-700-normal-gtcctNPv.woff2 +0 -0
- package/dist/web/assets/bricolage-grotesque-latin-800-normal-J50vIsBe.woff2 +0 -0
- package/dist/web/assets/chorus-D7bfON5Z.ogg +0 -0
- package/dist/web/assets/chorus-bass-CBTKpMv_.ogg +0 -0
- package/dist/web/assets/chorus-drums-BOzgLSoq.ogg +0 -0
- package/dist/web/assets/chorus-harmony-DnJYs_tp.ogg +0 -0
- package/dist/web/assets/chorus-lead-CFpg5DC1.ogg +0 -0
- package/dist/web/assets/chunk-BNfsY4o8.js +1 -0
- package/dist/web/assets/chunk-BSm8IhPY.js +1 -0
- package/dist/web/assets/chunk-Bi6EQAkf.js +1 -0
- package/dist/web/assets/chunk-D6HyoJCB.js +46 -0
- package/dist/web/assets/chunk-DrEayQLY.js +1 -0
- package/dist/web/assets/chunk-V3YGpFIw.js +1 -0
- package/dist/web/assets/chunk-XGhNFWse.js +1 -0
- package/dist/web/assets/dialogue-card-A5zmbNhu.ogg +0 -0
- package/dist/web/assets/groove-bass-BFNelLKi.ogg +0 -0
- package/dist/web/assets/groove-drums-BY1SBntR.ogg +0 -0
- package/dist/web/assets/groove-harmony-C0CrBzu3.ogg +0 -0
- package/dist/web/assets/groove-lead-CEYPzm5U.ogg +0 -0
- package/dist/web/assets/groove-ln-zQmTb.ogg +0 -0
- package/dist/web/assets/guess-high-CL6mF18x.ogg +0 -0
- package/dist/web/assets/guess-low-C3UnKayZ.ogg +0 -0
- package/dist/web/assets/higher-BevsMIWl.ogg +0 -0
- package/dist/web/assets/identity-0EPS3msD.ogg +0 -0
- package/dist/web/assets/index-DpT0dtHc.css +1 -0
- package/dist/web/assets/intro-DeRh6kUx.ogg +0 -0
- package/dist/web/assets/intro-bass-D63IPU0H.ogg +0 -0
- package/dist/web/assets/intro-drums-Dt9QO534.ogg +0 -0
- package/dist/web/assets/intro-harmony-DBsMG9jJ.ogg +0 -0
- package/dist/web/assets/intro-lead-DWcWS1ia.ogg +0 -0
- package/dist/web/assets/jar-coin-rtCvspuq.ogg +0 -0
- package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/web/assets/ledger-tick-C1rQgQGX.ogg +0 -0
- package/dist/web/assets/night-B_bMOZcf.ogg +0 -0
- package/dist/web/assets/night-bass-B-7Ay9ME.ogg +0 -0
- package/dist/web/assets/night-drums-zEtqWXX3.ogg +0 -0
- package/dist/web/assets/night-harmony-C5Ix2yce.ogg +0 -0
- package/dist/web/assets/night-lead-B7KMlRyj.ogg +0 -0
- package/dist/web/assets/ourturn-DX78hTEz.ogg +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-400-normal-Dhut76fR.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-500-normal-Bf-nb4oT.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-600-normal-DLTa1BUW.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-700-normal-CfpNZvy6.woff2 +0 -0
- package/dist/web/assets/reveal-BmWAGHih.ogg +0 -0
- package/dist/web/assets/review-split-Dac4zagw.ogg +0 -0
- package/dist/web/assets/shutter-uhz2Y9S9.ogg +0 -0
- package/dist/web/assets/soclose-CiUFR5St.ogg +0 -0
- package/dist/web/assets/stinger-TnnzHAMN.ogg +0 -0
- package/dist/web/assets/stomp-mzIk4cGm.ogg +0 -0
- package/dist/web/assets/syne-latin-700-normal-AF3Rs61n.woff2 +0 -0
- package/dist/web/assets/syne-latin-800-normal-EehdNYzx.woff2 +0 -0
- package/dist/web/assets/tension-BHvWG5ru.ogg +0 -0
- package/dist/web/assets/tension-bass-4G-2qA9W.ogg +0 -0
- package/dist/web/assets/tension-drums-D7sdehJr.ogg +0 -0
- package/dist/web/assets/tension-harmony-FyPldmLb.ogg +0 -0
- package/dist/web/assets/tension-lead-C5uoFMR8.ogg +0 -0
- package/dist/web/assets/why-clock-Dzs1A_ym.ogg +0 -0
- package/dist/web/favicon.svg +1 -0
- package/dist/web/index.html +16 -0
- package/dist/web/licenses/OFL-Archivo.txt +93 -0
- package/dist/web/licenses/OFL-DelaGothic.txt +93 -0
- package/dist/web/licenses/OFL-MartianMono.txt +93 -0
- package/package.json +63 -6
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
import { linkSync, mkdtempSync, renameSync, rmdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { createInterface, emitKeypressEvents } from 'node:readline';
|
|
4
|
+
import { CONTENT_FIELDS, CONTENT_EXCLUDED, CONTENT_VETO_ONLY } from '../report/content/policy.js';
|
|
5
|
+
import { validateWrappedReport } from '../report/validators.js';
|
|
6
|
+
import { PhraseReview } from './phrase-review.js';
|
|
7
|
+
const BANNER = 'coauthored · flight recorder 2026';
|
|
8
|
+
const RULE = '──────────────────────────────────────────────────────────────────────────';
|
|
9
|
+
const number = new Intl.NumberFormat('en', { maximumFractionDigits: 1 });
|
|
10
|
+
export function safeLine(value) {
|
|
11
|
+
return value.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
12
|
+
}
|
|
13
|
+
function section(title, lines) {
|
|
14
|
+
const text = lines.filter((line) => Boolean(line)).map((line) => ` ${safeLine(line)}`);
|
|
15
|
+
return `\n${title.toUpperCase()}\n${(text.length ? text : [' No evidence recovered for this section.']).join('\n')}\n`;
|
|
16
|
+
}
|
|
17
|
+
export function printBanner(output = process.stdout) {
|
|
18
|
+
output.write(`${BANNER}\n${RULE}\n`);
|
|
19
|
+
}
|
|
20
|
+
export function printDryRun(plan, ledger, output = process.stdout) {
|
|
21
|
+
printBanner(output);
|
|
22
|
+
output.write(section('Discovery plan', [
|
|
23
|
+
`${plan.year} · ${plan.timezone} · ${plan.planId}`,
|
|
24
|
+
'Directory and file metadata checked. Source content bytes read 0',
|
|
25
|
+
...(plan.candidates.length === 0 ? ['No recorders found.'] : []),
|
|
26
|
+
]));
|
|
27
|
+
for (const candidate of plan.candidates) {
|
|
28
|
+
const sources = ledger.filter(({ candidateId }) => candidateId === candidate.candidateId);
|
|
29
|
+
output.write(section(`${candidate.channelLabel} · ${safeLine(candidate.displayName)} · ${candidate.candidateId}`, [
|
|
30
|
+
`${number.format(candidate.fileCount)} files · ${number.format(candidate.totalBytes)} bytes · ${candidate.snapshotMethod}`,
|
|
31
|
+
...sources.map((source) => `${source.canonicalPath} [${number.format(source.fileCount)} files · ${source.snapshotMethod}]`),
|
|
32
|
+
...candidate.notes,
|
|
33
|
+
candidate.hasCredentialRiskWarning ? 'Private snapshot staging copies the database file. Credential fields are excluded from queries.' : null,
|
|
34
|
+
]));
|
|
35
|
+
}
|
|
36
|
+
output.write(section('Never read', plan.neverReadManifest));
|
|
37
|
+
}
|
|
38
|
+
export async function promptTerminalConsent(plan, ledger, { confirm = false } = {}) {
|
|
39
|
+
if (confirm)
|
|
40
|
+
return true;
|
|
41
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY) {
|
|
42
|
+
process.stderr.write('Read-out withheld. Pass --confirm to release the plan in a non-interactive run.\n');
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
printDryRun(plan, ledger, process.stderr);
|
|
46
|
+
const prompt = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
|
|
47
|
+
return new Promise((done) => {
|
|
48
|
+
prompt.once('close', () => done(false));
|
|
49
|
+
prompt.once('SIGINT', () => prompt.close());
|
|
50
|
+
prompt.question('\nType RELEASE to begin read-out. > ', (answer) => {
|
|
51
|
+
done(answer.trim() === 'RELEASE');
|
|
52
|
+
prompt.close();
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
export async function promptContentConsent(confirm) {
|
|
57
|
+
if (confirm)
|
|
58
|
+
return true;
|
|
59
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY) {
|
|
60
|
+
process.stderr.write('Word counting requires --content --confirm-content in a non-interactive run.\n');
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
process.stderr.write(section('Optional word counting', [
|
|
64
|
+
`Read locally ${CONTENT_FIELDS.join(', ')}`,
|
|
65
|
+
`Left out ${CONTENT_EXCLUDED.join(', ')}`,
|
|
66
|
+
`Read only to hide phrases, never counted ${CONTENT_VETO_ONLY.join(', ')}`,
|
|
67
|
+
'The readout contains counts, length and emoji statistics. Phrase candidates stay local. Raw text is never written by this analysis.',
|
|
68
|
+
]));
|
|
69
|
+
const prompt = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
|
|
70
|
+
return new Promise(done => {
|
|
71
|
+
prompt.once('close', () => done(false));
|
|
72
|
+
prompt.once('SIGINT', () => prompt.close());
|
|
73
|
+
prompt.question('Type COUNT to count words. > ', answer => {
|
|
74
|
+
done(answer.trim() === 'COUNT');
|
|
75
|
+
prompt.close();
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const FLAG_EMOJI = /\p{Regional_Indicator}|[\u{E0020}-\u{E007F}]|\u{1F3F3}|\u{1F3F4}/u;
|
|
80
|
+
const ALT_SCREEN_ON = '\x1b[?1049h';
|
|
81
|
+
const ALT_SCREEN_OFF = '\x1b[?1049l';
|
|
82
|
+
const CLEAR_SCREEN = '\x1b[2J\x1b[H';
|
|
83
|
+
const REVIEW_GUARD_MS = 300;
|
|
84
|
+
// H1/R1: the only way a phrase candidate leaves the process. It runs inside the ingest worker, so candidates never
|
|
85
|
+
// cross IPC; only the phrases the person kept do.
|
|
86
|
+
// - The count prints first, on the main screen. The review itself runs on the alternate screen buffer, so revealed
|
|
87
|
+
// terms never reach the scrollback, and the main screen is restored on every exit path.
|
|
88
|
+
// - Each candidate starts hidden. Space or Enter reveals it; any other key hides it.
|
|
89
|
+
// - After every prompt (hidden or revealed), keys that were already waiting or arrive within guardMs are discarded,
|
|
90
|
+
// and each discarded key restarts the window: only a fresh press after guardMs of quiet counts. On a revealed term,
|
|
91
|
+
// K keeps it, and H, Enter or any other key hides it. A held or repeating key therefore never keeps a candidate,
|
|
92
|
+
// and never carries over from one decision to the next.
|
|
93
|
+
// - Keys pressed while no prompt is waiting are dropped, and keys that arrive together in one burst (a paste, or a
|
|
94
|
+
// held key's repeats delivered at once after a stall) are all dropped, so neither can answer a prompt.
|
|
95
|
+
// - Ctrl+C, Ctrl+D, the end of input, a closed input, or an aborted signal (the parent died, SIGTERM) end the review
|
|
96
|
+
// with SCAN_CANCELLED, and raw mode and the main screen are restored first.
|
|
97
|
+
export async function reviewTerminalPhrases(report, { signal, input = process.stdin, output = process.stderr, guardMs = REVIEW_GUARD_MS } = {}) {
|
|
98
|
+
if (!input.isTTY || !output.isTTY)
|
|
99
|
+
throw new Error('PHRASE_REVIEW_REQUIRES_TTY');
|
|
100
|
+
const review = new PhraseReview();
|
|
101
|
+
review.take(report);
|
|
102
|
+
const pending = review.list();
|
|
103
|
+
if (report.content?.receipt.phraseCandidatesSuppressed) {
|
|
104
|
+
output.write('\nPhrase review unavailable for this run: a message exceeded the analysis budget, so no phrases are offered.\n');
|
|
105
|
+
}
|
|
106
|
+
output.write(`\n${pending.length} phrase candidates for review.\n`);
|
|
107
|
+
if (!pending.length)
|
|
108
|
+
return;
|
|
109
|
+
signal?.throwIfAborted();
|
|
110
|
+
let waiter;
|
|
111
|
+
let failure;
|
|
112
|
+
let ignoreUntil = 0;
|
|
113
|
+
let burst;
|
|
114
|
+
const fail = () => {
|
|
115
|
+
failure ??= new Error('SCAN_CANCELLED');
|
|
116
|
+
const pendingWaiter = waiter;
|
|
117
|
+
waiter = undefined;
|
|
118
|
+
pendingWaiter?.reject(failure);
|
|
119
|
+
};
|
|
120
|
+
const onKey = (char, details = {}) => {
|
|
121
|
+
if (details.ctrl && (details.name === 'c' || details.name === 'd'))
|
|
122
|
+
return fail();
|
|
123
|
+
const now = performance.now();
|
|
124
|
+
// Any key inside the guard window restarts it, so an auto-repeating (held) key can never get through.
|
|
125
|
+
if (now < ignoreUntil) {
|
|
126
|
+
ignoreUntil = now + guardMs;
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (!waiter)
|
|
130
|
+
return;
|
|
131
|
+
// A key counts only if it arrived alone. Keys that arrive together (a paste, or repeats of a held key buffered
|
|
132
|
+
// while the process was stalled) are all dropped and restart the guard. The decision waits for the end of the tick.
|
|
133
|
+
if (burst) {
|
|
134
|
+
burst.count++;
|
|
135
|
+
ignoreUntil = now + guardMs;
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const name = details.name ?? '';
|
|
139
|
+
const lower = char?.toLowerCase();
|
|
140
|
+
burst = { count: 1, key: name === 'space' || name === 'return' || name === 'enter' || char === ' ' || char === '\r' || char === '\n'
|
|
141
|
+
? 'reveal' : lower === 'k' ? 'keep' : lower === 'h' ? 'hide' : 'other' };
|
|
142
|
+
setImmediate(() => {
|
|
143
|
+
const settled = burst;
|
|
144
|
+
burst = undefined;
|
|
145
|
+
if (!settled || !waiter)
|
|
146
|
+
return;
|
|
147
|
+
if (settled.count > 1) {
|
|
148
|
+
ignoreUntil = performance.now() + guardMs;
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const pendingWaiter = waiter;
|
|
152
|
+
waiter = undefined;
|
|
153
|
+
pendingWaiter.resolve(settled.key);
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
const nextKey = () => new Promise((resolve, reject) => {
|
|
157
|
+
if (failure)
|
|
158
|
+
reject(failure);
|
|
159
|
+
else
|
|
160
|
+
waiter = { resolve, reject };
|
|
161
|
+
});
|
|
162
|
+
const wasRaw = input.isRaw;
|
|
163
|
+
let onAltScreen = false;
|
|
164
|
+
const restore = () => {
|
|
165
|
+
input.removeListener('keypress', onKey);
|
|
166
|
+
input.removeListener('end', fail);
|
|
167
|
+
input.removeListener('close', fail);
|
|
168
|
+
signal?.removeEventListener('abort', fail);
|
|
169
|
+
try {
|
|
170
|
+
input.setRawMode(wasRaw);
|
|
171
|
+
}
|
|
172
|
+
catch { /* the input may already be closed */ }
|
|
173
|
+
input.pause();
|
|
174
|
+
if (onAltScreen) {
|
|
175
|
+
onAltScreen = false;
|
|
176
|
+
output.write(ALT_SCREEN_OFF);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
emitKeypressEvents(input);
|
|
180
|
+
input.on('keypress', onKey);
|
|
181
|
+
input.once('end', fail);
|
|
182
|
+
input.once('close', fail);
|
|
183
|
+
signal?.addEventListener('abort', fail, { once: true });
|
|
184
|
+
try {
|
|
185
|
+
input.setRawMode(true);
|
|
186
|
+
input.resume();
|
|
187
|
+
output.write(ALT_SCREEN_ON);
|
|
188
|
+
onAltScreen = true;
|
|
189
|
+
let shown = 0;
|
|
190
|
+
let kept = 0;
|
|
191
|
+
let alsoHidden = 0;
|
|
192
|
+
for (const chip of pending) {
|
|
193
|
+
if (!review.has(chip.id))
|
|
194
|
+
continue;
|
|
195
|
+
shown++;
|
|
196
|
+
output.write(`${CLEAR_SCREEN}Candidate ${shown} (${chip.kind}, ${chip.count} uses, ${chip.sessions} sessions). Hidden.\n` +
|
|
197
|
+
'Space or Enter reveals it. Any other key hides it.\n');
|
|
198
|
+
// The same guard before every prompt: a key still held from the previous decision cannot act on this one.
|
|
199
|
+
ignoreUntil = performance.now() + guardMs;
|
|
200
|
+
let decision = await nextKey();
|
|
201
|
+
if (decision === 'reveal') {
|
|
202
|
+
const revealed = review.reveal(chip.id);
|
|
203
|
+
output.write(`\n ${safeLine(revealed.term)}\n\nK keeps it. H, Enter or any other key hides it.\n`);
|
|
204
|
+
ignoreUntil = performance.now() + guardMs;
|
|
205
|
+
decision = await nextKey();
|
|
206
|
+
}
|
|
207
|
+
else
|
|
208
|
+
decision = 'hide';
|
|
209
|
+
if (decision === 'keep') {
|
|
210
|
+
review.keep(chip.id);
|
|
211
|
+
kept++;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const keptBefore = review.list().filter(item => item.state === 'kept').length;
|
|
215
|
+
const before = review.list().length;
|
|
216
|
+
review.hide(chip.id);
|
|
217
|
+
const keptAfter = review.list().filter(item => item.state === 'kept').length;
|
|
218
|
+
alsoHidden += before - 1 - review.list().length;
|
|
219
|
+
kept -= keptBefore - keptAfter;
|
|
220
|
+
}
|
|
221
|
+
restore();
|
|
222
|
+
output.write(`Kept ${kept} of ${pending.length} phrase candidates.` +
|
|
223
|
+
(alsoHidden ? ` Hiding also removed ${alsoHidden} related candidates that shared a word, including any you had kept.` : '') + '\n');
|
|
224
|
+
return review.withKept(report).content?.private;
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
review.clear();
|
|
228
|
+
restore();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
export function serializeExport(report, reviewed) {
|
|
232
|
+
const validated = validateWrappedReport(reviewed && typeof reviewed === 'object' && report.content
|
|
233
|
+
? { ...report, content: { ...report.content, private: reviewed } } : report);
|
|
234
|
+
if (!validated.content)
|
|
235
|
+
return JSON.stringify(validated);
|
|
236
|
+
const { private: candidates, safety: _safety, receipt: contentReceipt, ...counted } = validated.content;
|
|
237
|
+
const { redactions: _redactions, ...exportedReceipt } = contentReceipt;
|
|
238
|
+
// R7: flags (country, subdivision, rainbow and other flag sequences), the per-script token mix and the languages of
|
|
239
|
+
// thank-yous are proxies for nationality, language or identity. Like `safety`, they stay local: out of every
|
|
240
|
+
// export. Skin tones are already folded to the base emoji by the analyzer.
|
|
241
|
+
const notFlag = (row) => !FLAG_EMOJI.test(row.emoji);
|
|
242
|
+
const chapter = {
|
|
243
|
+
...counted,
|
|
244
|
+
emoji: { ...counted.emoji, user: counted.emoji.user.filter(notFlag), agent: counted.emoji.agent.filter(notFlag) },
|
|
245
|
+
style: { ...counted.style, scripts: {} },
|
|
246
|
+
// The language mix of thank-yous is the same kind of proxy as the script mix.
|
|
247
|
+
combos: { ...counted.combos, thanksByLanguage: {} },
|
|
248
|
+
};
|
|
249
|
+
const { content: _contentReceipt, ...receipt } = validated.receipt;
|
|
250
|
+
return JSON.stringify({
|
|
251
|
+
...validated, receipt: { ...receipt, content: exportedReceipt },
|
|
252
|
+
content: { ...chapter, receipt: exportedReceipt, ...(reviewed && typeof reviewed === 'object' && candidates ? { private: candidates } : {}) },
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
export function printContentExportNotice(report, reviewed) {
|
|
256
|
+
if (!report.content)
|
|
257
|
+
return;
|
|
258
|
+
process.stderr.write(reviewed
|
|
259
|
+
? 'JSON includes word and emoji counts with hour and month series, and the phrases you kept. Flags, script and language mix, and safety counts stay out.\n'
|
|
260
|
+
: 'JSON includes word and emoji counts with hour and month series. Flags, script and language mix, safety counts and phrase candidates stay out.\n');
|
|
261
|
+
}
|
|
262
|
+
export function printTerminalReport(report, ledger, { privacyReceipt = false } = {}) {
|
|
263
|
+
const { capturedWindow, totals, rhythm, craft, delegation, evolution, scale, probableCause, archetype } = report;
|
|
264
|
+
printBanner();
|
|
265
|
+
process.stdout.write([
|
|
266
|
+
section('Docket', [
|
|
267
|
+
`${report.docketNumber} · REG ${report.registration} · ${report.format}`,
|
|
268
|
+
`${report.year} · ${report.timezone} · Investigator ${report.investigatorLabel}`,
|
|
269
|
+
report.isDemo ? 'Synthetic recorder · fictional evidence' : null,
|
|
270
|
+
]),
|
|
271
|
+
section('Captured Window', [
|
|
272
|
+
capturedWindow.titleLabel,
|
|
273
|
+
capturedWindow.disclosure,
|
|
274
|
+
`${number.format(totals.sessions)} sessions · ${number.format(capturedWindow.activeDays)} active days`,
|
|
275
|
+
...capturedWindow.perHarness.map(({ displayName, retentionNote, likelyTruncated }) => retentionNote || likelyTruncated ? `${displayName} · ${retentionNote ?? 'Captured history may be truncated.'}` : null),
|
|
276
|
+
]),
|
|
277
|
+
section('Rhythm', [rhythm.solarNoon.copy, rhythm.witchingHour.copy, rhythm.longestNight.copy, rhythm.streaks.copy, rhythm.weekendContrast.copy]),
|
|
278
|
+
section('Craft', [craft.coverageNote, craft.readEditCopy, craft.bounceBack.copy, craft.leashLength.copy, craft.pilotSplit.copy]),
|
|
279
|
+
section('Delegation', [delegation.orchestra.copy, delegation.cliffDiving.copy, delegation.parallelism.copy, delegation.unattended.copy]),
|
|
280
|
+
section('Evolution', [evolution.modelRiver.migration.copy, evolution.harnessPolyglot.copy, evolution.turningPoint.copy]),
|
|
281
|
+
section('Honest Scale', [
|
|
282
|
+
`≈ ${number.format(totals.wallClockActiveMinutes / 60)} wall-clock active hours`,
|
|
283
|
+
totals.tokens ? `${number.format(totals.tokens.totalProcessed)} tokens processed in the captured data` : 'Token totals unavailable.',
|
|
284
|
+
scale.writtenAnchor?.metaphorCopy,
|
|
285
|
+
scale.writtenAnchor?.methodNote,
|
|
286
|
+
scale.cacheMastery.copy,
|
|
287
|
+
scale.apiEquivalent.eligible ? scale.apiEquivalent.disclaimer : null,
|
|
288
|
+
]),
|
|
289
|
+
...(report.content ? [section('We only counted', report.content.lexicon.map(c => `${c.id} · ${number.format(c.total)}`))] : []),
|
|
290
|
+
section('Findings', report.findings.map(({ id, epistemic, statement, datum }) => `${id} [${epistemic}] ${statement} ${datum}`)),
|
|
291
|
+
section('Probable Cause', [`[interpretation] ${probableCause.headline}`, probableCause.evidence]),
|
|
292
|
+
section('Archetype', [archetype.title, archetype.tagline, archetype.body]),
|
|
293
|
+
section('Safety Recommendations', report.safetyRecommendations.map(({ id, text }) => `${id} ${text}`)),
|
|
294
|
+
...(privacyReceipt ? [section('Privacy Receipt', [
|
|
295
|
+
`External bytes sent ${report.receipt.externalBytesSent}`,
|
|
296
|
+
...(report.content ? [`Content-pass raw bytes persisted (declared and tested) ${report.content.receipt.rawBytesPersisted}`] : []),
|
|
297
|
+
...(report.receipt.contentNote ? ['Word counting unavailable. Metadata readout completed.'] : []),
|
|
298
|
+
`Extracted fields ${report.receipt.extractedFieldCategories.join(', ')}`,
|
|
299
|
+
`Discarded fields ${report.receipt.discardedFieldCategories.join(', ')}`,
|
|
300
|
+
...ledger.map((source) => `${source.candidateId} ${source.canonicalPath} [${source.status} · ${number.format(source.bytesRead)} bytes read${source.failureCode ? ` · ${source.failureCode}` : ''}]`),
|
|
301
|
+
])] : []),
|
|
302
|
+
`\n${RULE}\nExit ${report.exitCodeNote.displayCode} ${safeLine(report.exitCodeNote.reason)}\n`,
|
|
303
|
+
].join(''));
|
|
304
|
+
}
|
|
305
|
+
export function writeExportJson(filePath, report, { force = false, reviewed } = {}) {
|
|
306
|
+
const json = serializeExport(report, reviewed);
|
|
307
|
+
const destination = resolve(filePath);
|
|
308
|
+
const parentDir = dirname(destination);
|
|
309
|
+
let parentIsDir = false;
|
|
310
|
+
try {
|
|
311
|
+
parentIsDir = statSync(parentDir).isDirectory();
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
parentIsDir = false;
|
|
315
|
+
}
|
|
316
|
+
if (!parentIsDir) {
|
|
317
|
+
throw new Error(`Export directory does not exist: ${safeLine(parentDir)}`);
|
|
318
|
+
}
|
|
319
|
+
const stagingDir = mkdtempSync(join(parentDir, '.coauthored-'));
|
|
320
|
+
const staged = join(stagingDir, 'report.json');
|
|
321
|
+
try {
|
|
322
|
+
writeFileSync(staged, json, { flag: 'wx', mode: 0o600 });
|
|
323
|
+
if (force) {
|
|
324
|
+
renameSync(staged, destination);
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
try {
|
|
328
|
+
linkSync(staged, destination);
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
const code = error.code;
|
|
332
|
+
if (code === 'EPERM' || code === 'ENOTSUP' || code === 'EXDEV') {
|
|
333
|
+
writeFileSync(destination, json, { flag: 'wx', mode: 0o600 });
|
|
334
|
+
}
|
|
335
|
+
else {
|
|
336
|
+
throw error;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
catch (error) {
|
|
342
|
+
if (error.code === 'EEXIST') {
|
|
343
|
+
throw new Error('The export already exists. Pass --force to replace it.', { cause: error });
|
|
344
|
+
}
|
|
345
|
+
throw error;
|
|
346
|
+
}
|
|
347
|
+
finally {
|
|
348
|
+
try {
|
|
349
|
+
unlinkSync(staged);
|
|
350
|
+
}
|
|
351
|
+
catch (error) {
|
|
352
|
+
if (error.code !== 'ENOENT')
|
|
353
|
+
throw error;
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
rmdirSync(stagingDir);
|
|
357
|
+
}
|
|
358
|
+
catch (error) {
|
|
359
|
+
if (error.code !== 'ENOENT')
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { basename, dirname, relative } from 'node:path';
|
|
2
|
+
import { parseTimezones, zonedTimestamp } from '../time-window.js';
|
|
3
|
+
import { MAX_MESSAGE_BYTES } from './content.js';
|
|
4
|
+
import { count, defineAdapter, hasCounts, obj, str, timestamp, tokens } from './shared.js';
|
|
5
|
+
export const aiderAdapter = defineAdapter({
|
|
6
|
+
id: 'aider', displayName: 'Aider', tier: 2, defaultRetentionDays: null,
|
|
7
|
+
roots: ({ env }) => env.COAUTHORED_AIDER_ANALYTICS_LOG ? [env.COAUTHORED_AIDER_ANALYTICS_LOG] : [],
|
|
8
|
+
configuredMatch: (path, root, { env }) => root === env.COAUTHORED_AIDER_ANALYTICS_LOG && !relative(root, path),
|
|
9
|
+
matches: path => basename(path) === '.aider.chat.history.md' || /^(?:\.?(?:aider[-_.])?analytics(?:[-_.]log)?)\.jsonl$/i.test(basename(path)),
|
|
10
|
+
async parse(state, files) {
|
|
11
|
+
const zone = parseTimezones.get(state.ctx) ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
12
|
+
for (const path of files) {
|
|
13
|
+
if (basename(path) === '.aider.chat.history.md') {
|
|
14
|
+
let ordinal = 0;
|
|
15
|
+
let session;
|
|
16
|
+
let sessionTs = 0;
|
|
17
|
+
let role;
|
|
18
|
+
let lines = [];
|
|
19
|
+
let chars = 0;
|
|
20
|
+
let block = 0;
|
|
21
|
+
let fence;
|
|
22
|
+
let hasPrompt = false;
|
|
23
|
+
let promptBoundary = true;
|
|
24
|
+
let previousUserLine = false;
|
|
25
|
+
const flush = () => {
|
|
26
|
+
if (session && role && (lines.length || chars > MAX_MESSAGE_BYTES)) {
|
|
27
|
+
state.content(role, session, sessionTs, String(block++), chars > MAX_MESSAGE_BYTES ? null : lines.join('\n'));
|
|
28
|
+
}
|
|
29
|
+
role = undefined;
|
|
30
|
+
lines = [];
|
|
31
|
+
chars = 0;
|
|
32
|
+
};
|
|
33
|
+
await state.text(path, line => {
|
|
34
|
+
const match = /^# aider chat started at (\d{4}-\d\d-\d\d)[ T](\d\d:\d\d:\d\d)\b/i.exec(line);
|
|
35
|
+
if (match) {
|
|
36
|
+
const ts = zonedTimestamp(`${match[1]}T${match[2]}`, zone);
|
|
37
|
+
if (!Number.isFinite(ts))
|
|
38
|
+
return;
|
|
39
|
+
const key = JSON.stringify([path, ts, ++ordinal]);
|
|
40
|
+
state.session(key, ts, dirname(path));
|
|
41
|
+
if (!state.ctx.content)
|
|
42
|
+
return;
|
|
43
|
+
flush();
|
|
44
|
+
session = key;
|
|
45
|
+
sessionTs = ts;
|
|
46
|
+
hasPrompt = false;
|
|
47
|
+
promptBoundary = true;
|
|
48
|
+
fence = undefined;
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (!state.ctx.content || !session || !state.observed(sessionTs))
|
|
52
|
+
return;
|
|
53
|
+
// Aider writes each typed line as "#### text" plus two trailing spaces (a blank input line is "#### ").
|
|
54
|
+
// A reply can open with its own "#### Heading" one blank line later, so a heading counts as the user's only
|
|
55
|
+
// when it carries the two-space line break or directly follows another typed line (R6).
|
|
56
|
+
const typed = !fence && line.startsWith('#### ') && promptBoundary && (/ {2}$/.test(line) || previousUserLine);
|
|
57
|
+
previousUserLine = typed;
|
|
58
|
+
if (typed) {
|
|
59
|
+
if (role !== 'user')
|
|
60
|
+
flush();
|
|
61
|
+
role = 'user';
|
|
62
|
+
hasPrompt = true;
|
|
63
|
+
line = line.slice(5).trimEnd();
|
|
64
|
+
}
|
|
65
|
+
else if (!fence && (!line.trim() || /^\s*>/.test(line))) {
|
|
66
|
+
if (/^\s*>/.test(line)) {
|
|
67
|
+
promptBoundary = true;
|
|
68
|
+
// Aider's tool lines ("> Added src/app.py to the chat") feed only the open-vocabulary veto (R2).
|
|
69
|
+
state.identifiers(line.replace(/^\s*>\s?/, ''));
|
|
70
|
+
}
|
|
71
|
+
if (role === 'user' || /^\s*>/.test(line))
|
|
72
|
+
flush();
|
|
73
|
+
if (role !== 'agent')
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
else if (hasPrompt) {
|
|
77
|
+
if (line.trim())
|
|
78
|
+
promptBoundary = false;
|
|
79
|
+
if (role !== 'agent')
|
|
80
|
+
flush();
|
|
81
|
+
role = 'agent';
|
|
82
|
+
const delimiter = /^\s*(```|~~~)/.exec(line)?.[1];
|
|
83
|
+
if (delimiter)
|
|
84
|
+
fence = fence === delimiter ? undefined : fence ?? delimiter;
|
|
85
|
+
}
|
|
86
|
+
else
|
|
87
|
+
return;
|
|
88
|
+
chars += line.length + 1;
|
|
89
|
+
if (chars <= MAX_MESSAGE_BYTES)
|
|
90
|
+
lines.push(line);
|
|
91
|
+
else
|
|
92
|
+
lines = [];
|
|
93
|
+
});
|
|
94
|
+
if (state.ctx.content)
|
|
95
|
+
flush();
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
await state.jsonl(path, (row, ordinal) => {
|
|
99
|
+
if (row.event !== 'message_send')
|
|
100
|
+
return;
|
|
101
|
+
const p = obj(row.properties);
|
|
102
|
+
const time = typeof row.time === 'number' && Math.abs(row.time) < 100_000_000_000 ? row.time * 1000 : row.time;
|
|
103
|
+
const ts = timestamp(time, row.timestamp);
|
|
104
|
+
if (ts === undefined)
|
|
105
|
+
return;
|
|
106
|
+
const session = str(row.session_id, p.session_id) ?? path;
|
|
107
|
+
const id = str(row.event_id, row.id) ?? JSON.stringify([session, ts, ordinal]);
|
|
108
|
+
state.session(session, ts, str(p.cwd));
|
|
109
|
+
if (hasCounts(p, ['prompt_tokens', 'completion_tokens'])) {
|
|
110
|
+
state.request(session, ts, id, tokens(count(p.prompt_tokens), count(p.completion_tokens)), { model: p.main_model, contextFill: false });
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
});
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { basename, dirname, join } from 'node:path';
|
|
2
|
+
import { normalizeContentText } from '../../report/content/redact.js';
|
|
3
|
+
import { contentExcluded, textParts } from './content.js';
|
|
4
|
+
import { arr, count, defineAdapter, fileSession, hasCounts, obj, segments, str, timestamp, tokens } from './shared.js';
|
|
5
|
+
const usageFields = ['input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'];
|
|
6
|
+
export const claudeCodeAdapter = defineAdapter({
|
|
7
|
+
id: 'claude-code', displayName: 'Claude Code', tier: 1, defaultRetentionDays: 30,
|
|
8
|
+
roots: ({ env, homeDir }) => [join(env.CLAUDE_CONFIG_DIR || join(homeDir, '.claude'), 'projects')],
|
|
9
|
+
matches(path) {
|
|
10
|
+
const parts = segments(path);
|
|
11
|
+
return parts.includes('projects') && /\.jsonl$/i.test(path) &&
|
|
12
|
+
!['history.jsonl', 'sessions-index.jsonl'].includes(basename(path)) &&
|
|
13
|
+
(!parts.includes('subagents') || /^agent-/i.test(basename(path)));
|
|
14
|
+
},
|
|
15
|
+
async parse(state, files) {
|
|
16
|
+
const calls = new Map();
|
|
17
|
+
const outcomes = new Map();
|
|
18
|
+
const bareOwners = new Map();
|
|
19
|
+
const pairedOwners = new Map();
|
|
20
|
+
let recentIdentity;
|
|
21
|
+
const requests = new Map();
|
|
22
|
+
for (const path of files) {
|
|
23
|
+
const fileId = fileSession(path);
|
|
24
|
+
const isChild = basename(dirname(path)) === 'subagents' || fileId.startsWith('agent-');
|
|
25
|
+
const folderParent = basename(dirname(path)) === 'subagents' ? basename(dirname(dirname(path))) : undefined;
|
|
26
|
+
await state.jsonl(path, (row, ordinal) => {
|
|
27
|
+
const message = obj(row.message);
|
|
28
|
+
const ts = timestamp(row.timestamp);
|
|
29
|
+
if (ts === undefined)
|
|
30
|
+
return;
|
|
31
|
+
const child = isChild || row.isSidechain === true;
|
|
32
|
+
const agentId = str(row.agentId);
|
|
33
|
+
const parent = child ? str(row.parentSessionId, folderParent, row.sessionId) : undefined;
|
|
34
|
+
const unresolved = child && !isChild && !agentId;
|
|
35
|
+
const session = child ? (agentId ? (agentId.startsWith('agent-') ? agentId : `agent-${agentId}`) :
|
|
36
|
+
isChild ? fileId : JSON.stringify(['sidechain', parent ?? fileId])) : str(row.sessionId, fileId);
|
|
37
|
+
const entry = str(row.uuid) ?? JSON.stringify([path, ordinal]);
|
|
38
|
+
const cwd = str(row.cwd);
|
|
39
|
+
if (!unresolved)
|
|
40
|
+
state.session(session, ts, cwd, child, parent);
|
|
41
|
+
if (row.type === 'user') {
|
|
42
|
+
let hasResult = false;
|
|
43
|
+
let hasPrompt = typeof message.content === 'string';
|
|
44
|
+
for (const raw of arr(message.content)) {
|
|
45
|
+
const block = obj(raw);
|
|
46
|
+
if (block.type === 'tool_result') {
|
|
47
|
+
hasResult = true;
|
|
48
|
+
const id = str(block.tool_use_id);
|
|
49
|
+
if (id)
|
|
50
|
+
outcomes.set(id, block.is_error === true);
|
|
51
|
+
}
|
|
52
|
+
else if (block.type === 'text' || block.type === 'image')
|
|
53
|
+
hasPrompt = true;
|
|
54
|
+
}
|
|
55
|
+
if (!child && !row.isMeta && !row.isCompactSummary && !row.isReplay && !hasResult && hasPrompt) {
|
|
56
|
+
state.prompt(session, ts, entry);
|
|
57
|
+
if (state.ctx.content && !contentExcluded(row, message)) {
|
|
58
|
+
const text = textParts(message.content, 'text');
|
|
59
|
+
if (typeof text !== 'string' || !/^\s*<(?:bash-[\w-]+|local-command-stdout|command-name)\b/i.test(normalizeContentText(text))) {
|
|
60
|
+
state.content('user', session, ts, entry, text, typeof row.uuid === 'string');
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (!unresolved && row.type === 'system' && row.subtype === 'compact_boundary') {
|
|
66
|
+
state.compact(session, ts, entry, obj(row.compactMetadata).trigger);
|
|
67
|
+
}
|
|
68
|
+
if (row.type !== 'assistant' || row.isMeta || row.isCompactSummary)
|
|
69
|
+
return;
|
|
70
|
+
if (state.ctx.content && !unresolved && !contentExcluded(row, message) && Array.isArray(message.content)) {
|
|
71
|
+
state.content('agent', session, ts, entry, textParts(message.content, 'text'), typeof row.uuid === 'string');
|
|
72
|
+
}
|
|
73
|
+
const messageId = str(message.id) ?? entry;
|
|
74
|
+
const requestId = str(row.requestId);
|
|
75
|
+
const pair = requestId === undefined ? undefined : JSON.stringify([messageId, requestId]);
|
|
76
|
+
const owners = pair === undefined ? bareOwners : pairedOwners;
|
|
77
|
+
const ownerKey = pair ?? JSON.stringify(messageId);
|
|
78
|
+
let owner = owners.get(ownerKey);
|
|
79
|
+
const rank = isChild ? 3 : agentId ? 2 : child ? 0 : 1;
|
|
80
|
+
if (!owner || rank > owner.identity.rank) {
|
|
81
|
+
if (!recentIdentity || recentIdentity.session !== session || recentIdentity.cwd !== cwd ||
|
|
82
|
+
recentIdentity.child !== child || recentIdentity.parent !== parent || recentIdentity.rank !== rank) {
|
|
83
|
+
recentIdentity = { session, cwd, child, parent, rank };
|
|
84
|
+
}
|
|
85
|
+
// A request or tool call from an earlier row must see the final owner too.
|
|
86
|
+
if (owner) {
|
|
87
|
+
owner.identity = recentIdentity;
|
|
88
|
+
owner.ts = ts;
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
owner = { identity: recentIdentity, ts };
|
|
92
|
+
owners.set(ownerKey, owner);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
else if (owner.identity.session === session)
|
|
96
|
+
owner.ts = Math.min(ts, owner.ts);
|
|
97
|
+
const usage = obj(message.usage);
|
|
98
|
+
if (hasCounts(usage, usageFields)) {
|
|
99
|
+
const key = pair ?? JSON.stringify([messageId, null]);
|
|
100
|
+
const split = obj(usage.cache_creation);
|
|
101
|
+
const long = count(split.ephemeral_1h_input_tokens);
|
|
102
|
+
const short = Math.max(count(split.ephemeral_5m_input_tokens), count(usage.cache_creation_input_tokens) - long);
|
|
103
|
+
const current = tokens(count(usage.input_tokens), count(usage.output_tokens), count(usage.cache_read_input_tokens), short, long);
|
|
104
|
+
const cache = hasCounts(usage, ['cache_read_input_tokens', 'cache_creation_input_tokens']) ||
|
|
105
|
+
hasCounts(split, ['ephemeral_5m_input_tokens', 'ephemeral_1h_input_tokens']);
|
|
106
|
+
const quality = (message.stop_reason ? 4 : 0) + (hasCounts(usage, ['input_tokens']) ? 2 : 0) + Number(cache);
|
|
107
|
+
const prior = requests.get(key);
|
|
108
|
+
if (!prior || quality > prior.quality || (quality === prior.quality && current.output > prior.usage.output)) {
|
|
109
|
+
requests.set(key, { owner, usage: current, model: str(message.model, prior?.model), cache, quality });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const blocks = arr(message.content);
|
|
113
|
+
for (let index = 0; index < blocks.length; index++) {
|
|
114
|
+
const block = obj(blocks[index]);
|
|
115
|
+
if (block.type !== 'tool_use')
|
|
116
|
+
continue;
|
|
117
|
+
if (state.ctx.content)
|
|
118
|
+
state.identifiers(block.input);
|
|
119
|
+
const name = str(block.name);
|
|
120
|
+
if (!name)
|
|
121
|
+
continue;
|
|
122
|
+
const id = str(block.id) ?? JSON.stringify([pair ?? JSON.stringify([messageId, null]), index]);
|
|
123
|
+
if (!calls.has(id))
|
|
124
|
+
calls.set(id, { owner, ts, name });
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
for (const [key, request] of requests) {
|
|
129
|
+
const { identity, ts } = request.owner;
|
|
130
|
+
state.session(identity.session, ts, identity.cwd, identity.child, identity.parent);
|
|
131
|
+
state.request(identity.session, ts, key, request.usage, request);
|
|
132
|
+
}
|
|
133
|
+
for (const [id, call] of calls) {
|
|
134
|
+
const { session, cwd, child, parent } = call.owner.identity;
|
|
135
|
+
state.session(session, call.ts, cwd, child, parent);
|
|
136
|
+
state.tool(session, call.ts, id, call.name, outcomes.get(id) ?? null);
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
});
|