Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,6 @@ CLAUDE.md

# oh-my-claudecode 로컬 상태(세션 산출물)는 공개하지 않는다.
.omc/

# petri E2E 작업 폴더(SSOT, 테스트, 샌드박스, 실행 기록)는 로컬에만 둔다.
.petri/
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tokenphage",
"version": "2026.9.1",
"version": "2026.10.1",
"description": "AI 토큰 사용량 GitHub README 뱃지",
"author": "kobenlys <kobenlys@gmail.com>",
"license": "MIT",
Expand Down
21 changes: 7 additions & 14 deletions src/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { join } from 'path';
import { randomUUID } from 'crypto';
import { normalizeConfig } from './lib/config-schema.js';
import { localDateOf } from './lib/dates.js';
import { apiFetch } from './sync.js';

// 로컬 설정 파일 경로: ~/.tokenphage/config.json (JWT·deviceId·sync 상태 보관)
const CONFIG_DIR = join(homedir(), '.tokenphage');
Expand Down Expand Up @@ -79,18 +80,10 @@ export function getCustomClaudePaths() {
return Array.isArray(paths) ? paths : [];
}

/** 마지막 sync 완료 날짜(YYYY-MM-DD)를 반환한다. 없으면 null. */
export function getLastSyncDate() { return loadConfig().lastSyncDate ?? null; }

/** 마지막 sync 날짜를 저장한다. 다음 sync는 이 날짜 이후만 증분 파싱한다. */
export function saveLastSyncDate(date) {
saveConfig({ ...loadConfig(), lastSyncDate: date });
}

/** lastSyncDate를 제거해 다음 sync가 전체 히스토리를 재파싱하도록 한다. token/deviceId는 보존. */
export function clearLastSyncDate() {
const { lastSyncDate: _omit, ...rest } = loadConfig();
saveConfig(rest);
/** reset용: lastSyncDate와 lastSyncVersion을 지워 다음 sync가 토큰·실행시간을 처음부터 보내게 한다. 나머지는 보존. */
export function clearSyncState({ readConfig = loadConfig, writeConfig = saveConfig } = {}) {
const { lastSyncDate: _date, lastSyncVersion: _version, ...rest } = readConfig();
writeConfig(rest);
}

// Gist 소유권 검증용 파일명 — 사용자가 이 이름으로 Gist를 만들어야 한다.
Expand All @@ -113,8 +106,8 @@ export function parseGistId(input) {

/** url에 JSON body를 POST하고 {ok, status, body}를 반환한다. 응답이 JSON이 아니면 {error: 원문}으로 감싼다. */
async function postJson(url, body) {
// Node 18+ 전역 fetch 사용 (node-fetch 의존성 불필요).
const res = await fetch(url, {
// 이름표를 붙이고 지원 종료 헤더를 안내하는 공통 요청
const res = await apiFetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
Expand Down
35 changes: 8 additions & 27 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
* 맨 끝 program.parse()가 argv를 해석해 실제 시동을 건다.
*/
import { Command } from 'commander';
import { parseAll } from './parser.js';
import { loadConfig, loadToken, saveToken, getOrCreateDeviceId, gistLogin, setHookInstalled, getLastSyncDate, saveLastSyncDate, clearLastSyncDate } from './auth.js';
import { syncRecords, resetData } from './sync.js';
import { parseLogs } from './parser.js';
import { loadConfig, loadToken, saveToken, getOrCreateDeviceId, gistLogin, setHookInstalled, clearSyncState } from './auth.js';
import { resetData } from './sync.js';
import { runSyncFlow } from './sync-flow.js';
import { installHook, uninstallHook } from './scheduler.js';
import { reconcileHookRegistration } from './hook-reconcile.js';
import { promptFirstRun, promptDashboard, promptAdvanced, confirmReset, pauseForEnter, showError } from './ui.js';
import { accent } from './gradient.js';
import { localDateOf } from './lib/dates.js';
import { claudeDirCandidates } from './parser.js';
import { checkClaudeRetention, applyRetentionSetting, DEFAULT_CLEANUP_DAYS } from './lib/retention.js';
import { checkLatestVersion, getUpdateInfo } from './lib/update-check.js';
Expand Down Expand Up @@ -126,30 +126,11 @@ async function promptRetentionSetup() {
}
}

/** sync 명령 본체: 로컬 로그를 파싱(최초=전체 / 이후=증분)해 서버로 업로드하고, 마지막 sync 날짜를 갱신한다. */
/** sync 명령 본체: 인증·기기 ID를 확인하고 sync 흐름(sync-flow.js)을 실행한다. */
async function runSync() {
const token = requireToken();
const deviceId = getOrCreateDeviceId();
const today = localDateOf(new Date());

// 최초(lastSyncDate 없음)면 fromDate=null → 전체 히스토리 파싱.
// 이후엔 직전 sync일부터 오늘까지 증분만 파싱.
const lastSyncDate = getLastSyncDate();
const fromDate = lastSyncDate ?? null;

console.log(`Parsing local logs... (${fromDate ?? 'beginning'} ~ ${today})`);
const records = await parseAll(fromDate);
console.log(`${records.length} records aggregated (date×model)`);
if (records.length === 0) {
console.log('Nothing to sync.');
saveLastSyncDate(today);
return;
}

console.log('Uploading to server...');
await syncRecords(API_BASE, token, deviceId, records);
saveLastSyncDate(today);
console.log('Done! Badge will update shortly.');
await runSyncFlow({ apiBase: API_BASE, token, deviceId, parseLogs });
}

/**
Expand Down Expand Up @@ -183,8 +164,8 @@ async function runAdvanced(apiBase, cfg) {
await pauseForEnter();
return;
}
// 2단계: 로컬 워터마크 제거 후 전체 재-sync. 재-sync가 실패해도 서버 삭제는 이미 완료됐음을 명확히 안내.
clearLastSyncDate();
// 2단계: 로컬 워터마크(lastSyncDate·lastSyncVersion) 제거 후 전체 재-sync. 재-sync가 실패해도 서버 삭제는 이미 완료됐음을 명확히 안내.
clearSyncState();
console.log(accent(' [OK] Server data reset.') + ' Re-syncing from scratch...');
try {
await runSync();
Expand Down
1 change: 1 addition & 0 deletions src/lib/config-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export function normalizeConfig(raw, today) {
dropIf('token', isJwtShape);
dropIf('deviceId', isUuid); // 없으면 getOrCreateDeviceId가 재발급
dropIf('lastSyncDate', (v) => isYmdDate(v, today)); // 없으면 전체 재파싱
dropIf('lastSyncVersion', (v) => typeof v === 'string' && v !== ''); // 없으면 실행시간 전체 재전송
dropIf('hookInstalledAt', isIsoDate);
dropIf('hookInstalled', (v) => typeof v === 'boolean');
dropIf('claudePaths', isStringArray);
Expand Down
28 changes: 15 additions & 13 deletions src/parser.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { glob } from 'glob';
import { homedir } from 'os';
import { parseClaudeFiles } from './parsers/claude.js';
import { parseCodexFiles } from './parsers/codex.js';
import { parseOpencodeDatabase, parseOpencodeFiles } from './parsers/opencode.js';
import { resolveClaudeDirs, resolveOpencodeDirs } from './lib/paths.js';
import { getCustomClaudePaths } from './auth.js';
import { readLogs } from './runtime/read-logs.js';

/**
* 소스별 파서가 돌려준 항목들을 "날짜|모델" 단위 레코드로 합산한다.
Expand Down Expand Up @@ -50,7 +48,8 @@ export function opencodeDirCandidates() {
});
}

export async function parseAll(fromDate = null) {
/** 세 도구의 로그 경로를 기존 탐색 순서대로 찾는다. */
async function discoverLogPaths() {
// 경로가 겹쳐도 파일 간 first-wins dedup이 흡수하므로 순서만 보장하면 된다.
const claudeFiles = [];
for (const dir of claudeDirCandidates()) {
Expand Down Expand Up @@ -80,14 +79,17 @@ export async function parseAll(fromDate = null) {
}
}

const opencodePromise = opencodeDatabase
? parseOpencodeDatabase(opencodeDatabase)
: parseOpencodeFiles(opencodeFiles);
return { claudeFiles, codexFiles, opencodeDatabase, opencodeFiles };
}

const [claudeEntries, codexEntries, opencodeEntries] = await Promise.all([
parseClaudeFiles(claudeFiles),
parseCodexFiles(codexFiles),
opencodePromise,
]);
return aggregateRecords([...claudeEntries, ...codexEntries, ...opencodeEntries], fromDate);
/**
* 로그를 한 번 읽어 토큰 레코드와 실행시간을 함께 계산한다.
* @param {{ tokenFrom: string|null, runtimeFrom: string|null }} range YYYY-MM-DD(포함) 또는 null(전체 기간)
* @returns {Promise<{ records: Array<{date: string, model: string, inputTok: number, outputTok: number, cacheReadTok: number, cacheCreateTok: number}>,
* runtimes: Array<{ date: string, source: 'claude'|'codex'|'opencode', model: string, runtimeMs: number }>,
* allSourcesRead: boolean, failedSources: string[] }>}
*/
export async function parseLogs({ tokenFrom = null, runtimeFrom = null } = {}) {
const { entries, runtimes, allSourcesRead, failedSources } = await readLogs(await discoverLogPaths(), runtimeFrom);
return { records: aggregateRecords(entries, tokenFrom), runtimes, allSourcesRead, failedSources };
}
4 changes: 3 additions & 1 deletion src/parsers/claude.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ function mergedEntry(existing, usage, timestamp) {
/**
* Claude 트랜스크립트 파일들을 응답(dedup된 메시지) 단위 usage 목록으로 파싱한다.
* @param {string[]} files JSONL 파일 경로 목록 (정렬된 순서 = 파일 간 first-wins 기준)
* @param {((record: object, file: string) => void)|null} [onRecord] 파싱한 줄마다 부르는 수집기(예외를 던지지 않아야 한다)
* @returns {Promise<Array<{date: string, model: string, inputTok: number, outputTok: number, cacheReadTok: number, cacheCreateTok: number}>>}
*/
export async function parseClaudeFiles(files) {
export async function parseClaudeFiles(files, onRecord = null) {
const deduped = new Map(); // key → { file, ts, ...entry }
const noKey = []; // dedup 키를 만들 수 없는 라인은 전부 집계

Expand All @@ -62,6 +63,7 @@ export async function parseClaudeFiles(files) {
if (!line.trim()) continue;
try {
const obj = JSON.parse(line);
onRecord?.(obj, file);
if (obj.type !== 'assistant') continue;
const msg = obj.message;
if (!msg?.usage) continue;
Expand Down
4 changes: 3 additions & 1 deletion src/parsers/codex.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,10 @@ function resolveIncrement(total, last, previous) {
/**
* Codex rollout 파일들을 턴 증분 단위 usage 목록으로 파싱한다.
* @param {string[]} files JSONL 파일 경로 목록 (정렬된 순서 — sessions를 archived보다 먼저)
* @param {((record: object, file: string) => void)|null} [onRecord] 파싱한 줄마다 부르는 수집기(예외를 던지지 않아야 한다)
* @returns {Promise<Array<{date: string, model: string, inputTok: number, outputTok: number, cacheReadTok: number, cacheCreateTok: number}>>}
*/
export async function parseCodexFiles(files) {
export async function parseCodexFiles(files, onRecord = null) {
const entries = [];
const seenKeys = new Set(); // 파일 간 replay/복제 dedup

Expand All @@ -158,6 +159,7 @@ export async function parseCodexFiles(files) {
if (!line.trim()) continue;
try {
const obj = JSON.parse(line);
onRecord?.(obj, file);
const payload = obj.payload;
if (!payload) continue;

Expand Down
10 changes: 6 additions & 4 deletions src/parsers/opencode.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,12 @@ function hasAnyTable(db) {
// 예외를 올리지 않고 빈 목록으로 격리한다(경고만 남긴다).
// better-sqlite3는 네이티브 모듈이라 로드 자체가 실패할 수 있다
// 정적 import면 그 실패가 CLI 전체를 죽이므로 격리 대상인 이 try 안에서 동적으로 불러온다.
async function queryOpencodeRows(dbPath) {
async function queryOpencodeRows(dbPath, onDatabase = null) {
let db;
try {
const { default: Database } = await import('better-sqlite3');
db = new Database(dbPath, { readonly: true, fileMustExist: true });
onDatabase?.(db); // 실행시간 수집도 같은 연결로 읽는다(수집기는 예외를 던지지 않는다)
// 기록이 아직 없는 빈 DB는 정상 상태다. 반대로 다른 테이블은 있는데 message/part만
// 없다면 OpenCode 스키마가 바뀐 것이므로 집계가 0으로 새지 않게 알린다.
if (!hasUsageTables(db)) {
Expand Down Expand Up @@ -119,10 +120,11 @@ export function parseOpencodeRows(rows) {
/**
* opencode.db(SQLite)를 직접 조회해 tokenphage usage 목록으로 변환한다.
* @param {string} dbPath opencode.db 절대 경로
* @param {(dbPath: string) => Array<object>} [queryRows] 조회 구현(테스트 주입용)
* @param {(dbPath: string, onDatabase?: Function|null) => Array<object>} [queryRows] 조회 구현(테스트 주입용)
* @param {((db: object) => void)|null} [onDatabase] 연 DB로 실행시간을 모으는 수집기(예외를 던지지 않아야 한다)
*/
export async function parseOpencodeDatabase(dbPath, queryRows = queryOpencodeRows) {
return parseOpencodeRows(await queryRows(dbPath));
export async function parseOpencodeDatabase(dbPath, queryRows = queryOpencodeRows, onDatabase = null) {
return parseOpencodeRows(await queryRows(dbPath, onDatabase));
}

/**
Expand Down
Loading
Loading