@the-seeker/madefeed 0.1.0 → 0.2.0

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 (3) hide show
  1. package/README.md +21 -3
  2. package/dist/cli.mjs +934 -125
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -14,8 +14,11 @@ npx @the-seeker/madefeed@latest
14
14
  | --- | --- |
15
15
  | `madefeed` 또는 `madefeed upload` | 연결이 없으면 연결하고, 사용량을 올려요. |
16
16
  | `madefeed login` | 기기만 연결해요. |
17
- | `madefeed status` | 연결 상태를 보여줘요. |
18
- | `madefeed logout` | 이 기기의 연결을 지워요. |
17
+ | `madefeed status` | 연결과 자동 전송 상태를 보여줘요. |
18
+ | `madefeed auto [status]` | 자동 전송 상태를 보여줘요. `--json`도 지원해요. |
19
+ | `madefeed auto on` | 연결된 기기의 자동 전송을 켜요. |
20
+ | `madefeed auto off` | 자동 전송을 끄고 실행 파일 복사본을 지워요. |
21
+ | `madefeed logout` | 자동 전송을 해제하고 이 기기의 로컬 연결을 지워요. |
19
22
 
20
23
  | 옵션 | 뜻 |
21
24
  | --- | --- |
@@ -23,6 +26,21 @@ npx @the-seeker/madefeed@latest
23
26
  | `--days N` | 오늘을 포함해 며칠 치를 셀지 정해요. 기본 14, 최대 35예요. |
24
27
  | `--json` | 결과를 JSON으로만 출력해요. |
25
28
  | `--url URL` | 서버 주소예요. 기본은 `https://madefeed.dev`예요. |
29
+ | `--no-auto` | 이번 실행에서만 자동 전송 등록·갱신을 건너뛰어요. |
30
+
31
+ ## 자동 전송
32
+
33
+ 기기를 연결하면 한 시간마다 최근 3일의 사용량을 자동으로 올려요. 이전 버전에서 연결했다면 다음 `upload` 실행 때 등록해요. 터미널을 계속 열어 둘 필요가 없어요.
34
+
35
+ - macOS: `~/Library/LaunchAgents/dev.madefeed.meter.plist`를 launchd에 등록해요. macOS가 **“백그라운드 항목이 추가됨”** 알림을 보여줄 수 있어요.
36
+ - Linux: `~/.config/systemd/user/madefeed-meter.service`와 `madefeed-meter.timer`를 등록해요. 사용자 systemd를 사용할 수 없으면 crontab의 `# madefeed-meter` 줄로 실행해요.
37
+ - Windows: 작업 스케줄러의 `MadeFeed Meter` 작업과 `~/.config/madefeed/agent/run.cmd`를 등록해요. Windows 경로에서는 `\` 구분자를 사용해요.
38
+
39
+ 실행 파일은 `~/.config/madefeed/agent/cli.mjs`에 복사해 두고 Node.js로 실행해요. 매시간 npx나 npm에 접속하지 않아요. 자동 전송이 켜진 상태에서 새 CLI로 `login` 또는 `upload`를 실행하면 복사본도 갱신해요. `status`와 `auto status`는 조회만 해요. 로그는 `~/.config/madefeed/auto.log`에 남기고, 256 KB를 넘으면 다음 예약 실행 시작 때 마지막 200줄만 남겨요. 토큰과 전송 본문은 로그에 남기지 않아요.
40
+
41
+ `madefeed auto off`로 끄고, `madefeed auto on`으로 다시 켤 수 있어요. `--no-auto` 또는 `MADEFEED_NO_AUTO=1`은 이번 실행의 등록·갱신만 건너뛰며, 이미 등록한 작업을 끄지는 않아요. `--dry-run`도 등록하지 않아요. 예약 실행에는 `--scheduled`가 붙고, 연결 정보가 없으면 로그인 없이 건너뛰어요. 등록에 실패해도 `madefeed upload`로 수동 전송할 수 있어요.
42
+
43
+ 설치할 때 설정한 `OPENCODE_DATA_DIR`, `XDG_DATA_HOME`, `GEMINI_DATA_DIR`, `MADEFEED_URL`은 예약 작업에도 전달해요. `logout`은 스케줄·agent 디렉터리·`cli.json`만 지우고 다른 설정 파일과 로그는 남겨요.
26
44
 
27
45
  ## 보내는 것과 보내지 않는 것
28
46
 
@@ -33,4 +51,4 @@ npx @the-seeker/madefeed@latest
33
51
 
34
52
  ## 읽는 곳
35
53
 
36
- Claude Code, Codex, OpenCode의 로컬 사용 기록을 읽기 전용으로 읽어요. Cursor는 아직 지원하지 않아요.
54
+ Claude Code, Codex, OpenCode, Gemini CLI의 로컬 사용 기록을 읽기 전용으로 읽어요. Cursor는 아직 지원하지 않아요.
package/dist/cli.mjs CHANGED
@@ -4,13 +4,14 @@
4
4
  import { realpathSync } from "node:fs";
5
5
  import { homedir, hostname } from "node:os";
6
6
  import { pathToFileURL } from "node:url";
7
- import { parseArgs } from "node:util";
7
+ import { execFile } from "node:child_process";
8
8
 
9
9
  // src/aggregate.ts
10
10
  import { createReadStream } from "node:fs";
11
11
  import { readdir, stat } from "node:fs/promises";
12
12
  import { join } from "node:path";
13
13
  import { createInterface } from "node:readline";
14
+ var MAX_ROW_TOKENS = 1e11;
14
15
  var MeterError = class extends Error {
15
16
  };
16
17
  function isRecord(value) {
@@ -19,9 +20,9 @@ function isRecord(value) {
19
20
  function record(value) {
20
21
  return isRecord(value) ? value : {};
21
22
  }
22
- function parseJson(text) {
23
+ function parseJson(text2) {
23
24
  try {
24
- const value = JSON.parse(text);
25
+ const value = JSON.parse(text2);
25
26
  return value;
26
27
  } catch (error) {
27
28
  if (error instanceof SyntaxError) return void 0;
@@ -43,8 +44,10 @@ function aggregate(rows) {
43
44
  const model = modelName(row.model);
44
45
  const key = JSON.stringify([row.date, row.tool, model]);
45
46
  const tokens = (totals.get(key)?.tokens ?? 0) + row.tokens;
46
- if (!Number.isSafeInteger(tokens) || tokens < 0 || tokens > 2e9)
47
- throw new MeterError("\uD1A0\uD070 \uD569\uACC4\uAC00 \uC11C\uBC84 \uD5C8\uC6A9 \uBC94\uC704(0~2e9)\uB97C \uBC97\uC5B4\uB098\uC694.");
47
+ if (!Number.isSafeInteger(tokens) || tokens < 0 || tokens > MAX_ROW_TOKENS)
48
+ throw new MeterError(
49
+ "\uD1A0\uD070 \uD569\uACC4\uAC00 \uC11C\uBC84 \uD5C8\uC6A9 \uBC94\uC704(0~100,000,000,000)\uB97C \uBC97\uC5B4\uB098\uC694."
50
+ );
48
51
  totals.set(key, { date: row.date, tool: row.tool, model, tokens });
49
52
  }
50
53
  return [...totals.values()].sort(
@@ -156,10 +159,10 @@ async function pollToken(api, device) {
156
159
  body: { device_code: device.device_code }
157
160
  });
158
161
  if (status === 200) {
159
- const token = data["token"];
160
- if (typeof token !== "string" || !/^mfd_[A-Za-z0-9_-]+$/.test(token))
162
+ const token2 = data["token"];
163
+ if (typeof token2 !== "string" || !/^mfd_[A-Za-z0-9_-]+$/.test(token2))
161
164
  throw new MeterError("\uAE30\uAE30 \uD1A0\uD070 \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
162
- return token;
165
+ return token2;
163
166
  }
164
167
  const code = typeof data["error"] === "string" ? data["error"] : record(data["error"])["code"];
165
168
  if (status !== 400) throw new ApiError(status);
@@ -182,7 +185,7 @@ async function pollToken(api, device) {
182
185
  "\uAE30\uAE30 \uC778\uC99D \uCF54\uB4DC\uAC00 \uB9CC\uB8CC\uB410\uC5B4\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
183
186
  );
184
187
  }
185
- async function uploadUsage(api, token, body) {
188
+ async function uploadUsage(api, token2, body) {
186
189
  let accepted = 0;
187
190
  let weekTokens = 0;
188
191
  let votesGranted = 0;
@@ -190,7 +193,7 @@ async function uploadUsage(api, token, body) {
190
193
  for (let offset = 0; offset < safe.rows.length; offset += 200) {
191
194
  const { status, data } = await post(api, {
192
195
  path: "/api/meter/usage",
193
- token,
196
+ token: token2,
194
197
  body: {
195
198
  deviceName: safe.deviceName,
196
199
  rows: safe.rows.slice(offset, offset + 200)
@@ -246,7 +249,8 @@ async function readConfig(home) {
246
249
  return {
247
250
  url: serviceUrl(data["url"]),
248
251
  deviceToken: data["deviceToken"],
249
- deviceName: data["deviceName"]
252
+ deviceName: data["deviceName"],
253
+ ...data["auto"] === "on" || data["auto"] === "off" ? { auto: data["auto"] } : {}
250
254
  };
251
255
  } catch (error) {
252
256
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -255,16 +259,16 @@ async function readConfig(home) {
255
259
  }
256
260
  }
257
261
  async function saveConfig(home, config) {
258
- const directory = join2(home, ".config/madefeed");
259
- await mkdir(directory, { recursive: true, mode: 448 });
260
- const temporary = join2(directory, `cli-${randomUUID()}.tmp`);
262
+ const directory2 = join2(home, ".config/madefeed");
263
+ await mkdir(directory2, { recursive: true, mode: 448 });
264
+ const temporary = join2(directory2, `cli-${randomUUID()}.tmp`);
261
265
  try {
262
266
  await writeFile(temporary, JSON.stringify(config), {
263
267
  mode: 384,
264
268
  flag: "wx"
265
269
  });
266
270
  await chmod(temporary, 384);
267
- await rename(temporary, join2(directory, "cli.json"));
271
+ await rename(temporary, join2(directory2, "cli.json"));
268
272
  } finally {
269
273
  await rm(temporary, { force: true });
270
274
  }
@@ -292,17 +296,17 @@ async function readClaude(options) {
292
296
  if (!path.endsWith(".jsonl") || !await recentFile(path, options.sinceMs))
293
297
  continue;
294
298
  for await (const value of jsonLines(path)) {
295
- const event = record(value);
296
- if (event["type"] !== "assistant") continue;
297
- const message = record(event["message"]);
298
- const ms = timestamp(event["timestamp"]);
299
+ const event2 = record(value);
300
+ if (event2["type"] !== "assistant") continue;
301
+ const message = record(event2["message"]);
302
+ const ms = timestamp(event2["timestamp"]);
299
303
  if (!Number.isFinite(ms) || ms < options.sinceMs || message["model"] === "<synthetic>")
300
304
  continue;
301
- if (typeof message["id"] !== "string" || typeof event["requestId"] !== "string")
305
+ if (typeof message["id"] !== "string" || typeof event2["requestId"] !== "string")
302
306
  continue;
303
- const usage2 = record(message["usage"]);
304
- const tokens = count(usage2["input_tokens"]) + count(usage2["output_tokens"]) + count(usage2["cache_creation_input_tokens"]) + count(usage2["cache_read_input_tokens"]);
305
- const key = JSON.stringify([message["id"], event["requestId"]]);
307
+ const usage = record(message["usage"]);
308
+ const tokens = count(usage["input_tokens"]) + count(usage["output_tokens"]) + count(usage["cache_creation_input_tokens"]) + count(usage["cache_read_input_tokens"]);
309
+ const key = JSON.stringify([message["id"], event2["requestId"]]);
306
310
  if (tokens > (messages.get(key)?.tokens ?? -1))
307
311
  messages.set(key, {
308
312
  date: kstDateOf(ms),
@@ -332,13 +336,13 @@ async function readCodex(options) {
332
336
  let model = "unknown";
333
337
  let previous = 0;
334
338
  for await (const value of jsonLines(path)) {
335
- const event = record(value);
336
- const data = record(event["payload"]);
337
- if (event["type"] === "turn_context") {
339
+ const event2 = record(value);
340
+ const data = record(event2["payload"]);
341
+ if (event2["type"] === "turn_context") {
338
342
  model = modelName(data["model"]);
339
343
  continue;
340
344
  }
341
- if (event["type"] !== "event_msg" || data["type"] !== "token_count")
345
+ if (event2["type"] !== "event_msg" || data["type"] !== "token_count")
342
346
  continue;
343
347
  const info = record(data["info"]);
344
348
  const total = record(info["total_token_usage"])["total_tokens"];
@@ -346,7 +350,7 @@ async function readCodex(options) {
346
350
  continue;
347
351
  const delta = total >= previous ? total - previous : count(record(info["last_token_usage"])["total_tokens"]);
348
352
  previous = total;
349
- const ms = timestamp(event["timestamp"]);
353
+ const ms = timestamp(event2["timestamp"]);
350
354
  if (Number.isFinite(ms) && ms >= options.sinceMs && delta > 0)
351
355
  rows.push({
352
356
  date: kstDateOf(ms),
@@ -366,139 +370,868 @@ async function readCodex(options) {
366
370
  }
367
371
 
368
372
  // src/sources/opencode.ts
369
- import { readFile as readFile2 } from "node:fs/promises";
370
- import { join as join5 } from "node:path";
373
+ import { readFile as readFile2, readdir as readdir2, stat as stat2 } from "node:fs/promises";
374
+ import { basename as basename2, isAbsolute, join as join5 } from "node:path";
371
375
  import { Worker } from "node:worker_threads";
372
- function databaseWorker() {
373
- const { parentPort, workerData } = process.getBuiltinModule(
374
- "node:worker_threads"
375
- );
376
+
377
+ // src/sources/opencode-db.ts
378
+ function databaseWorker(input) {
376
379
  try {
377
- const sqlite = process.getBuiltinModule?.("node:sqlite");
378
- if (!sqlite) throw new TypeError("sqlite unavailable");
379
- const db = new sqlite.DatabaseSync(workerData.path, { readOnly: true });
380
+ const { DatabaseSync } = process.getBuiltinModule("node:sqlite");
381
+ const db = new DatabaseSync(input.path, { readOnly: true });
380
382
  try {
381
383
  db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=200");
382
- const sql = "SELECT time_created, data FROM message WHERE time_created >= ?";
383
- const plan = db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all(workerData.sinceMs);
384
- if (plan.some(
385
- (row) => typeof row["detail"] !== "string" || !/SEARCH message .*INDEX .*\(time_created>\?\)/.test(row["detail"])
386
- ))
387
- throw new TypeError("no time index");
388
- const rows = [];
389
- for (const row of db.prepare(sql).iterate(workerData.sinceMs)) {
390
- if (rows.length >= 2e5) throw new RangeError("row budget");
391
- rows.push(row);
384
+ const exists = (table) => Boolean(
385
+ db.prepare(
386
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?"
387
+ ).get(table)
388
+ );
389
+ const columns = (table) => new Set(
390
+ db.prepare(`PRAGMA table_info(${table})`).all().map((row) => row["name"])
391
+ );
392
+ const number = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
393
+ const ids = /* @__PURE__ */ new Set();
394
+ const excluded = new Set(input.excludedIds);
395
+ const totals = /* @__PURE__ */ new Map();
396
+ const numeric = (path) => `CASE WHEN json_type(m.data,'${path}') IN ('integer','real') THEN json_extract(m.data,'${path}') ELSE 0 END`;
397
+ const projection = (model) => `coalesce(json_extract(m.data,'$.time.created'),m.time_created) AS ms,
398
+ ${model} AS model, json_type(m.data,'$.tokens') AS token_type,
399
+ ${numeric("$.tokens.total")} AS total,
400
+ ${numeric("$.tokens.input")} AS input,
401
+ ${numeric("$.tokens.output")} AS output,
402
+ ${numeric("$.tokens.reasoning")} AS reasoning,
403
+ ${numeric("$.tokens.cache.read")} AS cache_read,
404
+ ${numeric("$.tokens.cache.write")} AS cache_write`;
405
+ const add = (row) => {
406
+ const ms = row["ms"];
407
+ const model = row["model"];
408
+ const id = row["id"];
409
+ if (typeof id === "string" && (excluded.has(id) || ids.has(id))) return;
410
+ if (typeof ms !== "number" || !Number.isFinite(ms) || ms < input.sinceMs || typeof model !== "string" || row["token_type"] !== "object")
411
+ return;
412
+ const parts = [
413
+ "input",
414
+ "output",
415
+ "reasoning",
416
+ "cache_read",
417
+ "cache_write"
418
+ ].reduce((sum, key2) => sum + number(row[key2]), 0);
419
+ const tokens = Math.max(parts, number(row["total"]));
420
+ if (tokens === 0) return;
421
+ const date = new Date(ms + 324e5).toISOString().slice(0, 10);
422
+ const key = JSON.stringify([date, model]);
423
+ const previous = totals.get(key);
424
+ totals.set(key, [date, model, (previous?.[2] ?? 0) + tokens]);
425
+ if (typeof id === "string") ids.add(id);
426
+ };
427
+ const since = input.sinceMs - 864e5;
428
+ const hasMessage = exists("message");
429
+ const hasV2 = exists("session_message");
430
+ const hasId = hasMessage && columns("message").has("id");
431
+ if (hasMessage) {
432
+ const fields = `${hasId ? "m.id" : "NULL AS id"}, ${projection("json_extract(m.data,'$.modelID')")}`;
433
+ let statement;
434
+ try {
435
+ statement = db.prepare(
436
+ `SELECT ${fields} FROM session s CROSS JOIN message m ON m.session_id=s.id AND m.time_created >= ?`
437
+ );
438
+ } catch (error) {
439
+ if (!(error instanceof Error)) throw error;
440
+ statement = db.prepare(
441
+ `SELECT ${fields} FROM message m WHERE m.time_created >= ?`
442
+ );
443
+ }
444
+ for (const row of statement.iterate(since)) add(row);
392
445
  }
393
- parentPort?.postMessage({ rows });
446
+ if (hasV2) {
447
+ const cutoffs = /* @__PURE__ */ new Map();
448
+ if (exists("session_v2") && ["id", "fork_session_id", "fork_boundary"].every(
449
+ (key) => columns("session_v2").has(key)
450
+ )) {
451
+ const boundaryRow = db.prepare(
452
+ "SELECT seq FROM session_message WHERE session_id=? AND id=?"
453
+ );
454
+ const before = db.prepare(
455
+ "SELECT MAX(seq) AS seq FROM session_message WHERE session_id=? AND seq<?"
456
+ );
457
+ for (const fork of db.prepare(
458
+ "SELECT id,fork_session_id,fork_boundary FROM session_v2 WHERE fork_session_id IS NOT NULL AND fork_boundary IS NOT NULL"
459
+ ).iterate()) {
460
+ if (typeof fork["fork_boundary"] !== "string" || typeof fork["id"] !== "string" || typeof fork["fork_session_id"] !== "string")
461
+ continue;
462
+ let boundary;
463
+ try {
464
+ boundary = JSON.parse(fork["fork_boundary"]);
465
+ } catch (error) {
466
+ if (error instanceof SyntaxError) continue;
467
+ throw error;
468
+ }
469
+ if (typeof boundary !== "object" || boundary === null || !("messageID" in boundary) || typeof boundary.messageID !== "string" || !("type" in boundary))
470
+ continue;
471
+ const seq = boundaryRow.get(
472
+ fork["fork_session_id"],
473
+ boundary.messageID
474
+ )?.["seq"];
475
+ if (typeof seq !== "number") continue;
476
+ let cutoff;
477
+ switch (boundary.type) {
478
+ case "through":
479
+ cutoff = seq;
480
+ break;
481
+ case "before":
482
+ cutoff = before.get(fork["fork_session_id"], seq)?.["seq"];
483
+ break;
484
+ default:
485
+ continue;
486
+ }
487
+ if (typeof cutoff === "number") cutoffs.set(fork["id"], cutoff);
488
+ }
489
+ }
490
+ const model = "coalesce(json_extract(m.data,'$.model.id'),json_extract(m.data,'$.model.modelID'),json_extract(m.data,'$.modelID'))";
491
+ const statement = db.prepare(
492
+ `SELECT m.id,m.session_id,m.type,m.seq,m.time_created, json_extract(m.data,'$.status') AS status, ${projection(model)} FROM session_message m WHERE m.time_created >= ?`
493
+ );
494
+ for (const row of statement.iterate(since)) {
495
+ if (row["type"] !== "assistant" && !(row["type"] === "compaction" && row["status"] === "completed"))
496
+ continue;
497
+ const cutoff = typeof row["session_id"] === "string" ? cutoffs.get(row["session_id"]) : void 0;
498
+ if (cutoff !== void 0 && typeof row["seq"] === "number" && row["seq"] <= cutoff)
499
+ continue;
500
+ add(row);
501
+ }
502
+ }
503
+ const lookups = [
504
+ ...hasId ? [db.prepare("SELECT 1 FROM message WHERE id=?")] : [],
505
+ ...hasV2 ? [db.prepare("SELECT 1 FROM session_message WHERE id=?")] : []
506
+ ];
507
+ for (const id of input.legacyIds)
508
+ if (lookups.some((statement) => statement.get(id))) ids.add(id);
509
+ return { totals: [...totals.values()], knownIds: [...ids] };
394
510
  } finally {
395
511
  db.close();
396
512
  }
397
513
  } catch (error) {
398
- if (error instanceof Error) parentPort?.postMessage({ error: true });
399
- else throw error;
514
+ if (error instanceof Error) return { error: true };
515
+ throw error;
400
516
  }
401
517
  }
402
- async function databaseRows(options) {
403
- const worker = new Worker(`(${databaseWorker.toString()})()`, {
404
- eval: true,
405
- workerData: {
406
- path: join5(options.home, ".local/share/opencode/opencode.db"),
407
- sinceMs: options.sinceMs
518
+
519
+ // src/sources/opencode.ts
520
+ var failure = "OpenCode DB\uB97C \uC81C\uD55C \uC2DC\uAC04 \uC548\uC5D0 \uC77D\uC744 \uC218 \uC5C6\uC5B4 \uBD80\uBD84 \uC9D1\uACC4 \uC5C6\uC774 unsupported\uB85C \uCC98\uB9AC\uD574\uC694.";
521
+ async function databaseRows(input) {
522
+ const worker = new Worker(
523
+ `const {parentPort,workerData}=require('node:worker_threads'); parentPort.postMessage((${databaseWorker.toString()})(workerData))`,
524
+ {
525
+ eval: true,
526
+ workerData: input
408
527
  }
409
- });
528
+ );
410
529
  try {
411
- return await new Promise((resolve, reject) => {
412
- const timer = setTimeout(
413
- () => reject(new MeterError("OpenCode DB \uC2DC\uAC04 \uC608\uC0B0\uC744 \uCD08\uACFC\uD574\uC694.")),
414
- 2500
415
- );
530
+ return await new Promise((resolve2, reject) => {
416
531
  const fail = () => {
417
- clearTimeout(timer);
418
- reject(new MeterError("OpenCode DB\uB97C \uC548\uC804\uD558\uAC8C \uC870\uD68C\uD560 \uC218 \uC5C6\uC5B4\uC694."));
532
+ clearTimeout(timer2);
533
+ reject(new MeterError(failure));
419
534
  };
535
+ const timer2 = setTimeout(fail, 45e3);
420
536
  worker.once("error", fail);
421
537
  worker.once("exit", fail);
422
538
  worker.once("message", (value) => {
423
- clearTimeout(timer);
424
- const rows = record(value)["rows"];
425
- if (Array.isArray(rows)) resolve(rows);
426
- else fail();
539
+ clearTimeout(timer2);
540
+ resolve2(value);
427
541
  });
428
542
  });
429
543
  } finally {
430
544
  await worker.terminate();
431
545
  }
432
546
  }
433
- function usage(value, ms) {
434
- const data = record(value);
435
- if (data["role"] !== "assistant") return void 0;
436
- const tokens = record(data["tokens"]);
437
- const cache = record(tokens["cache"]);
438
- const total = tokens["total"];
439
- const sum = typeof total === "number" ? count(total) : count(tokens["input"]) + count(tokens["output"]) + count(tokens["reasoning"]) + count(cache["read"]) + count(cache["write"]);
440
- return {
441
- date: kstDateOf(ms),
442
- tool: "opencode",
443
- model: modelName(data["modelID"]),
444
- tokens: sum
445
- };
547
+ async function directory(path) {
548
+ try {
549
+ return (await stat2(path)).isDirectory();
550
+ } catch (error) {
551
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
552
+ return false;
553
+ throw error;
554
+ }
555
+ }
556
+ async function legacyRows(root, options) {
557
+ const rows = /* @__PURE__ */ new Map();
558
+ const storage = join5(root, "storage/message");
559
+ if (!await directory(storage)) return rows;
560
+ for await (const path of files(storage)) {
561
+ if (!path.endsWith(".json") || (await stat2(path)).mtimeMs < options.sinceMs)
562
+ continue;
563
+ const data = record(parseJson(await readFile2(path, "utf8")));
564
+ const ms = timestamp(record(data["time"])["created"]);
565
+ if (!Number.isFinite(ms) || ms < options.sinceMs || typeof data["modelID"] !== "string")
566
+ continue;
567
+ const raw = data["tokens"];
568
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) continue;
569
+ const tokens = record(raw);
570
+ const cache = record(tokens["cache"]);
571
+ const sum = Math.max(
572
+ count(tokens["total"]),
573
+ count(tokens["input"]) + count(tokens["output"]) + count(tokens["reasoning"]) + count(cache["read"]) + count(cache["write"])
574
+ );
575
+ if (sum === 0) continue;
576
+ const id = typeof data["id"] === "string" ? data["id"] : basename2(path, ".json");
577
+ rows.set(id, {
578
+ date: kstDateOf(ms),
579
+ tool: "opencode",
580
+ model: modelName(data["modelID"]),
581
+ tokens: sum
582
+ });
583
+ }
584
+ return rows;
446
585
  }
447
586
  async function readOpenCode(options) {
448
587
  try {
588
+ const env = options.env ?? {};
589
+ const custom = env["OPENCODE_DATA_DIR"];
590
+ const xdg = env["XDG_DATA_HOME"];
591
+ const roots = custom !== void 0 ? custom.split(",") : [
592
+ xdg && isAbsolute(xdg) ? join5(xdg, "opencode") : join5(options.home, ".local/share/opencode")
593
+ ];
449
594
  const rows = [];
450
- for (const value of await databaseRows(options)) {
451
- const row = record(value);
452
- const ms = timestamp(row["time_created"]);
453
- if (typeof row["data"] !== "string" || !Number.isFinite(ms)) continue;
454
- const parsed = usage(parseJson(row["data"]), ms);
455
- if (parsed) rows.push(parsed);
595
+ const seen = /* @__PURE__ */ new Set();
596
+ for (const root of roots) {
597
+ if (!root || !await directory(root)) continue;
598
+ const legacy = await legacyRows(root, options);
599
+ const entries = await readdir2(root, { withFileTypes: true });
600
+ const names = entries.filter((entry) => entry.isFile()).map((entry) => entry.name);
601
+ const db = names.includes("opencode.db") ? "opencode.db" : names.filter((name) => /^opencode-.*\.db$/.test(name)).sort()[0];
602
+ if (db) {
603
+ const result = await databaseRows({
604
+ path: join5(root, db),
605
+ sinceMs: options.sinceMs,
606
+ legacyIds: [...legacy.keys()],
607
+ excludedIds: [...seen]
608
+ });
609
+ if ("error" in result)
610
+ return { supported: false, reason: failure, rows: [] };
611
+ rows.push(
612
+ ...result.totals.map(([date, model, tokens]) => ({
613
+ date,
614
+ tool: "opencode",
615
+ model: modelName(model),
616
+ tokens
617
+ }))
618
+ );
619
+ for (const id of result.knownIds) seen.add(id);
620
+ }
621
+ for (const [id, row] of legacy) {
622
+ if (seen.has(id)) continue;
623
+ rows.push(row);
624
+ seen.add(id);
625
+ }
456
626
  }
457
627
  return { supported: true, rows };
458
628
  } catch (error) {
459
- if (!(error instanceof Error)) throw error;
629
+ return unsupported(error, failure);
460
630
  }
631
+ }
632
+
633
+ // src/sources/gemini.ts
634
+ import { readFile as readFile3, stat as stat3 } from "node:fs/promises";
635
+ import { join as join6 } from "node:path";
636
+ function text(value) {
637
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
638
+ }
639
+ function time(value, fallback) {
640
+ const ms = typeof value === "string" ? timestamp(value) : NaN;
641
+ return Number.isFinite(ms) ? ms : fallback;
642
+ }
643
+ function token(value) {
644
+ return typeof value === "number" && Number.isFinite(value) ? Math.trunc(Math.max(0, value)) : void 0;
645
+ }
646
+ function event(raw, context) {
647
+ const data = record(raw);
648
+ const model = text(data["model"]) ?? context.model;
649
+ const rawTokens = data["tokens"];
650
+ if (!model || typeof rawTokens !== "object" || rawTokens === null || Array.isArray(rawTokens))
651
+ return void 0;
652
+ const tokens = record(rawTokens);
653
+ const part = (keys) => keys.map((key) => token(tokens[key])).find((value) => value !== void 0) ?? 0;
654
+ const input = part(["input", "prompt", "input_tokens", "prompt_tokens"]);
655
+ const output = part([
656
+ "output",
657
+ "candidates",
658
+ "output_tokens",
659
+ "candidates_tokens"
660
+ ]);
661
+ const cached = part(["cached", "cached_tokens"]);
662
+ const thoughts = part([
663
+ "thoughts",
664
+ "reasoning",
665
+ "thoughts_tokens",
666
+ "reasoning_tokens"
667
+ ]);
668
+ const tool = part(["tool", "tool_tokens"]);
669
+ const total = token(
670
+ Object.hasOwn(tokens, "total") ? tokens["total"] : tokens["total_tokens"]
671
+ );
672
+ const inclusive = input + output + thoughts + tool;
673
+ const net = context.stats || cached > 0 && total === inclusive ? input - Math.min(input, cached) : input;
674
+ const sum = Math.max(net + output + cached + thoughts + tool, total ?? 0);
675
+ if (sum === 0) return void 0;
676
+ return {
677
+ model,
678
+ tokens: sum,
679
+ ms: time(data["timestamp"], time(data["created_at"], context.ms))
680
+ };
681
+ }
682
+ function statsEvents(data, context) {
683
+ const stats = record(
684
+ Object.hasOwn(data, "stats") ? data["stats"] : record(data["result"])["stats"]
685
+ );
686
+ const events = [];
687
+ for (const [model, value] of Object.entries(record(stats["models"]))) {
688
+ const parsed2 = event(
689
+ { model, tokens: record(value)["tokens"] },
690
+ { ...context, stats: true }
691
+ );
692
+ if (parsed2) events.push(parsed2);
693
+ }
694
+ if (events.length) return events;
695
+ const parsed = event(
696
+ { model: context.model ?? "unknown", tokens: stats },
697
+ { ...context, stats: true }
698
+ );
699
+ return parsed ? [parsed] : [];
700
+ }
701
+ function jsonEvents(value, mtime) {
702
+ const data = record(value);
703
+ if (Array.isArray(data["messages"])) {
704
+ const context = {
705
+ ms: time(data["startTime"], time(data["lastUpdated"], mtime)),
706
+ stats: false
707
+ };
708
+ return data["messages"].flatMap((value2) => {
709
+ const message = record(value2);
710
+ const parsed = message["type"] === "gemini" ? event(message, context) : void 0;
711
+ return parsed ? [parsed] : [];
712
+ });
713
+ }
714
+ if (data["type"] === "gemini") {
715
+ const parsed = event(data, { ms: mtime, stats: false });
716
+ return parsed ? [parsed] : [];
717
+ }
718
+ const model = text(data["model"]);
719
+ return statsEvents(data, {
720
+ ...model ? { model } : {},
721
+ ms: time(data["timestamp"], mtime),
722
+ stats: true
723
+ });
724
+ }
725
+ async function jsonlEvents(path, mtime) {
726
+ const events = [];
727
+ const ids = /* @__PURE__ */ new Map();
728
+ let model;
729
+ for await (const value of jsonLines(path)) {
730
+ const data = record(value);
731
+ model = text(data["model"]) ?? model;
732
+ const context = { ...model ? { model } : {}, ms: mtime, stats: false };
733
+ if (data["type"] === "gemini") {
734
+ const parsed = event(data, context);
735
+ if (!parsed) continue;
736
+ const id = text(data["id"]);
737
+ const previous = id ? ids.get(id) : void 0;
738
+ if (previous !== void 0) events[previous] = parsed;
739
+ else {
740
+ if (id) ids.set(id, events.length);
741
+ events.push(parsed);
742
+ }
743
+ } else
744
+ events.push(
745
+ ...statsEvents(data, {
746
+ ...context,
747
+ ms: time(data["timestamp"], mtime)
748
+ })
749
+ );
750
+ }
751
+ return events;
752
+ }
753
+ async function readGemini(options) {
754
+ const custom = options.env?.["GEMINI_DATA_DIR"];
755
+ const roots = custom !== void 0 ? custom.split(",") : [join6(options.home, ".gemini/tmp")];
756
+ const rows = [];
757
+ for (const root of roots) {
758
+ if (!root) continue;
759
+ try {
760
+ for await (const path of files(root)) {
761
+ if (!path.endsWith(".json") && !path.endsWith(".jsonl")) continue;
762
+ try {
763
+ const mtime = (await stat3(path)).mtimeMs;
764
+ if (mtime < options.sinceMs) continue;
765
+ const events = path.endsWith(".jsonl") ? await jsonlEvents(path, mtime) : jsonEvents(parseJson(await readFile3(path, "utf8")), mtime);
766
+ for (const event2 of events)
767
+ if (event2.ms >= options.sinceMs)
768
+ rows.push({
769
+ date: kstDateOf(event2.ms),
770
+ tool: "gemini",
771
+ model: modelName(event2.model),
772
+ tokens: event2.tokens
773
+ });
774
+ } catch (error) {
775
+ if (!(error instanceof Error)) throw error;
776
+ }
777
+ }
778
+ } catch (error) {
779
+ if (!(error instanceof Error)) throw error;
780
+ }
781
+ }
782
+ return { supported: true, rows };
783
+ }
784
+
785
+ // src/agent.ts
786
+ import { randomUUID as randomUUID2 } from "node:crypto";
787
+ import { chmod as chmod2, mkdir as mkdir2, open, realpath, rename as rename2, rm as rm2 } from "node:fs/promises";
788
+ import { join as join7, resolve } from "node:path";
789
+ function agentPath(home) {
790
+ return join7(home, ".config/madefeed/agent/cli.mjs");
791
+ }
792
+ async function installAgent(self, home) {
793
+ const target = agentPath(home);
794
+ const source = await realpath(self);
795
+ if (source === resolve(target)) return target;
461
796
  try {
462
- const rows = [];
463
- for await (const path of files(
464
- join5(options.home, ".local/share/opencode/storage/message")
465
- )) {
466
- if (!path.endsWith(".json")) continue;
467
- const data = parseJson(await readFile2(path, "utf8"));
468
- const ms = timestamp(record(record(data)["time"])["created"]);
469
- if (!Number.isFinite(ms) || ms < options.sinceMs) continue;
470
- const parsed = usage(data, ms);
471
- if (parsed) rows.push(parsed);
797
+ if (source === await realpath(target)) return target;
798
+ } catch (error) {
799
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
800
+ throw error;
801
+ }
802
+ const directory2 = join7(home, ".config/madefeed/agent");
803
+ await mkdir2(directory2, { recursive: true, mode: 448 });
804
+ await chmod2(directory2, 448);
805
+ const temporary = join7(directory2, `${randomUUID2()}.tmp`);
806
+ try {
807
+ const input = await open(source, "r");
808
+ try {
809
+ const output = await open(temporary, "wx", 384);
810
+ try {
811
+ await output.writeFile(await input.readFile());
812
+ } finally {
813
+ await output.close();
814
+ }
815
+ } finally {
816
+ await input.close();
472
817
  }
473
- return { supported: true, reason: "OpenCode legacy JSON\uC744 \uC0AC\uC6A9\uD574\uC694.", rows };
818
+ await rename2(temporary, target);
819
+ } finally {
820
+ await rm2(temporary, { force: true });
821
+ }
822
+ return target;
823
+ }
824
+ async function removeAgent(home) {
825
+ await rm2(join7(home, ".config/madefeed/agent"), {
826
+ recursive: true,
827
+ force: true
828
+ });
829
+ }
830
+ async function trimLog(home) {
831
+ let file;
832
+ try {
833
+ file = await open(join7(home, ".config/madefeed/auto.log"), "r+");
474
834
  } catch (error) {
475
- if (!(error instanceof Error)) throw error;
476
- return {
477
- supported: false,
478
- reason: "OpenCode\uB294 \uC2DC\uAC04 \uC778\uB371\uC2A4\xB7\uC870\uD68C \uC2DC\uAC04 \uC608\uC0B0 \uB610\uB294 legacy JSON\uC744 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC5B4 unsupported\uB85C \uCC98\uB9AC\uD574\uC694.",
479
- rows: []
480
- };
835
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
836
+ return;
837
+ throw error;
838
+ }
839
+ try {
840
+ if ((await file.stat()).size <= 256 * 1024) return;
841
+ const text2 = await file.readFile("utf8");
842
+ const lines = text2.replace(/\n$/, "").split("\n").slice(-200).join("\n") + "\n";
843
+ await file.truncate(0);
844
+ await file.write(lines, 0, "utf8");
845
+ } finally {
846
+ await file.close();
481
847
  }
482
848
  }
483
849
 
484
- // src/cli.ts
485
- var help = `madefeed 0.1.0 \u2014 \uD1A0\uD070 \uBBF8\uD130\uC608\uC694.
486
- \uC0AC\uC6A9\uBC95: madefeed [login|upload|logout|status] [\uC635\uC158]
850
+ // src/schedule.ts
851
+ import { mkdir as mkdir3, readFile as readFile4, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
852
+ import { dirname } from "node:path";
853
+ import { setTimeout as setTimeout3 } from "node:timers/promises";
854
+
855
+ // src/schedule-builders.ts
856
+ import { join as join8, win32 } from "node:path";
857
+ var marker = "# madefeed-meter";
858
+ var label = "dev.madefeed.meter";
859
+ var timer = "madefeed-meter.timer";
860
+ var environmentKeys = [
861
+ "OPENCODE_DATA_DIR",
862
+ "XDG_DATA_HOME",
863
+ "GEMINI_DATA_DIR",
864
+ "MADEFEED_URL"
865
+ ];
866
+ function jobEnvironment(context) {
867
+ return environmentKeys.flatMap((key) => {
868
+ const value = context.env[key];
869
+ return value === void 0 ? [] : [[key, value]];
870
+ });
871
+ }
872
+ function schedulePaths(context) {
873
+ const path = context.platform === "win32" && !context.home.startsWith("/") ? win32 : { join: join8 };
874
+ const config = path.join(context.home, ".config", "madefeed");
875
+ const units = join8(context.home, ".config/systemd/user");
876
+ return {
877
+ log: path.join(config, "auto.log"),
878
+ plist: join8(context.home, "Library/LaunchAgents", `${label}.plist`),
879
+ service: join8(units, "madefeed-meter.service"),
880
+ timer: join8(units, timer),
881
+ wrapper: path.join(config, "agent", "run.cmd")
882
+ };
883
+ }
884
+ function jobArguments(context) {
885
+ return [context.node, context.agent, "upload", "--days", "3", "--scheduled"];
886
+ }
887
+ function xml(value) {
888
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
889
+ }
890
+ function buildPlist(context) {
891
+ const string = (value) => `<string>${xml(value)}</string>`;
892
+ const paths = schedulePaths(context);
893
+ const env = jobEnvironment(context);
894
+ return `<?xml version="1.0" encoding="UTF-8"?>
895
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
896
+ <plist version="1.0"><dict>
897
+ <key>Label</key>${string(label)}
898
+ <key>ProgramArguments</key><array>${jobArguments(context).map(string).join("")}</array>
899
+ <key>StartInterval</key><integer>3600</integer>
900
+ <key>RunAtLoad</key><false/>
901
+ <key>StandardOutPath</key>${string(paths.log)}
902
+ <key>StandardErrorPath</key>${string(paths.log)}
903
+ ${env.length ? `<key>EnvironmentVariables</key><dict>${env.map(([key, value]) => `<key>${xml(key)}</key>${string(value)}`).join("")}</dict>
904
+ ` : ""}</dict></plist>
905
+ `;
906
+ }
907
+ function shellQuote(value) {
908
+ return `'${value.replaceAll("'", "'\\''")}'`;
909
+ }
910
+ function unitQuote(value) {
911
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll("%", "%%")}"`;
912
+ }
913
+ function buildService(context) {
914
+ const log = schedulePaths(context).log.replaceAll("%", "%%");
915
+ const env = jobEnvironment(context).map(([key, value]) => `Environment=${unitQuote(`${key}=${value}`)}
916
+ `).join("");
917
+ return `[Unit]
918
+ Description=MadeFeed Meter
919
+ [Service]
920
+ Type=oneshot
921
+ ${env}ExecStart=${jobArguments(
922
+ context
923
+ ).map((arg) => unitQuote(arg).replaceAll("$", "$$")).join(" ")}
924
+ StandardOutput=append:${log}
925
+ StandardError=append:${log}
926
+ `;
927
+ }
928
+ function buildTimer() {
929
+ return "[Unit]\nDescription=MadeFeed Meter hourly upload\n[Timer]\nOnCalendar=hourly\nPersistent=true\nRandomizedDelaySec=300\n[Install]\nWantedBy=timers.target\n";
930
+ }
931
+ function buildCron(context) {
932
+ const minute = Array.from(context.home).reduce(
933
+ (hash, char) => (hash * 31 + (char.codePointAt(0) ?? 0)) % 60,
934
+ 0
935
+ );
936
+ const env = jobEnvironment(context).map(([key, value]) => `${key}=${shellQuote(value)} `).join("");
937
+ const command = `${env}${jobArguments(context).map(shellQuote).join(" ")} >> ${shellQuote(schedulePaths(context).log)} 2>&1`;
938
+ return `${minute} * * * * ${command.replaceAll("%", "\\%")} ${marker}`;
939
+ }
940
+ function withoutMarker(text2) {
941
+ return text2.split("\n").filter((line) => !line.trimEnd().endsWith(marker)).join("\n");
942
+ }
943
+ function cmdQuote(value) {
944
+ return `"${value.replaceAll("%", "%%").replaceAll('"', '"^""')}"`;
945
+ }
946
+ function buildWrapper(context) {
947
+ const env = jobEnvironment(context).map(([key, value]) => `set ${cmdQuote(`${key}=${value}`)}\r
948
+ `).join("");
949
+ return `@echo off\r
950
+ setlocal DisableDelayedExpansion\r
951
+ chcp 65001 >nul\r
952
+ ${env}${jobArguments(context).map(cmdQuote).join(" ")} >> ${cmdQuote(schedulePaths(context).log)} 2>&1\r
953
+ `;
954
+ }
955
+
956
+ // src/schedule.ts
957
+ async function fileText(path) {
958
+ try {
959
+ return await readFile4(path, "utf8");
960
+ } catch (error) {
961
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
962
+ return void 0;
963
+ throw error;
964
+ }
965
+ }
966
+ async function succeeds(context, file, args) {
967
+ if (!context.exec) return false;
968
+ try {
969
+ await context.exec(file, args);
970
+ return true;
971
+ } catch (error) {
972
+ if (error instanceof Error) return false;
973
+ throw error;
974
+ }
975
+ }
976
+ async function write(path, text2) {
977
+ await mkdir3(dirname(path), { recursive: true, mode: 448 });
978
+ await writeFile2(path, text2, { mode: 384 });
979
+ }
980
+ async function crontab(context) {
981
+ if (!context.exec) return "";
982
+ try {
983
+ return (await context.exec("crontab", ["-l"])).stdout;
984
+ } catch (error) {
985
+ if (error instanceof Error) return "";
986
+ throw error;
987
+ }
988
+ }
989
+ async function installSchedule(context) {
990
+ const paths = schedulePaths(context);
991
+ if (!context.exec) return { enabled: false, kind: "none", supported: false };
992
+ switch (context.platform) {
993
+ case "darwin": {
994
+ if (context.uid === void 0)
995
+ throw new MeterError("\uC0AC\uC6A9\uC790 \uC2A4\uCF00\uC904\uB7EC\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC5B4\uC694.");
996
+ const domain = `gui/${context.uid}`;
997
+ const service = `${domain}/${label}`;
998
+ const plist = buildPlist(context);
999
+ const identical = await fileText(paths.plist) === plist;
1000
+ if (identical && await succeeds(context, "launchctl", ["print", service]))
1001
+ return { enabled: true, kind: "launchd", supported: true };
1002
+ await write(paths.plist, plist);
1003
+ await succeeds(context, "launchctl", ["bootout", service]);
1004
+ try {
1005
+ await context.exec("launchctl", ["bootstrap", domain, paths.plist]);
1006
+ } catch (error) {
1007
+ if (!(error instanceof Error)) throw error;
1008
+ await setTimeout3(1e3);
1009
+ await context.exec("launchctl", ["bootstrap", domain, paths.plist]);
1010
+ }
1011
+ return { enabled: true, kind: "launchd", supported: true };
1012
+ }
1013
+ case "linux": {
1014
+ await write(paths.service, buildService(context));
1015
+ await write(paths.timer, buildTimer());
1016
+ const loaded = await succeeds(context, "systemctl", [
1017
+ "--user",
1018
+ "daemon-reload"
1019
+ ]);
1020
+ if (loaded && await succeeds(context, "systemctl", [
1021
+ "--user",
1022
+ "enable",
1023
+ "--now",
1024
+ timer
1025
+ ]))
1026
+ return { enabled: true, kind: "systemd", supported: true };
1027
+ await rm3(paths.service, { force: true });
1028
+ await rm3(paths.timer, { force: true });
1029
+ const previous = withoutMarker(await crontab(context));
1030
+ const line = buildCron(context);
1031
+ if (/[\r\n]/.test(line))
1032
+ throw new MeterError("\uC2A4\uCF00\uC904 \uACBD\uB85C\uC5D0 \uC904\uBC14\uAFC8\uC744 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC5B4\uC694.");
1033
+ await context.exec("crontab", ["-"], {
1034
+ input: `${previous}${previous && !previous.endsWith("\n") ? "\n" : ""}${line}
1035
+ `
1036
+ });
1037
+ return { enabled: true, kind: "cron", supported: true };
1038
+ }
1039
+ case "win32":
1040
+ await write(paths.wrapper, buildWrapper(context));
1041
+ await context.exec("schtasks", [
1042
+ "/Create",
1043
+ "/F",
1044
+ "/SC",
1045
+ "HOURLY",
1046
+ "/TN",
1047
+ "MadeFeed Meter",
1048
+ "/TR",
1049
+ `"${paths.wrapper}"`
1050
+ ]);
1051
+ return { enabled: true, kind: "schtasks", supported: true };
1052
+ default:
1053
+ return { enabled: false, kind: "none", supported: false };
1054
+ }
1055
+ }
1056
+ async function removeSchedule(context) {
1057
+ if (!context.exec) return;
1058
+ const paths = schedulePaths(context);
1059
+ switch (context.platform) {
1060
+ case "darwin":
1061
+ await succeeds(context, "launchctl", [
1062
+ "bootout",
1063
+ `gui/${context.uid}/${label}`
1064
+ ]);
1065
+ await rm3(paths.plist, { force: true });
1066
+ return;
1067
+ case "linux": {
1068
+ await succeeds(context, "systemctl", [
1069
+ "--user",
1070
+ "disable",
1071
+ "--now",
1072
+ timer
1073
+ ]);
1074
+ await rm3(paths.service, { force: true });
1075
+ await rm3(paths.timer, { force: true });
1076
+ await succeeds(context, "systemctl", ["--user", "daemon-reload"]);
1077
+ const previous = await crontab(context);
1078
+ const remaining = withoutMarker(previous);
1079
+ if (remaining !== previous)
1080
+ await context.exec("crontab", ["-"], {
1081
+ input: remaining.trim() ? remaining : ""
1082
+ });
1083
+ return;
1084
+ }
1085
+ case "win32":
1086
+ await succeeds(context, "schtasks", [
1087
+ "/Delete",
1088
+ "/F",
1089
+ "/TN",
1090
+ "MadeFeed Meter"
1091
+ ]);
1092
+ await rm3(paths.wrapper, { force: true });
1093
+ return;
1094
+ default:
1095
+ return;
1096
+ }
1097
+ }
1098
+ async function scheduleStatus(context) {
1099
+ const paths = schedulePaths(context);
1100
+ switch (context.platform) {
1101
+ case "darwin":
1102
+ if (await fileText(paths.plist) !== void 0 || await succeeds(context, "launchctl", [
1103
+ "print",
1104
+ `gui/${context.uid}/${label}`
1105
+ ]))
1106
+ return { enabled: true, kind: "launchd" };
1107
+ break;
1108
+ case "linux":
1109
+ if (await fileText(paths.timer) !== void 0 && (!context.exec || await succeeds(context, "systemctl", [
1110
+ "--user",
1111
+ "is-enabled",
1112
+ timer
1113
+ ])))
1114
+ return { enabled: true, kind: "systemd" };
1115
+ if ((await crontab(context)).split("\n").some((line) => line.trimEnd().endsWith(marker)))
1116
+ return { enabled: true, kind: "cron" };
1117
+ break;
1118
+ case "win32":
1119
+ if (context.exec ? await succeeds(context, "schtasks", [
1120
+ "/Query",
1121
+ "/TN",
1122
+ "MadeFeed Meter"
1123
+ ]) : await fileText(paths.wrapper) !== void 0)
1124
+ return { enabled: true, kind: "schtasks" };
1125
+ break;
1126
+ default:
1127
+ break;
1128
+ }
1129
+ return { enabled: false, kind: "none" };
1130
+ }
1131
+
1132
+ // src/auto.ts
1133
+ var failure2 = "\uC790\uB3D9 \uC804\uC1A1\uC744 \uC124\uC815\uD560 \uC218 \uC5C6\uC5B4\uC694. madefeed upload\uB85C \uC218\uB3D9 \uC804\uC1A1\uD560 \uC218 \uC788\uC5B4\uC694.";
1134
+ function automatic(options) {
1135
+ const { runtime, home, env, diagnostic } = options;
1136
+ const active = runtime.exec !== void 0 && runtime.self !== void 0;
1137
+ const context = {
1138
+ platform: runtime.platform ?? process.platform,
1139
+ home,
1140
+ uid: runtime.uid,
1141
+ node: process.execPath,
1142
+ agent: agentPath(home),
1143
+ env,
1144
+ ...active ? { exec: runtime.exec } : {}
1145
+ };
1146
+ async function safely(action) {
1147
+ try {
1148
+ await action();
1149
+ } catch (error) {
1150
+ if (error instanceof Error) diagnostic(failure2);
1151
+ else throw error;
1152
+ }
1153
+ }
1154
+ return {
1155
+ async status() {
1156
+ try {
1157
+ return await scheduleStatus(context);
1158
+ } catch (error) {
1159
+ if (!(error instanceof Error)) throw error;
1160
+ diagnostic(failure2);
1161
+ return { enabled: false, kind: "none" };
1162
+ }
1163
+ },
1164
+ async install(config) {
1165
+ const self = runtime.self;
1166
+ if (!active || !self) return;
1167
+ await safely(async () => {
1168
+ await installAgent(self, home);
1169
+ const result = await installSchedule(context);
1170
+ if (!result.supported) {
1171
+ diagnostic(failure2);
1172
+ return;
1173
+ }
1174
+ await saveConfig(home, { ...config, auto: "on" });
1175
+ if (config.auto !== "on")
1176
+ diagnostic(
1177
+ "\uC774\uC81C \uD55C \uC2DC\uAC04\uB9C8\uB2E4 \uC0AC\uC6A9\uB7C9\uC744 \uC790\uB3D9 \uC804\uC1A1\uD574\uC694. \uB044\uB824\uBA74 madefeed auto off\uB97C \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
1178
+ );
1179
+ });
1180
+ },
1181
+ async remove() {
1182
+ if (!active) return;
1183
+ await safely(() => removeSchedule(context));
1184
+ await safely(() => removeAgent(home));
1185
+ },
1186
+ async trim() {
1187
+ await safely(() => trimLog(home));
1188
+ }
1189
+ };
1190
+ }
1191
+ async function autoCommand(action, config, options) {
1192
+ const auto = automatic(options);
1193
+ switch (action) {
1194
+ case "on":
1195
+ if (!config)
1196
+ throw new MeterError("\uBA3C\uC800 madefeed login\uC73C\uB85C \uAE30\uAE30\uB97C \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694.");
1197
+ await auto.install(config);
1198
+ break;
1199
+ case "off":
1200
+ await auto.remove();
1201
+ if (config) await saveConfig(options.home, { ...config, auto: "off" });
1202
+ break;
1203
+ case "status":
1204
+ break;
1205
+ default:
1206
+ throw new MeterError("auto on, off, status \uC911 \uD558\uB098\uB97C \uC0AC\uC6A9\uD574 \uC8FC\uC138\uC694.");
1207
+ }
1208
+ return auto.status();
1209
+ }
1210
+
1211
+ // src/cli-options.ts
1212
+ import { parseArgs } from "node:util";
1213
+ var VERSION = "0.2.0";
1214
+ var help = `madefeed ${VERSION} \u2014 \uD1A0\uD070 \uBBF8\uD130\uC608\uC694.
1215
+ \uC0AC\uC6A9\uBC95: madefeed [login|upload|logout|status|auto [on|off|status]] [\uC635\uC158]
487
1216
  --dry-run \uC804\uC1A1 \uC5C6\uC774 \uD569\uACC4\uC640 \uC815\uD655\uD55C \uC694\uCCAD JSON\uC744 \uCD9C\uB825\uD574\uC694.
488
1217
  --days N \uC624\uB298\uC744 \uD3EC\uD568\uD55C KST \uC77C\uC218\uC608\uC694. \uAE30\uBCF8 14, \uCD5C\uB300 35\uC608\uC694.
489
1218
  --url URL \uC11C\uBC84 \uC8FC\uC18C\uC608\uC694. MADEFEED_URL \uB610\uB294 https://madefeed.dev\uB97C \uC0AC\uC6A9\uD574\uC694.
490
1219
  --json \uAE30\uACC4\uAC00 \uC77D\uC744 JSON\uB9CC \uD45C\uC900 \uCD9C\uB825\uC73C\uB85C \uB0B4\uBCF4\uB0B4\uC694.
1220
+ --no-auto \uC774\uBC88 \uC2E4\uD589\uC5D0\uC11C\uB294 \uC790\uB3D9 \uC804\uC1A1\uC744 \uB4F1\uB85D\uD558\uAC70\uB098 \uAC31\uC2E0\uD558\uC9C0 \uC54A\uC544\uC694.
1221
+ --scheduled \uC2A4\uCF00\uC904\uB7EC\uC5D0\uC11C \uB85C\uADF8\uC778 \uC5C6\uC774 \uC2E4\uD589\uD574\uC694.
491
1222
  --help \uB3C4\uC6C0\uB9D0\uC744 \uBCF4\uC5EC\uC918\uC694.
492
1223
  --version \uBC84\uC804\uC744 \uBCF4\uC5EC\uC918\uC694.
1224
+ Claude Code, Codex, OpenCode, Gemini CLI\uB97C \uC77D\uC5B4\uC694.
493
1225
  \uAE30\uBCF8 \uC2E4\uD589\uC740 \uB85C\uADF8\uC778 \uD6C4 \uC0AC\uC6A9\uB7C9\uC744 \uC804\uC1A1\uD574\uC694. Cursor\uB294 unsupported\uC608\uC694.`;
494
- async function runCli(args, runtime = {}) {
495
- let parsed;
1226
+ function cliOptions(args) {
496
1227
  try {
497
- parsed = parseArgs({
1228
+ return parseArgs({
498
1229
  args: [...args],
499
1230
  allowPositionals: true,
500
1231
  options: {
501
1232
  "dry-run": { type: "boolean" },
1233
+ "no-auto": { type: "boolean" },
1234
+ scheduled: { type: "boolean" },
502
1235
  days: { type: "string" },
503
1236
  url: { type: "string" },
504
1237
  json: { type: "boolean" },
@@ -513,6 +1246,11 @@ async function runCli(args, runtime = {}) {
513
1246
  );
514
1247
  throw error;
515
1248
  }
1249
+ }
1250
+
1251
+ // src/cli.ts
1252
+ async function runCli(args, runtime = {}) {
1253
+ const parsed = cliOptions(args);
516
1254
  const { values, positionals } = parsed;
517
1255
  const output = runtime.output ?? console.log;
518
1256
  const diagnostic = runtime.diagnostic ?? console.error;
@@ -521,43 +1259,84 @@ async function runCli(args, runtime = {}) {
521
1259
  return;
522
1260
  }
523
1261
  if (values["version"]) {
524
- output("0.1.0");
1262
+ output(VERSION);
525
1263
  return;
526
1264
  }
527
1265
  const days = Number(values["days"] ?? 14);
528
1266
  if (!Number.isInteger(days) || days < 1 || days > 35)
529
1267
  throw new MeterError("--days\uB294 1~35 \uC0AC\uC774\uC758 \uC815\uC218\uC5EC\uC57C \uD574\uC694.");
530
1268
  const command = positionals[0] ?? "upload";
531
- if (positionals.length > 1 || !["login", "upload", "logout", "status"].includes(command))
1269
+ if (positionals.length > (command === "auto" ? 2 : 1) || !["login", "upload", "logout", "status", "auto"].includes(command))
532
1270
  throw new MeterError("\uC54C \uC218 \uC5C6\uB294 \uBA85\uB839\uC774\uC5D0\uC694. --help\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694.");
533
1271
  if (values["dry-run"] && command !== "upload")
534
1272
  throw new MeterError(
535
1273
  "--dry-run\uC740 \uAE30\uBCF8 \uC2E4\uD589 \uB610\uB294 upload\uC5D0\uC11C\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC5B4\uC694."
536
1274
  );
1275
+ if (values["scheduled"] && command !== "upload")
1276
+ throw new MeterError("--scheduled\uB294 upload\uC5D0\uC11C\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC5B4\uC694.");
537
1277
  const home = runtime.home ?? homedir();
1278
+ const env = runtime.env ?? process.env;
1279
+ const autoOptions = { runtime, home, env, diagnostic };
1280
+ const auto = automatic(autoOptions);
1281
+ if (values["scheduled"]) await auto.trim();
538
1282
  if (command === "logout") {
1283
+ await auto.remove();
539
1284
  await logout(home);
540
1285
  output(
541
1286
  values["json"] ? JSON.stringify({ loggedIn: false }) : "\uB85C\uCEEC \uAE30\uAE30 \uD1A0\uD070\uC744 \uC9C0\uC6E0\uC5B4\uC694. \uC11C\uBC84 \uAE30\uAE30 \uD574\uC81C\uB294 \uC6F9 \uC124\uC815\uC5D0\uC11C \uD560 \uC218 \uC788\uC5B4\uC694."
542
1287
  );
543
1288
  return;
544
1289
  }
545
- const config = await readConfig(home);
546
- const chosen = values["url"] ?? process.env["MADEFEED_URL"] ?? config?.url ?? "https://madefeed.dev";
1290
+ let config;
1291
+ try {
1292
+ config = await readConfig(home);
1293
+ } catch (error) {
1294
+ if (values["scheduled"] && error instanceof MeterError) {
1295
+ output("\uC5F0\uACB0\uB41C \uAE30\uAE30 \uD1A0\uD070\uC774 \uC5C6\uC5B4 \uC790\uB3D9 \uC804\uC1A1\uC744 \uAC74\uB108\uB6F0\uC5C8\uC5B4\uC694.");
1296
+ return;
1297
+ }
1298
+ throw error;
1299
+ }
1300
+ if (command === "auto") {
1301
+ const state = await autoCommand(
1302
+ positionals[1] ?? "status",
1303
+ config,
1304
+ autoOptions
1305
+ );
1306
+ output(
1307
+ values["json"] ? JSON.stringify(state) : `\uC790\uB3D9 \uC804\uC1A1: ${state.enabled ? `\uCF1C\uC838 \uC788\uC5B4\uC694 (${state.kind}).` : "\uAEBC\uC838 \uC788\uC5B4\uC694."}`
1308
+ );
1309
+ return;
1310
+ }
1311
+ const chosen = values["url"] ?? env["MADEFEED_URL"] ?? config?.url ?? "https://madefeed.dev";
547
1312
  if (typeof chosen !== "string")
548
1313
  throw new MeterError("\uC11C\uBC84 URL\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
549
1314
  const url = serviceUrl(chosen);
550
1315
  const configured = config?.url === url ? config : void 0;
1316
+ if (values["scheduled"] && !configured) {
1317
+ output("\uC5F0\uACB0\uB41C \uAE30\uAE30 \uD1A0\uD070\uC774 \uC5C6\uC5B4 \uC790\uB3D9 \uC804\uC1A1\uC744 \uAC74\uB108\uB6F0\uC5C8\uC5B4\uC694.");
1318
+ return;
1319
+ }
551
1320
  const deviceName = configured?.deviceName ?? hostname().replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 80);
552
1321
  if (command === "status") {
553
- const status = { loggedIn: Boolean(configured), url, deviceName };
1322
+ const state = await auto.status();
1323
+ const status = {
1324
+ loggedIn: Boolean(configured),
1325
+ url,
1326
+ deviceName,
1327
+ auto: state
1328
+ };
554
1329
  output(
555
1330
  values["json"] ? JSON.stringify(status) : configured ? "\uAE30\uAE30\uC5D0 \uB85C\uADF8\uC778 \uC815\uBCF4\uAC00 \uC788\uC5B4\uC694. \uC11C\uBC84 \uC5F0\uACB0\uC740 \uC804\uC1A1\uD560 \uB54C \uD655\uC778\uD574\uC694." : "\uC544\uC9C1 \uB85C\uADF8\uC778\uD558\uC9C0 \uC54A\uC558\uC5B4\uC694. login\uC73C\uB85C \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694."
556
1331
  );
1332
+ if (!values["json"])
1333
+ output(
1334
+ `\uC790\uB3D9 \uC804\uC1A1: ${state.enabled ? `\uCF1C\uC838 \uC788\uC5B4\uC694 (${state.kind}).` : "\uAEBC\uC838 \uC788\uC5B4\uC694."}`
1335
+ );
557
1336
  return;
558
1337
  }
559
1338
  const now = runtime.now ?? Date.now();
560
- const options = { home, sinceMs: windowStart(now, days) };
1339
+ const options = { home, sinceMs: windowStart(now, days), env };
561
1340
  const api = {
562
1341
  url,
563
1342
  fetch: runtime.fetch ?? fetch,
@@ -566,7 +1345,8 @@ async function runCli(args, runtime = {}) {
566
1345
  const sources = command === "upload" ? await Promise.all([
567
1346
  readClaude(options),
568
1347
  readCodex(options),
569
- readOpenCode(options)
1348
+ readOpenCode(options),
1349
+ readGemini(options)
570
1350
  ]) : [];
571
1351
  for (const source of sources) if (source.reason) diagnostic(source.reason);
572
1352
  const rows = aggregate(
@@ -585,25 +1365,35 @@ async function runCli(args, runtime = {}) {
585
1365
  output(JSON.stringify(body, null, values["json"] ? void 0 : 2));
586
1366
  return;
587
1367
  }
588
- let token = configured?.deviceToken;
589
- if (command === "login" || !token) {
1368
+ let token2 = configured?.deviceToken;
1369
+ let saved = configured;
1370
+ if (!values["scheduled"] && (command === "login" || !token2)) {
590
1371
  const device = await requestDevice(api, deviceName);
591
1372
  const instructions = values["json"] ? diagnostic : output;
592
1373
  instructions(
593
1374
  `\uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C ${device.verification_uri} \uC8FC\uC18C\uB97C \uC5F4\uACE0 ${device.user_code} \uCF54\uB4DC\uB97C \uC785\uB825\uD574 \uC8FC\uC138\uC694.`
594
1375
  );
595
- token = await pollToken(api, device);
596
- await saveConfig(home, { url, deviceName, deviceToken: token });
1376
+ token2 = await pollToken(api, device);
1377
+ saved = {
1378
+ url,
1379
+ deviceName,
1380
+ deviceToken: token2,
1381
+ ...config?.auto ? { auto: config.auto } : {}
1382
+ };
1383
+ await saveConfig(home, saved);
597
1384
  }
1385
+ if (!values["scheduled"] && !values["no-auto"] && env["MADEFEED_NO_AUTO"] !== "1" && saved && saved.auto !== "off")
1386
+ await auto.install(saved);
598
1387
  if (command === "login") {
599
1388
  output(
600
1389
  values["json"] ? JSON.stringify({ loggedIn: true }) : "\uAE30\uAE30\uB97C \uC5F0\uACB0\uD588\uC5B4\uC694."
601
1390
  );
602
1391
  return;
603
1392
  }
604
- const result = await uploadUsage(api, token, body);
1393
+ if (!token2) return;
1394
+ const result = await uploadUsage(api, token2, body);
605
1395
  output(
606
- values["json"] ? JSON.stringify(result) : `${result.accepted}\uAC1C \uC0AC\uC6A9\uB7C9 \uD569\uACC4\uB97C \uC804\uC1A1\uD588\uC5B4\uC694.`
1396
+ values["scheduled"] ? `${new Date(now).toISOString()} ${result.accepted}\uAC1C \uC0AC\uC6A9\uB7C9 \uD569\uACC4\uB97C \uC804\uC1A1\uD588\uC5B4\uC694.` : values["json"] ? JSON.stringify(result) : `${result.accepted}\uAC1C \uC0AC\uC6A9\uB7C9 \uD569\uACC4\uB97C \uC804\uC1A1\uD588\uC5B4\uC694.`
607
1397
  );
608
1398
  }
609
1399
  function invokedDirectly() {
@@ -617,7 +1407,26 @@ function invokedDirectly() {
617
1407
  }
618
1408
  }
619
1409
  if (invokedDirectly()) {
620
- runCli(process.argv.slice(2)).catch((error) => {
1410
+ const entry = process.argv[1];
1411
+ const exec = (file, args, options) => new Promise((resolve2, reject) => {
1412
+ const child = execFile(
1413
+ file,
1414
+ [...args],
1415
+ { encoding: "utf8" },
1416
+ (error, stdout) => {
1417
+ if (error) reject(error);
1418
+ else resolve2({ stdout });
1419
+ }
1420
+ );
1421
+ child.stdin?.on("error", (error) => reject(error));
1422
+ child.stdin?.end(options?.input);
1423
+ });
1424
+ runCli(process.argv.slice(2), {
1425
+ exec,
1426
+ ...entry ? { self: realpathSync(entry) } : {},
1427
+ platform: process.platform,
1428
+ ...process.getuid ? { uid: process.getuid() } : {}
1429
+ }).catch((error) => {
621
1430
  const message = error instanceof MeterError ? error.message : "\uB85C\uCEEC \uC0AC\uC6A9\uB7C9 \uB610\uB294 \uC124\uC815\uC744 \uCC98\uB9AC\uD560 \uC218 \uC5C6\uC5B4\uC694. \uC811\uADFC \uAD8C\uD55C\uACFC Node.js \uBC84\uC804\uC744 \uD655\uC778\uD574 \uC8FC\uC138\uC694.";
622
1431
  if (process.argv.includes("--json"))
623
1432
  console.error(JSON.stringify({ error: message }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@the-seeker/madefeed",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "MadeFeed 토큰 미터: AI 코딩 도구의 토큰 사용량 합계를 madefeed.dev 에 올려요.",
5
5
  "homepage": "https://madefeed.dev/meter",
6
6
  "license": "UNLICENSED",
@@ -9,7 +9,7 @@
9
9
  "node": ">=22.13"
10
10
  },
11
11
  "bin": {
12
- "madefeed": "./dist/cli.mjs"
12
+ "madefeed": "dist/cli.mjs"
13
13
  },
14
14
  "files": [
15
15
  "dist",