wrapt-cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,200 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import readline from "node:readline";
4
+ import { AssistantLine, Envelope, UserLine } from "./schema.js";
5
+ /** Prefixes of user-role content injected by Claude Code rather than typed by a human. */
6
+ export const INJECTED_PREFIXES = [
7
+ "<command-",
8
+ "<system-reminder>",
9
+ "<local-command",
10
+ "Caveat:",
11
+ "[Request interrupted",
12
+ "<bash-input>",
13
+ "<bash-stdout>",
14
+ "<bash-stderr>",
15
+ "<task-notification>",
16
+ "<user-prompt-submit-hook>",
17
+ "<side-sessions-event>",
18
+ "<ci-monitor-event>",
19
+ ];
20
+ /** Decide whether a user line is a real, human-typed prompt. Pure; exported for tests. */
21
+ export function classifyUser(line) {
22
+ if (line.isCompactSummary)
23
+ return { kind: "excluded", reason: "compact-summary" };
24
+ if (line.isMeta)
25
+ return { kind: "excluded", reason: "meta" };
26
+ if (line.isVisibleInTranscriptOnly)
27
+ return { kind: "excluded", reason: "transcript-only" };
28
+ if (line.isSidechain)
29
+ return { kind: "excluded", reason: "sidechain" };
30
+ const originKind = line.origin?.kind;
31
+ if (originKind && originKind !== "human")
32
+ return { kind: "excluded", reason: `origin:${originKind}` };
33
+ const content = line.message.content;
34
+ let text;
35
+ if (typeof content === "string") {
36
+ text = content;
37
+ }
38
+ else {
39
+ if (content.some((b) => b.type === "tool_result"))
40
+ return { kind: "tool_result" };
41
+ text = content
42
+ .filter((b) => b.type === "text" && typeof b.text === "string")
43
+ .map((b) => b.text)
44
+ .join("\n");
45
+ const hasImage = content.some((b) => b.type === "image");
46
+ if (!text.trim() && !hasImage)
47
+ return { kind: "excluded", reason: "empty" };
48
+ }
49
+ const trimmed = text.trimStart();
50
+ for (const p of INJECTED_PREFIXES) {
51
+ if (trimmed.startsWith(p))
52
+ return { kind: "excluded", reason: `injected:${p}` };
53
+ }
54
+ // Remove any inline system reminders that rode along with a real prompt.
55
+ const cleaned = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "").trim();
56
+ if (!cleaned && typeof content === "string")
57
+ return { kind: "excluded", reason: "empty" };
58
+ return { kind: "prompt", text: cleaned };
59
+ }
60
+ export function findJsonlFiles(root) {
61
+ const out = [];
62
+ const walk = (dir) => {
63
+ let entries;
64
+ try {
65
+ entries = fs.readdirSync(dir, { withFileTypes: true });
66
+ }
67
+ catch {
68
+ return;
69
+ }
70
+ for (const e of entries) {
71
+ const p = path.join(dir, e.name);
72
+ if (e.isDirectory())
73
+ walk(p);
74
+ else if (e.isFile() && e.name.endsWith(".jsonl"))
75
+ out.push(p);
76
+ }
77
+ };
78
+ walk(root);
79
+ return out.sort();
80
+ }
81
+ /** "/Users/me/code/app" -> "app". Falls back to the encoded project dir name. */
82
+ export function projectName(cwd, file, root) {
83
+ if (cwd) {
84
+ const base = path.basename(cwd.replace(/[\\/]+$/, ""));
85
+ if (base)
86
+ return base;
87
+ }
88
+ const rel = path.relative(root, file).split(path.sep)[0] ?? "";
89
+ const parts = rel.split("-").filter(Boolean);
90
+ return parts[parts.length - 1] ?? "unknown";
91
+ }
92
+ function toolCalls(blocks) {
93
+ if (!blocks)
94
+ return [];
95
+ const out = [];
96
+ for (const b of blocks) {
97
+ if (b.type === "tool_use" && typeof b.name === "string") {
98
+ const input = b.input;
99
+ out.push({
100
+ name: b.name,
101
+ input: input && typeof input === "object" ? input : {},
102
+ });
103
+ }
104
+ }
105
+ return out;
106
+ }
107
+ function inc(map, key) {
108
+ map[key] = (map[key] ?? 0) + 1;
109
+ }
110
+ /**
111
+ * Stream every JSONL file under `root` and yield normalized events.
112
+ * Lines are deduplicated by `uuid` (resumed sessions can copy history across files).
113
+ */
114
+ export async function* readEvents(root, report) {
115
+ const files = findJsonlFiles(root);
116
+ report.files += files.length;
117
+ const seen = new Set();
118
+ // A session belongs to the folder it started in, even if it later cd's into a subfolder.
119
+ const sessionProject = new Map();
120
+ for (const file of files) {
121
+ const rl = readline.createInterface({ input: fs.createReadStream(file, "utf8"), crlfDelay: Infinity });
122
+ for await (const raw of rl) {
123
+ if (!raw.trim())
124
+ continue;
125
+ report.lines++;
126
+ let json;
127
+ try {
128
+ json = JSON.parse(raw);
129
+ }
130
+ catch {
131
+ report.malformed++;
132
+ continue;
133
+ }
134
+ const env = Envelope.safeParse(json);
135
+ if (!env.success) {
136
+ report.malformed++;
137
+ continue;
138
+ }
139
+ const type = env.data.type;
140
+ if (type !== "user" && type !== "assistant") {
141
+ inc(report.skippedTypes, type);
142
+ continue;
143
+ }
144
+ const parsed = type === "user" ? UserLine.safeParse(json) : AssistantLine.safeParse(json);
145
+ if (!parsed.success) {
146
+ report.malformed++;
147
+ continue;
148
+ }
149
+ const line = parsed.data;
150
+ if (line.uuid) {
151
+ if (seen.has(line.uuid)) {
152
+ report.duplicates++;
153
+ continue;
154
+ }
155
+ seen.add(line.uuid);
156
+ }
157
+ const ts = new Date(line.timestamp);
158
+ if (Number.isNaN(ts.getTime())) {
159
+ report.malformed++;
160
+ continue;
161
+ }
162
+ const sessionId = line.sessionId ?? path.basename(file, ".jsonl");
163
+ let project = sessionProject.get(sessionId);
164
+ if (!project) {
165
+ project = projectName(line.cwd, file, root);
166
+ sessionProject.set(sessionId, project);
167
+ }
168
+ if (line.type === "user") {
169
+ const c = classifyUser(line);
170
+ if (c.kind === "prompt") {
171
+ yield { kind: "prompt", ts, sessionId, project, text: c.text };
172
+ }
173
+ else {
174
+ if (c.kind === "excluded")
175
+ inc(report.excludedUser, c.reason);
176
+ else
177
+ inc(report.excludedUser, "tool_result");
178
+ yield { kind: "activity", ts, sessionId, project };
179
+ }
180
+ }
181
+ else {
182
+ const msg = line.message;
183
+ yield {
184
+ kind: "assistant",
185
+ ts,
186
+ sessionId,
187
+ project,
188
+ // Claude Code writes one line per content block, all sharing message.id and usage.
189
+ messageId: msg.id ?? line.requestId ?? line.uuid ?? `${file}:${report.lines}`,
190
+ model: msg.model,
191
+ usage: msg.usage ?? undefined,
192
+ tools: toolCalls(msg.content),
193
+ };
194
+ }
195
+ }
196
+ }
197
+ }
198
+ export function emptyReport() {
199
+ return { files: 0, lines: 0, malformed: 0, duplicates: 0, skippedTypes: {}, excludedUser: {} };
200
+ }
@@ -0,0 +1,75 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Schemas for the Claude Code transcript lines we care about, built from the
4
+ * shapes actually observed in ~/.claude/projects/**\/*.jsonl (Claude Code 2.1.x).
5
+ *
6
+ * Every schema is deliberately loose: optional fields, unknown keys allowed.
7
+ * A line that fails these schemas is counted as malformed and skipped.
8
+ *
9
+ * Observed line types we read: "user", "assistant".
10
+ * Observed line types we skip (counted): attachment, system, api-request,
11
+ * api-request-blob, api-request-shape, custom-title, last-prompt, agent-name,
12
+ * atis-latch, queue-operation, file-history-snapshot, file-history-delta,
13
+ * data-flow-records, mode, tools-used, derived-from, bridge-session,
14
+ * cost-state, relocated, summary, ...
15
+ */
16
+ const Usage = z
17
+ .object({
18
+ input_tokens: z.number().nullish(),
19
+ output_tokens: z.number().nullish(),
20
+ cache_creation_input_tokens: z.number().nullish(),
21
+ cache_read_input_tokens: z.number().nullish(),
22
+ })
23
+ .loose();
24
+ const TextBlock = z.object({ type: z.literal("text"), text: z.string() }).loose();
25
+ const ToolUseBlock = z
26
+ .object({
27
+ type: z.literal("tool_use"),
28
+ id: z.string().optional(),
29
+ name: z.string(),
30
+ input: z.unknown().optional(),
31
+ })
32
+ .loose();
33
+ const ToolResultBlock = z.object({ type: z.literal("tool_result") }).loose();
34
+ const OtherBlock = z.object({ type: z.string() }).loose();
35
+ const Block = z.union([TextBlock, ToolUseBlock, ToolResultBlock, OtherBlock]);
36
+ const Common = {
37
+ uuid: z.string().optional(),
38
+ sessionId: z.string().optional(),
39
+ timestamp: z.string(),
40
+ cwd: z.string().optional(),
41
+ isSidechain: z.boolean().optional(),
42
+ isMeta: z.boolean().optional(),
43
+ };
44
+ export const UserLine = z
45
+ .object({
46
+ ...Common,
47
+ type: z.literal("user"),
48
+ isCompactSummary: z.boolean().optional(),
49
+ isVisibleInTranscriptOnly: z.boolean().optional(),
50
+ origin: z.object({ kind: z.string().optional() }).loose().nullish(),
51
+ message: z
52
+ .object({
53
+ role: z.string().optional(),
54
+ content: z.union([z.string(), z.array(Block)]),
55
+ })
56
+ .loose(),
57
+ })
58
+ .loose();
59
+ export const AssistantLine = z
60
+ .object({
61
+ ...Common,
62
+ type: z.literal("assistant"),
63
+ requestId: z.string().optional(),
64
+ message: z
65
+ .object({
66
+ id: z.string().optional(),
67
+ model: z.string().optional(),
68
+ content: z.array(Block).optional(),
69
+ usage: Usage.nullish(),
70
+ })
71
+ .loose(),
72
+ })
73
+ .loose();
74
+ /** Minimal envelope: anything with a string `type`. */
75
+ export const Envelope = z.object({ type: z.string() }).loose();
@@ -0,0 +1,130 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { brandFor } from "./brand.js";
7
+ import { human } from "./format.js";
8
+ import { possessive } from "./render/cards.js";
9
+ import { sharePage } from "./share/page.js";
10
+ import { collectAssets } from "./share/server.js";
11
+ const FONT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../assets/fonts/SpaceGrotesk-Bold.ttf");
12
+ /**
13
+ * "owner/name", "git@github.com:owner/name.git", "https://github.com/owner/name" or a local
14
+ * path (tests). Pages URL: https://owner.github.io/name/<year>/ (or /<year>/ for owner.github.io).
15
+ */
16
+ export function resolveTarget(repo, year, urlOverride) {
17
+ const base = (u) => (u.endsWith("/") ? u : u + "/");
18
+ let owner;
19
+ let name;
20
+ let remote = repo;
21
+ const short = /^([\w.-]+)\/([\w.-]+)$/.exec(repo);
22
+ const gh = /github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(repo);
23
+ if (short && !fs.existsSync(repo)) {
24
+ [, owner, name] = short;
25
+ remote = `git@github.com:${owner}/${name}.git`;
26
+ }
27
+ else if (gh) {
28
+ [, owner, name] = gh;
29
+ }
30
+ if (urlOverride)
31
+ return { remote, pageUrl: `${base(urlOverride)}${year}/` };
32
+ if (!owner || !name)
33
+ throw new Error(`Can't work out the GitHub Pages URL for "${repo}". Pass --url https://…`);
34
+ const site = name.toLowerCase() === `${owner.toLowerCase()}.github.io` ? `https://${owner.toLowerCase()}.github.io/` : `https://${owner.toLowerCase()}.github.io/${name}/`;
35
+ return { remote, pageUrl: `${site}${year}/` };
36
+ }
37
+ /**
38
+ * Write the public site to <dir>/site: index.html with Open Graph tags plus the rendered
39
+ * cards and PDF. Only files on this allowlist are copied — never stats/samples/report.
40
+ */
41
+ export function buildSite(o) {
42
+ const assets = collectAssets(o.dir);
43
+ if (!assets.story.length || !assets.xCard)
44
+ throw new Error(`No rendered cards in ${o.dir}. Run \`wrapt render\` first.`);
45
+ const siteDir = path.join(o.dir, "site");
46
+ fs.rmSync(siteDir, { recursive: true, force: true });
47
+ const files = [];
48
+ const copy = (rel, from = path.join(o.dir, rel)) => {
49
+ fs.mkdirSync(path.dirname(path.join(siteDir, rel)), { recursive: true });
50
+ fs.copyFileSync(from, path.join(siteDir, rel));
51
+ files.push(rel);
52
+ };
53
+ for (const rel of [...assets.story, ...assets.carousel, assets.pdf, assets.xCard])
54
+ if (rel)
55
+ copy(rel);
56
+ copy("font.ttf", FONT);
57
+ const brand = brandFor(o.stats);
58
+ const t = o.stats.totals;
59
+ const who = possessive(o.name);
60
+ const title = `${who} ${o.stats.year} with ${brand.long}`;
61
+ const description = `${human(t.prompts)} prompts · ${human(Math.round(t.hours))} hours · ${human(t.tokens.total)} tokens · ${t.activeDays} active days. Made with wrapt.`;
62
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
63
+ const html = sharePage(assets, {
64
+ year: o.stats.year,
65
+ base: ".",
66
+ mode: "public",
67
+ fileUrl: (rel) => rel,
68
+ fontUrl: "font.ttf",
69
+ heading: `${esc(who)} <em>${o.stats.year}</em>, wrapped.`,
70
+ og: { title, description, image: `${o.pageUrl}${assets.xCard}`, url: o.pageUrl },
71
+ });
72
+ fs.writeFileSync(path.join(siteDir, "index.html"), html);
73
+ files.push("index.html");
74
+ return { siteDir, files };
75
+ }
76
+ function git(args, cwd, env) {
77
+ return execFileSync("git", args, { cwd, env: { ...process.env, ...env }, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
78
+ }
79
+ /** Who the public Pages commits are made as. */
80
+ export const PUBLISH_IDENTITY = { name: "wrapt", email: "noreply@wrapt.cc" };
81
+ /**
82
+ * Update <year>/ on the Pages branch, keeping other years. Works in a throwaway clone, so
83
+ * the user's own checkouts are never touched. Returns false when there was nothing to change.
84
+ */
85
+ export function pushSite(o) {
86
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "wrapt-publish-"));
87
+ try {
88
+ const exists = git(["ls-remote", "--heads", o.remote, o.branch], tmp) !== "";
89
+ if (exists)
90
+ git(["clone", "--quiet", "--depth", "1", "--branch", o.branch, o.remote, "repo"], tmp);
91
+ else {
92
+ fs.mkdirSync(path.join(tmp, "repo"));
93
+ git(["init", "--quiet"], path.join(tmp, "repo"));
94
+ git(["checkout", "--quiet", "--orphan", o.branch], path.join(tmp, "repo"));
95
+ git(["remote", "add", "origin", o.remote], path.join(tmp, "repo"));
96
+ }
97
+ const repo = path.join(tmp, "repo");
98
+ // The Pages branch is public, so its commits must not carry the user's name, email or time zone.
99
+ const author = o.author ?? PUBLISH_IDENTITY;
100
+ git(["config", "user.name", author.name], repo);
101
+ git(["config", "user.email", author.email], repo);
102
+ const yearDir = path.join(repo, String(o.year));
103
+ fs.rmSync(yearDir, { recursive: true, force: true });
104
+ if (o.siteDir)
105
+ fs.cpSync(o.siteDir, yearDir, { recursive: true });
106
+ fs.writeFileSync(path.join(repo, ".nojekyll"), "");
107
+ const years = fs.readdirSync(repo).filter((f) => /^\d{4}$/.test(f)).sort();
108
+ const latest = years[years.length - 1];
109
+ // Root page: send visitors to the newest year.
110
+ fs.writeFileSync(path.join(repo, "index.html"), latest
111
+ ? `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0; url=${latest}/"><link rel="canonical" href="${latest}/"><a href="${latest}/">${latest}</a>\n`
112
+ : `<!doctype html><meta charset="utf-8"><title>wrapt</title><p>Nothing published.</p>\n`);
113
+ git(["add", "-A"], repo);
114
+ if (!git(["status", "--porcelain"], repo))
115
+ return false;
116
+ // Env vars win over git config, so set them too in case the user's shell exports GIT_AUTHOR_*.
117
+ git(["commit", "--quiet", "-m", o.message], repo, {
118
+ TZ: "UTC",
119
+ GIT_AUTHOR_NAME: author.name,
120
+ GIT_AUTHOR_EMAIL: author.email,
121
+ GIT_COMMITTER_NAME: author.name,
122
+ GIT_COMMITTER_EMAIL: author.email,
123
+ });
124
+ git(["push", "--quiet", "origin", `HEAD:refs/heads/${o.branch}`], repo);
125
+ return true;
126
+ }
127
+ finally {
128
+ fs.rmSync(tmp, { recursive: true, force: true });
129
+ }
130
+ }