Skip to content

An agent skill for creating detailed, interactive isometric illustrations of real-world machines and complex systems. Generates polished SVGs with optional WebGL shaders and 3D effects.

publish.mjs records the time to make and tokens spent, read from the Claude Code session

R.ca046c337d8e
diff --git a/references/publish.md b/references/publish.md
index 594ce8a..a7fd027 100644
--- a/references/publish.md
+++ b/references/publish.md
@@ -18,10 +18,11 @@ Publish only when the user asks to share or publish a figure. Never send anythin
```sh
node <skill>/scripts/publish.mjs <figure folder> --into <clone> --id <kebab-id> \
--title "..." --author <github user> --prompt "..." \
- [--agent "Claude Code"|OpenCode|Codex|Other] [--model "..."] [--license MIT|CC-BY-4.0] \
+ [--agent "Claude Code"|OpenCode|Codex|Other] --model "..." [--minutes 45] [--tokens 1.2M] \
+ [--license MIT|CC-BY-4.0] \
[--tags a,b] [--audit] [--pages a.html,b.html] --submit --dry-run
```
- Pass `--agent` for the agent you are running in. Read the plan back to the user: it names the fork (if any), the branch, the folder it adds and where the pull request goes.
+ Pass `--agent` for the agent you are running in and `--model` for the model you are (the gallery requires it, like `claude-opus-5-5` or `gpt-5-codex`). In Claude Code the time to make and the tokens spent are read from this session's log on their own: from the request that made the figure to the request to publish it, idle gaps over 10 minutes left out, cache reads not counted. In another agent, pass `--minutes` and `--tokens` if you can see your session's usage; otherwise leave them out rather than guess. Read the plan back to the user: it names the fork (if any), the branch, the folder it adds and where the pull request goes.
5. **Only after the user says yes,** run the same command with `--yes` instead of `--dry-run`. It copies only the figure's source into `figures/<author>/<id>/src/`, points its kit imports at the clone's `.skill/` link, records the kit fingerprint, checks the build, saves a preview to `shots/<author>-<id>/preview.png`, then commits that folder alone, pushes, and opens the pull request. Give the user the link it prints.
- If it says a file reaches outside the figure folder and the skill, copy what that file needs into the figure folder, rebuild, and publish again.
- If it can't tell which pages are the figure, pass `--pages`.
diff --git a/scripts/publish.mjs b/scripts/publish.mjs
index 86e12a9..8fa7610 100644
--- a/scripts/publish.mjs
+++ b/scripts/publish.mjs
@@ -3,6 +3,7 @@ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, re
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { fingerprintOfSkill } from "./fingerprint.mjs";
+import { describe, fromThisSession, parseMinutes, parseTokens } from "./session.mjs";
const SKILL = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const SOURCE_TYPES = [".mjs", ".js", ".css", ".html", ".json", ".md", ".txt", ".svg"];
@@ -19,12 +20,16 @@ function usage(message) {
console.log(`Copy a figure into a local clone of the community gallery, ready for a pull request.
node scripts/publish.mjs <figure folder> --into <anatomy-community clone> --id <kebab-id> --title "..." --prompt "..." --author <github user>
- [--agent "Claude Code"|OpenCode|Codex|Other] [--model "..."] [--license MIT|CC-BY-4.0] [--tags a,b]
+ [--agent "Claude Code"|OpenCode|Codex|Other] [--model "..."] [--minutes 45] [--tokens 1.2M] [--no-session]
+ [--license MIT|CC-BY-4.0] [--tags a,b]
[--build build.mjs] [--pages a.html,b.html] [--kind "SVG + WebGL"] [--audit] [--no-preview] [--force]
[--submit [--yes] [--dry-run] [--upstream owner/repo]]
The figure must be plain HTML: a build script that writes standalone pages next to itself, in any theme.
Only the source is copied, to figures/<author>/<id>/: the gallery's CI builds the pages and the poster.
+In Claude Code, the time to make and the tokens spent are read from this session's own log (from the request that
+made the figure up to the request to publish it, with idle gaps over 10 minutes left out); --minutes and --tokens
+override them, and --no-session leaves them out. Other agents pass them if they know them.
Without --submit nothing is pushed: the command prints the git and gh commands to run when you are ready.
With --submit it also sends the figure as a pull request, using the GitHub CLI (gh): it shows the plan and asks
first (--yes skips the question, --dry-run only shows the plan). People who can push to the gallery get a branch
@@ -45,6 +50,13 @@ function parse(argv) {
else if (["--into", "--id", "--title", "--prompt", "--author", "--agent", "--model", "--license", "--build", "--kind", "--date"].includes(arg)) options[arg.slice(2)] = take(index++);
else if (arg === "--tags") options.tags = take(index++).split(",").map((tag) => tag.trim()).filter(Boolean);
else if (arg === "--pages") options.pages = take(index++).split(",").map((page) => page.trim());
+ else if (arg === "--minutes") {
+ options.minutes = parseMinutes(take(index++));
+ if (!options.minutes) usage("--minutes takes a duration like 45, 45m, 2h or 1h30m");
+ } else if (arg === "--tokens") {
+ options.tokens = parseTokens(take(index++));
+ if (!options.tokens) usage("--tokens takes a count like 380000, 450k or 1.2M");
+ } else if (arg === "--no-session") options.noSession = true;
else if (arg === "--audit") options.audit = true;
else if (arg === "--force") options.force = true;
else if (arg === "--no-preview") options.noPreview = true;
@@ -187,6 +199,10 @@ export function publish(options) {
preview = join(shots, "preview.png");
run([join(SKILL, "scripts", "capture.mjs"), join(dest, "src", lightPage ?? Object.values(pages)[0]), "--reduced", "--width", "1200", "--out", preview], dest);
}
+ const measured = options.noSession || (options.minutes && options.tokens) ? null : fromThisSession({ prompt: options.prompt });
+ const minutes = options.minutes ?? measured?.minutes;
+ const tokens = options.tokens ?? measured?.tokens;
+ if (measured) log(`time and tokens from this session: ${describe(measured)}`);
const pageText = Object.values(pages).filter(Boolean).map((page) => readFileSync(join(dest, "src", page), "utf8")).join("\n");
for (const page of outputs) rmSync(join(dest, "src", page), { force: true });
const figure = {
@@ -197,6 +213,8 @@ export function publish(options) {
kind: options.kind ?? detectKind(pageText),
agent: options.agent,
...(options.model ? { model: options.model } : {}),
+ ...(minutes ? { minutes } : {}),
+ ...(tokens ? { tokens } : {}),
skill: { kit },
build,
pages: Object.fromEntries(Object.entries(pages).filter(([, page]) => page).map(([key, page]) => [key, `src/${page}`])),
@@ -208,7 +226,7 @@ export function publish(options) {
};
writeFileSync(join(dest, "figure.json"), JSON.stringify(figure, null, 2) + "\n");
- return { dest, figure, skipped, linked, preview };
+ return { dest, figure, skipped, linked, preview, measured };
}
export function submitPlan({ login, canPush, upstream, author, id, title }) {
@@ -252,6 +270,11 @@ async function submit(options) {
const plan = submitPlan({ login, canPush: perm.stdout.trim() === "true", upstream: options.upstream, author, id: options.id, title: options.title.trim() });
console.log(`\nSubmitting as @${login}:`);
for (const step of plan.steps) if (step.say) console.log(` · ${step.say}`);
+ if (!options.noSession && !(options.minutes && options.tokens)) {
+ const measured = fromThisSession({ prompt: options.prompt });
+ const shown = { minutes: options.minutes ?? measured?.minutes, tokens: options.tokens ?? measured?.tokens };
+ console.log(shown.minutes && shown.tokens ? ` · record ${describe(shown)} to make it${measured ? " (read from this session)" : ""}` : " · no time or token count (not run inside Claude Code; pass --minutes and --tokens to add them)");
+ } else if (options.minutes || options.tokens) console.log(` · record${options.minutes ? ` ${options.minutes} min` : ""}${options.tokens ? ` ${options.tokens} tokens` : ""}`);
console.log(` (in ${repo})`);
if (options.dryRun) return console.log("\ndry run: nothing was done");
if (!options.yes && !(await confirm("\nGo ahead? [y/N] "))) throw new Error("not submitted (answer y, or pass --yes after asking)");
@@ -288,6 +311,7 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.ur
const { dest, figure, skipped, linked, preview } = publish({ ...options, log: (line) => console.log(` ${line}`) });
const repo = resolve(options.into);
console.log(`published figures/${figure.author.toLowerCase()}/${figure.id} (${figure.kind}, kit ${figure.skill.kit.slice(7, 19)}): source only, the gallery builds the pages`);
+ if (figure.minutes && figure.tokens) console.log(` made in ${describe(figure)}`);
if (skipped.length) console.log(` left out (not a source type): ${skipped.join(", ")}`);
console.log(` .skill link: ${linked}`);
if (preview) console.log(` preview: ${preview} (not committed; CI makes the real one)`);
diff --git a/scripts/session.mjs b/scripts/session.mjs
new file mode 100644
index 0000000..014803d
--- /dev/null
+++ b/scripts/session.mjs
@@ -0,0 +1,107 @@
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+export const IDLE_CAP = 10 * 60 * 1000;
+
+export function parseMinutes(text) {
+ const value = String(text ?? "").trim().toLowerCase();
+ if (!value) return null;
+ if (/^\d+$/.test(value)) return Number(value);
+ const match = value.match(/^(?:(\d+(?:[.,]\d+)?)\s*(?:h|hr|hrs|hours?))?\s*(?:(\d+)\s*(?:m|min|mins|minutes?))?$/);
+ if (!match || (!match[1] && !match[2])) return undefined;
+ return Math.round(Number((match[1] ?? "0").replace(",", ".")) * 60 + Number(match[2] ?? 0)) || undefined;
+}
+
+export function parseTokens(text) {
+ const value = String(text ?? "").trim().toLowerCase().replace(/[\s,_]/g, "").replace(/tokens?$/, "");
+ if (!value) return null;
+ const match = value.match(/^(\d+(?:\.\d+)?)([km]?)$/);
+ if (!match) return undefined;
+ const tokens = Math.round(Number(match[1]) * (match[2] === "m" ? 1e6 : match[2] === "k" ? 1e3 : 1));
+ return tokens >= 1 && tokens <= 1e10 ? tokens : undefined;
+}
+
+function walk(dir, out = []) {
+ for (const name of existsSync(dir) ? readdirSync(dir) : []) {
+ const full = join(dir, name);
+ if (statSync(full).isDirectory()) walk(full, out);
+ else if (name.endsWith(".jsonl")) out.push(full);
+ }
+ return out;
+}
+
+export function sessionFiles(sessionId, root = join(homedir(), ".claude", "projects")) {
+ if (!sessionId || !/^[0-9a-f-]{8,64}$/i.test(sessionId) || !existsSync(root)) return [];
+ for (const project of readdirSync(root)) {
+ const main = join(root, project, `${sessionId}.jsonl`);
+ if (existsSync(main)) return [main, ...walk(join(root, project, sessionId))];
+ }
+ return [];
+}
+
+function entriesOf(file) {
+ const out = [];
+ for (const line of readFileSync(file, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ const entry = JSON.parse(line);
+ if (entry && typeof entry.timestamp === "string") out.push(entry);
+ } catch {}
+ }
+ return out;
+}
+
+const textOf = (entry) => {
+ const content = entry.message?.content;
+ if (typeof content === "string") return content;
+ if (Array.isArray(content)) return content.filter((part) => part?.type === "text").map((part) => part.text).join("\n");
+ return "";
+};
+
+const squash = (text) => text.toLowerCase().replace(/\s+/g, " ").trim();
+
+export function measure(files, { prompt = "" } = {}) {
+ if (!files.length) return null;
+ const [main, ...side] = files;
+ const mainEntries = entriesOf(main).sort((a, b) => a.timestamp.localeCompare(b.timestamp));
+ const asks = mainEntries.filter((entry) => entry.type === "user" && !entry.isSidechain && textOf(entry));
+ const head = squash(prompt).slice(0, 48);
+ const start =
+ (head && asks.find((entry) => squash(textOf(entry)).includes(head))) ??
+ asks.find((entry) => /\/anatomy\b|\banatomy\b/i.test(textOf(entry))) ??
+ mainEntries[0];
+ if (!start) return null;
+ const end = asks.find((entry) => entry.timestamp > start.timestamp && /\bpublish\b/i.test(textOf(entry)) && /\b(community|gallery)\b/i.test(textOf(entry)));
+ const from = start.timestamp;
+ const to = end?.timestamp ?? "￿";
+ const inWindow = (entry) => entry.timestamp >= from && entry.timestamp < to;
+
+ const all = [...mainEntries, ...side.flatMap(entriesOf)].filter(inWindow);
+ const times = [...new Set(all.map((entry) => Date.parse(entry.timestamp)).filter(Number.isFinite))].sort((a, b) => a - b);
+ let active = 0;
+ for (let i = 1; i < times.length; i++) active += Math.min(times[i] - times[i - 1], IDLE_CAP);
+
+ const perMessage = new Map();
+ for (const entry of all) {
+ const usage = entry.type === "assistant" ? entry.message?.usage : null;
+ if (!usage) continue;
+ const key = `${entry.sessionId ?? ""}:${entry.agentId ?? ""}:${entry.message?.id ?? entry.uuid}`;
+ const spent = (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.output_tokens ?? 0);
+ perMessage.set(key, Math.max(perMessage.get(key) ?? 0, spent));
+ }
+ const tokens = [...perMessage.values()].reduce((sum, spent) => sum + spent, 0);
+ if (!tokens) return null;
+ const last = end?.timestamp ?? (times.length ? new Date(times.at(-1)).toISOString() : from);
+ return { minutes: Math.max(1, Math.round(active / 60000)), tokens, from, to: last };
+}
+
+export function fromThisSession({ prompt, env = process.env, root } = {}) {
+ return measure(sessionFiles(env.CLAUDE_CODE_SESSION_ID, root), { prompt });
+}
+
+export function describe({ minutes, tokens }) {
+ const time = minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h${minutes % 60 ? ` ${minutes % 60} min` : ""}`;
+ const count = tokens >= 1e6 ? `${(tokens / 1e6).toFixed(1).replace(/\.0$/, "")}M` : tokens >= 1e3 ? `${Math.round(tokens / 1e3)}k` : String(tokens);
+ return `about ${time} and ${count} tokens`;
+}
diff --git a/scripts/session.test.mjs b/scripts/session.test.mjs
new file mode 100644
index 0000000..ebb10dc
--- /dev/null
+++ b/scripts/session.test.mjs
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { test } from "node:test";
+import { describe, fromThisSession, measure, parseMinutes, parseTokens } from "./session.mjs";
+
+const at = (minute) => new Date(Date.UTC(2026, 9, 12, 10, 0) + minute * 60000).toISOString();
+const user = (minute, text) => ({ type: "user", timestamp: at(minute), message: { role: "user", content: text } });
+const reply = (minute, id, input, output, extra = {}) => ({ type: "assistant", timestamp: at(minute), message: { id, usage: { input_tokens: input, cache_creation_input_tokens: 1000, cache_read_input_tokens: 999999, output_tokens: output } }, ...extra });
+const lines = (entries) => entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n";
+
+function session() {
+ const root = mkdtempSync(join(tmpdir(), "session-"));
+ const id = "0123abcd-0000-0000-0000-000000000000";
+ mkdirSync(join(root, "-work", id, "subagents"), { recursive: true });
+ writeFileSync(join(root, "-work", `${id}.jsonl`), lines([
+ user(0, "fix the readme"),
+ reply(1, "m0", 50, 50),
+ user(5, "/anatomy explain how a token bucket works, interactive"),
+ reply(6, "m1", 100, 200),
+ reply(6, "m1", 100, 400),
+ reply(8, "m2", 10, 20),
+ reply(70, "m3", 10, 20),
+ user(80, "publish this figure to the community gallery"),
+ reply(81, "m4", 5000, 5000),
+ ]));
+ writeFileSync(join(root, "-work", id, "subagents", "agent-1.jsonl"), lines([reply(7, "s1", 300, 300, { isSidechain: true, agentId: "a1" })]));
+ return { root, id };
+}
+
+test("time and tokens cover the figure's request up to the publish request", () => {
+ const { root, id } = session();
+ const result = fromThisSession({ prompt: "/anatomy explain how a token bucket works, interactive", env: { CLAUDE_CODE_SESSION_ID: id }, root });
+ assert.equal(result.tokens, 1100 + 400 + 1030 + 1030 + 1600);
+ assert.equal(result.minutes, 3 + 10);
+ assert.equal(result.from, at(5));
+ assert.equal(result.to, at(80));
+});
+
+test("no session, no numbers", () => {
+ assert.equal(fromThisSession({ env: {} }), null);
+ assert.equal(measure([]), null);
+});
+
+test("hand-given values are read like the gallery reads them", () => {
+ assert.equal(parseMinutes("1h30m"), 90);
+ assert.equal(parseMinutes("45"), 45);
+ assert.equal(parseMinutes("soon"), undefined);
+ assert.equal(parseTokens("1.2M"), 1200000);
+ assert.equal(parseTokens("450k"), 450000);
+ assert.equal(parseTokens("lots"), undefined);
+ assert.equal(describe({ minutes: 95, tokens: 1240000 }), "about 1 h 35 min and 1.2M tokens");
+});