@the-seeker/madefeed 0.0.0-stage → 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.
- package/README.md +53 -2
- package/dist/cli.mjs +1439 -0
- package/package.json +28 -4
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,1439 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { homedir, hostname } from "node:os";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { execFile } from "node:child_process";
|
|
8
|
+
|
|
9
|
+
// src/aggregate.ts
|
|
10
|
+
import { createReadStream } from "node:fs";
|
|
11
|
+
import { readdir, stat } from "node:fs/promises";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { createInterface } from "node:readline";
|
|
14
|
+
var MAX_ROW_TOKENS = 1e11;
|
|
15
|
+
var MeterError = class extends Error {
|
|
16
|
+
};
|
|
17
|
+
function isRecord(value) {
|
|
18
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
function record(value) {
|
|
21
|
+
return isRecord(value) ? value : {};
|
|
22
|
+
}
|
|
23
|
+
function parseJson(text2) {
|
|
24
|
+
try {
|
|
25
|
+
const value = JSON.parse(text2);
|
|
26
|
+
return value;
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (error instanceof SyntaxError) return void 0;
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function count(value) {
|
|
33
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
34
|
+
}
|
|
35
|
+
function timestamp(value) {
|
|
36
|
+
return typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : NaN;
|
|
37
|
+
}
|
|
38
|
+
function modelName(value) {
|
|
39
|
+
return typeof value === "string" && /^[A-Za-z0-9._:/-]{1,80}$/.test(value) ? value : "unknown";
|
|
40
|
+
}
|
|
41
|
+
function aggregate(rows) {
|
|
42
|
+
const totals = /* @__PURE__ */ new Map();
|
|
43
|
+
for (const row of rows) {
|
|
44
|
+
const model = modelName(row.model);
|
|
45
|
+
const key = JSON.stringify([row.date, row.tool, model]);
|
|
46
|
+
const tokens = (totals.get(key)?.tokens ?? 0) + row.tokens;
|
|
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
|
+
);
|
|
51
|
+
totals.set(key, { date: row.date, tool: row.tool, model, tokens });
|
|
52
|
+
}
|
|
53
|
+
return [...totals.values()].sort(
|
|
54
|
+
(a, b) => a.date.localeCompare(b.date) || a.tool.localeCompare(b.tool) || a.model.localeCompare(b.model)
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
function payload(deviceName, rows) {
|
|
58
|
+
return { deviceName, rows: aggregate(rows) };
|
|
59
|
+
}
|
|
60
|
+
async function* files(root) {
|
|
61
|
+
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
62
|
+
const path = join(root, entry.name);
|
|
63
|
+
if (entry.isDirectory()) yield* files(path);
|
|
64
|
+
else if (entry.isFile()) yield path;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function* jsonLines(path) {
|
|
68
|
+
const stream = createReadStream(path, { encoding: "utf8" });
|
|
69
|
+
const reader = createInterface({ input: stream, crlfDelay: Infinity });
|
|
70
|
+
try {
|
|
71
|
+
for await (const line of reader) yield parseJson(line);
|
|
72
|
+
} finally {
|
|
73
|
+
reader.close();
|
|
74
|
+
stream.destroy();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async function recentFile(path, sinceMs) {
|
|
78
|
+
return (await stat(path)).mtimeMs >= sinceMs;
|
|
79
|
+
}
|
|
80
|
+
function unsupported(error, reason) {
|
|
81
|
+
if (error instanceof Error) return { supported: false, reason, rows: [] };
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/api.ts
|
|
86
|
+
import { setTimeout as setTimeout2 } from "node:timers/promises";
|
|
87
|
+
var ApiError = class extends MeterError {
|
|
88
|
+
constructor(status) {
|
|
89
|
+
super(
|
|
90
|
+
status === 401 ? "HTTP 401: \uAE30\uAE30 \uC778\uC99D\uC774 \uC720\uD6A8\uD558\uC9C0 \uC54A\uC544\uC694. login\uC73C\uB85C \uB2E4\uC2DC \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694." : status === 422 ? "HTTP 422: \uC0AC\uC6A9\uB7C9 \uD615\uC2DD\uC774 \uC11C\uBC84 \uADDC\uCE59\uACFC \uB9DE\uC9C0 \uC54A\uC544\uC694." : `HTTP ${status}: \uC11C\uBC84 \uC694\uCCAD\uC5D0 \uC2E4\uD328\uD588\uC5B4\uC694.`
|
|
91
|
+
);
|
|
92
|
+
this.status = status;
|
|
93
|
+
}
|
|
94
|
+
status;
|
|
95
|
+
};
|
|
96
|
+
async function post(api, request) {
|
|
97
|
+
try {
|
|
98
|
+
const response = await api.fetch(`${api.url}${request.path}`, {
|
|
99
|
+
method: "POST",
|
|
100
|
+
redirect: "error",
|
|
101
|
+
signal: AbortSignal.timeout(15e3),
|
|
102
|
+
headers: {
|
|
103
|
+
"content-type": "application/json",
|
|
104
|
+
...request.token ? { authorization: `Bearer ${request.token}` } : {}
|
|
105
|
+
},
|
|
106
|
+
body: JSON.stringify(request.body)
|
|
107
|
+
});
|
|
108
|
+
const data = await response.json();
|
|
109
|
+
return { status: response.status, data: record(data) };
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (error instanceof Error)
|
|
112
|
+
throw new MeterError(
|
|
113
|
+
"\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0 \uB610\uB294 \uC11C\uBC84 \uC751\uB2F5\uC744 \uD655\uC778\uD574 \uC8FC\uC138\uC694. \uC790\uB3D9 \uC7AC\uC804\uC1A1\uD558\uC9C0 \uC54A\uC544\uC694."
|
|
114
|
+
);
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function requestDevice(api, deviceName) {
|
|
119
|
+
const { status, data } = await post(api, {
|
|
120
|
+
path: "/api/meter/device",
|
|
121
|
+
body: { deviceName }
|
|
122
|
+
});
|
|
123
|
+
if (status !== 200) throw new ApiError(status);
|
|
124
|
+
const code = data["device_code"];
|
|
125
|
+
const user = data["user_code"];
|
|
126
|
+
const uri = data["verification_uri"];
|
|
127
|
+
const expires = data["expires_in"];
|
|
128
|
+
const interval = data["interval"];
|
|
129
|
+
if (typeof code !== "string" || typeof user !== "string" || typeof uri !== "string" || typeof expires !== "number" || !Number.isFinite(expires) || expires <= 0 || typeof interval !== "number" || !Number.isFinite(interval) || interval <= 0)
|
|
130
|
+
throw new MeterError("\uAE30\uAE30 \uC778\uC99D \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
131
|
+
let verification;
|
|
132
|
+
try {
|
|
133
|
+
verification = new URL(uri);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (error instanceof TypeError)
|
|
136
|
+
throw new MeterError("\uC778\uC99D \uC8FC\uC18C\uAC00 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
if (verification.protocol !== "https:" && verification.origin !== api.url)
|
|
140
|
+
throw new MeterError("\uC548\uC804\uD558\uC9C0 \uC54A\uC740 \uC778\uC99D \uC8FC\uC18C\uC608\uC694.");
|
|
141
|
+
return {
|
|
142
|
+
device_code: code,
|
|
143
|
+
user_code: user,
|
|
144
|
+
verification_uri: uri,
|
|
145
|
+
expires_in: expires,
|
|
146
|
+
interval
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
async function pollToken(api, device) {
|
|
150
|
+
const deadline = Date.now() + device.expires_in * 1e3;
|
|
151
|
+
const sleep = api.sleep ?? (async (ms) => {
|
|
152
|
+
await setTimeout2(ms);
|
|
153
|
+
});
|
|
154
|
+
for (let attempt = 0; attempt < Math.ceil(device.expires_in / device.interval); attempt++) {
|
|
155
|
+
await sleep(device.interval * 1e3);
|
|
156
|
+
if (Date.now() >= deadline) break;
|
|
157
|
+
const { status, data } = await post(api, {
|
|
158
|
+
path: "/api/meter/token",
|
|
159
|
+
body: { device_code: device.device_code }
|
|
160
|
+
});
|
|
161
|
+
if (status === 200) {
|
|
162
|
+
const token2 = data["token"];
|
|
163
|
+
if (typeof token2 !== "string" || !/^mfd_[A-Za-z0-9_-]+$/.test(token2))
|
|
164
|
+
throw new MeterError("\uAE30\uAE30 \uD1A0\uD070 \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
165
|
+
return token2;
|
|
166
|
+
}
|
|
167
|
+
const code = typeof data["error"] === "string" ? data["error"] : record(data["error"])["code"];
|
|
168
|
+
if (status !== 400) throw new ApiError(status);
|
|
169
|
+
switch (code) {
|
|
170
|
+
case "authorization_pending":
|
|
171
|
+
continue;
|
|
172
|
+
case "expired_token":
|
|
173
|
+
throw new MeterError(
|
|
174
|
+
"\uAE30\uAE30 \uC778\uC99D \uCF54\uB4DC\uAC00 \uB9CC\uB8CC\uB410\uC5B4\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
|
|
175
|
+
);
|
|
176
|
+
case "invalid_grant":
|
|
177
|
+
throw new MeterError(
|
|
178
|
+
"\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 \uC778\uC99D \uCF54\uB4DC\uC608\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
|
|
179
|
+
);
|
|
180
|
+
default:
|
|
181
|
+
throw new ApiError(status);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
throw new MeterError(
|
|
185
|
+
"\uAE30\uAE30 \uC778\uC99D \uCF54\uB4DC\uAC00 \uB9CC\uB8CC\uB410\uC5B4\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
async function uploadUsage(api, token2, body) {
|
|
189
|
+
let accepted = 0;
|
|
190
|
+
let weekTokens = 0;
|
|
191
|
+
let votesGranted = 0;
|
|
192
|
+
const safe = payload(body.deviceName, body.rows);
|
|
193
|
+
for (let offset = 0; offset < safe.rows.length; offset += 200) {
|
|
194
|
+
const { status, data } = await post(api, {
|
|
195
|
+
path: "/api/meter/usage",
|
|
196
|
+
token: token2,
|
|
197
|
+
body: {
|
|
198
|
+
deviceName: safe.deviceName,
|
|
199
|
+
rows: safe.rows.slice(offset, offset + 200)
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
if (status !== 200) throw new ApiError(status);
|
|
203
|
+
const values = [data["accepted"], data["weekTokens"], data["votesGranted"]];
|
|
204
|
+
if (!values.every(
|
|
205
|
+
(value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0
|
|
206
|
+
))
|
|
207
|
+
throw new MeterError("\uC0AC\uC6A9\uB7C9 \uC800\uC7A5 \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
208
|
+
const a = data["accepted"];
|
|
209
|
+
const w = data["weekTokens"];
|
|
210
|
+
const v = data["votesGranted"];
|
|
211
|
+
if (typeof a === "number" && typeof w === "number" && typeof v === "number") {
|
|
212
|
+
accepted += a;
|
|
213
|
+
weekTokens = w;
|
|
214
|
+
votesGranted += v;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return { accepted, weekTokens, votesGranted };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// src/config.ts
|
|
221
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
222
|
+
import { randomUUID } from "node:crypto";
|
|
223
|
+
import { join as join2 } from "node:path";
|
|
224
|
+
function serviceUrl(value) {
|
|
225
|
+
let url;
|
|
226
|
+
try {
|
|
227
|
+
url = new URL(value);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
if (error instanceof TypeError)
|
|
230
|
+
throw new MeterError("\uC11C\uBC84 URL\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
231
|
+
throw error;
|
|
232
|
+
}
|
|
233
|
+
const local = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
|
|
234
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local) || url.username || url.password || url.search || url.hash || url.pathname !== "/")
|
|
235
|
+
throw new MeterError("\uC11C\uBC84 URL\uC740 \uC778\uC99D \uC815\uBCF4 \uC5C6\uB294 HTTPS origin\uC774\uC5B4\uC57C \uD574\uC694.");
|
|
236
|
+
return url.origin;
|
|
237
|
+
}
|
|
238
|
+
async function readConfig(home) {
|
|
239
|
+
try {
|
|
240
|
+
const data = record(
|
|
241
|
+
parseJson(
|
|
242
|
+
await readFile(join2(home, ".config/madefeed/cli.json"), "utf8")
|
|
243
|
+
)
|
|
244
|
+
);
|
|
245
|
+
if (typeof data["url"] !== "string" || typeof data["deviceToken"] !== "string" || !/^mfd_[A-Za-z0-9_-]+$/.test(data["deviceToken"]) || typeof data["deviceName"] !== "string")
|
|
246
|
+
throw new MeterError(
|
|
247
|
+
"\uC124\uC815 \uD30C\uC77C\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694. login\uC73C\uB85C \uB2E4\uC2DC \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694."
|
|
248
|
+
);
|
|
249
|
+
return {
|
|
250
|
+
url: serviceUrl(data["url"]),
|
|
251
|
+
deviceToken: data["deviceToken"],
|
|
252
|
+
deviceName: data["deviceName"],
|
|
253
|
+
...data["auto"] === "on" || data["auto"] === "off" ? { auto: data["auto"] } : {}
|
|
254
|
+
};
|
|
255
|
+
} catch (error) {
|
|
256
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
257
|
+
return void 0;
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
async function saveConfig(home, config) {
|
|
262
|
+
const directory2 = join2(home, ".config/madefeed");
|
|
263
|
+
await mkdir(directory2, { recursive: true, mode: 448 });
|
|
264
|
+
const temporary = join2(directory2, `cli-${randomUUID()}.tmp`);
|
|
265
|
+
try {
|
|
266
|
+
await writeFile(temporary, JSON.stringify(config), {
|
|
267
|
+
mode: 384,
|
|
268
|
+
flag: "wx"
|
|
269
|
+
});
|
|
270
|
+
await chmod(temporary, 384);
|
|
271
|
+
await rename(temporary, join2(directory2, "cli.json"));
|
|
272
|
+
} finally {
|
|
273
|
+
await rm(temporary, { force: true });
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async function logout(home) {
|
|
277
|
+
await rm(join2(home, ".config/madefeed/cli.json"), { force: true });
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// src/kst.ts
|
|
281
|
+
var offsetMs = 9 * 60 * 60 * 1e3;
|
|
282
|
+
function kstDateOf(value) {
|
|
283
|
+
const ms = typeof value === "number" ? value : Date.parse(value);
|
|
284
|
+
return new Date(ms + offsetMs).toISOString().slice(0, 10);
|
|
285
|
+
}
|
|
286
|
+
function windowStart(now, days) {
|
|
287
|
+
return Date.parse(`${kstDateOf(now)}T00:00:00+09:00`) - (days - 1) * 864e5;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// src/sources/claude.ts
|
|
291
|
+
import { join as join3 } from "node:path";
|
|
292
|
+
async function readClaude(options) {
|
|
293
|
+
const messages = /* @__PURE__ */ new Map();
|
|
294
|
+
try {
|
|
295
|
+
for await (const path of files(join3(options.home, ".claude/projects"))) {
|
|
296
|
+
if (!path.endsWith(".jsonl") || !await recentFile(path, options.sinceMs))
|
|
297
|
+
continue;
|
|
298
|
+
for await (const value of jsonLines(path)) {
|
|
299
|
+
const event2 = record(value);
|
|
300
|
+
if (event2["type"] !== "assistant") continue;
|
|
301
|
+
const message = record(event2["message"]);
|
|
302
|
+
const ms = timestamp(event2["timestamp"]);
|
|
303
|
+
if (!Number.isFinite(ms) || ms < options.sinceMs || message["model"] === "<synthetic>")
|
|
304
|
+
continue;
|
|
305
|
+
if (typeof message["id"] !== "string" || typeof event2["requestId"] !== "string")
|
|
306
|
+
continue;
|
|
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"]]);
|
|
310
|
+
if (tokens > (messages.get(key)?.tokens ?? -1))
|
|
311
|
+
messages.set(key, {
|
|
312
|
+
date: kstDateOf(ms),
|
|
313
|
+
tool: "claude-code",
|
|
314
|
+
model: modelName(message["model"]),
|
|
315
|
+
tokens
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return { supported: true, rows: [...messages.values()] };
|
|
320
|
+
} catch (error) {
|
|
321
|
+
return unsupported(
|
|
322
|
+
error,
|
|
323
|
+
"Claude Code \uB85C\uADF8\uB97C \uC77D\uC744 \uC218 \uC5C6\uC5B4 unsupported\uB85C \uCC98\uB9AC\uD574\uC694."
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// src/sources/codex.ts
|
|
329
|
+
import { join as join4, basename } from "node:path";
|
|
330
|
+
async function readCodex(options) {
|
|
331
|
+
const rows = [];
|
|
332
|
+
try {
|
|
333
|
+
for await (const path of files(join4(options.home, ".codex/sessions"))) {
|
|
334
|
+
if (!basename(path).startsWith("rollout-") || !path.endsWith(".jsonl") || !await recentFile(path, options.sinceMs))
|
|
335
|
+
continue;
|
|
336
|
+
let model = "unknown";
|
|
337
|
+
let previous = 0;
|
|
338
|
+
for await (const value of jsonLines(path)) {
|
|
339
|
+
const event2 = record(value);
|
|
340
|
+
const data = record(event2["payload"]);
|
|
341
|
+
if (event2["type"] === "turn_context") {
|
|
342
|
+
model = modelName(data["model"]);
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
if (event2["type"] !== "event_msg" || data["type"] !== "token_count")
|
|
346
|
+
continue;
|
|
347
|
+
const info = record(data["info"]);
|
|
348
|
+
const total = record(info["total_token_usage"])["total_tokens"];
|
|
349
|
+
if (typeof total !== "number" || !Number.isSafeInteger(total) || total < 0)
|
|
350
|
+
continue;
|
|
351
|
+
const delta = total >= previous ? total - previous : count(record(info["last_token_usage"])["total_tokens"]);
|
|
352
|
+
previous = total;
|
|
353
|
+
const ms = timestamp(event2["timestamp"]);
|
|
354
|
+
if (Number.isFinite(ms) && ms >= options.sinceMs && delta > 0)
|
|
355
|
+
rows.push({
|
|
356
|
+
date: kstDateOf(ms),
|
|
357
|
+
tool: "codex",
|
|
358
|
+
model,
|
|
359
|
+
tokens: delta
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return { supported: true, rows };
|
|
364
|
+
} catch (error) {
|
|
365
|
+
return unsupported(
|
|
366
|
+
error,
|
|
367
|
+
"Codex \uB85C\uADF8\uB97C \uC77D\uC744 \uC218 \uC5C6\uC5B4 unsupported\uB85C \uCC98\uB9AC\uD574\uC694."
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/sources/opencode.ts
|
|
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";
|
|
375
|
+
import { Worker } from "node:worker_threads";
|
|
376
|
+
|
|
377
|
+
// src/sources/opencode-db.ts
|
|
378
|
+
function databaseWorker(input) {
|
|
379
|
+
try {
|
|
380
|
+
const { DatabaseSync } = process.getBuiltinModule("node:sqlite");
|
|
381
|
+
const db = new DatabaseSync(input.path, { readOnly: true });
|
|
382
|
+
try {
|
|
383
|
+
db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=200");
|
|
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);
|
|
445
|
+
}
|
|
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] };
|
|
510
|
+
} finally {
|
|
511
|
+
db.close();
|
|
512
|
+
}
|
|
513
|
+
} catch (error) {
|
|
514
|
+
if (error instanceof Error) return { error: true };
|
|
515
|
+
throw error;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
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
|
|
527
|
+
}
|
|
528
|
+
);
|
|
529
|
+
try {
|
|
530
|
+
return await new Promise((resolve2, reject) => {
|
|
531
|
+
const fail = () => {
|
|
532
|
+
clearTimeout(timer2);
|
|
533
|
+
reject(new MeterError(failure));
|
|
534
|
+
};
|
|
535
|
+
const timer2 = setTimeout(fail, 45e3);
|
|
536
|
+
worker.once("error", fail);
|
|
537
|
+
worker.once("exit", fail);
|
|
538
|
+
worker.once("message", (value) => {
|
|
539
|
+
clearTimeout(timer2);
|
|
540
|
+
resolve2(value);
|
|
541
|
+
});
|
|
542
|
+
});
|
|
543
|
+
} finally {
|
|
544
|
+
await worker.terminate();
|
|
545
|
+
}
|
|
546
|
+
}
|
|
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;
|
|
585
|
+
}
|
|
586
|
+
async function readOpenCode(options) {
|
|
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
|
+
];
|
|
594
|
+
const rows = [];
|
|
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
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return { supported: true, rows };
|
|
628
|
+
} catch (error) {
|
|
629
|
+
return unsupported(error, failure);
|
|
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;
|
|
796
|
+
try {
|
|
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();
|
|
817
|
+
}
|
|
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+");
|
|
834
|
+
} catch (error) {
|
|
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();
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
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("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
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]
|
|
1216
|
+
--dry-run \uC804\uC1A1 \uC5C6\uC774 \uD569\uACC4\uC640 \uC815\uD655\uD55C \uC694\uCCAD JSON\uC744 \uCD9C\uB825\uD574\uC694.
|
|
1217
|
+
--days N \uC624\uB298\uC744 \uD3EC\uD568\uD55C KST \uC77C\uC218\uC608\uC694. \uAE30\uBCF8 14, \uCD5C\uB300 35\uC608\uC694.
|
|
1218
|
+
--url URL \uC11C\uBC84 \uC8FC\uC18C\uC608\uC694. MADEFEED_URL \uB610\uB294 https://madefeed.dev\uB97C \uC0AC\uC6A9\uD574\uC694.
|
|
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.
|
|
1222
|
+
--help \uB3C4\uC6C0\uB9D0\uC744 \uBCF4\uC5EC\uC918\uC694.
|
|
1223
|
+
--version \uBC84\uC804\uC744 \uBCF4\uC5EC\uC918\uC694.
|
|
1224
|
+
Claude Code, Codex, OpenCode, Gemini CLI\uB97C \uC77D\uC5B4\uC694.
|
|
1225
|
+
\uAE30\uBCF8 \uC2E4\uD589\uC740 \uB85C\uADF8\uC778 \uD6C4 \uC0AC\uC6A9\uB7C9\uC744 \uC804\uC1A1\uD574\uC694. Cursor\uB294 unsupported\uC608\uC694.`;
|
|
1226
|
+
function cliOptions(args) {
|
|
1227
|
+
try {
|
|
1228
|
+
return parseArgs({
|
|
1229
|
+
args: [...args],
|
|
1230
|
+
allowPositionals: true,
|
|
1231
|
+
options: {
|
|
1232
|
+
"dry-run": { type: "boolean" },
|
|
1233
|
+
"no-auto": { type: "boolean" },
|
|
1234
|
+
scheduled: { type: "boolean" },
|
|
1235
|
+
days: { type: "string" },
|
|
1236
|
+
url: { type: "string" },
|
|
1237
|
+
json: { type: "boolean" },
|
|
1238
|
+
help: { type: "boolean" },
|
|
1239
|
+
version: { type: "boolean" }
|
|
1240
|
+
}
|
|
1241
|
+
});
|
|
1242
|
+
} catch (error) {
|
|
1243
|
+
if (error instanceof Error)
|
|
1244
|
+
throw new MeterError(
|
|
1245
|
+
"\uBA85\uB839 \uC635\uC158\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694. --help\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694."
|
|
1246
|
+
);
|
|
1247
|
+
throw error;
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// src/cli.ts
|
|
1252
|
+
async function runCli(args, runtime = {}) {
|
|
1253
|
+
const parsed = cliOptions(args);
|
|
1254
|
+
const { values, positionals } = parsed;
|
|
1255
|
+
const output = runtime.output ?? console.log;
|
|
1256
|
+
const diagnostic = runtime.diagnostic ?? console.error;
|
|
1257
|
+
if (values["help"]) {
|
|
1258
|
+
output(help);
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
if (values["version"]) {
|
|
1262
|
+
output(VERSION);
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
const days = Number(values["days"] ?? 14);
|
|
1266
|
+
if (!Number.isInteger(days) || days < 1 || days > 35)
|
|
1267
|
+
throw new MeterError("--days\uB294 1~35 \uC0AC\uC774\uC758 \uC815\uC218\uC5EC\uC57C \uD574\uC694.");
|
|
1268
|
+
const command = positionals[0] ?? "upload";
|
|
1269
|
+
if (positionals.length > (command === "auto" ? 2 : 1) || !["login", "upload", "logout", "status", "auto"].includes(command))
|
|
1270
|
+
throw new MeterError("\uC54C \uC218 \uC5C6\uB294 \uBA85\uB839\uC774\uC5D0\uC694. --help\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694.");
|
|
1271
|
+
if (values["dry-run"] && command !== "upload")
|
|
1272
|
+
throw new MeterError(
|
|
1273
|
+
"--dry-run\uC740 \uAE30\uBCF8 \uC2E4\uD589 \uB610\uB294 upload\uC5D0\uC11C\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC5B4\uC694."
|
|
1274
|
+
);
|
|
1275
|
+
if (values["scheduled"] && command !== "upload")
|
|
1276
|
+
throw new MeterError("--scheduled\uB294 upload\uC5D0\uC11C\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC5B4\uC694.");
|
|
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();
|
|
1282
|
+
if (command === "logout") {
|
|
1283
|
+
await auto.remove();
|
|
1284
|
+
await logout(home);
|
|
1285
|
+
output(
|
|
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."
|
|
1287
|
+
);
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
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";
|
|
1312
|
+
if (typeof chosen !== "string")
|
|
1313
|
+
throw new MeterError("\uC11C\uBC84 URL\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
1314
|
+
const url = serviceUrl(chosen);
|
|
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
|
+
}
|
|
1320
|
+
const deviceName = configured?.deviceName ?? hostname().replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 80);
|
|
1321
|
+
if (command === "status") {
|
|
1322
|
+
const state = await auto.status();
|
|
1323
|
+
const status = {
|
|
1324
|
+
loggedIn: Boolean(configured),
|
|
1325
|
+
url,
|
|
1326
|
+
deviceName,
|
|
1327
|
+
auto: state
|
|
1328
|
+
};
|
|
1329
|
+
output(
|
|
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."
|
|
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
|
+
);
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
const now = runtime.now ?? Date.now();
|
|
1339
|
+
const options = { home, sinceMs: windowStart(now, days), env };
|
|
1340
|
+
const api = {
|
|
1341
|
+
url,
|
|
1342
|
+
fetch: runtime.fetch ?? fetch,
|
|
1343
|
+
...runtime.sleep ? { sleep: runtime.sleep } : {}
|
|
1344
|
+
};
|
|
1345
|
+
const sources = command === "upload" ? await Promise.all([
|
|
1346
|
+
readClaude(options),
|
|
1347
|
+
readCodex(options),
|
|
1348
|
+
readOpenCode(options),
|
|
1349
|
+
readGemini(options)
|
|
1350
|
+
]) : [];
|
|
1351
|
+
for (const source of sources) if (source.reason) diagnostic(source.reason);
|
|
1352
|
+
const rows = aggregate(
|
|
1353
|
+
sources.flatMap((source) => source.rows).filter((row) => row.date <= kstDateOf(now))
|
|
1354
|
+
);
|
|
1355
|
+
const body = payload(deviceName, rows);
|
|
1356
|
+
if (values["dry-run"]) {
|
|
1357
|
+
if (!values["json"]) {
|
|
1358
|
+
output("\uC804\uC1A1\uD558\uC9C0 \uC54A\uC558\uC5B4\uC694. \uC544\uB798 \uD569\uACC4\uC640 JSON\uB9CC \uC804\uC1A1 \uB300\uC0C1\uC774\uC5D0\uC694.");
|
|
1359
|
+
output("date tool model tokens");
|
|
1360
|
+
for (const row of rows)
|
|
1361
|
+
output(
|
|
1362
|
+
`${row.date} ${row.tool.padEnd(11)} ${row.model.padEnd(28)} ${row.tokens}`
|
|
1363
|
+
);
|
|
1364
|
+
}
|
|
1365
|
+
output(JSON.stringify(body, null, values["json"] ? void 0 : 2));
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
let token2 = configured?.deviceToken;
|
|
1369
|
+
let saved = configured;
|
|
1370
|
+
if (!values["scheduled"] && (command === "login" || !token2)) {
|
|
1371
|
+
const device = await requestDevice(api, deviceName);
|
|
1372
|
+
const instructions = values["json"] ? diagnostic : output;
|
|
1373
|
+
instructions(
|
|
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.`
|
|
1375
|
+
);
|
|
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);
|
|
1384
|
+
}
|
|
1385
|
+
if (!values["scheduled"] && !values["no-auto"] && env["MADEFEED_NO_AUTO"] !== "1" && saved && saved.auto !== "off")
|
|
1386
|
+
await auto.install(saved);
|
|
1387
|
+
if (command === "login") {
|
|
1388
|
+
output(
|
|
1389
|
+
values["json"] ? JSON.stringify({ loggedIn: true }) : "\uAE30\uAE30\uB97C \uC5F0\uACB0\uD588\uC5B4\uC694."
|
|
1390
|
+
);
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
if (!token2) return;
|
|
1394
|
+
const result = await uploadUsage(api, token2, body);
|
|
1395
|
+
output(
|
|
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.`
|
|
1397
|
+
);
|
|
1398
|
+
}
|
|
1399
|
+
function invokedDirectly() {
|
|
1400
|
+
const entry = process.argv[1];
|
|
1401
|
+
if (!entry) return false;
|
|
1402
|
+
try {
|
|
1403
|
+
return import.meta.url === pathToFileURL(realpathSync(entry)).href;
|
|
1404
|
+
} catch (error) {
|
|
1405
|
+
if (error instanceof Error) return false;
|
|
1406
|
+
throw error;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
if (invokedDirectly()) {
|
|
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) => {
|
|
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.";
|
|
1431
|
+
if (process.argv.includes("--json"))
|
|
1432
|
+
console.error(JSON.stringify({ error: message }));
|
|
1433
|
+
else console.error(message);
|
|
1434
|
+
process.exitCode = 1;
|
|
1435
|
+
});
|
|
1436
|
+
}
|
|
1437
|
+
export {
|
|
1438
|
+
runCli
|
|
1439
|
+
};
|