ai-wrapped 1.18.0 → 1.19.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.
- package/README.md +33 -3
- package/package.json +1 -1
- package/skills/ai-wrapped/SKILL.md +2 -2
- package/src/bun/coverage.ts +9 -2
- package/src/bun/discovery/codex.ts +12 -8
- package/src/bun/headless.ts +7 -2
- package/src/bun/scan.test.ts +22 -1
- package/src/bun/scan.ts +32 -1
- package/src/bun/t3History.ts +178 -0
package/README.md
CHANGED
|
@@ -12,12 +12,41 @@
|
|
|
12
12
|
|
|
13
13
|
No desktop app to install: `npx ai-wrapped@latest` reads the session logs on your machine, serves the stories from `127.0.0.1` and opens them in your browser. Nothing is uploaded unless you press Share.
|
|
14
14
|
|
|
15
|
+
<p align="center">
|
|
16
|
+
<a href="https://ai-wrapped.com/demo"><img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/ai-wrapped-demo.webp" width="760" alt="AI Wrapped stories playing through" /></a>
|
|
17
|
+
<br />
|
|
18
|
+
<sub><a href="https://ai-wrapped.com/demo">Open the live demo</a> · <a href="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/ai-wrapped-demo.mp4">Watch the video (MP4)</a></sub>
|
|
19
|
+
</p>
|
|
20
|
+
|
|
21
|
+
<table>
|
|
22
|
+
<tr>
|
|
23
|
+
<td><img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/desktop-00.webp" alt="Intro: sessions, tokens, spend and tool calls" /></td>
|
|
24
|
+
<td><img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/desktop-02.webp" alt="Prompts: how many prompts and words you wrote" /></td>
|
|
25
|
+
</tr>
|
|
26
|
+
<tr>
|
|
27
|
+
<td><img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/desktop-04.webp" alt="Your agents, ranked on a podium" /></td>
|
|
28
|
+
<td><img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/desktop-06.webp" alt="Token cost with a spend chart" /></td>
|
|
29
|
+
</tr>
|
|
30
|
+
<tr>
|
|
31
|
+
<td><img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/desktop-08.webp" alt="Your coding persona and peak hours" /></td>
|
|
32
|
+
<td><img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/desktop-09.webp" alt="Summary card to share" /></td>
|
|
33
|
+
</tr>
|
|
34
|
+
</table>
|
|
35
|
+
|
|
36
|
+
<p align="center">
|
|
37
|
+
<img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/mobile-01.webp" width="150" alt="Time on a phone" />
|
|
38
|
+
<img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/mobile-02.webp" width="150" alt="Prompts on a phone" />
|
|
39
|
+
<img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/mobile-04.webp" width="150" alt="Agents on a phone" />
|
|
40
|
+
<img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/mobile-05.webp" width="150" alt="Activity on a phone" />
|
|
41
|
+
<img src="https://raw.githubusercontent.com/gulivan/ai-wrapped/main/docs/media/mobile-08.webp" width="150" alt="Peak hours on a phone" />
|
|
42
|
+
</p>
|
|
43
|
+
|
|
15
44
|
Built on top of [agent-sessions](https://github.com/jazzyalex/agent-sessions) session format discovery — reads JSONL/JSON session logs that AI coding agents write to disk.
|
|
16
45
|
|
|
17
46
|
## Supported Agents
|
|
18
47
|
|
|
19
|
-
- **Claude Code** — `~/.claude/projects/` JSONL sessions + subagent logs
|
|
20
|
-
- **OpenAI Codex** — Codex CLI session files
|
|
48
|
+
- **Claude Code** — `~/.claude/projects/` (also `~/.config/claude` and `$CLAUDE_CONFIG_DIR`) JSONL sessions + subagent logs
|
|
49
|
+
- **OpenAI Codex** — Codex CLI session files (`~/.codex/sessions` and `archived_sessions`, or `$CODEX_HOME`)
|
|
21
50
|
- **Google Gemini CLI** — Gemini session logs
|
|
22
51
|
- **OpenCode** — OpenCode session data
|
|
23
52
|
- **Droid** — Droid session files
|
|
@@ -36,12 +65,13 @@ Built on top of [agent-sessions](https://github.com/jazzyalex/agent-sessions) se
|
|
|
36
65
|
- **Grok CLI** — `~/.grok/sessions/*/*/updates.jsonl`
|
|
37
66
|
- **ZCode (Z.ai)** — `~/.zcode/cli/db/db.sqlite` (`model_usage` rows)
|
|
38
67
|
- **Cursor CLI** — `~/.cursor/projects/*/agent-transcripts` (sessions, messages and tool calls; Cursor keeps token counts on its servers)
|
|
68
|
+
- **T3 Code history** — `~/.t3/userdata/usage-scan-cache-v*.json`: if you use [T3 Code](https://t3.codes), its usage cache still holds Claude Code and Codex sessions whose logs were deleted. Those come back as tokens, models and times (no prompts or tool calls), and each message counts once next to the logs still on disk.
|
|
39
69
|
|
|
40
70
|
The newer readers (agy, DeepSeek Harness, Grok, ZCode, Cursor) take numbers only: tokens, models, times and counts, never message text.
|
|
41
71
|
|
|
42
72
|
Usage from chat apps and provider APIs (claude.ai, ChatGPT, Anthropic/OpenAI usage APIs, Cursor's dashboard) can be added as totals with `--cloud`; see [agents.md](https://ai-wrapped.com/agents.md). Missing a harness? Open an issue or a PR with a discoverer and parser in `src/bun/discovery/additional.ts` and `src/bun/parsers/additional.ts`.
|
|
43
73
|
|
|
44
|
-
> **Older sessions may be gone.** Some agents delete old logs; Claude Code keeps 30 days unless you raise `cleanupPeriodDays` in `~/.claude/settings.json` (e.g. `3650`).
|
|
74
|
+
> **Older sessions may be gone.** Some agents delete old logs; Claude Code keeps 30 days unless you raise `cleanupPeriodDays` in `~/.claude/settings.json` (e.g. `3650`). AI Wrapped keeps what it has already read after the logs are deleted, and fills older Claude Code and Codex history from T3 Code's usage cache when it's there. Otherwise the wrapped notes which agents are affected and from which day their numbers start.
|
|
45
75
|
|
|
46
76
|
## What It Shows
|
|
47
77
|
|
package/package.json
CHANGED
|
@@ -26,10 +26,10 @@ Read it. Don't paste the raw JSON back to the user; tell them the highlights.
|
|
|
26
26
|
|
|
27
27
|
### Trimmed logs
|
|
28
28
|
|
|
29
|
-
Some agents delete old sessions. Claude Code removes sessions older than `cleanupPeriodDays` (30 days unless the user changed it in `~/.claude/settings.json`), so a year-long wrapped may hold only the last month of Claude Code. The digest's `logGaps` lists every such agent and the day its data starts; the wrapped itself shows a short note on the first story.
|
|
29
|
+
Some agents delete old sessions. Claude Code removes sessions older than `cleanupPeriodDays` (30 days unless the user changed it in `~/.claude/settings.json`), so a year-long wrapped may hold only the last month of Claude Code. The digest's `logGaps` lists every such agent and the day its data starts; the wrapped itself shows a short note on the first story. The CLI keeps sessions it has read after the logs are deleted, and fills older Claude Code and Codex history from T3 Code's usage cache (`~/.t3/userdata`) when it exists; then `logGaps` is empty.
|
|
30
30
|
|
|
31
31
|
- **Tell the user plainly** what period is covered, before they share. Don't present partial numbers as the whole year.
|
|
32
|
-
- **Next time:** suggest raising `cleanupPeriodDays` (e.g. `3650`) in `~/.claude/settings.json`. It keeps future sessions only; deleted ones can't come back
|
|
32
|
+
- **Next time:** suggest raising `cleanupPeriodDays` (e.g. `3650`) in `~/.claude/settings.json`. It keeps future sessions only; deleted ones can't come back, except from a backup of their home folder or T3 Code's usage cache, which the CLI already reads.
|
|
33
33
|
- **Fill the gap with real numbers** where possible: API usage from the provider's usage API, added with `--cloud` (see below).
|
|
34
34
|
- **Extrapolating:** the wrapped's numbers always stay measured. If the user wants an estimate, you may give one in your own `note` or `subtitle`, clearly marked as an estimate with its basis (e.g. "≈ 4.1B tokens if the rest of the year looked like these 30 days"), and only after the user agrees. Coding usage comes in bursts, so say how rough it is.
|
|
35
35
|
|
package/src/bun/coverage.ts
CHANGED
|
@@ -26,14 +26,21 @@ export const claudeRetentionDays = async (): Promise<number> => {
|
|
|
26
26
|
const isoDay = (date: Date) => date.toISOString().slice(0, 10);
|
|
27
27
|
|
|
28
28
|
/** Agents whose logs don't reach back to the start of the range. */
|
|
29
|
-
export const findLogGaps = async (
|
|
29
|
+
export const findLogGaps = async (
|
|
30
|
+
payload: SharePayload,
|
|
31
|
+
now = new Date(),
|
|
32
|
+
/** First day with Claude Code data we still hold (kept from deleted logs or T3's history). */
|
|
33
|
+
claudeFrom?: string | null,
|
|
34
|
+
): Promise<LogGap[]> => {
|
|
30
35
|
const gaps: LogGap[] = [];
|
|
31
36
|
const usesClaude = payload.agentBreakdown.some((row) => row.source === "claude" && (row.tokens > 0 || row.sessions > 0));
|
|
32
37
|
if (usesClaude) {
|
|
33
38
|
const days = await claudeRetentionDays();
|
|
34
39
|
const cutoff = new Date(now.getTime() - days * 86_400_000);
|
|
35
40
|
const since = isoDay(cutoff);
|
|
36
|
-
|
|
41
|
+
// Data from before the cutoff means the deleted logs were kept elsewhere.
|
|
42
|
+
const kept = Boolean(claudeFrom && claudeFrom < since);
|
|
43
|
+
if (since > payload.dateFrom && !kept) gaps.push({ source: "claude", retentionDays: days, since });
|
|
37
44
|
}
|
|
38
45
|
return gaps;
|
|
39
46
|
};
|
|
@@ -1,19 +1,23 @@
|
|
|
1
|
-
import { join } from "node:path";
|
|
1
|
+
import { basename, join } from "node:path";
|
|
2
2
|
import type { AgentDiscoverer } from "./types";
|
|
3
|
-
import { expandHome, scanGlobCandidates } from "./utils";
|
|
3
|
+
import { dedupeCandidates, expandHome, scanGlobCandidates } from "./utils";
|
|
4
4
|
|
|
5
|
-
const
|
|
5
|
+
const resolveCodexHome = (): string => {
|
|
6
6
|
const codexHome = process.env.CODEX_HOME;
|
|
7
|
-
|
|
8
|
-
return join(codexHome, "sessions");
|
|
9
|
-
}
|
|
10
|
-
return expandHome("~/.codex/sessions");
|
|
7
|
+
return codexHome && codexHome.trim().length > 0 ? codexHome : expandHome("~/.codex");
|
|
11
8
|
};
|
|
12
9
|
|
|
13
10
|
export const codexDiscoverer: AgentDiscoverer = {
|
|
14
11
|
source: "codex",
|
|
15
12
|
async discover() {
|
|
16
|
-
|
|
13
|
+
const home = resolveCodexHome();
|
|
14
|
+
// Codex moves older rollouts to archived_sessions (flat).
|
|
15
|
+
const [live, archived] = await Promise.all([
|
|
16
|
+
scanGlobCandidates(join(home, "sessions"), "????/??/??/rollout-*.jsonl", "codex"),
|
|
17
|
+
scanGlobCandidates(join(home, "archived_sessions"), "rollout-*.jsonl", "codex"),
|
|
18
|
+
]);
|
|
19
|
+
const names = new Set(live.map((candidate) => basename(candidate.path)));
|
|
20
|
+
return dedupeCandidates([...live, ...archived.filter((candidate) => !names.has(basename(candidate.path)))]);
|
|
17
21
|
},
|
|
18
22
|
};
|
|
19
23
|
|
package/src/bun/headless.ts
CHANGED
|
@@ -16,7 +16,7 @@ import { getDailyTimelineFromStore, getDashboardSummaryFromStore } from "./queri
|
|
|
16
16
|
import { runScan } from "./scan";
|
|
17
17
|
import { createShareLink, SHARE_ORIGIN } from "./share";
|
|
18
18
|
import { findLogGaps } from "./coverage";
|
|
19
|
-
import { dailyStoreMissingActiveDimension, dailyStoreMissingHourDimension, dailyStoreMissingRepoDimension } from "./store";
|
|
19
|
+
import { dailyStoreMissingActiveDimension, dailyStoreMissingHourDimension, dailyStoreMissingRepoDimension, readDailyStore } from "./store";
|
|
20
20
|
|
|
21
21
|
export const parseRange = (value: string | undefined): WrappedRange => {
|
|
22
22
|
if (!value) return `year:${new Date().getFullYear()}`;
|
|
@@ -29,7 +29,12 @@ export const parseRange = (value: string | undefined): WrappedRange => {
|
|
|
29
29
|
|
|
30
30
|
export const loadPayload = async (range: WrappedRange, options: { scan?: boolean } = {}): Promise<SharePayload> => {
|
|
31
31
|
const payload = await buildPayloadFromStore(range, options);
|
|
32
|
-
const
|
|
32
|
+
const daily = await readDailyStore();
|
|
33
|
+
const claudeFrom =
|
|
34
|
+
Object.keys(daily)
|
|
35
|
+
.filter((day) => (daily[day]?.bySource.claude?.sessions ?? 0) > 0)
|
|
36
|
+
.sort()[0] ?? null;
|
|
37
|
+
const gaps = await findLogGaps(payload, new Date(), claudeFrom);
|
|
33
38
|
return gaps.length > 0 ? { ...payload, gaps } : payload;
|
|
34
39
|
};
|
|
35
40
|
|
package/src/bun/scan.test.ts
CHANGED
|
@@ -16,7 +16,7 @@ console.log(JSON.stringify({ input: sum("inputTokens"), output: sum("outputToken
|
|
|
16
16
|
|
|
17
17
|
const scanIn = async (home: string) => {
|
|
18
18
|
const proc = Bun.spawn(["bun", "-e", SCRIPT], {
|
|
19
|
-
env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: "" },
|
|
19
|
+
env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: "", T3_HOME: "", CODEX_HOME: "" },
|
|
20
20
|
stdout: "pipe",
|
|
21
21
|
stderr: "pipe",
|
|
22
22
|
});
|
|
@@ -58,6 +58,27 @@ test("a message logged on several lines, and copied into a fork, counts once; la
|
|
|
58
58
|
// Another session on the same day; the earlier ones must stay counted.
|
|
59
59
|
write(join(project, "c-other.jsonl"), [user("u3", "2026-03-01T12:00:00Z", "hi"), assistant("msg_c", "2026-03-01T12:00:05Z", 500, 5, "text")]);
|
|
60
60
|
expect(await scanIn(home)).toEqual({ input: 3500, output: 105, sessions: 3 });
|
|
61
|
+
|
|
62
|
+
// T3 Code remembers a deleted log: its copy of msg_a is already counted,
|
|
63
|
+
// msg_old is new. A row for a file we can still read is ignored.
|
|
64
|
+
const t3 = join(home, ".t3", "userdata");
|
|
65
|
+
mkdirSync(t3, { recursive: true });
|
|
66
|
+
const row = (at: string, input: number, output: number, id: string) => [Date.parse(at), 0, 0, input, 0, 0, output, 0, id, null, 0, null];
|
|
67
|
+
writeFileSync(
|
|
68
|
+
join(t3, "usage-scan-cache-v17.json"),
|
|
69
|
+
JSON.stringify({
|
|
70
|
+
version: 17,
|
|
71
|
+
models: ["claude-sonnet-4-5"],
|
|
72
|
+
files: {
|
|
73
|
+
[join(project, "b-original.jsonl")]: { p: "claude", r: [row("2026-03-01T10:00:07Z", 1000, 80, "msg_a:req-msg_a")] },
|
|
74
|
+
[join(project, "z-deleted.jsonl")]: {
|
|
75
|
+
p: "claude",
|
|
76
|
+
r: [row("2026-02-01T09:00:00Z", 1000, 80, "msg_a:req-msg_a"), row("2026-02-01T09:05:00Z", 700, 7, "msg_old:req-old")],
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
}),
|
|
80
|
+
);
|
|
81
|
+
expect(await scanIn(home)).toEqual({ input: 4200, output: 112, sessions: 4 });
|
|
61
82
|
} finally {
|
|
62
83
|
rmSync(home, { recursive: true, force: true });
|
|
63
84
|
}
|
package/src/bun/scan.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
writeSessionCache,
|
|
16
16
|
} from "./store";
|
|
17
17
|
import { prefetchPricing } from "./pricing";
|
|
18
|
+
import { fileKey, findT3Cache, readT3History, T3_KEY_PREFIX } from "./t3History";
|
|
18
19
|
|
|
19
20
|
export interface ScanOptions {
|
|
20
21
|
fullScan?: boolean;
|
|
@@ -29,6 +30,7 @@ export interface ScanResult {
|
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
type CacheEntry = SessionCacheEntry;
|
|
33
|
+
const T3_STATE_KEY = "t3:usage-cache";
|
|
32
34
|
type Candidate = Awaited<ReturnType<typeof discoverAll>>[number];
|
|
33
35
|
|
|
34
36
|
/** Message ids that carry usage in a parsed Claude file. */
|
|
@@ -143,9 +145,38 @@ export const runScan = async (options: ScanOptions = {}): Promise<ScanResult> =>
|
|
|
143
145
|
}
|
|
144
146
|
}
|
|
145
147
|
|
|
148
|
+
// A file that moved (Codex archives old rollouts) is the same file: keep
|
|
149
|
+
// the copy we can still read.
|
|
150
|
+
const liveKeys = new Set(candidates.map((candidate) => fileKey(candidate.source, candidate.path)));
|
|
151
|
+
const livePaths = new Set(candidates.map((candidate) => candidate.path));
|
|
152
|
+
let moved = 0;
|
|
153
|
+
for (const [path, entry] of Object.entries(entries)) {
|
|
154
|
+
if (path.startsWith(T3_KEY_PREFIX) || livePaths.has(path)) continue;
|
|
155
|
+
const source = entry.sessions[0]?.source;
|
|
156
|
+
if (source && liveKeys.has(fileKey(source, path))) {
|
|
157
|
+
delete entries[path];
|
|
158
|
+
moved += 1;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Older history from T3 Code's usage cache, for logs that are gone.
|
|
163
|
+
const t3 = await findT3Cache();
|
|
164
|
+
const t3State = scanState[T3_STATE_KEY];
|
|
165
|
+
const t3Changed = t3
|
|
166
|
+
? !t3State || t3State.mtimeMs !== t3.mtimeMs || t3State.fileSize !== t3.size
|
|
167
|
+
: Object.keys(entries).some((path) => path.startsWith(T3_KEY_PREFIX));
|
|
168
|
+
const rebuild = shouldFullScan || changed.length > 0 || reassigned > 0 || moved > 0 || t3Changed;
|
|
169
|
+
if (rebuild) {
|
|
170
|
+
for (const path of Object.keys(entries)) if (path.startsWith(T3_KEY_PREFIX)) delete entries[path];
|
|
171
|
+
if (t3) Object.assign(entries, await readT3History(t3, entries, livePaths));
|
|
172
|
+
if (t3) {
|
|
173
|
+
scanState[T3_STATE_KEY] = { source: "claude", fileSize: t3.size, mtimeMs: t3.mtimeMs, parsedAt: new Date().toISOString() };
|
|
174
|
+
} else delete scanState[T3_STATE_KEY];
|
|
175
|
+
}
|
|
176
|
+
|
|
146
177
|
await writeScanState(scanState);
|
|
147
178
|
|
|
148
|
-
if (
|
|
179
|
+
if (rebuild) {
|
|
149
180
|
await writeSessionCache(entries);
|
|
150
181
|
await writeDailyStore(
|
|
151
182
|
aggregateSessionsByDate(
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Older history from T3 Code's usage cache.
|
|
2
|
+
//
|
|
3
|
+
// T3 Code (https://t3.codes) keeps per-request usage for every Claude Code and
|
|
4
|
+
// Codex log it has seen, in ~/.t3/userdata/usage-scan-cache-v<N>.json, and it
|
|
5
|
+
// keeps them after the agent deletes the log (Claude Code drops sessions
|
|
6
|
+
// older than 30 days by default). For logs that are gone, those rows are the
|
|
7
|
+
// only record left, so they're added here as sessions: tokens, models and
|
|
8
|
+
// times only (no prompts, tool calls or text; T3 doesn't keep those).
|
|
9
|
+
//
|
|
10
|
+
// Overlaps: a log we can still read, or one we read before it was deleted,
|
|
11
|
+
// always wins; Claude messages are matched by message id, so a message counts
|
|
12
|
+
// once even when T3 saw it in a fork or in a file we still have.
|
|
13
|
+
//
|
|
14
|
+
// The format is T3's own and undocumented; anything that doesn't look as
|
|
15
|
+
// expected is skipped.
|
|
16
|
+
|
|
17
|
+
import { readdir, stat } from "node:fs/promises";
|
|
18
|
+
import { basename, dirname, join } from "node:path";
|
|
19
|
+
import type { SessionSource } from "../shared/schema";
|
|
20
|
+
import { expandHome } from "./discovery/utils";
|
|
21
|
+
import { normalizeSession } from "./normalizer";
|
|
22
|
+
import type { SessionEvent } from "./session-schema";
|
|
23
|
+
import type { SessionCacheEntry } from "./store";
|
|
24
|
+
|
|
25
|
+
/** Where T3 keeps its data (T3_HOME overrides ~/.t3). */
|
|
26
|
+
const t3UserData = () => join(Bun.env.T3_HOME?.trim() || expandHome("~/.t3"), "userdata");
|
|
27
|
+
|
|
28
|
+
/** Agents whose rows were checked against our own parsers. */
|
|
29
|
+
const SOURCES: Partial<Record<string, SessionSource>> = { claude: "claude", codex: "codex" };
|
|
30
|
+
|
|
31
|
+
export const T3_KEY_PREFIX = "t3:";
|
|
32
|
+
|
|
33
|
+
export interface T3CacheFile {
|
|
34
|
+
path: string;
|
|
35
|
+
mtimeMs: number;
|
|
36
|
+
size: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The newest T3 usage cache, if T3 is installed. */
|
|
40
|
+
export const findT3Cache = async (): Promise<T3CacheFile | null> => {
|
|
41
|
+
const dir = t3UserData();
|
|
42
|
+
let names: string[];
|
|
43
|
+
try {
|
|
44
|
+
names = await readdir(dir);
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
const best = names
|
|
49
|
+
.map((name) => ({ name, version: Number(/^usage-scan-cache-v(\d+)\.json$/.exec(name)?.[1] ?? Number.NaN) }))
|
|
50
|
+
.filter((entry) => Number.isFinite(entry.version))
|
|
51
|
+
.sort((a, b) => b.version - a.version)[0];
|
|
52
|
+
if (!best) return null;
|
|
53
|
+
const path = join(dir, best.name);
|
|
54
|
+
try {
|
|
55
|
+
const info = await stat(path);
|
|
56
|
+
return { path, mtimeMs: info.mtimeMs, size: info.size };
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);
|
|
63
|
+
|
|
64
|
+
/** Same file wherever it lives (Codex moves rollouts into archived_sessions). */
|
|
65
|
+
export const fileKey = (source: string, path: string) => `${source}:${basename(path)}`;
|
|
66
|
+
|
|
67
|
+
const sessionIdFor = (source: SessionSource, path: string) => {
|
|
68
|
+
if (source === "claude" && path.includes("/subagents/")) return basename(dirname(dirname(path)));
|
|
69
|
+
const name = basename(path).replace(/\.jsonl$/, "");
|
|
70
|
+
const uuid = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.exec(name)?.[1];
|
|
71
|
+
return uuid ?? name;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** Claude Code project folder of a log ("-home-me-app"), used to find its working directory. */
|
|
75
|
+
const claudeProject = (path: string) => {
|
|
76
|
+
const parts = path.split(/[\\/]/);
|
|
77
|
+
const at = parts.lastIndexOf("projects");
|
|
78
|
+
return at >= 0 ? parts[at + 1] ?? null : null;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Sessions for logs T3 remembers but we can't read anymore, keyed
|
|
83
|
+
* "t3:<original path>". `entries` are our own parsed files (live or cached).
|
|
84
|
+
*/
|
|
85
|
+
export const readT3History = async (
|
|
86
|
+
cache: T3CacheFile,
|
|
87
|
+
entries: Record<string, SessionCacheEntry>,
|
|
88
|
+
livePaths: Set<string>,
|
|
89
|
+
): Promise<Record<string, SessionCacheEntry>> => {
|
|
90
|
+
let data: { files?: unknown; models?: unknown };
|
|
91
|
+
try {
|
|
92
|
+
data = (await Bun.file(cache.path).json()) as typeof data;
|
|
93
|
+
} catch {
|
|
94
|
+
return {};
|
|
95
|
+
}
|
|
96
|
+
const files = data.files && typeof data.files === "object" ? (data.files as Record<string, unknown>) : null;
|
|
97
|
+
const models = Array.isArray(data.models) ? data.models : null;
|
|
98
|
+
if (!files || !models) return {};
|
|
99
|
+
|
|
100
|
+
// What we already have: files (by name, so moved ones match), Claude
|
|
101
|
+
// message ids, and the working directory of each Claude project folder.
|
|
102
|
+
const known = new Set<string>();
|
|
103
|
+
const claimed = new Set<string>();
|
|
104
|
+
const projectCwd = new Map<string, string>();
|
|
105
|
+
for (const [path, entry] of Object.entries(entries)) {
|
|
106
|
+
if (path.startsWith(T3_KEY_PREFIX)) continue;
|
|
107
|
+
const source = entry.sessions[0]?.source;
|
|
108
|
+
if (source) known.add(fileKey(source, path));
|
|
109
|
+
for (const id of entry.ids ?? []) claimed.add(id);
|
|
110
|
+
for (const session of entry.sessions) {
|
|
111
|
+
const project = session.source === "claude" ? claudeProject(session.filePath) : null;
|
|
112
|
+
if (project && session.cwd && !projectCwd.has(project)) projectCwd.set(project, session.cwd);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const out: Record<string, SessionCacheEntry> = {};
|
|
117
|
+
const seen = new Set<string>();
|
|
118
|
+
for (const [path, raw] of Object.entries(files)) {
|
|
119
|
+
const file = raw && typeof raw === "object" ? (raw as { p?: unknown; r?: unknown }) : null;
|
|
120
|
+
const source = typeof file?.p === "string" ? SOURCES[file.p] : undefined;
|
|
121
|
+
if (!file || !source || !Array.isArray(file.r) || file.r.length === 0) continue;
|
|
122
|
+
if (livePaths.has(path) || entries[path] || known.has(fileKey(source, path))) continue;
|
|
123
|
+
|
|
124
|
+
const sessionId = sessionIdFor(source, path);
|
|
125
|
+
const events: SessionEvent[] = [];
|
|
126
|
+
file.r.forEach((row: unknown, index: number) => {
|
|
127
|
+
if (!Array.isArray(row) || row.length < 9) return;
|
|
128
|
+
const at = num(row[0]);
|
|
129
|
+
const model = typeof row[1] === "number" ? models[row[1]] : null;
|
|
130
|
+
if (!at || typeof model !== "string") return;
|
|
131
|
+
const id = typeof row[8] === "string" ? row[8] : null;
|
|
132
|
+
if (id) {
|
|
133
|
+
// Claude ids are "msg_…:req_…"; match ours on the message id.
|
|
134
|
+
const messageId = source === "claude" ? id.split(":")[0] ?? id : id;
|
|
135
|
+
if (claimed.has(messageId) || seen.has(id)) return;
|
|
136
|
+
seen.add(id);
|
|
137
|
+
}
|
|
138
|
+
const reasoning = num(row[7]);
|
|
139
|
+
events.push({
|
|
140
|
+
id: `${sessionId}:t3:${index}`,
|
|
141
|
+
sessionId,
|
|
142
|
+
kind: "assistant",
|
|
143
|
+
timestamp: new Date(at).toISOString(),
|
|
144
|
+
role: "assistant",
|
|
145
|
+
text: null,
|
|
146
|
+
toolName: null,
|
|
147
|
+
toolInput: null,
|
|
148
|
+
toolOutput: null,
|
|
149
|
+
model,
|
|
150
|
+
parentId: null,
|
|
151
|
+
messageId: null,
|
|
152
|
+
isDelta: false,
|
|
153
|
+
// Output includes reasoning in T3's rows; ours keeps them apart.
|
|
154
|
+
tokens: {
|
|
155
|
+
inputTokens: num(row[3]),
|
|
156
|
+
cacheReadTokens: num(row[4]),
|
|
157
|
+
cacheWriteTokens: num(row[5]),
|
|
158
|
+
outputTokens: Math.max(0, num(row[6]) - reasoning),
|
|
159
|
+
reasoningTokens: reasoning,
|
|
160
|
+
},
|
|
161
|
+
costUsd: null,
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
if (events.length === 0) continue;
|
|
165
|
+
|
|
166
|
+
const project = source === "claude" ? claudeProject(path) : null;
|
|
167
|
+
const { session } = normalizeSession({
|
|
168
|
+
sessionId,
|
|
169
|
+
source,
|
|
170
|
+
filePath: path,
|
|
171
|
+
fileSizeBytes: 0,
|
|
172
|
+
metadata: { cwd: (project && projectCwd.get(project)) ?? null, gitBranch: null, model: null, cliVersion: null, title: null },
|
|
173
|
+
events,
|
|
174
|
+
});
|
|
175
|
+
out[`${T3_KEY_PREFIX}${path}`] = { sessions: [{ ...session, title: null }] };
|
|
176
|
+
}
|
|
177
|
+
return out;
|
|
178
|
+
};
|