charge-connect 0.1.4 → 0.1.5

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.
Files changed (2) hide show
  1. package/collect.js +125 -55
  2. package/package.json +1 -1
package/collect.js CHANGED
@@ -124,6 +124,9 @@ function dropExpired(w) {
124
124
 
125
125
  // 캐시에서 복원한 프로바이더도 신선 수집과 같은 만료 규칙을 적용한다.
126
126
  // 안 하면 수집이 실패하는 동안 리셋이 지난 창이 무한 재업로드된다 (유령 게이지).
127
+ // {...prev} 전개가 collected_at을 그대로 보존하는 것이 신선도 규칙의 핵심 —
128
+ // 서버는 collected_at이 더 신선한 행만 덮어쓰므로, 토큰이 만료된 기기의 캐시 폴백이
129
+ // 건강한 기기가 방금 올린 값을 덮어쓰지 못한다. collected_at을 여기서 갱신하면 안 된다.
127
130
  function sanitizeCachedProvider(prev) {
128
131
  if (!prev || typeof prev !== "object") return null;
129
132
  const extras = (prev.extras ?? [])
@@ -261,10 +264,18 @@ async function claudeCredentials() {
261
264
  }
262
265
  }
263
266
 
264
- // Claude: Claude Code OAuth 세션을 재사용해 공식 usage API 조회
265
- async function claudeProvider() {
267
+ // Claude: Claude Code OAuth 세션을 재사용해 공식 usage API 조회.
268
+ // 반환: { provider, status } — status "ok" | "auth_expired" | "error",
269
+ // 자격증명 자체가 없으면(미설치) status null이라 collect_status에 항목이 안 생긴다.
270
+ // fetchFn/loadCredentials는 테스트 주입용 — 기본값이면 기존 동작 그대로.
271
+ async function claudeProvider({ fetchFn = fetch, loadCredentials = claudeCredentials } = {}) {
272
+ let cred;
273
+ try {
274
+ cred = await loadCredentials();
275
+ } catch {
276
+ return { provider: null, status: null }; // 자격증명 없음 = Claude Code 미설치
277
+ }
266
278
  try {
267
- const cred = await claudeCredentials();
268
279
  const oauth = cred.claudeAiOauth ?? cred;
269
280
  const token = oauth.accessToken;
270
281
  // rateLimitTier "default_claude_max_20x" → "Max 20x", 없으면 subscriptionType "max" → "Max"
@@ -274,20 +285,21 @@ async function claudeProvider() {
274
285
  : oauth.subscriptionType
275
286
  ? oauth.subscriptionType[0].toUpperCase() + oauth.subscriptionType.slice(1)
276
287
  : null;
277
- const res = await fetch("https://api.anthropic.com/api/oauth/usage", {
288
+ const res = await fetchFn("https://api.anthropic.com/api/oauth/usage", {
278
289
  headers: { Authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" },
279
290
  signal: AbortSignal.timeout(10_000),
280
291
  });
281
292
  if (!res.ok) {
282
- // 401 = 토큰 만료 (Claude Code를 한 번 실행하면 갱신됨), 그 외는 일시 장애일 가능성
293
+ // 401 = 토큰 만료 (Claude Code를 한 번 실행하면 갱신됨), 그 외는 일시 장애일 가능성.
294
+ // 이 구분이 서버 collect_status로 올라가 앱이 "재로그인 필요"를 안내할 수 있다.
283
295
  console.error(`claude usage API ${res.status}${res.status === 401 ? " — 토큰 만료, Claude Code를 실행하면 갱신됩니다" : ""}`);
284
- return null;
296
+ return { provider: null, status: res.status === 401 ? "auth_expired" : "error" };
285
297
  }
286
298
  const d = await res.json();
287
299
  // 계정 UUID → 해시 (프로필 조회 실패 시 null — 캐시 폴백이 채워준다)
288
300
  let account = null;
289
301
  try {
290
- const pr = await fetch("https://api.anthropic.com/api/oauth/profile", {
302
+ const pr = await fetchFn("https://api.anthropic.com/api/oauth/profile", {
291
303
  headers: { Authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" },
292
304
  signal: AbortSignal.timeout(10_000),
293
305
  });
@@ -308,17 +320,21 @@ async function claudeProvider() {
308
320
  },
309
321
  }));
310
322
  return {
311
- id: "claude",
312
- name: "Claude",
313
- plan,
314
- account,
315
- session: dropExpired(win(d.five_hour, 300)),
316
- weekly: dropExpired(win(d.seven_day, 10080)),
317
- extras: extras.length ? extras : null,
323
+ provider: {
324
+ id: "claude",
325
+ name: "Claude",
326
+ plan,
327
+ account,
328
+ session: dropExpired(win(d.five_hour, 300)),
329
+ weekly: dropExpired(win(d.seven_day, 10080)),
330
+ extras: extras.length ? extras : null,
331
+ collected_at: new Date().toISOString(), // usage API 성공 시각
332
+ },
333
+ status: "ok",
318
334
  };
319
335
  } catch (e) {
320
336
  console.error(`claude 프로바이더 수집 실패: ${e.message ?? e}`);
321
- return null;
337
+ return { provider: null, status: "error" };
322
338
  }
323
339
  }
324
340
 
@@ -427,26 +443,38 @@ function codexSnapshotWindows() {
427
443
  window_minutes: w.window_minutes ?? null,
428
444
  }
429
445
  : null;
430
- return { session: win(rl.primary), weekly: win(rl.secondary) };
446
+ // collected_at = 로그 파일 mtime — 스냅샷은 "지금"이 아니라 마지막 사용 시점의 값이므로
447
+ // 수집 시각을 넣으면 다른 기기의 진짜 최신 데이터를 신선도 규칙에서 이겨버린다.
448
+ return { session: win(rl.primary), weekly: win(rl.secondary), collected_at: new Date(latest.m).toISOString() };
431
449
  }
432
450
 
451
+ // 반환: { provider, status } — live 성공 "ok", 스냅샷 폴백 "stale",
452
+ // ~/.codex는 있는데 둘 다 실패면 "error", 미설치면 status null(항목 없음).
433
453
  async function codexProvider() {
454
+ if (!fs.existsSync(path.join(HOME, ".codex"))) return { provider: null, status: null }; // Codex 미설치
434
455
  try {
435
456
  const auth = codexAuth();
436
- const windows = (await codexLiveWindows(auth)) ?? codexSnapshotWindows();
437
- if (!windows) return null;
457
+ const live = await codexLiveWindows(auth);
458
+ const snapshot = live ? null : codexSnapshotWindows();
459
+ const windows = live ?? snapshot;
460
+ if (!windows) return { provider: null, status: "error" };
438
461
  return {
439
- id: "codex",
440
- name: "Codex",
441
- plan: windows.plan ?? auth?.plan ?? null,
442
- account: auth?.account ?? null,
443
- session: dropExpired(windows.session),
444
- weekly: dropExpired(windows.weekly),
445
- extras: null,
462
+ provider: {
463
+ id: "codex",
464
+ name: "Codex",
465
+ plan: windows.plan ?? auth?.plan ?? null,
466
+ account: auth?.account ?? null,
467
+ session: dropExpired(windows.session),
468
+ weekly: dropExpired(windows.weekly),
469
+ extras: null,
470
+ // live면 지금이 관측 시각, 스냅샷 폴백이면 .jsonl mtime이 실제 관측 시각
471
+ collected_at: live ? new Date().toISOString() : snapshot.collected_at,
472
+ },
473
+ status: live ? "ok" : "stale",
446
474
  };
447
475
  } catch (e) {
448
476
  console.error(`codex 프로바이더 수집 실패: ${e.message ?? e}`);
449
- return null;
477
+ return { provider: null, status: "error" };
450
478
  }
451
479
  }
452
480
 
@@ -533,6 +561,7 @@ function codexBarEntryToProvider(entry) {
533
561
  extras: extras.length ? extras : null,
534
562
  status: null,
535
563
  collector_source: "codexbar",
564
+ collected_at: new Date().toISOString(), // CodexBar CLI 성공 시각
536
565
  };
537
566
  }
538
567
 
@@ -555,11 +584,11 @@ function parseCodexBarJSON(raw) {
555
584
  }
556
585
 
557
586
  async function collectCodexBarProviders() {
558
- if (process.env.CHARGE_DISABLE_CODEXBAR === "1") return { providers: [], complete: false };
587
+ if (process.env.CHARGE_DISABLE_CODEXBAR === "1") return { providers: [], complete: false, statuses: {} };
559
588
  // 따옴표로 감싼 경로(Windows에서 흔한 습관)는 벗겨서 execFile에 그대로 넘긴다
560
589
  const cli = process.env.CHARGE_CODEXBAR_CLI?.replace(/^"(.*)"$/s, "$1")
561
590
  ?? (!WIN && fs.existsSync(DEFAULT_CODEXBAR_CLI) ? DEFAULT_CODEXBAR_CLI : null);
562
- if (!cli) return { providers: [], complete: false };
591
+ if (!cli) return { providers: [], complete: false, statuses: {} };
563
592
 
564
593
  let raw = "";
565
594
  let commandSucceeded = true;
@@ -572,22 +601,33 @@ async function collectCodexBarProviders() {
572
601
  raw = e.stdout?.toString?.() ?? "";
573
602
  if (!raw.trim()) {
574
603
  console.error(`CodexBar 프로바이더 수집 실패: ${e.message ?? e}`);
575
- return { providers: [], complete: false };
604
+ return { providers: [], complete: false, statuses: {} };
576
605
  }
577
606
  }
578
607
 
579
608
  const entries = parseCodexBarJSON(raw);
580
609
  if (!entries) {
581
610
  console.error("CodexBar 프로바이더 수집 실패: JSON 출력을 해석할 수 없습니다.");
582
- return { providers: [], complete: false };
611
+ return { providers: [], complete: false, statuses: {} };
583
612
  }
584
613
  const bridgeEntries = entries.filter((entry) => !["claude", "codex"].includes(entry?.provider));
585
- const providers = bridgeEntries.map(codexBarEntryToProvider).filter(Boolean);
586
- const complete = commandSucceeded && !bridgeEntries.some((entry) => entry?.error);
587
- for (const entry of bridgeEntries.filter((item) => item?.error)) {
588
- console.error(`CodexBar ${entry.provider ?? "프로바이더"} 수집 실패: ${entry.error.message ?? "알 수 없는 오류"}`);
614
+ const providers = [];
615
+ const statuses = {};
616
+ for (const entry of bridgeEntries) {
617
+ if (entry?.error) {
618
+ console.error(`CodexBar ${entry.provider ?? "프로바이더"} 수집 실패: ${entry.error.message ?? "알 수 없는 오류"}`);
619
+ // claude/codex 상태는 자체 수집기가 판정한다 — entry.id로 새어 들어와도 덮지 않는다
620
+ const id = textValue(entry.provider, entry.id)?.toLowerCase();
621
+ if (id && id !== "claude" && id !== "codex") statuses[id] = "error";
622
+ continue;
623
+ }
624
+ const provider = codexBarEntryToProvider(entry);
625
+ if (!provider) continue; // 창이 하나도 없는 엔트리 — 성공도 실패도 아니라 상태 미기록
626
+ providers.push(provider);
627
+ statuses[provider.id] = "ok";
589
628
  }
590
- return { providers, complete };
629
+ const complete = commandSucceeded && !bridgeEntries.some((entry) => entry?.error);
630
+ return { providers, complete, statuses };
591
631
  }
592
632
 
593
633
  // 프로바이더 상태 페이지 (Statuspage 공용 API)
@@ -610,11 +650,16 @@ async function collectProviders() {
610
650
  statusOf("https://status.openai.com/api/v2/status.json"),
611
651
  collectCodexBarProviders(),
612
652
  ]);
613
- if (claude) claude.status = claudeStatus;
614
- if (codex) codex.status = codexStatus;
653
+ if (claude.provider) claude.provider.status = claudeStatus;
654
+ if (codex.provider) codex.provider.status = codexStatus;
655
+ // collect_status: 미설치(status null)는 항목을 만들지 않는다 — 설치된 소스만 정직하게 보고
656
+ const statuses = { ...codexBar.statuses };
657
+ if (claude.status) statuses.claude = claude.status;
658
+ if (codex.status) statuses.codex = codex.status;
615
659
  return {
616
- providers: [claude, codex, ...codexBar.providers].filter(Boolean),
660
+ providers: [claude.provider, codex.provider, ...codexBar.providers].filter(Boolean),
617
661
  codexBarComplete: codexBar.complete,
662
+ statuses,
618
663
  };
619
664
  }
620
665
 
@@ -632,18 +677,33 @@ function resolveMode() {
632
677
  }
633
678
 
634
679
  // 디바이스 토큰으로 charge_upload RPC 호출 (서버가 본인 행에만 기록)
635
- async function pairedUpload(mode, daily, live, providers) {
636
- const res = await fetch(`${mode.url}/rest/v1/rpc/charge_upload`, {
637
- method: "POST",
638
- headers: {
639
- apikey: mode.anon,
640
- Authorization: `Bearer ${mode.anon}`,
641
- "Content-Type": "application/json",
642
- },
643
- body: JSON.stringify({ p_token: mode.token, p_daily: daily, p_live: live, p_providers: providers }),
644
- signal: AbortSignal.timeout(30_000),
645
- });
646
- if (!res.ok) throw new Error(`업로드 실패 (${res.status}): ${await res.text()}`);
680
+ async function pairedUpload(mode, daily, live, providers, collectStatus = null) {
681
+ const post = (body) =>
682
+ fetch(`${mode.url}/rest/v1/rpc/charge_upload`, {
683
+ method: "POST",
684
+ headers: {
685
+ apikey: mode.anon,
686
+ Authorization: `Bearer ${mode.anon}`,
687
+ "Content-Type": "application/json",
688
+ },
689
+ body: JSON.stringify(body),
690
+ signal: AbortSignal.timeout(30_000),
691
+ });
692
+ const body = { p_token: mode.token, p_daily: daily, p_live: live, p_providers: providers, p_collect_status: collectStatus };
693
+ let res = await post(body);
694
+ if (res.ok) return;
695
+ const text = await res.text();
696
+ // 서버에 5번째 파라미터(p_collect_status)가 아직 배포 전이면 PostgREST가 함수
697
+ // 시그니처를 못 찾아 404/PGRST202를 낸다 — 수집기가 먼저 업데이트된 배포 순서
698
+ // 역전 대비로, 구버전 시그니처(파라미터 제외)로 1회만 재시도한다.
699
+ if (res.status === 404 || text.includes("PGRST202")) {
700
+ console.error("charge_upload 구버전 서버 감지(404/PGRST202) — p_collect_status 없이 재시도합니다");
701
+ const { p_collect_status: _omitted, ...legacyBody } = body;
702
+ res = await post(legacyBody);
703
+ if (res.ok) return;
704
+ throw new Error(`업로드 실패 (${res.status}): ${await res.text()}`);
705
+ }
706
+ throw new Error(`업로드 실패 (${res.status}): ${text}`);
647
707
  }
648
708
 
649
709
  async function main() {
@@ -679,16 +739,25 @@ async function main() {
679
739
  providerCollection = providersR.value;
680
740
  } else {
681
741
  console.error(`프로바이더 수집 실패, 이전 값 유지: ${providersR.reason?.message ?? providersR.reason}`);
682
- providerCollection = { providers: [], codexBarComplete: false };
742
+ // 수집이 통째로 죽으면 상태를 알 수 없다 — null로 보내 정직한 미상 처리 (서버도 null로 덮음)
743
+ providerCollection = { providers: [], codexBarComplete: false, statuses: null };
683
744
  }
684
745
  providers = providerCollection.providers;
685
- // 일부 프로바이더만 실패해도 목록에서 사라지지 않게 이전 값으로 채운다 (앱 설정 토글 유지)
746
+ // 일부 프로바이더만 실패해도 목록에서 사라지지 않게 이전 값으로 채운다 (앱 설정 토글 유지).
747
+ // 이렇게 캐시로 채운 프로바이더의 상태는 statuses에 이미 실패(auth_expired/error 등)로
748
+ // 기록돼 있다 — 캐시 복원이 성공처럼 보이면 안 되므로 여기서 덮지 않는다.
686
749
  for (const prev of cache.providers ?? []) {
687
750
  if (providers.some((p) => p.id === prev.id)) continue;
688
751
  // CodexBar가 정상 완료된 경우, 거기서 더 이상 반환하지 않는 항목은 사용자가 끈 것으로 본다.
689
752
  if (providerCollection.codexBarComplete && prev.collector_source === "codexbar") continue;
690
753
  const sanitized = sanitizeCachedProvider(prev);
691
- if (sanitized) providers.push(sanitized);
754
+ if (sanitized) {
755
+ // 0.1.4 이전 캐시엔 collected_at이 없다. 그대로 보내면 서버가 now()로 취급해
756
+ // 나이 미상의 캐시가 건강한 기기의 진짜 최신 데이터를 이겨버린다 — epoch로 스탬프해
757
+ // "언제 것인지 모르는 데이터는 항상 진다"로 만든다 (행 유지에는 지장 없음).
758
+ if (!sanitized.collected_at) sanitized.collected_at = new Date(0).toISOString();
759
+ providers.push(sanitized);
760
+ }
692
761
  }
693
762
  // 계정 식별 실패 시 마지막으로 알려진 계정 해시 유지 (계정 미상('')과 실제 계정 행이 갈라지는 것 방지)
694
763
  for (const p of providers) {
@@ -696,7 +765,7 @@ async function main() {
696
765
  }
697
766
 
698
767
  if (DRY_RUN) {
699
- console.log(JSON.stringify({ daily: daily.slice(-1), live, providers }, null, 2));
768
+ console.log(JSON.stringify({ daily: daily.slice(-1), live, providers, collect_status: providerCollection.statuses }, null, 2));
700
769
  console.log(`\n[dry-run] daily ${daily.length}행 + live + providers ${providers.length}개 업로드 예정`);
701
770
  return;
702
771
  }
@@ -708,7 +777,7 @@ async function main() {
708
777
  }
709
778
 
710
779
  const now = new Date().toISOString();
711
- await pairedUpload(mode, daily, live, providers);
780
+ await pairedUpload(mode, daily, live, providers, providerCollection.statuses);
712
781
 
713
782
  fs.writeFileSync(CACHE_FILE, JSON.stringify({ daily, live, providers }));
714
783
  console.log(`[${now}] daily ${daily.length}행 + live + providers ${providers.length}개 업로드 완료`);
@@ -724,6 +793,7 @@ if (require.main === module) {
724
793
  module.exports = {
725
794
  CCUSAGE_PKG,
726
795
  accountHash,
796
+ claudeProvider,
727
797
  codexBarEntryToProvider,
728
798
  collectCodexBarProviders,
729
799
  dropExpired,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "charge-connect",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Connects your computer to the Charge iPhone app and uploads AI coding usage",
5
5
  "bin": {
6
6
  "charge-connect": "cli.js"