Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
4bf35c5
fix: OpenCode SQLite 사용량 파싱 지원
haazz Aug 4, 2026
807f1ef
Merge branch 'TOKENPHAGE:main' into feature/opencode-sqlite-storage
haazz Aug 25, 2026
6693b38
chore: better-sqlite3 의존성 추가
haazz Aug 25, 2026
775f5c9
fix: OpenCode DB를 외부 App 없이 직접 조회
haazz Aug 25, 2026
ad07270
fix: DB 조회 행을 쿼리 별칭 그대로 다루도록 정리
haazz Aug 25, 2026
e91db8f
Merge pull request #22 from haazz/feature/opencode-sqlite-storage
kobenlys Sep 3, 2026
631bfd5
fix: better-sqlite3 로드 실패가 CLI 전체를 죽이지 않게 격리
kobenlys Sep 3, 2026
34c2788
chore: better-sqlite3 13으로 올리고 지원 Node 범위 정리
kobenlys Sep 3, 2026
c5dbb3c
Merge pull request #24 from TOKENPHAGE/feature/better-sqlite3-v13
kobenlys Sep 3, 2026
23510c8
ci: 테스트 매트릭스에 macOS·Windows 추가
kobenlys Sep 4, 2026
da9dd3f
test: launchctl 조회 인자를 정규식 대신 완전 일치로 단언
kobenlys Sep 4, 2026
c92f153
ci: npm ci에서 install script 스킵하고 전역 설치 스모크 추가
kobenlys Sep 4, 2026
978617b
docs: 요구 Node 버전을 22.14로 갱신
kobenlys Sep 4, 2026
fe34cdf
Merge pull request #25 from TOKENPHAGE/feature/ci-os-matrix
kobenlys Sep 4, 2026
fc6e158
Merge pull request #26 from TOKENPHAGE/docs/readme-node-version
kobenlys Sep 4, 2026
a39f33c
chore: 버전 2026.9.1로 올리고 .omc 무시 추가
kobenlys Sep 19, 2026
7aa82bb
Merge pull request #27 from TOKENPHAGE/feature/bump-2026.9.1
kobenlys Sep 19, 2026
f9c4efa
chore: petri 작업 폴더를 git 무시 목록에 추가
kobenlys Oct 30, 2026
6e05822
feat: 로그에서 도구별 AI 실행시간 계산
kobenlys Oct 30, 2026
d6a49b4
feat: sync에 실행시간 전송과 버전별 재전송 추가
kobenlys Oct 30, 2026
038e6ba
chore: 버전 2026.10.1로 올림
kobenlys Oct 30, 2026
26c6f93
Merge pull request #29 from TOKENPHAGE/feature/agent-running-time-parse
kobenlys Oct 31, 2026
61e5bbe
fix: Claude 설정 폴더가 없으면 만들어 기록 보존 설정 저장 (#28)
kobenlys Nov 1, 2026
0bf1ed3
test: retention 새 테스트에 줄별 설명 주석 추가 (#28)
kobenlys Nov 1, 2026
6330541
Merge pull request #30 from TOKENPHAGE/feature/retention-missing-clau…
kobenlys Nov 1, 2026
b930460
chore: 버전 2026.11.1로 올림
kobenlys Nov 5, 2026
6b8d695
Merge pull request #32 from TOKENPHAGE/feature/bump-2026.11.1
kobenlys Nov 5, 2026
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
25 changes: 19 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ concurrency:

jobs:
unit-tests:
name: Unit Tests (Node ${{ matrix.node }})
runs-on: ubuntu-latest
name: Unit Tests (${{ matrix.os }} / Node ${{ matrix.node }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
node: ['20', '22', '24'] # 지원 Node 버전
# better-sqlite3는 네이티브 모듈이라 플랫폼별 prebuild가 실제로 붙는지 확인해야 한다.
os: [ubuntu-latest, macos-latest, windows-latest]
node: ['22', '24', '26'] # 지원 Node 버전(engines와 일치)
steps:
- uses: actions/checkout@v4

Expand All @@ -27,8 +29,19 @@ jobs:
node-version: ${{ matrix.node }}
cache: npm # 의존성 캐시

- run: npm ci # 의존성 설치
- run: npm test # 테스트 실행
# npm#9837: lockfile 경로에서 better-sqlite3의 gypfile:false가 무시돼 암묵 node-gyp가 돈다.
# prebuild는 압축 해제만으로 로드되므로(lib/binding.js) 스크립트를 건너뛰어도 무해하다.
# 이 트리에 install script를 쓰는 의존성은 없다 — 추가하려면 이 플래그를 먼저 재검토할 것.
- run: npm ci --ignore-scripts # 의존성 설치
- run: npm test # 테스트 실행

# 실사용자는 lockfile 없는 경로(npm i -g)로 설치한다. CI가 그 경로를 안 보고 있었다.
- name: 전역 설치 스모크
shell: bash
run: |
TARBALL=$(npm pack --silent)
npm i -g "./$TARBALL"
tokenphage --version

coverage:
name: Coverage
Expand All @@ -41,5 +54,5 @@ jobs:
node-version: '24' # 커버리지 임계 플래그 지원
cache: npm

- run: npm ci # 의존성 설치
- run: npm ci --ignore-scripts # 의존성 설치 (위 unit-tests 주석 참조)
- run: npm run test:coverage # 로직 코어 80% 미만이면 실패
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,9 @@ coverage/
# Claude Code 작업 파일(작업 환경 전용 규칙·세션 메타)은 공개하지 않는다.
.claude/
CLAUDE.md

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

# petri E2E 작업 폴더(SSOT, 테스트, 샌드박스, 실행 기록)는 로컬에만 둔다.
.petri/
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Claude Code, Codex, opencode의 토큰 사용량을 모아 GitHub README에 붙

## 📋 요구 사항

- **Node.js 20.17 이상**
- **Node.js 22.14 이상**
- macOS 또는 Windows (자동 동기화 사용 시)
- GitHub 계정

Expand Down
28 changes: 25 additions & 3 deletions package-lock.json

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

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tokenphage",
"version": "2026.8.1",
"version": "2026.11.1",
"description": "AI 토큰 사용량 GitHub README 뱃지",
"author": "kobenlys <kobenlys@gmail.com>",
"license": "MIT",
Expand All @@ -24,6 +24,7 @@
},
"dependencies": {
"@inquirer/prompts": "^8.5.0",
"better-sqlite3": "^13.0.3",
"chalk": "^5.6.2",
"commander": "^12.1.0",
"glob": "^11.0.0",
Expand All @@ -37,6 +38,6 @@
"mute-stream": "^3.0.0"
},
"engines": {
"node": "^20.17.0 || ^22.13.0 || >=23.5.0"
"node": "^22.14.0 || >=23.6.0"
}
}
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
9 changes: 5 additions & 4 deletions src/lib/retention.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { existsSync, readFileSync, writeFileSync, renameSync } from 'fs';
import { join } from 'path';
import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync } from 'fs';
import { dirname, join } from 'path';

// Claude Code의 cleanupPeriodDays(트랜스크립트 보존 기간) 검사·설정.
// 규칙은 하나: 99999 이상이면 통과, 아니면 동의를 받아 무조건 99999로 설정한다.
Expand Down Expand Up @@ -41,9 +41,9 @@ export function checkClaudeRetention(claudeDirs) {
}

/**
* settings.json의 cleanupPeriodDays를 무조건 99999로 설정한다 (다른 필드 보존, 원자 쓰기).
* settings.json의 cleanupPeriodDays를 무조건 99999로 설정한다 (다른 필드 보존, 원자 쓰기, 상위 폴더가 없으면 0700으로 생성).
* @param {string} settingsPath checkClaudeRetention()이 돌려준 settings.json 경로
* @returns {boolean} 성공 여부 — 손상 JSON이면 수정하지 않고 false
* @returns {boolean} 성공 여부 — 손상 JSON이면 수정하지 않고 false, 쓰기(폴더 생성 포함)에 실패해도 false
*/
export function applyRetentionSetting(settingsPath) {
let config = {};
Expand All @@ -57,6 +57,7 @@ export function applyRetentionSetting(settingsPath) {

try {
const next = { ...config, cleanupPeriodDays: FOREVER_DAYS };
mkdirSync(dirname(settingsPath), { recursive: true, mode: 0o700 }); // Claude Code가 이 폴더에 대화 기록을 쌓는다
const tmpPath = settingsPath + '.tmp';
writeFileSync(tmpPath, JSON.stringify(next, null, 2) + '\n');
renameSync(tmpPath, settingsPath); // 같은 디렉터리 내 rename = 원자적 교체
Expand Down
41 changes: 27 additions & 14 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 { 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 All @@ -64,19 +63,33 @@ export async function parseAll(fromDate = null) {
...(await globSorted(`${codexHome}/archived_sessions/**/*.jsonl`)),
];

// opencode는 message(모델·시각)와 part(step-finish 토큰)를 모두 읽어야 조인할 수 있다.
// parseOpencodeFiles가 내용으로 분류하므로 두 목록을 합쳐 넘긴다(순서 무관).
// 최신 opencode는 data home 바로 아래 opencode.db에 저장한다.
// DB가 있으면 그 파일만 직접 읽고(구버전에서 마이그레이션된 JSON과의 이중 집계 방지),
// DB가 없는 구버전만 storage/message·part JSON을 읽는다.
let opencodeDatabase = null;
const opencodeFiles = [];
for (const dir of opencodeDirCandidates()) {
const base = dir.replaceAll('\\', '/');
opencodeFiles.push(...await globSorted(`${base}/storage/message/**/*.json`));
opencodeFiles.push(...await globSorted(`${base}/storage/part/**/*.json`));
if (!opencodeDatabase) {
[opencodeDatabase = null] = await globSorted(`${base}/opencode.db`);
}
if (!opencodeDatabase) {
opencodeFiles.push(...await globSorted(`${base}/storage/message/**/*.json`));
opencodeFiles.push(...await globSorted(`${base}/storage/part/**/*.json`));
}
}

const [claudeEntries, codexEntries, opencodeEntries] = await Promise.all([
parseClaudeFiles(claudeFiles),
parseCodexFiles(codexFiles),
parseOpencodeFiles(opencodeFiles),
]);
return aggregateRecords([...claudeEntries, ...codexEntries, ...opencodeEntries], fromDate);
return { claudeFiles, codexFiles, opencodeDatabase, opencodeFiles };
}

/**
* 로그를 한 번 읽어 토큰 레코드와 실행시간을 함께 계산한다.
* @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
Loading
Loading