tracehub 0.0.0-stage → 0.5.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 (48) hide show
  1. package/README.md +424 -2
  2. package/dist/cli/args.js +28 -0
  3. package/dist/cli/clipboard.js +46 -0
  4. package/dist/cli/commands/context.js +115 -0
  5. package/dist/cli/commands/hook.js +209 -0
  6. package/dist/cli/commands/providers.js +55 -0
  7. package/dist/cli/commands/setup.js +448 -0
  8. package/dist/cli/commands/uninstall.js +156 -0
  9. package/dist/cli/io.js +26 -0
  10. package/dist/cli/remote.js +81 -0
  11. package/dist/cli/repo.js +65 -0
  12. package/dist/cli/signin.js +90 -0
  13. package/dist/cli/ui.js +130 -0
  14. package/dist/cli/usage.js +151 -0
  15. package/dist/cli.js +38 -0
  16. package/dist/client/auth.js +70 -0
  17. package/dist/client/consent.js +94 -0
  18. package/dist/client/errors.js +4 -0
  19. package/dist/client/github.js +129 -0
  20. package/dist/client/registry.js +112 -0
  21. package/dist/client/tracehub.js +98 -0
  22. package/dist/client/upload.js +106 -0
  23. package/dist/client/uploadPolicy.js +60 -0
  24. package/dist/git/git.js +166 -0
  25. package/dist/git/global-hooks.js +221 -0
  26. package/dist/git/hooks.js +67 -0
  27. package/dist/git/markers.js +93 -0
  28. package/dist/git/trailers.js +36 -0
  29. package/dist/local/commitBoundary.js +38 -0
  30. package/dist/local/discover.js +283 -0
  31. package/dist/local/files.js +55 -0
  32. package/dist/local/lines.js +16 -0
  33. package/dist/local/opencode.js +124 -0
  34. package/dist/local/paths.js +51 -0
  35. package/dist/local/providers.js +171 -0
  36. package/dist/local/subagents.js +63 -0
  37. package/dist/protocol/context.js +202 -0
  38. package/dist/protocol/sessionRef.js +24 -0
  39. package/dist/protocol/trace.js +111 -0
  40. package/dist/redact/deny.js +25 -0
  41. package/dist/redact/redact.js +189 -0
  42. package/dist/trace/build.js +256 -0
  43. package/dist/transcript/parseClaude.js +105 -0
  44. package/dist/transcript/parseCodex.js +164 -0
  45. package/dist/transcript/parseOpencode.js +84 -0
  46. package/dist/transcript/title.js +27 -0
  47. package/dist/transcript/transcript.js +120 -0
  48. package/package.json +46 -4
@@ -0,0 +1,189 @@
1
+ const REDACTED = "[redacted]";
2
+ const ENTROPY_THRESHOLD = 3.8;
3
+ const ENTROPY_MIN_LENGTH = 32;
4
+ const HEX_KEYWORD_WINDOW = 40;
5
+ const HEX_KEYWORD = /(token|secret|key|password|bearer|auth|api)/i;
6
+ function escapeRegExp(s) {
7
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8
+ }
9
+ function whole(type, re) {
10
+ return {
11
+ type,
12
+ run: (text, _opts, hit) => text.replace(re, () => {
13
+ hit();
14
+ return REDACTED;
15
+ }),
16
+ };
17
+ }
18
+ function keepPrefix(type, re) {
19
+ return {
20
+ type,
21
+ run: (text, _opts, hit) => text.replace(re, (m, prefix) => {
22
+ if (m.slice(prefix.length) === REDACTED)
23
+ return m;
24
+ hit();
25
+ return `${prefix}${REDACTED}`;
26
+ }),
27
+ };
28
+ }
29
+ export function shannonEntropy(s) {
30
+ const counts = new Map();
31
+ for (const ch of s)
32
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
33
+ let h = 0;
34
+ for (const n of counts.values()) {
35
+ const p = n / s.length;
36
+ h -= p * Math.log2(p);
37
+ }
38
+ return h;
39
+ }
40
+ const HEX = /^[0-9a-f]+$/i;
41
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
42
+ const HOSTNAME = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
43
+ // A random secret almost always carries several digits and mixes character
44
+ // classes; long identifiers, paths and hostnames do not, so they never reach
45
+ // the entropy measurement. Neither does hex, which has detectors of its own
46
+ // that leave a commit sha alone.
47
+ export function looksLikeSecretToken(token) {
48
+ if (token.length < ENTROPY_MIN_LENGTH)
49
+ return false;
50
+ const digits = (token.match(/\d/g) ?? []).length;
51
+ const classes = [/[a-z]/, /[A-Z]/, /\d/].filter((re) => re.test(token));
52
+ if (digits < 2 || classes.length < 2)
53
+ return false;
54
+ if (HEX.test(token) || UUID.test(token) || HOSTNAME.test(token))
55
+ return false;
56
+ const isPath = /^[~.]?\//.test(token);
57
+ const isPathLike = token.includes("/") && !/[+=]/.test(token);
58
+ if (isPath || isPathLike)
59
+ return false;
60
+ return shannonEntropy(token) > ENTROPY_THRESHOLD;
61
+ }
62
+ const DETECTORS = [
63
+ {
64
+ type: "home_path",
65
+ run: (text, opts, hit) => opts.homePaths
66
+ ? text.replace(/(?:\/private)?\/(?:Users|home)\/[^\/\s"'`<>]+(?=\/|[\s"'`<>]|$)|[A-Za-z]:\\Users\\[^\\\s"'`<>]+(?=\\|[\s"'`<>]|$)/g, () => {
67
+ hit();
68
+ return "~";
69
+ })
70
+ : text,
71
+ },
72
+ {
73
+ type: "deny_list",
74
+ run: (text, opts, hit) => {
75
+ let out = text;
76
+ for (const literal of opts.deny ?? []) {
77
+ if (!literal)
78
+ continue;
79
+ out = out.replace(new RegExp(escapeRegExp(literal), "g"), () => {
80
+ hit();
81
+ return REDACTED;
82
+ });
83
+ }
84
+ return out;
85
+ },
86
+ },
87
+ keepPrefix("url_credentials", /(\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@"'`]+:)[^\s/@"'`]+(?=@)/gi),
88
+ whole("pem_block", /-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/g),
89
+ whole("pem_block", /-----BEGIN [A-Z ]+-----[\s\S]*$/gm),
90
+ whole("openai_key", /\bsk-[A-Za-z0-9_-]{8,}\b/g),
91
+ whole("stripe_key", /\b[sr]k_(?:live|test)_[A-Za-z0-9]{8,}\b/g),
92
+ whole("webhook_secret", /\bwhsec_[A-Za-z0-9]{8,}\b/g),
93
+ whole("github_token", /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g),
94
+ whole("github_token", /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g),
95
+ whole("gitlab_token", /\bglpat-[A-Za-z0-9_-]{16,}\b/g),
96
+ whole("aws_key", /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g),
97
+ whole("slack_token", /\bxox[abpr]-[A-Za-z0-9-]{10,}\b/g),
98
+ whole("google_api_key", /\bAIza[0-9A-Za-z_-]{30,}\b/g),
99
+ whole("neon_key", /\bnpg_[A-Za-z0-9]{8,}\b/g),
100
+ whole("pat_token", /\bpat_[A-Za-z0-9_-]{16,}\b/g),
101
+ whole("square_token", /\bsq0[a-z]{3}-[A-Za-z0-9_-]{16,}\b/g),
102
+ whole("dotted_token", /\btoken\.[A-Za-z0-9_-]{20,}\b/g),
103
+ whole("jwt", /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g),
104
+ keepPrefix("authorization_header", /(\bauthorization\s*[:=]\s*)(?:(?:bearer|basic|token)\s+)?\S+/gi),
105
+ keepPrefix("bearer_token", /(\bBearer\s+)[A-Za-z0-9._~+/=-]{8,}/g),
106
+ keepPrefix("basic_auth", /(\bBasic\s+)[A-Za-z0-9+/]{8,}={0,2}/g),
107
+ keepPrefix("keyed_assignment", /(\b(?:(?:[A-Za-z0-9]+[_-])+(?:key|token|secret|password|passwd|pwd)|password|passwd|pwd|secret|token|credentials?)\s*[=:]\s*["']?)[^\s"'&,;]+/gi),
108
+ keepPrefix("keyed_assignment", /(\b(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD)\s*[=:]\s*["']?)[^\s"'&,;]+/g),
109
+ keepPrefix("json_secret_assignment", /(\b(?:[a-z0-9_\-]*(?:password|passwd|secret|token|api_key|apikey|private_key|credentials?))["']\s*:\s*["'])[^"'\r\n]+/gi),
110
+ whole("long_hex", /\b[0-9a-fA-F]{64,}\b/g),
111
+ {
112
+ type: "keyed_hex",
113
+ run: (text, _opts, hit) => text.replace(/\b[0-9a-fA-F]{32,63}\b/g, (m, offset) => {
114
+ const start = Math.max(0, offset - HEX_KEYWORD_WINDOW);
115
+ if (!HEX_KEYWORD.test(text.slice(start, offset)))
116
+ return m;
117
+ hit();
118
+ return REDACTED;
119
+ }),
120
+ },
121
+ {
122
+ type: "high_entropy",
123
+ run: (text, _opts, hit) => text.replace(/[A-Za-z0-9_\-+/=.]{32,}/g, (m) => {
124
+ if (!looksLikeSecretToken(m))
125
+ return m;
126
+ hit();
127
+ return REDACTED;
128
+ }),
129
+ },
130
+ ];
131
+ function addFinding(counts, type, count = 1) {
132
+ counts.set(type, (counts.get(type) ?? 0) + count);
133
+ }
134
+ export function addFindings(counts, findings) {
135
+ for (const f of findings)
136
+ addFinding(counts, f.type, f.count);
137
+ }
138
+ export function findingsOf(counts) {
139
+ return [...counts].map(([type, count]) => ({ type, count }));
140
+ }
141
+ // "2 findings (github_token ×1, aws_key ×1)": types and counts, never values.
142
+ export function formatFindings(findings) {
143
+ const total = findings.reduce((n, f) => n + f.count, 0);
144
+ const byType = findings.map((f) => `${f.type} ×${f.count}`).join(", ");
145
+ return `${total} finding${total === 1 ? "" : "s"} (${byType})`;
146
+ }
147
+ export function redactText(text, opts = {}) {
148
+ const counts = new Map();
149
+ let out = text;
150
+ for (const detector of DETECTORS) {
151
+ out = detector.run(out, opts, () => addFinding(counts, detector.type));
152
+ }
153
+ if (opts.homeDir)
154
+ out = rewriteHome(out, opts.homeDir);
155
+ return { text: out, findings: findingsOf(counts) };
156
+ }
157
+ function redactDeep(value, opts, counts) {
158
+ if (typeof value === "string") {
159
+ const redacted = redactText(value, opts);
160
+ addFindings(counts, redacted.findings);
161
+ return redacted.text;
162
+ }
163
+ if (Array.isArray(value)) {
164
+ return value.map((v) => redactDeep(v, opts, counts));
165
+ }
166
+ if (value && typeof value === "object") {
167
+ const entries = Object.entries(value).map(([k, v]) => [
168
+ k,
169
+ /^(?:(?:.*[_-])?(?:password|passwd|secret|token|api_key|private_key|credentials?)|accessToken|refreshToken)$/i.test(k) && typeof v === "string"
170
+ ? REDACTED
171
+ : redactDeep(v, opts, counts),
172
+ ]);
173
+ return Object.fromEntries(entries);
174
+ }
175
+ return value;
176
+ }
177
+ // Every string in a JSON value, redacted.
178
+ export function redactValue(value, opts = {}) {
179
+ const counts = new Map();
180
+ const out = redactDeep(value, opts, counts);
181
+ return { value: out, findings: findingsOf(counts) };
182
+ }
183
+ export function rewriteHome(text, homeDir) {
184
+ const trimmed = homeDir.replace(/\/+$/, "");
185
+ if (!trimmed)
186
+ return text;
187
+ const home = new RegExp(`(?:/private)?${escapeRegExp(trimmed)}(?=/|\\b)`, "g");
188
+ return text.replace(home, "~");
189
+ }
@@ -0,0 +1,256 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep, } from "node:path";
3
+ import { gitDir, repoRoot } from "../git/git.js";
4
+ import { ranInside } from "../local/discover.js";
5
+ import { contextRefsIn } from "../protocol/context.js";
6
+ import { lineHash, } from "../protocol/trace.js";
7
+ import { redactValue, } from "../redact/redact.js";
8
+ import { parseClaude } from "../transcript/parseClaude.js";
9
+ import { parseCodex } from "../transcript/parseCodex.js";
10
+ import { parseOpencode } from "../transcript/parseOpencode.js";
11
+ import { sessionTitle } from "../transcript/title.js";
12
+ import { sliceTranscript, } from "../transcript/transcript.js";
13
+ export function parseSessionLines(agent, id, lines, sidechain = false) {
14
+ switch (agent) {
15
+ case "claude":
16
+ return parseClaude(lines, id, { sidechain });
17
+ case "codex":
18
+ return parseCodex(lines, id);
19
+ case "opencode":
20
+ return parseOpencode(lines, id);
21
+ }
22
+ }
23
+ function realOrSelf(path) {
24
+ try {
25
+ return realpathSync(path);
26
+ }
27
+ catch {
28
+ try {
29
+ return join(realpathSync(dirname(path)), basename(path));
30
+ }
31
+ catch {
32
+ return path;
33
+ }
34
+ }
35
+ }
36
+ // A file's path in the repository, or nothing for a file outside it: a
37
+ // local path never leaves the machine.
38
+ function repoPath(path, cwd, roots) {
39
+ const abs = isAbsolute(path) ? path : resolve(cwd, path);
40
+ for (const root of roots) {
41
+ for (const candidate of [abs, realOrSelf(abs)]) {
42
+ const rel = relative(root, candidate);
43
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel))
44
+ return rel.split(sep).join("/");
45
+ }
46
+ }
47
+ return undefined;
48
+ }
49
+ function addChange(turn, path, added, removed) {
50
+ const change = turn.changes.find((c) => c.path === path);
51
+ if (change) {
52
+ change.added += added;
53
+ change.removed += removed;
54
+ }
55
+ else
56
+ turn.changes.push({ path, added, removed });
57
+ }
58
+ // The turns of a transcript: a turn starts at each prompt and holds the
59
+ // messages after it, the files its edits changed and the subagents it ran.
60
+ function turnsOf(events, cwd, prefix, ctx, children) {
61
+ const turns = [];
62
+ const callTurn = new Map();
63
+ for (const event of events) {
64
+ if (event.kind === "tool_result")
65
+ continue;
66
+ const opens = event.kind === "user" && !event.steering;
67
+ if (opens || !turns.length)
68
+ turns.push({ at: event.ts, messages: [], changes: [], runs: [] });
69
+ const turn = turns.at(-1);
70
+ const index = turns.length - 1;
71
+ if (event.kind === "user")
72
+ turn.messages.push({ role: "user", at: event.ts, text: event.text });
73
+ else if (event.kind === "assistant")
74
+ turn.messages.push({ role: "agent", at: event.ts, text: event.text });
75
+ else {
76
+ if (event.callId)
77
+ callTurn.set(event.callId, index);
78
+ for (const edit of event.edits ?? []) {
79
+ const abs = isAbsolute(edit.path) ? edit.path : resolve(cwd, edit.path);
80
+ const path = repoPath(abs, cwd, ctx.roots(dirname(abs)));
81
+ if (!path)
82
+ continue;
83
+ addChange(turn, path, edit.added.length, edit.removed.length);
84
+ const hashes = new Set(edit.added.map(lineHash).filter((h) => h !== undefined));
85
+ const ts = Date.parse(event.ts);
86
+ ctx.written.push({ turn: `${prefix}${index}`, ts, path, hashes });
87
+ }
88
+ }
89
+ }
90
+ // A subagent goes under the turn whose call launched it, else under the
91
+ // last turn that started before it did.
92
+ for (const child of children) {
93
+ let index = child.callId === undefined ? undefined : callTurn.get(child.callId);
94
+ if (index === undefined) {
95
+ index = turns.length - 1;
96
+ while (index > 0 && Date.parse(turns[index].at) > child.startMs)
97
+ index--;
98
+ }
99
+ const turn = turns[index];
100
+ if (!turn)
101
+ continue;
102
+ const runPrefix = `${prefix}${index}.${turn.runs.length}.`;
103
+ const childCwd = child.transcript.cwd || cwd;
104
+ const runTurns = turnsOf(child.transcript.events, childCwd, runPrefix, ctx, []);
105
+ const first = runTurns[0];
106
+ if (child.prompt && !first?.messages.some((m) => m.role === "user")) {
107
+ const at = first?.at ?? turn.at;
108
+ if (first)
109
+ first.messages.unshift({ role: "user", at, text: child.prompt });
110
+ else
111
+ runTurns.push({
112
+ at,
113
+ messages: [{ role: "user", at, text: child.prompt }],
114
+ changes: [],
115
+ runs: [],
116
+ });
117
+ }
118
+ turn.runs.push({ label: child.label, turns: runTurns });
119
+ }
120
+ return turns;
121
+ }
122
+ // For each line the commit adds, the turn of the last edit that wrote it.
123
+ function sourcemapOf(written, added) {
124
+ const byPath = new Map();
125
+ const ordered = written
126
+ .map((w, order) => ({ w, order }))
127
+ .sort((a, b) => (a.w.ts || 0) - (b.w.ts || 0) || a.order - b.order)
128
+ .map(({ w }) => w);
129
+ for (const w of ordered)
130
+ byPath.set(w.path, [...(byPath.get(w.path) ?? []), w]);
131
+ const map = {};
132
+ for (const [path, lines] of added) {
133
+ const edits = byPath.get(path);
134
+ if (!edits)
135
+ continue;
136
+ for (const line of lines) {
137
+ const hash = lineHash(line);
138
+ if (!hash)
139
+ continue;
140
+ const last = [...edits].reverse().find((w) => w.hashes.has(hash));
141
+ if (last)
142
+ (map[path] ??= {})[hash] = last.turn;
143
+ }
144
+ }
145
+ return map;
146
+ }
147
+ // The first user message of the session and of each run: the briefs, where
148
+ // a coordinator names the conversation the work is for.
149
+ function briefsOf(turns) {
150
+ const first = turns[0]?.messages.find((m) => m.role === "user");
151
+ return [
152
+ ...(first ? [first.text] : []),
153
+ ...turns.flatMap((t) => t.runs.flatMap((r) => briefsOf(r.turns))),
154
+ ];
155
+ }
156
+ // What leaves the machine for one session at one commit: the turns up to
157
+ // the commit (and the agent's replies that finish the commit's turn), the
158
+ // changes of each turn and the sourcemap of the commit's lines, redacted.
159
+ // Whether any of the turns, or their runs, changed a file.
160
+ function changed(turns) {
161
+ return turns.some((t) => t.changes.length > 0 || t.runs.some((r) => changed(r.turns)));
162
+ }
163
+ // Undefined when there is nothing to share: a session that ran outside the
164
+ // repository and whose subagents changed none of its files.
165
+ export function buildTrace(input, opts = {}) {
166
+ const { agent, id, lines, cut, committedAt } = input;
167
+ const cutoffMs = Date.parse(committedAt);
168
+ const sidechain = input.subagent !== undefined;
169
+ const whole = parseSessionLines(agent, id, lines, sidechain);
170
+ const before = parseSessionLines(agent, id, lines.slice(0, cut), sidechain);
171
+ const events = [...before.events];
172
+ for (const event of whole.events.slice(before.events.length)) {
173
+ if (event.kind === "user" && !event.steering)
174
+ break;
175
+ if (event.kind === "assistant")
176
+ events.push(event);
177
+ }
178
+ const children = input.subagents.map((subagent) => {
179
+ const parsed = parseSessionLines(agent, subagent.id, subagent.lines, true);
180
+ const transcript = sliceTranscript(parsed, cutoffMs);
181
+ const callId = subagent.toolUseId ?? whole.agentLinks[subagent.id];
182
+ const spawn = whole.spawns.find((s) => s.callId === callId);
183
+ const start = Date.parse(transcript.events[0]?.ts ?? "");
184
+ return {
185
+ transcript,
186
+ label: spawn?.description || subagent.kind,
187
+ prompt: spawn?.prompt ?? "",
188
+ callId,
189
+ startMs: Number.isNaN(start) ? Infinity : start,
190
+ };
191
+ });
192
+ // A file counts as the repository's when it is in a checkout of it: this
193
+ // one, or a worktree that shares its git directory.
194
+ const common = gitDir(input.root);
195
+ const worktrees = new Map();
196
+ const worktreeOf = (dir) => {
197
+ if (!worktrees.has(dir)) {
198
+ const root = repoRoot(dir);
199
+ worktrees.set(dir, root && gitDir(root) === common ? root : undefined);
200
+ }
201
+ return worktrees.get(dir);
202
+ };
203
+ const ownCheckout = (cwd) => !!cwd && (ranInside(cwd, input.root) || worktreeOf(cwd) !== undefined);
204
+ // The checkout a file is in, when it is one of the repository's.
205
+ const nearest = (dir) => {
206
+ for (let at = dir;; at = dirname(at)) {
207
+ try {
208
+ realpathSync(at);
209
+ return worktreeOf(at);
210
+ }
211
+ catch {
212
+ if (dirname(at) === at)
213
+ return undefined;
214
+ }
215
+ }
216
+ };
217
+ const roots = (dir) => [input.root, realOrSelf(input.root), nearest(dir)].filter((r) => !!r);
218
+ const ctx = { roots, written: [] };
219
+ const cwd = before.cwd || input.root;
220
+ let turns = turnsOf(events, cwd, "", ctx, children.filter((c) => c.transcript.events.length));
221
+ // A session that ran outside the repository (a coordinator whose
222
+ // subagents work in a worktree) shares nothing of its own: only the
223
+ // subagent runs that changed the repository's files.
224
+ // A subagent found by what it did in the repository counts as inside it,
225
+ // whatever cwd its lines carry over from its parent.
226
+ const outside = !sidechain && !ownCheckout(cwd);
227
+ if (outside) {
228
+ turns = turns.map((turn) => ({
229
+ at: turn.at,
230
+ messages: [],
231
+ changes: [],
232
+ runs: turn.runs.map((run) => changed(run.turns) ? run : { label: run.label, turns: [] }),
233
+ }));
234
+ ctx.written = ctx.written.filter((w) => w.turn.includes("."));
235
+ if (!turns.some((turn) => turn.runs.some((run) => run.turns.length)))
236
+ return undefined;
237
+ }
238
+ const title = sidechain
239
+ ? input.subagent?.label
240
+ : agent === "claude" && !outside
241
+ ? sessionTitle(lines.slice(0, cut))
242
+ : undefined;
243
+ const upload = {
244
+ agent,
245
+ ...(title ? { title } : {}),
246
+ ...(whole.model ? { model: whole.model } : {}),
247
+ committedAt,
248
+ turns,
249
+ sourcemap: sourcemapOf(ctx.written, input.added),
250
+ };
251
+ const refs = [
252
+ ...new Set(briefsOf(turns).flatMap((t) => contextRefsIn(t, input.providers ?? []))),
253
+ ];
254
+ const redacted = redactValue(upload, opts);
255
+ return { upload: redacted.value, findings: redacted.findings, refs };
256
+ }
@@ -0,0 +1,105 @@
1
+ import { editsOf, firstArg, parseJsonl, } from "./transcript.js";
2
+ const INJECTED_PREFIX = /^\s*<(command-message|command-name|local-command-stdout|local-command-caveat|system-reminder|task-notification|bash-input|bash-stdout)/;
3
+ function cleanUserText(text) {
4
+ return text
5
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "")
6
+ .replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>/g, "")
7
+ .trim();
8
+ }
9
+ function blocksOf(content) {
10
+ return Array.isArray(content) ? content : [];
11
+ }
12
+ function blockText(content) {
13
+ if (typeof content === "string")
14
+ return content;
15
+ return blocksOf(content)
16
+ .map((block) => (block?.type === "text" ? String(block.text ?? "") : ""))
17
+ .filter(Boolean)
18
+ .join("\n");
19
+ }
20
+ // A user line holds what the human typed or the results of tool calls.
21
+ function readUserLine(t, line) {
22
+ if (line.isMeta || line.isCompactSummary)
23
+ return;
24
+ const ts = line.timestamp ?? "";
25
+ const content = line.message?.content;
26
+ for (const block of blocksOf(content)) {
27
+ if (block.type !== "tool_result")
28
+ continue;
29
+ const callId = block.tool_use_id ?? "";
30
+ // The result of the call that launched a subagent names the subagent.
31
+ const agentId = line.toolUseResult?.agentId;
32
+ if (agentId && callId)
33
+ t.agentLinks[agentId] = callId;
34
+ const text = blockText(block.content);
35
+ t.events.push({ kind: "tool_result", ts, callId, text });
36
+ }
37
+ const text = cleanUserText(blockText(content));
38
+ if (text && !INJECTED_PREFIX.test(text)) {
39
+ t.events.push({ kind: "user", ts, text });
40
+ }
41
+ }
42
+ const SPAWN_TOOLS = ["Task", "Agent"];
43
+ function readToolCall(t, block, ts, turnId) {
44
+ const name = block.name ?? "tool";
45
+ const callId = block.id ?? "";
46
+ if (SPAWN_TOOLS.includes(name) && callId) {
47
+ const { prompt, description } = (block.input ?? {});
48
+ t.spawns.push({
49
+ callId,
50
+ prompt: prompt ?? "",
51
+ ...(description ? { description } : {}),
52
+ });
53
+ }
54
+ const edits = editsOf(name, block.input);
55
+ t.events.push({
56
+ kind: "tool_call",
57
+ ts,
58
+ name,
59
+ arg: firstArg(block.input),
60
+ callId,
61
+ turnId,
62
+ ...(edits.length ? { edits } : {}),
63
+ });
64
+ }
65
+ // Claude Code writes one line per block of an assistant turn.
66
+ function readAssistantLine(t, line) {
67
+ const ts = line.timestamp ?? "";
68
+ const message = line.message ?? {};
69
+ const turnId = message.id ?? ts;
70
+ if (message.model && !t.model)
71
+ t.model = message.model;
72
+ for (const block of blocksOf(message.content)) {
73
+ if (block.type === "text" && block.text?.trim()) {
74
+ t.events.push({ kind: "assistant", ts, text: block.text, turnId });
75
+ }
76
+ else if (block.type === "tool_use") {
77
+ readToolCall(t, block, ts, turnId);
78
+ }
79
+ }
80
+ }
81
+ export function parseClaude(jsonl, id, opts = {}) {
82
+ const transcript = {
83
+ agent: "claude",
84
+ id,
85
+ cwd: "",
86
+ model: undefined,
87
+ events: [],
88
+ spawns: [],
89
+ agentLinks: {},
90
+ };
91
+ for (const line of parseJsonl(jsonl)) {
92
+ if (!!line.isSidechain !== !!opts.sidechain)
93
+ continue;
94
+ if (!transcript.cwd && line.cwd)
95
+ transcript.cwd = line.cwd;
96
+ if (!line.message)
97
+ continue;
98
+ if (line.type === "user")
99
+ readUserLine(transcript, line);
100
+ if (line.type === "assistant") {
101
+ readAssistantLine(transcript, line);
102
+ }
103
+ }
104
+ return transcript;
105
+ }