@the-seeker/madefeed 0.1.0 → 0.3.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 +29 -5
- package/dist/cli.mjs +1132 -195
- package/package.json +2 -2
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 {
|
|
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(
|
|
23
|
+
function parseJson(text2) {
|
|
23
24
|
try {
|
|
24
|
-
const value = JSON.parse(
|
|
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 >
|
|
47
|
-
throw new MeterError(
|
|
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(
|
|
@@ -54,6 +57,15 @@ function aggregate(rows) {
|
|
|
54
57
|
function payload(deviceName, rows) {
|
|
55
58
|
return { deviceName, rows: aggregate(rows) };
|
|
56
59
|
}
|
|
60
|
+
async function directory(path) {
|
|
61
|
+
try {
|
|
62
|
+
return (await stat(path)).isDirectory();
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
65
|
+
return false;
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
57
69
|
async function* files(root) {
|
|
58
70
|
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
59
71
|
const path = join(root, entry.name);
|
|
@@ -81,15 +93,82 @@ function unsupported(error, reason) {
|
|
|
81
93
|
|
|
82
94
|
// src/api.ts
|
|
83
95
|
import { setTimeout as setTimeout2 } from "node:timers/promises";
|
|
96
|
+
|
|
97
|
+
// src/copy.ts
|
|
98
|
+
var RUN = "npx @the-seeker/madefeed@latest";
|
|
99
|
+
var setupFailure = `\uC790\uB3D9 \uC804\uC1A1\uC744 \uB4F1\uB85D\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694. ${RUN} \uB85C \uC9C1\uC811 \uC62C\uB9B4 \uC218 \uC788\uC5B4\uC694.`;
|
|
100
|
+
var cleanupFailure = (scope) => `\uC9C0\uC6B0\uC9C0 \uBABB\uD55C \uD30C\uC77C\uC774 \uC788\uC5B4\uC694. ${RUN} ${scope === "auto" ? "auto off" : "logout"} \uC744 \uD55C \uBC88 \uB354 \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`;
|
|
101
|
+
var autoEnabled = [
|
|
102
|
+
"\uD55C \uC2DC\uAC04\uB9C8\uB2E4 \uC790\uB3D9\uC73C\uB85C \uC62C\uB824\uC694. \uD130\uBBF8\uB110\uC744 \uC5F4\uC5B4 \uB450\uC9C0 \uC54A\uC544\uB3C4 \uB3FC\uC694.",
|
|
103
|
+
` \uC790\uB3D9 \uC804\uC1A1 \uB044\uAE30 ${RUN} auto off`,
|
|
104
|
+
` \uC5F0\uACB0 \uB04A\uAE30 ${RUN} logout`
|
|
105
|
+
];
|
|
106
|
+
var connectionRequired = `\uBA3C\uC800 ${RUN} \uB85C \uAE30\uAE30\uB97C \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694.`;
|
|
107
|
+
var invalidAuto = "auto on, off, status \uC911 \uD558\uB098\uB97C \uC0AC\uC6A9\uD574 \uC8FC\uC138\uC694.";
|
|
108
|
+
var invalidDays = "--days\uB294 1~35 \uC0AC\uC774\uC758 \uC815\uC218\uC5EC\uC57C \uD574\uC694.";
|
|
109
|
+
var unknownCommand = "\uC54C \uC218 \uC5C6\uB294 \uBA85\uB839\uC774\uC5D0\uC694. --help\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694.";
|
|
110
|
+
var invalidDryRun = "--dry-run\uC740 \uAE30\uBCF8 \uC2E4\uD589 \uB610\uB294 upload\uC5D0\uC11C\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC5B4\uC694.";
|
|
111
|
+
var invalidScheduled = "--scheduled\uB294 upload\uC5D0\uC11C\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC5B4\uC694.";
|
|
112
|
+
var invalidOptions = "\uBA85\uB839 \uC635\uC158\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694. --help\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694.";
|
|
113
|
+
var invalidUrl = "\uC11C\uBC84 URL\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.";
|
|
114
|
+
var unsafeUrl = "\uC11C\uBC84 URL\uC740 \uC778\uC99D \uC815\uBCF4 \uC5C6\uB294 HTTPS origin\uC774\uC5B4\uC57C \uD574\uC694.";
|
|
115
|
+
var invalidConfig = `\uC124\uC815 \uD30C\uC77C\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694. ${RUN} login \uC73C\uB85C \uB2E4\uC2DC \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694.`;
|
|
116
|
+
var scheduledSkip = "\uC5F0\uACB0\uB41C \uAE30\uAE30\uAC00 \uC5C6\uC5B4 \uC790\uB3D9 \uC804\uC1A1\uC744 \uAC74\uB108\uB6F0\uC5C8\uC5B4\uC694.";
|
|
117
|
+
var dryRunHeader = "\uC804\uC1A1\uD558\uC9C0 \uC54A\uC558\uC5B4\uC694. \uC544\uB798 \uD569\uACC4\uC640 JSON\uB9CC \uC804\uC1A1 \uB300\uC0C1\uC774\uC5D0\uC694.";
|
|
118
|
+
var dryRunColumns = "date tool model tokens";
|
|
119
|
+
var localFailure = "\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.";
|
|
120
|
+
var disconnected = `\uC11C\uBC84\uC5D0\uC11C \uC774 \uAE30\uAE30 \uC5F0\uACB0\uC774 \uB04A\uACA8 \uC788\uC5B4\uC694. \uC790\uB3D9 \uC804\uC1A1\uACFC \uC774 \uCEF4\uD4E8\uD130\uC758 \uC5F0\uACB0 \uC815\uBCF4\uB97C \uC9C0\uC6E0\uC5B4\uC694. \uB2E4\uC2DC \uC5F0\uACB0\uD558\uB824\uBA74 ${RUN} \uB97C \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`;
|
|
121
|
+
var logoutRevoked = "\uC5F0\uACB0\uC744 \uB04A\uC5C8\uC5B4\uC694. \uC790\uB3D9 \uC804\uC1A1\uACFC \uC774 \uCEF4\uD4E8\uD130\uC758 \uC5F0\uACB0 \uC815\uBCF4\uB97C \uC9C0\uC6E0\uC5B4\uC694. \uC62C\uB9B0 \uC0AC\uC6A9\uB7C9\uC740 \uACC4\uC815\uC5D0 \uADF8\uB300\uB85C \uB0A8\uC544\uC694.";
|
|
122
|
+
var logoutLocal = "\uC774 \uCEF4\uD4E8\uD130\uC758 \uC5F0\uACB0 \uC815\uBCF4\uC640 \uC790\uB3D9 \uC804\uC1A1\uC744 \uC9C0\uC6E0\uC5B4\uC694.";
|
|
123
|
+
var logoutUnreachable = (url) => `\uC774 \uCEF4\uD4E8\uD130\uC758 \uC5F0\uACB0 \uC815\uBCF4\uC640 \uC790\uB3D9 \uC804\uC1A1\uC740 \uC9C0\uC6E0\uC5B4\uC694. \uC11C\uBC84\uC5D0\uB294 \uB2FF\uC9C0 \uBABB\uD588\uC73C\uB2C8 ${url}/meter \uC5D0\uC11C \uC774 \uAE30\uAE30 \uC5F0\uACB0\uC744 \uB04A\uC5B4 \uC8FC\uC138\uC694.`;
|
|
124
|
+
var scheduledDisconnected = (now) => `${new Date(now).toISOString()} \uC11C\uBC84\uC5D0\uC11C \uC774 \uAE30\uAE30 \uC5F0\uACB0\uC774 \uB04A\uACA8 \uC790\uB3D9 \uC804\uC1A1\uC744 \uD574\uC81C\uD558\uACE0 \uC5F0\uACB0 \uC815\uBCF4\uB97C \uC9C0\uC6E0\uC5B4\uC694.`;
|
|
125
|
+
var connected = (deviceName) => `${deviceName} \uAE30\uAE30\uB97C \uC5F0\uACB0\uD588\uC5B4\uC694.`;
|
|
126
|
+
var approval = (device) => [
|
|
127
|
+
"\uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C \uC544\uB798 \uC8FC\uC18C\uB97C \uC5F4\uACE0, \uCF54\uB4DC\uAC00 \uAC19\uC73C\uBA74 \uC2B9\uC778\uD574 \uC8FC\uC138\uC694.",
|
|
128
|
+
` \uC8FC\uC18C ${device.verification_uri}`,
|
|
129
|
+
` \uCF54\uB4DC ${device.user_code}`
|
|
130
|
+
];
|
|
131
|
+
var autoLine = (state) => state.enabled ? `\uC790\uB3D9 \uC804\uC1A1: \uCF1C\uC838 \uC788\uC5B4\uC694 (\uD55C \uC2DC\uAC04\uB9C8\uB2E4, ${state.kind}).` : "\uC790\uB3D9 \uC804\uC1A1: \uAEBC\uC838 \uC788\uC5B4\uC694.";
|
|
132
|
+
var connectionLine = (config) => config ? `\uC5F0\uACB0: ${config.deviceName} (${config.url})` : `\uC5F0\uACB0: \uC544\uC9C1 \uC5F0\uACB0\uD558\uC9C0 \uC54A\uC558\uC5B4\uC694. ${RUN} \uB85C \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694.`;
|
|
133
|
+
var uploadResult = (result) => `\uC0AC\uC6A9\uB7C9 ${result.accepted}\uAC74\uC744 \uC62C\uB838\uC5B4\uC694.${result.votesGranted > 0 ? ` \uC0C8\uB85C \uBC1B\uC740 \uD45C ${result.votesGranted}\uD45C.` : ""}`;
|
|
134
|
+
var scheduledUpload = (now, accepted) => `${new Date(now).toISOString()} \uC0AC\uC6A9\uB7C9 ${accepted}\uAC74\uC744 \uC62C\uB838\uC5B4\uC694.`;
|
|
135
|
+
var apiFailure = (status) => status === 401 ? `HTTP 401: \uAE30\uAE30 \uC5F0\uACB0\uC774 \uC720\uD6A8\uD558\uC9C0 \uC54A\uC544\uC694. ${RUN} 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.`;
|
|
136
|
+
var expiredCode = `\uAE30\uAE30 \uC778\uC99D \uCF54\uB4DC\uAC00 \uB9CC\uB8CC\uB410\uC5B4\uC694. ${RUN} login \uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`;
|
|
137
|
+
var invalidCode = `\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 \uC778\uC99D \uCF54\uB4DC\uC608\uC694. ${RUN} login \uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`;
|
|
138
|
+
function helpText(version) {
|
|
139
|
+
return `madefeed ${version} \u2014 MadeFeed \uD1A0\uD070 \uBBF8\uD130
|
|
140
|
+
\uC0AC\uC6A9\uBC95: ${RUN} [\uBA85\uB839] [\uC635\uC158]
|
|
141
|
+
|
|
142
|
+
\uBA85\uB839
|
|
143
|
+
(\uC5C6\uC74C), upload \uC5F0\uACB0\uC774 \uC5C6\uC73C\uBA74 \uC5F0\uACB0\uD558\uACE0, \uC0AC\uC6A9\uB7C9\uC744 \uC62C\uB824\uC694.
|
|
144
|
+
login \uAE30\uAE30\uB9CC \uC5F0\uACB0\uD574\uC694.
|
|
145
|
+
status \uC5F0\uACB0\uACFC \uC790\uB3D9 \uC804\uC1A1 \uC0C1\uD0DC\uB97C \uBCF4\uC5EC\uC918\uC694.
|
|
146
|
+
auto [on|off|status] \uC790\uB3D9 \uC804\uC1A1\uC744 \uCF1C\uAC70\uB098 \uB044\uAC70\uB098 \uD655\uC778\uD574\uC694.
|
|
147
|
+
logout \uC5F0\uACB0\uC744 \uB04A\uACE0 \uC774 \uCEF4\uD4E8\uD130\uC758 \uC5F0\uACB0 \uC815\uBCF4\uC640 \uC790\uB3D9 \uC804\uC1A1\uC744 \uC9C0\uC6CC\uC694.
|
|
148
|
+
|
|
149
|
+
\uC635\uC158
|
|
150
|
+
--dry-run \uBCF4\uB0B4\uC9C0 \uC54A\uACE0, \uBCF4\uB0BC \uD569\uACC4\uC640 \uC694\uCCAD JSON\uB9CC \uBCF4\uC5EC\uC918\uC694.
|
|
151
|
+
--days N \uC624\uB298\uC744 \uD3EC\uD568\uD574 \uBA70\uCE60 \uCE58\uB97C \uC140\uC9C0 \uC815\uD574\uC694. \uAE30\uBCF8 14, \uCD5C\uB300 35 (KST).
|
|
152
|
+
--url URL \uC11C\uBC84 \uC8FC\uC18C\uC608\uC694. \uAE30\uBCF8\uC740 MADEFEED_URL \uB610\uB294 https://madefeed.dev.
|
|
153
|
+
--json \uAE30\uACC4\uAC00 \uC77D\uC744 JSON\uB9CC \uD45C\uC900 \uCD9C\uB825\uC73C\uB85C \uB0B4\uBCF4\uB0B4\uC694.
|
|
154
|
+
--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.
|
|
155
|
+
--scheduled \uC608\uC57D \uC791\uC5C5\uC6A9\uC774\uC5D0\uC694. \uC5F0\uACB0 \uC808\uCC28 \uC5C6\uC774 \uC62C\uB824\uC694.
|
|
156
|
+
--help \uB3C4\uC6C0\uB9D0\uC744 \uBCF4\uC5EC\uC918\uC694.
|
|
157
|
+
--version \uBC84\uC804\uC744 \uBCF4\uC5EC\uC918\uC694.
|
|
158
|
+
|
|
159
|
+
\uC77D\uB294 \uB3C4\uAD6C: Claude Code, Codex, OpenCode, Gemini CLI (Cursor\uB294 \uC544\uC9C1 \uC9C0\uC6D0\uD558\uC9C0 \uC54A\uC544\uC694)`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/api.ts
|
|
84
163
|
var ApiError = class extends MeterError {
|
|
85
164
|
constructor(status) {
|
|
86
|
-
super(
|
|
87
|
-
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.`
|
|
88
|
-
);
|
|
165
|
+
super(apiFailure(status));
|
|
89
166
|
this.status = status;
|
|
90
167
|
}
|
|
91
168
|
status;
|
|
92
169
|
};
|
|
170
|
+
var DisconnectedError = class extends MeterError {
|
|
171
|
+
};
|
|
93
172
|
async function post(api, request) {
|
|
94
173
|
try {
|
|
95
174
|
const response = await api.fetch(`${api.url}${request.path}`, {
|
|
@@ -156,10 +235,10 @@ async function pollToken(api, device) {
|
|
|
156
235
|
body: { device_code: device.device_code }
|
|
157
236
|
});
|
|
158
237
|
if (status === 200) {
|
|
159
|
-
const
|
|
160
|
-
if (typeof
|
|
238
|
+
const token2 = data["token"];
|
|
239
|
+
if (typeof token2 !== "string" || !/^mfd_[A-Za-z0-9_-]+$/.test(token2))
|
|
161
240
|
throw new MeterError("\uAE30\uAE30 \uD1A0\uD070 \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
162
|
-
return
|
|
241
|
+
return token2;
|
|
163
242
|
}
|
|
164
243
|
const code = typeof data["error"] === "string" ? data["error"] : record(data["error"])["code"];
|
|
165
244
|
if (status !== 400) throw new ApiError(status);
|
|
@@ -167,55 +246,72 @@ async function pollToken(api, device) {
|
|
|
167
246
|
case "authorization_pending":
|
|
168
247
|
continue;
|
|
169
248
|
case "expired_token":
|
|
170
|
-
throw new MeterError(
|
|
171
|
-
"\uAE30\uAE30 \uC778\uC99D \uCF54\uB4DC\uAC00 \uB9CC\uB8CC\uB410\uC5B4\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
|
|
172
|
-
);
|
|
249
|
+
throw new MeterError(expiredCode);
|
|
173
250
|
case "invalid_grant":
|
|
174
|
-
throw new MeterError(
|
|
175
|
-
"\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 \uC778\uC99D \uCF54\uB4DC\uC608\uC694. login\uC744 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
|
|
176
|
-
);
|
|
251
|
+
throw new MeterError(invalidCode);
|
|
177
252
|
default:
|
|
178
253
|
throw new ApiError(status);
|
|
179
254
|
}
|
|
180
255
|
}
|
|
181
|
-
throw new MeterError(
|
|
182
|
-
|
|
183
|
-
|
|
256
|
+
throw new MeterError(expiredCode);
|
|
257
|
+
}
|
|
258
|
+
async function revokeDevice(api, token2) {
|
|
259
|
+
try {
|
|
260
|
+
const { status, data } = await post(api, {
|
|
261
|
+
path: "/api/meter/revoke",
|
|
262
|
+
body: {},
|
|
263
|
+
token: token2
|
|
264
|
+
});
|
|
265
|
+
if (status === 200 && data["ok"] === true) return "revoked";
|
|
266
|
+
if (status === 401 && record(data["error"])["code"] === "unauthorized")
|
|
267
|
+
return "already";
|
|
268
|
+
return "unreachable";
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error instanceof MeterError) return "unreachable";
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
184
273
|
}
|
|
185
|
-
|
|
274
|
+
function responseNumber(value) {
|
|
275
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
|
|
276
|
+
throw new MeterError("\uC0AC\uC6A9\uB7C9 \uC800\uC7A5 \uC751\uB2F5\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
277
|
+
return value;
|
|
278
|
+
}
|
|
279
|
+
async function uploadUsage(api, token2, body) {
|
|
186
280
|
let accepted = 0;
|
|
187
281
|
let weekTokens = 0;
|
|
188
282
|
let votesGranted = 0;
|
|
189
283
|
const safe = payload(body.deviceName, body.rows);
|
|
190
|
-
|
|
284
|
+
let offset = 0;
|
|
285
|
+
do {
|
|
191
286
|
const { status, data } = await post(api, {
|
|
192
287
|
path: "/api/meter/usage",
|
|
193
|
-
token,
|
|
288
|
+
token: token2,
|
|
194
289
|
body: {
|
|
195
290
|
deviceName: safe.deviceName,
|
|
196
291
|
rows: safe.rows.slice(offset, offset + 200)
|
|
197
292
|
}
|
|
198
293
|
});
|
|
294
|
+
if (status === 401 && record(data["error"])["code"] === "unauthorized")
|
|
295
|
+
throw new DisconnectedError(apiFailure(status));
|
|
199
296
|
if (status !== 200) throw new ApiError(status);
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
const a = data["accepted"];
|
|
206
|
-
const w = data["weekTokens"];
|
|
207
|
-
const v = data["votesGranted"];
|
|
208
|
-
if (typeof a === "number" && typeof w === "number" && typeof v === "number") {
|
|
209
|
-
accepted += a;
|
|
210
|
-
weekTokens = w;
|
|
211
|
-
votesGranted += v;
|
|
212
|
-
}
|
|
213
|
-
}
|
|
297
|
+
accepted += responseNumber(data["accepted"]);
|
|
298
|
+
weekTokens = responseNumber(data["weekTokens"]);
|
|
299
|
+
votesGranted += responseNumber(data["votesGranted"]);
|
|
300
|
+
offset += 200;
|
|
301
|
+
} while (offset < safe.rows.length);
|
|
214
302
|
return { accepted, weekTokens, votesGranted };
|
|
215
303
|
}
|
|
216
304
|
|
|
217
305
|
// src/config.ts
|
|
218
|
-
import {
|
|
306
|
+
import {
|
|
307
|
+
chmod,
|
|
308
|
+
mkdir,
|
|
309
|
+
readFile,
|
|
310
|
+
rename,
|
|
311
|
+
rm,
|
|
312
|
+
rmdir,
|
|
313
|
+
writeFile
|
|
314
|
+
} from "node:fs/promises";
|
|
219
315
|
import { randomUUID } from "node:crypto";
|
|
220
316
|
import { join as join2 } from "node:path";
|
|
221
317
|
function serviceUrl(value) {
|
|
@@ -223,13 +319,12 @@ function serviceUrl(value) {
|
|
|
223
319
|
try {
|
|
224
320
|
url = new URL(value);
|
|
225
321
|
} catch (error) {
|
|
226
|
-
if (error instanceof TypeError)
|
|
227
|
-
throw new MeterError("\uC11C\uBC84 URL\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
322
|
+
if (error instanceof TypeError) throw new MeterError(invalidUrl);
|
|
228
323
|
throw error;
|
|
229
324
|
}
|
|
230
325
|
const local = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
|
|
231
326
|
if (url.protocol !== "https:" && !(url.protocol === "http:" && local) || url.username || url.password || url.search || url.hash || url.pathname !== "/")
|
|
232
|
-
throw new MeterError(
|
|
327
|
+
throw new MeterError(unsafeUrl);
|
|
233
328
|
return url.origin;
|
|
234
329
|
}
|
|
235
330
|
async function readConfig(home) {
|
|
@@ -240,13 +335,12 @@ async function readConfig(home) {
|
|
|
240
335
|
)
|
|
241
336
|
);
|
|
242
337
|
if (typeof data["url"] !== "string" || typeof data["deviceToken"] !== "string" || !/^mfd_[A-Za-z0-9_-]+$/.test(data["deviceToken"]) || typeof data["deviceName"] !== "string")
|
|
243
|
-
throw new MeterError(
|
|
244
|
-
"\uC124\uC815 \uD30C\uC77C\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694. login\uC73C\uB85C \uB2E4\uC2DC \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694."
|
|
245
|
-
);
|
|
338
|
+
throw new MeterError(invalidConfig);
|
|
246
339
|
return {
|
|
247
340
|
url: serviceUrl(data["url"]),
|
|
248
341
|
deviceToken: data["deviceToken"],
|
|
249
|
-
deviceName: data["deviceName"]
|
|
342
|
+
deviceName: data["deviceName"],
|
|
343
|
+
...data["auto"] === "on" || data["auto"] === "off" ? { auto: data["auto"] } : {}
|
|
250
344
|
};
|
|
251
345
|
} catch (error) {
|
|
252
346
|
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
@@ -255,22 +349,29 @@ async function readConfig(home) {
|
|
|
255
349
|
}
|
|
256
350
|
}
|
|
257
351
|
async function saveConfig(home, config) {
|
|
258
|
-
const
|
|
259
|
-
await mkdir(
|
|
260
|
-
const temporary = join2(
|
|
352
|
+
const directory2 = join2(home, ".config/madefeed");
|
|
353
|
+
await mkdir(directory2, { recursive: true, mode: 448 });
|
|
354
|
+
const temporary = join2(directory2, `cli-${randomUUID()}.tmp`);
|
|
261
355
|
try {
|
|
262
356
|
await writeFile(temporary, JSON.stringify(config), {
|
|
263
357
|
mode: 384,
|
|
264
358
|
flag: "wx"
|
|
265
359
|
});
|
|
266
360
|
await chmod(temporary, 384);
|
|
267
|
-
await rename(temporary, join2(
|
|
361
|
+
await rename(temporary, join2(directory2, "cli.json"));
|
|
268
362
|
} finally {
|
|
269
363
|
await rm(temporary, { force: true });
|
|
270
364
|
}
|
|
271
365
|
}
|
|
272
366
|
async function logout(home) {
|
|
273
367
|
await rm(join2(home, ".config/madefeed/cli.json"), { force: true });
|
|
368
|
+
try {
|
|
369
|
+
await rmdir(join2(home, ".config/madefeed"));
|
|
370
|
+
} catch (error) {
|
|
371
|
+
if (error instanceof Error && "code" in error && (error.code === "ENOTEMPTY" || error.code === "EEXIST" || error.code === "ENOENT"))
|
|
372
|
+
return;
|
|
373
|
+
throw error;
|
|
374
|
+
}
|
|
274
375
|
}
|
|
275
376
|
|
|
276
377
|
// src/kst.ts
|
|
@@ -288,21 +389,23 @@ import { join as join3 } from "node:path";
|
|
|
288
389
|
async function readClaude(options) {
|
|
289
390
|
const messages = /* @__PURE__ */ new Map();
|
|
290
391
|
try {
|
|
291
|
-
|
|
392
|
+
const root = join3(options.home, ".claude/projects");
|
|
393
|
+
if (!await directory(root)) return { supported: true, rows: [] };
|
|
394
|
+
for await (const path of files(root)) {
|
|
292
395
|
if (!path.endsWith(".jsonl") || !await recentFile(path, options.sinceMs))
|
|
293
396
|
continue;
|
|
294
397
|
for await (const value of jsonLines(path)) {
|
|
295
|
-
const
|
|
296
|
-
if (
|
|
297
|
-
const message = record(
|
|
298
|
-
const ms = timestamp(
|
|
398
|
+
const event2 = record(value);
|
|
399
|
+
if (event2["type"] !== "assistant") continue;
|
|
400
|
+
const message = record(event2["message"]);
|
|
401
|
+
const ms = timestamp(event2["timestamp"]);
|
|
299
402
|
if (!Number.isFinite(ms) || ms < options.sinceMs || message["model"] === "<synthetic>")
|
|
300
403
|
continue;
|
|
301
|
-
if (typeof message["id"] !== "string" || typeof
|
|
404
|
+
if (typeof message["id"] !== "string" || typeof event2["requestId"] !== "string")
|
|
302
405
|
continue;
|
|
303
|
-
const
|
|
304
|
-
const tokens = count(
|
|
305
|
-
const key = JSON.stringify([message["id"],
|
|
406
|
+
const usage = record(message["usage"]);
|
|
407
|
+
const tokens = count(usage["input_tokens"]) + count(usage["output_tokens"]) + count(usage["cache_creation_input_tokens"]) + count(usage["cache_read_input_tokens"]);
|
|
408
|
+
const key = JSON.stringify([message["id"], event2["requestId"]]);
|
|
306
409
|
if (tokens > (messages.get(key)?.tokens ?? -1))
|
|
307
410
|
messages.set(key, {
|
|
308
411
|
date: kstDateOf(ms),
|
|
@@ -316,7 +419,7 @@ async function readClaude(options) {
|
|
|
316
419
|
} catch (error) {
|
|
317
420
|
return unsupported(
|
|
318
421
|
error,
|
|
319
|
-
"Claude Code \
|
|
422
|
+
"Claude Code \uAE30\uB85D\uC744 \uC77D\uC9C0 \uBABB\uD574 \uC774\uBC88\uC5D0\uB294 \uBE7C\uACE0 \uC62C\uB824\uC694."
|
|
320
423
|
);
|
|
321
424
|
}
|
|
322
425
|
}
|
|
@@ -326,19 +429,21 @@ import { join as join4, basename } from "node:path";
|
|
|
326
429
|
async function readCodex(options) {
|
|
327
430
|
const rows = [];
|
|
328
431
|
try {
|
|
329
|
-
|
|
432
|
+
const root = join4(options.home, ".codex/sessions");
|
|
433
|
+
if (!await directory(root)) return { supported: true, rows: [] };
|
|
434
|
+
for await (const path of files(root)) {
|
|
330
435
|
if (!basename(path).startsWith("rollout-") || !path.endsWith(".jsonl") || !await recentFile(path, options.sinceMs))
|
|
331
436
|
continue;
|
|
332
437
|
let model = "unknown";
|
|
333
438
|
let previous = 0;
|
|
334
439
|
for await (const value of jsonLines(path)) {
|
|
335
|
-
const
|
|
336
|
-
const data = record(
|
|
337
|
-
if (
|
|
440
|
+
const event2 = record(value);
|
|
441
|
+
const data = record(event2["payload"]);
|
|
442
|
+
if (event2["type"] === "turn_context") {
|
|
338
443
|
model = modelName(data["model"]);
|
|
339
444
|
continue;
|
|
340
445
|
}
|
|
341
|
-
if (
|
|
446
|
+
if (event2["type"] !== "event_msg" || data["type"] !== "token_count")
|
|
342
447
|
continue;
|
|
343
448
|
const info = record(data["info"]);
|
|
344
449
|
const total = record(info["total_token_usage"])["total_tokens"];
|
|
@@ -346,7 +451,7 @@ async function readCodex(options) {
|
|
|
346
451
|
continue;
|
|
347
452
|
const delta = total >= previous ? total - previous : count(record(info["last_token_usage"])["total_tokens"]);
|
|
348
453
|
previous = total;
|
|
349
|
-
const ms = timestamp(
|
|
454
|
+
const ms = timestamp(event2["timestamp"]);
|
|
350
455
|
if (Number.isFinite(ms) && ms >= options.sinceMs && delta > 0)
|
|
351
456
|
rows.push({
|
|
352
457
|
date: kstDateOf(ms),
|
|
@@ -358,147 +463,859 @@ async function readCodex(options) {
|
|
|
358
463
|
}
|
|
359
464
|
return { supported: true, rows };
|
|
360
465
|
} catch (error) {
|
|
361
|
-
return unsupported(
|
|
362
|
-
error,
|
|
363
|
-
"Codex \uB85C\uADF8\uB97C \uC77D\uC744 \uC218 \uC5C6\uC5B4 unsupported\uB85C \uCC98\uB9AC\uD574\uC694."
|
|
364
|
-
);
|
|
466
|
+
return unsupported(error, "Codex \uAE30\uB85D\uC744 \uC77D\uC9C0 \uBABB\uD574 \uC774\uBC88\uC5D0\uB294 \uBE7C\uACE0 \uC62C\uB824\uC694.");
|
|
365
467
|
}
|
|
366
468
|
}
|
|
367
469
|
|
|
368
470
|
// src/sources/opencode.ts
|
|
369
|
-
import { readFile as readFile2 } from "node:fs/promises";
|
|
370
|
-
import { join as join5 } from "node:path";
|
|
471
|
+
import { readFile as readFile2, readdir as readdir2, stat as stat2 } from "node:fs/promises";
|
|
472
|
+
import { basename as basename2, isAbsolute, join as join5 } from "node:path";
|
|
371
473
|
import { Worker } from "node:worker_threads";
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
);
|
|
474
|
+
|
|
475
|
+
// src/sources/opencode-db.ts
|
|
476
|
+
function databaseWorker(input) {
|
|
376
477
|
try {
|
|
377
|
-
const
|
|
378
|
-
|
|
379
|
-
const db = new sqlite.DatabaseSync(workerData.path, { readOnly: true });
|
|
478
|
+
const { DatabaseSync } = process.getBuiltinModule("node:sqlite");
|
|
479
|
+
const db = new DatabaseSync(input.path, { readOnly: true });
|
|
380
480
|
try {
|
|
381
481
|
db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=200");
|
|
382
|
-
const
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
)
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
482
|
+
const exists = (table) => Boolean(
|
|
483
|
+
db.prepare(
|
|
484
|
+
"SELECT 1 FROM sqlite_master WHERE type='table' AND name=?"
|
|
485
|
+
).get(table)
|
|
486
|
+
);
|
|
487
|
+
const columns = (table) => new Set(
|
|
488
|
+
db.prepare(`PRAGMA table_info(${table})`).all().map((row) => row["name"])
|
|
489
|
+
);
|
|
490
|
+
const number = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
|
|
491
|
+
const ids = /* @__PURE__ */ new Set();
|
|
492
|
+
const excluded = new Set(input.excludedIds);
|
|
493
|
+
const totals = /* @__PURE__ */ new Map();
|
|
494
|
+
const numeric = (path) => `CASE WHEN json_type(m.data,'${path}') IN ('integer','real') THEN json_extract(m.data,'${path}') ELSE 0 END`;
|
|
495
|
+
const projection = (model) => `coalesce(json_extract(m.data,'$.time.created'),m.time_created) AS ms,
|
|
496
|
+
${model} AS model, json_type(m.data,'$.tokens') AS token_type,
|
|
497
|
+
${numeric("$.tokens.total")} AS total,
|
|
498
|
+
${numeric("$.tokens.input")} AS input,
|
|
499
|
+
${numeric("$.tokens.output")} AS output,
|
|
500
|
+
${numeric("$.tokens.reasoning")} AS reasoning,
|
|
501
|
+
${numeric("$.tokens.cache.read")} AS cache_read,
|
|
502
|
+
${numeric("$.tokens.cache.write")} AS cache_write`;
|
|
503
|
+
const add = (row) => {
|
|
504
|
+
const ms = row["ms"];
|
|
505
|
+
const model = row["model"];
|
|
506
|
+
const id = row["id"];
|
|
507
|
+
if (typeof id === "string" && (excluded.has(id) || ids.has(id))) return;
|
|
508
|
+
if (typeof ms !== "number" || !Number.isFinite(ms) || ms < input.sinceMs || typeof model !== "string" || row["token_type"] !== "object")
|
|
509
|
+
return;
|
|
510
|
+
const parts = [
|
|
511
|
+
"input",
|
|
512
|
+
"output",
|
|
513
|
+
"reasoning",
|
|
514
|
+
"cache_read",
|
|
515
|
+
"cache_write"
|
|
516
|
+
].reduce((sum, key2) => sum + number(row[key2]), 0);
|
|
517
|
+
const tokens = Math.max(parts, number(row["total"]));
|
|
518
|
+
if (tokens === 0) return;
|
|
519
|
+
const date = new Date(ms + 324e5).toISOString().slice(0, 10);
|
|
520
|
+
const key = JSON.stringify([date, model]);
|
|
521
|
+
const previous = totals.get(key);
|
|
522
|
+
totals.set(key, [date, model, (previous?.[2] ?? 0) + tokens]);
|
|
523
|
+
if (typeof id === "string") ids.add(id);
|
|
524
|
+
};
|
|
525
|
+
const since = input.sinceMs - 864e5;
|
|
526
|
+
const hasMessage = exists("message");
|
|
527
|
+
const hasV2 = exists("session_message");
|
|
528
|
+
const hasId = hasMessage && columns("message").has("id");
|
|
529
|
+
if (hasMessage) {
|
|
530
|
+
const fields = `${hasId ? "m.id" : "NULL AS id"}, ${projection("json_extract(m.data,'$.modelID')")}`;
|
|
531
|
+
let statement;
|
|
532
|
+
try {
|
|
533
|
+
statement = db.prepare(
|
|
534
|
+
`SELECT ${fields} FROM session s CROSS JOIN message m ON m.session_id=s.id AND m.time_created >= ?`
|
|
535
|
+
);
|
|
536
|
+
} catch (error) {
|
|
537
|
+
if (!(error instanceof Error)) throw error;
|
|
538
|
+
statement = db.prepare(
|
|
539
|
+
`SELECT ${fields} FROM message m WHERE m.time_created >= ?`
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
for (const row of statement.iterate(since)) add(row);
|
|
392
543
|
}
|
|
393
|
-
|
|
544
|
+
if (hasV2) {
|
|
545
|
+
const cutoffs = /* @__PURE__ */ new Map();
|
|
546
|
+
if (exists("session_v2") && ["id", "fork_session_id", "fork_boundary"].every(
|
|
547
|
+
(key) => columns("session_v2").has(key)
|
|
548
|
+
)) {
|
|
549
|
+
const boundaryRow = db.prepare(
|
|
550
|
+
"SELECT seq FROM session_message WHERE session_id=? AND id=?"
|
|
551
|
+
);
|
|
552
|
+
const before = db.prepare(
|
|
553
|
+
"SELECT MAX(seq) AS seq FROM session_message WHERE session_id=? AND seq<?"
|
|
554
|
+
);
|
|
555
|
+
for (const fork of db.prepare(
|
|
556
|
+
"SELECT id,fork_session_id,fork_boundary FROM session_v2 WHERE fork_session_id IS NOT NULL AND fork_boundary IS NOT NULL"
|
|
557
|
+
).iterate()) {
|
|
558
|
+
if (typeof fork["fork_boundary"] !== "string" || typeof fork["id"] !== "string" || typeof fork["fork_session_id"] !== "string")
|
|
559
|
+
continue;
|
|
560
|
+
let boundary;
|
|
561
|
+
try {
|
|
562
|
+
boundary = JSON.parse(fork["fork_boundary"]);
|
|
563
|
+
} catch (error) {
|
|
564
|
+
if (error instanceof SyntaxError) continue;
|
|
565
|
+
throw error;
|
|
566
|
+
}
|
|
567
|
+
if (typeof boundary !== "object" || boundary === null || !("messageID" in boundary) || typeof boundary.messageID !== "string" || !("type" in boundary))
|
|
568
|
+
continue;
|
|
569
|
+
const seq = boundaryRow.get(
|
|
570
|
+
fork["fork_session_id"],
|
|
571
|
+
boundary.messageID
|
|
572
|
+
)?.["seq"];
|
|
573
|
+
if (typeof seq !== "number") continue;
|
|
574
|
+
let cutoff;
|
|
575
|
+
switch (boundary.type) {
|
|
576
|
+
case "through":
|
|
577
|
+
cutoff = seq;
|
|
578
|
+
break;
|
|
579
|
+
case "before":
|
|
580
|
+
cutoff = before.get(fork["fork_session_id"], seq)?.["seq"];
|
|
581
|
+
break;
|
|
582
|
+
default:
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
if (typeof cutoff === "number") cutoffs.set(fork["id"], cutoff);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
const model = "coalesce(json_extract(m.data,'$.model.id'),json_extract(m.data,'$.model.modelID'),json_extract(m.data,'$.modelID'))";
|
|
589
|
+
const statement = db.prepare(
|
|
590
|
+
`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 >= ?`
|
|
591
|
+
);
|
|
592
|
+
for (const row of statement.iterate(since)) {
|
|
593
|
+
if (row["type"] !== "assistant" && !(row["type"] === "compaction" && row["status"] === "completed"))
|
|
594
|
+
continue;
|
|
595
|
+
const cutoff = typeof row["session_id"] === "string" ? cutoffs.get(row["session_id"]) : void 0;
|
|
596
|
+
if (cutoff !== void 0 && typeof row["seq"] === "number" && row["seq"] <= cutoff)
|
|
597
|
+
continue;
|
|
598
|
+
add(row);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
const lookups = [
|
|
602
|
+
...hasId ? [db.prepare("SELECT 1 FROM message WHERE id=?")] : [],
|
|
603
|
+
...hasV2 ? [db.prepare("SELECT 1 FROM session_message WHERE id=?")] : []
|
|
604
|
+
];
|
|
605
|
+
for (const id of input.legacyIds)
|
|
606
|
+
if (lookups.some((statement) => statement.get(id))) ids.add(id);
|
|
607
|
+
return { totals: [...totals.values()], knownIds: [...ids] };
|
|
394
608
|
} finally {
|
|
395
609
|
db.close();
|
|
396
610
|
}
|
|
397
611
|
} catch (error) {
|
|
398
|
-
if (error instanceof Error)
|
|
399
|
-
|
|
612
|
+
if (error instanceof Error) return { error: true };
|
|
613
|
+
throw error;
|
|
400
614
|
}
|
|
401
615
|
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
616
|
+
|
|
617
|
+
// src/sources/opencode.ts
|
|
618
|
+
var failure = "OpenCode \uAE30\uB85D\uC744 \uC81C\uD55C \uC2DC\uAC04 \uC548\uC5D0 \uC77D\uC9C0 \uBABB\uD574 \uC774\uBC88\uC5D0\uB294 \uBE7C\uACE0 \uC62C\uB824\uC694.";
|
|
619
|
+
async function databaseRows(input) {
|
|
620
|
+
const worker = new Worker(
|
|
621
|
+
`const {parentPort,workerData}=require('node:worker_threads'); parentPort.postMessage((${databaseWorker.toString()})(workerData))`,
|
|
622
|
+
{
|
|
623
|
+
eval: true,
|
|
624
|
+
workerData: input
|
|
408
625
|
}
|
|
409
|
-
|
|
626
|
+
);
|
|
410
627
|
try {
|
|
411
|
-
return await new Promise((
|
|
412
|
-
const timer = setTimeout(
|
|
413
|
-
() => reject(new MeterError("OpenCode DB \uC2DC\uAC04 \uC608\uC0B0\uC744 \uCD08\uACFC\uD574\uC694.")),
|
|
414
|
-
2500
|
|
415
|
-
);
|
|
628
|
+
return await new Promise((resolve2, reject) => {
|
|
416
629
|
const fail = () => {
|
|
417
|
-
clearTimeout(
|
|
418
|
-
reject(new MeterError(
|
|
630
|
+
clearTimeout(timer2);
|
|
631
|
+
reject(new MeterError(failure));
|
|
419
632
|
};
|
|
633
|
+
const timer2 = setTimeout(fail, 45e3);
|
|
420
634
|
worker.once("error", fail);
|
|
421
635
|
worker.once("exit", fail);
|
|
422
636
|
worker.once("message", (value) => {
|
|
423
|
-
clearTimeout(
|
|
424
|
-
|
|
425
|
-
if (Array.isArray(rows)) resolve(rows);
|
|
426
|
-
else fail();
|
|
637
|
+
clearTimeout(timer2);
|
|
638
|
+
resolve2(value);
|
|
427
639
|
});
|
|
428
640
|
});
|
|
429
641
|
} finally {
|
|
430
642
|
await worker.terminate();
|
|
431
643
|
}
|
|
432
644
|
}
|
|
433
|
-
function
|
|
434
|
-
const
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
const
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
tokens
|
|
445
|
-
|
|
645
|
+
async function legacyRows(root, options) {
|
|
646
|
+
const rows = /* @__PURE__ */ new Map();
|
|
647
|
+
const storage = join5(root, "storage/message");
|
|
648
|
+
if (!await directory(storage)) return rows;
|
|
649
|
+
for await (const path of files(storage)) {
|
|
650
|
+
if (!path.endsWith(".json") || (await stat2(path)).mtimeMs < options.sinceMs)
|
|
651
|
+
continue;
|
|
652
|
+
const data = record(parseJson(await readFile2(path, "utf8")));
|
|
653
|
+
const ms = timestamp(record(data["time"])["created"]);
|
|
654
|
+
if (!Number.isFinite(ms) || ms < options.sinceMs || typeof data["modelID"] !== "string")
|
|
655
|
+
continue;
|
|
656
|
+
const raw = data["tokens"];
|
|
657
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) continue;
|
|
658
|
+
const tokens = record(raw);
|
|
659
|
+
const cache = record(tokens["cache"]);
|
|
660
|
+
const sum = Math.max(
|
|
661
|
+
count(tokens["total"]),
|
|
662
|
+
count(tokens["input"]) + count(tokens["output"]) + count(tokens["reasoning"]) + count(cache["read"]) + count(cache["write"])
|
|
663
|
+
);
|
|
664
|
+
if (sum === 0) continue;
|
|
665
|
+
const id = typeof data["id"] === "string" ? data["id"] : basename2(path, ".json");
|
|
666
|
+
rows.set(id, {
|
|
667
|
+
date: kstDateOf(ms),
|
|
668
|
+
tool: "opencode",
|
|
669
|
+
model: modelName(data["modelID"]),
|
|
670
|
+
tokens: sum
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
return rows;
|
|
446
674
|
}
|
|
447
675
|
async function readOpenCode(options) {
|
|
448
676
|
try {
|
|
677
|
+
const env = options.env ?? {};
|
|
678
|
+
const custom = env["OPENCODE_DATA_DIR"];
|
|
679
|
+
const xdg = env["XDG_DATA_HOME"];
|
|
680
|
+
const roots = custom !== void 0 ? custom.split(",") : [
|
|
681
|
+
xdg && isAbsolute(xdg) ? join5(xdg, "opencode") : join5(options.home, ".local/share/opencode")
|
|
682
|
+
];
|
|
449
683
|
const rows = [];
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
const
|
|
455
|
-
|
|
684
|
+
const seen = /* @__PURE__ */ new Set();
|
|
685
|
+
for (const root of roots) {
|
|
686
|
+
if (!root || !await directory(root)) continue;
|
|
687
|
+
const legacy = await legacyRows(root, options);
|
|
688
|
+
const entries = await readdir2(root, { withFileTypes: true });
|
|
689
|
+
const names = entries.filter((entry) => entry.isFile()).map((entry) => entry.name);
|
|
690
|
+
const db = names.includes("opencode.db") ? "opencode.db" : names.filter((name) => /^opencode-.*\.db$/.test(name)).sort()[0];
|
|
691
|
+
if (db) {
|
|
692
|
+
const result = await databaseRows({
|
|
693
|
+
path: join5(root, db),
|
|
694
|
+
sinceMs: options.sinceMs,
|
|
695
|
+
legacyIds: [...legacy.keys()],
|
|
696
|
+
excludedIds: [...seen]
|
|
697
|
+
});
|
|
698
|
+
if ("error" in result)
|
|
699
|
+
return { supported: false, reason: failure, rows: [] };
|
|
700
|
+
rows.push(
|
|
701
|
+
...result.totals.map(([date, model, tokens]) => ({
|
|
702
|
+
date,
|
|
703
|
+
tool: "opencode",
|
|
704
|
+
model: modelName(model),
|
|
705
|
+
tokens
|
|
706
|
+
}))
|
|
707
|
+
);
|
|
708
|
+
for (const id of result.knownIds) seen.add(id);
|
|
709
|
+
}
|
|
710
|
+
for (const [id, row] of legacy) {
|
|
711
|
+
if (seen.has(id)) continue;
|
|
712
|
+
rows.push(row);
|
|
713
|
+
seen.add(id);
|
|
714
|
+
}
|
|
456
715
|
}
|
|
457
716
|
return { supported: true, rows };
|
|
458
717
|
} catch (error) {
|
|
459
|
-
|
|
718
|
+
return unsupported(error, failure);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// src/sources/gemini.ts
|
|
723
|
+
import { readFile as readFile3, stat as stat3 } from "node:fs/promises";
|
|
724
|
+
import { join as join6 } from "node:path";
|
|
725
|
+
function text(value) {
|
|
726
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
727
|
+
}
|
|
728
|
+
function time(value, fallback) {
|
|
729
|
+
const ms = typeof value === "string" ? timestamp(value) : NaN;
|
|
730
|
+
return Number.isFinite(ms) ? ms : fallback;
|
|
731
|
+
}
|
|
732
|
+
function token(value) {
|
|
733
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.trunc(Math.max(0, value)) : void 0;
|
|
734
|
+
}
|
|
735
|
+
function event(raw, context) {
|
|
736
|
+
const data = record(raw);
|
|
737
|
+
const model = text(data["model"]) ?? context.model;
|
|
738
|
+
const rawTokens = data["tokens"];
|
|
739
|
+
if (!model || typeof rawTokens !== "object" || rawTokens === null || Array.isArray(rawTokens))
|
|
740
|
+
return void 0;
|
|
741
|
+
const tokens = record(rawTokens);
|
|
742
|
+
const part = (keys) => keys.map((key) => token(tokens[key])).find((value) => value !== void 0) ?? 0;
|
|
743
|
+
const input = part(["input", "prompt", "input_tokens", "prompt_tokens"]);
|
|
744
|
+
const output = part([
|
|
745
|
+
"output",
|
|
746
|
+
"candidates",
|
|
747
|
+
"output_tokens",
|
|
748
|
+
"candidates_tokens"
|
|
749
|
+
]);
|
|
750
|
+
const cached = part(["cached", "cached_tokens"]);
|
|
751
|
+
const thoughts = part([
|
|
752
|
+
"thoughts",
|
|
753
|
+
"reasoning",
|
|
754
|
+
"thoughts_tokens",
|
|
755
|
+
"reasoning_tokens"
|
|
756
|
+
]);
|
|
757
|
+
const tool = part(["tool", "tool_tokens"]);
|
|
758
|
+
const total = token(
|
|
759
|
+
Object.hasOwn(tokens, "total") ? tokens["total"] : tokens["total_tokens"]
|
|
760
|
+
);
|
|
761
|
+
const inclusive = input + output + thoughts + tool;
|
|
762
|
+
const net = context.stats || cached > 0 && total === inclusive ? input - Math.min(input, cached) : input;
|
|
763
|
+
const sum = Math.max(net + output + cached + thoughts + tool, total ?? 0);
|
|
764
|
+
if (sum === 0) return void 0;
|
|
765
|
+
return {
|
|
766
|
+
model,
|
|
767
|
+
tokens: sum,
|
|
768
|
+
ms: time(data["timestamp"], time(data["created_at"], context.ms))
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
function statsEvents(data, context) {
|
|
772
|
+
const stats = record(
|
|
773
|
+
Object.hasOwn(data, "stats") ? data["stats"] : record(data["result"])["stats"]
|
|
774
|
+
);
|
|
775
|
+
const events = [];
|
|
776
|
+
for (const [model, value] of Object.entries(record(stats["models"]))) {
|
|
777
|
+
const parsed2 = event(
|
|
778
|
+
{ model, tokens: record(value)["tokens"] },
|
|
779
|
+
{ ...context, stats: true }
|
|
780
|
+
);
|
|
781
|
+
if (parsed2) events.push(parsed2);
|
|
782
|
+
}
|
|
783
|
+
if (events.length) return events;
|
|
784
|
+
const parsed = event(
|
|
785
|
+
{ model: context.model ?? "unknown", tokens: stats },
|
|
786
|
+
{ ...context, stats: true }
|
|
787
|
+
);
|
|
788
|
+
return parsed ? [parsed] : [];
|
|
789
|
+
}
|
|
790
|
+
function jsonEvents(value, mtime) {
|
|
791
|
+
const data = record(value);
|
|
792
|
+
if (Array.isArray(data["messages"])) {
|
|
793
|
+
const context = {
|
|
794
|
+
ms: time(data["startTime"], time(data["lastUpdated"], mtime)),
|
|
795
|
+
stats: false
|
|
796
|
+
};
|
|
797
|
+
return data["messages"].flatMap((value2) => {
|
|
798
|
+
const message = record(value2);
|
|
799
|
+
const parsed = message["type"] === "gemini" ? event(message, context) : void 0;
|
|
800
|
+
return parsed ? [parsed] : [];
|
|
801
|
+
});
|
|
460
802
|
}
|
|
803
|
+
if (data["type"] === "gemini") {
|
|
804
|
+
const parsed = event(data, { ms: mtime, stats: false });
|
|
805
|
+
return parsed ? [parsed] : [];
|
|
806
|
+
}
|
|
807
|
+
const model = text(data["model"]);
|
|
808
|
+
return statsEvents(data, {
|
|
809
|
+
...model ? { model } : {},
|
|
810
|
+
ms: time(data["timestamp"], mtime),
|
|
811
|
+
stats: true
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
async function jsonlEvents(path, mtime) {
|
|
815
|
+
const events = [];
|
|
816
|
+
const ids = /* @__PURE__ */ new Map();
|
|
817
|
+
let model;
|
|
818
|
+
for await (const value of jsonLines(path)) {
|
|
819
|
+
const data = record(value);
|
|
820
|
+
model = text(data["model"]) ?? model;
|
|
821
|
+
const context = { ...model ? { model } : {}, ms: mtime, stats: false };
|
|
822
|
+
if (data["type"] === "gemini") {
|
|
823
|
+
const parsed = event(data, context);
|
|
824
|
+
if (!parsed) continue;
|
|
825
|
+
const id = text(data["id"]);
|
|
826
|
+
const previous = id ? ids.get(id) : void 0;
|
|
827
|
+
if (previous !== void 0) events[previous] = parsed;
|
|
828
|
+
else {
|
|
829
|
+
if (id) ids.set(id, events.length);
|
|
830
|
+
events.push(parsed);
|
|
831
|
+
}
|
|
832
|
+
} else
|
|
833
|
+
events.push(
|
|
834
|
+
...statsEvents(data, {
|
|
835
|
+
...context,
|
|
836
|
+
ms: time(data["timestamp"], mtime)
|
|
837
|
+
})
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
return events;
|
|
841
|
+
}
|
|
842
|
+
async function readGemini(options) {
|
|
843
|
+
const custom = options.env?.["GEMINI_DATA_DIR"];
|
|
844
|
+
const roots = custom !== void 0 ? custom.split(",") : [join6(options.home, ".gemini/tmp")];
|
|
845
|
+
const rows = [];
|
|
846
|
+
for (const root of roots) {
|
|
847
|
+
if (!root) continue;
|
|
848
|
+
try {
|
|
849
|
+
for await (const path of files(root)) {
|
|
850
|
+
if (!path.endsWith(".json") && !path.endsWith(".jsonl")) continue;
|
|
851
|
+
try {
|
|
852
|
+
const mtime = (await stat3(path)).mtimeMs;
|
|
853
|
+
if (mtime < options.sinceMs) continue;
|
|
854
|
+
const events = path.endsWith(".jsonl") ? await jsonlEvents(path, mtime) : jsonEvents(parseJson(await readFile3(path, "utf8")), mtime);
|
|
855
|
+
for (const event2 of events)
|
|
856
|
+
if (event2.ms >= options.sinceMs)
|
|
857
|
+
rows.push({
|
|
858
|
+
date: kstDateOf(event2.ms),
|
|
859
|
+
tool: "gemini",
|
|
860
|
+
model: modelName(event2.model),
|
|
861
|
+
tokens: event2.tokens
|
|
862
|
+
});
|
|
863
|
+
} catch (error) {
|
|
864
|
+
if (!(error instanceof Error)) throw error;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
} catch (error) {
|
|
868
|
+
if (!(error instanceof Error)) throw error;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
return { supported: true, rows };
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// src/agent.ts
|
|
875
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
876
|
+
import { chmod as chmod2, mkdir as mkdir2, open, realpath, rename as rename2, rm as rm2 } from "node:fs/promises";
|
|
877
|
+
import { join as join7, resolve } from "node:path";
|
|
878
|
+
function agentPath(home) {
|
|
879
|
+
return join7(home, ".config/madefeed/agent/cli.mjs");
|
|
880
|
+
}
|
|
881
|
+
async function installAgent(self, home) {
|
|
882
|
+
const target = agentPath(home);
|
|
883
|
+
const source = await realpath(self);
|
|
884
|
+
if (source === resolve(target)) return target;
|
|
461
885
|
try {
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
886
|
+
if (source === await realpath(target)) return target;
|
|
887
|
+
} catch (error) {
|
|
888
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
889
|
+
throw error;
|
|
890
|
+
}
|
|
891
|
+
const directory2 = join7(home, ".config/madefeed/agent");
|
|
892
|
+
await mkdir2(directory2, { recursive: true, mode: 448 });
|
|
893
|
+
await chmod2(directory2, 448);
|
|
894
|
+
const temporary = join7(directory2, `${randomUUID2()}.tmp`);
|
|
895
|
+
try {
|
|
896
|
+
const input = await open(source, "r");
|
|
897
|
+
try {
|
|
898
|
+
const output = await open(temporary, "wx", 384);
|
|
899
|
+
try {
|
|
900
|
+
await output.writeFile(await input.readFile());
|
|
901
|
+
} finally {
|
|
902
|
+
await output.close();
|
|
903
|
+
}
|
|
904
|
+
} finally {
|
|
905
|
+
await input.close();
|
|
472
906
|
}
|
|
473
|
-
|
|
907
|
+
await rename2(temporary, target);
|
|
908
|
+
} finally {
|
|
909
|
+
await rm2(temporary, { force: true });
|
|
910
|
+
}
|
|
911
|
+
return target;
|
|
912
|
+
}
|
|
913
|
+
async function removeAgent(home) {
|
|
914
|
+
await rm2(join7(home, ".config/madefeed/agent"), {
|
|
915
|
+
recursive: true,
|
|
916
|
+
force: true
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
async function removeLog(home) {
|
|
920
|
+
await rm2(join7(home, ".config/madefeed/auto.log"), { force: true });
|
|
921
|
+
}
|
|
922
|
+
async function trimLog(home) {
|
|
923
|
+
let file;
|
|
924
|
+
try {
|
|
925
|
+
file = await open(join7(home, ".config/madefeed/auto.log"), "r+");
|
|
474
926
|
} catch (error) {
|
|
475
|
-
if (
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
927
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
928
|
+
return;
|
|
929
|
+
throw error;
|
|
930
|
+
}
|
|
931
|
+
try {
|
|
932
|
+
if ((await file.stat()).size <= 256 * 1024) return;
|
|
933
|
+
const text2 = await file.readFile("utf8");
|
|
934
|
+
const lines = text2.replace(/\n$/, "").split("\n").slice(-200).join("\n") + "\n";
|
|
935
|
+
await file.truncate(0);
|
|
936
|
+
await file.write(lines, 0, "utf8");
|
|
937
|
+
} finally {
|
|
938
|
+
await file.close();
|
|
481
939
|
}
|
|
482
940
|
}
|
|
483
941
|
|
|
484
|
-
// src/
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
942
|
+
// src/schedule.ts
|
|
943
|
+
import { mkdir as mkdir3, readFile as readFile4, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
|
|
944
|
+
import { dirname } from "node:path";
|
|
945
|
+
import { setTimeout as setTimeout3 } from "node:timers/promises";
|
|
946
|
+
|
|
947
|
+
// src/schedule-builders.ts
|
|
948
|
+
import { join as join8, win32 } from "node:path";
|
|
949
|
+
var marker = "# madefeed-meter";
|
|
950
|
+
var label = "dev.madefeed.meter";
|
|
951
|
+
var timer = "madefeed-meter.timer";
|
|
952
|
+
var environmentKeys = [
|
|
953
|
+
"OPENCODE_DATA_DIR",
|
|
954
|
+
"XDG_DATA_HOME",
|
|
955
|
+
"GEMINI_DATA_DIR",
|
|
956
|
+
"MADEFEED_URL"
|
|
957
|
+
];
|
|
958
|
+
function jobEnvironment(context) {
|
|
959
|
+
return environmentKeys.flatMap((key) => {
|
|
960
|
+
const value = context.env[key];
|
|
961
|
+
return value === void 0 ? [] : [[key, value]];
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
function schedulePaths(context) {
|
|
965
|
+
const path = context.platform === "win32" && !context.home.startsWith("/") ? win32 : { join: join8 };
|
|
966
|
+
const config = path.join(context.home, ".config", "madefeed");
|
|
967
|
+
const units = join8(context.home, ".config/systemd/user");
|
|
968
|
+
return {
|
|
969
|
+
log: path.join(config, "auto.log"),
|
|
970
|
+
plist: join8(context.home, "Library/LaunchAgents", `${label}.plist`),
|
|
971
|
+
service: join8(units, "madefeed-meter.service"),
|
|
972
|
+
timer: join8(units, timer),
|
|
973
|
+
wrapper: path.join(config, "agent", "run.cmd")
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
function jobArguments(context) {
|
|
977
|
+
return [context.node, context.agent, "upload", "--days", "3", "--scheduled"];
|
|
978
|
+
}
|
|
979
|
+
function xml(value) {
|
|
980
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
981
|
+
}
|
|
982
|
+
function buildPlist(context) {
|
|
983
|
+
const string = (value) => `<string>${xml(value)}</string>`;
|
|
984
|
+
const paths = schedulePaths(context);
|
|
985
|
+
const env = jobEnvironment(context);
|
|
986
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
987
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
988
|
+
<plist version="1.0"><dict>
|
|
989
|
+
<key>Label</key>${string(label)}
|
|
990
|
+
<key>ProgramArguments</key><array>${jobArguments(context).map(string).join("")}</array>
|
|
991
|
+
<key>StartInterval</key><integer>3600</integer>
|
|
992
|
+
<key>RunAtLoad</key><false/>
|
|
993
|
+
<key>StandardOutPath</key>${string(paths.log)}
|
|
994
|
+
<key>StandardErrorPath</key>${string(paths.log)}
|
|
995
|
+
${env.length ? `<key>EnvironmentVariables</key><dict>${env.map(([key, value]) => `<key>${xml(key)}</key>${string(value)}`).join("")}</dict>
|
|
996
|
+
` : ""}</dict></plist>
|
|
997
|
+
`;
|
|
998
|
+
}
|
|
999
|
+
function shellQuote(value) {
|
|
1000
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
1001
|
+
}
|
|
1002
|
+
function unitQuote(value) {
|
|
1003
|
+
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll("%", "%%")}"`;
|
|
1004
|
+
}
|
|
1005
|
+
function buildService(context) {
|
|
1006
|
+
const log = schedulePaths(context).log.replaceAll("%", "%%");
|
|
1007
|
+
const env = jobEnvironment(context).map(([key, value]) => `Environment=${unitQuote(`${key}=${value}`)}
|
|
1008
|
+
`).join("");
|
|
1009
|
+
return `[Unit]
|
|
1010
|
+
Description=MadeFeed Meter
|
|
1011
|
+
[Service]
|
|
1012
|
+
Type=oneshot
|
|
1013
|
+
${env}ExecStart=${jobArguments(
|
|
1014
|
+
context
|
|
1015
|
+
).map((arg) => unitQuote(arg).replaceAll("$", "$$")).join(" ")}
|
|
1016
|
+
StandardOutput=append:${log}
|
|
1017
|
+
StandardError=append:${log}
|
|
1018
|
+
`;
|
|
1019
|
+
}
|
|
1020
|
+
function buildTimer() {
|
|
1021
|
+
return "[Unit]\nDescription=MadeFeed Meter hourly upload\n[Timer]\nOnCalendar=hourly\nPersistent=true\nRandomizedDelaySec=300\n[Install]\nWantedBy=timers.target\n";
|
|
1022
|
+
}
|
|
1023
|
+
function buildCron(context) {
|
|
1024
|
+
const minute = Array.from(context.home).reduce(
|
|
1025
|
+
(hash, char) => (hash * 31 + (char.codePointAt(0) ?? 0)) % 60,
|
|
1026
|
+
0
|
|
1027
|
+
);
|
|
1028
|
+
const env = jobEnvironment(context).map(([key, value]) => `${key}=${shellQuote(value)} `).join("");
|
|
1029
|
+
const command = `${env}${jobArguments(context).map(shellQuote).join(" ")} >> ${shellQuote(schedulePaths(context).log)} 2>&1`;
|
|
1030
|
+
return `${minute} * * * * ${command.replaceAll("%", "\\%")} ${marker}`;
|
|
1031
|
+
}
|
|
1032
|
+
function withoutMarker(text2) {
|
|
1033
|
+
return text2.split("\n").filter((line) => !line.trimEnd().endsWith(marker)).join("\n");
|
|
1034
|
+
}
|
|
1035
|
+
function cmdQuote(value) {
|
|
1036
|
+
return `"${value.replaceAll("%", "%%").replaceAll('"', '"^""')}"`;
|
|
1037
|
+
}
|
|
1038
|
+
function buildWrapper(context) {
|
|
1039
|
+
const env = jobEnvironment(context).map(([key, value]) => `set ${cmdQuote(`${key}=${value}`)}\r
|
|
1040
|
+
`).join("");
|
|
1041
|
+
return `@echo off\r
|
|
1042
|
+
setlocal DisableDelayedExpansion\r
|
|
1043
|
+
chcp 65001 >nul\r
|
|
1044
|
+
${env}${jobArguments(context).map(cmdQuote).join(" ")} >> ${cmdQuote(schedulePaths(context).log)} 2>&1\r
|
|
1045
|
+
`;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// src/schedule.ts
|
|
1049
|
+
async function fileText(path) {
|
|
1050
|
+
try {
|
|
1051
|
+
return await readFile4(path, "utf8");
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
1054
|
+
return void 0;
|
|
1055
|
+
throw error;
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
async function succeeds(context, file, args) {
|
|
1059
|
+
if (!context.exec) return false;
|
|
1060
|
+
try {
|
|
1061
|
+
await context.exec(file, args);
|
|
1062
|
+
return true;
|
|
1063
|
+
} catch (error) {
|
|
1064
|
+
if (error instanceof Error) return false;
|
|
1065
|
+
throw error;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
async function write(path, text2) {
|
|
1069
|
+
await mkdir3(dirname(path), { recursive: true, mode: 448 });
|
|
1070
|
+
await writeFile2(path, text2, { mode: 384 });
|
|
1071
|
+
}
|
|
1072
|
+
async function crontab(context) {
|
|
1073
|
+
if (!context.exec) return "";
|
|
1074
|
+
try {
|
|
1075
|
+
return (await context.exec("crontab", ["-l"])).stdout;
|
|
1076
|
+
} catch (error) {
|
|
1077
|
+
if (error instanceof Error) return "";
|
|
1078
|
+
throw error;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
async function installSchedule(context) {
|
|
1082
|
+
const paths = schedulePaths(context);
|
|
1083
|
+
if (!context.exec) return { enabled: false, kind: "none", supported: false };
|
|
1084
|
+
switch (context.platform) {
|
|
1085
|
+
case "darwin": {
|
|
1086
|
+
if (context.uid === void 0)
|
|
1087
|
+
throw new MeterError("\uC0AC\uC6A9\uC790 \uC2A4\uCF00\uC904\uB7EC\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC5B4\uC694.");
|
|
1088
|
+
const domain = `gui/${context.uid}`;
|
|
1089
|
+
const service = `${domain}/${label}`;
|
|
1090
|
+
const plist = buildPlist(context);
|
|
1091
|
+
const identical = await fileText(paths.plist) === plist;
|
|
1092
|
+
if (identical && await succeeds(context, "launchctl", ["print", service]))
|
|
1093
|
+
return { enabled: true, kind: "launchd", supported: true };
|
|
1094
|
+
await write(paths.plist, plist);
|
|
1095
|
+
await succeeds(context, "launchctl", ["bootout", service]);
|
|
1096
|
+
try {
|
|
1097
|
+
await context.exec("launchctl", ["bootstrap", domain, paths.plist]);
|
|
1098
|
+
} catch (error) {
|
|
1099
|
+
if (!(error instanceof Error)) throw error;
|
|
1100
|
+
await setTimeout3(1e3);
|
|
1101
|
+
await context.exec("launchctl", ["bootstrap", domain, paths.plist]);
|
|
1102
|
+
}
|
|
1103
|
+
return { enabled: true, kind: "launchd", supported: true };
|
|
1104
|
+
}
|
|
1105
|
+
case "linux": {
|
|
1106
|
+
await write(paths.service, buildService(context));
|
|
1107
|
+
await write(paths.timer, buildTimer());
|
|
1108
|
+
const loaded = await succeeds(context, "systemctl", [
|
|
1109
|
+
"--user",
|
|
1110
|
+
"daemon-reload"
|
|
1111
|
+
]);
|
|
1112
|
+
if (loaded && await succeeds(context, "systemctl", [
|
|
1113
|
+
"--user",
|
|
1114
|
+
"enable",
|
|
1115
|
+
"--now",
|
|
1116
|
+
timer
|
|
1117
|
+
]))
|
|
1118
|
+
return { enabled: true, kind: "systemd", supported: true };
|
|
1119
|
+
await rm3(paths.service, { force: true });
|
|
1120
|
+
await rm3(paths.timer, { force: true });
|
|
1121
|
+
const previous = withoutMarker(await crontab(context));
|
|
1122
|
+
const line = buildCron(context);
|
|
1123
|
+
if (/[\r\n]/.test(line))
|
|
1124
|
+
throw new MeterError("\uC2A4\uCF00\uC904 \uACBD\uB85C\uC5D0 \uC904\uBC14\uAFC8\uC744 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC5B4\uC694.");
|
|
1125
|
+
await context.exec("crontab", ["-"], {
|
|
1126
|
+
input: `${previous}${previous && !previous.endsWith("\n") ? "\n" : ""}${line}
|
|
1127
|
+
`
|
|
1128
|
+
});
|
|
1129
|
+
return { enabled: true, kind: "cron", supported: true };
|
|
1130
|
+
}
|
|
1131
|
+
case "win32":
|
|
1132
|
+
await write(paths.wrapper, buildWrapper(context));
|
|
1133
|
+
await context.exec("schtasks", [
|
|
1134
|
+
"/Create",
|
|
1135
|
+
"/F",
|
|
1136
|
+
"/SC",
|
|
1137
|
+
"HOURLY",
|
|
1138
|
+
"/TN",
|
|
1139
|
+
"MadeFeed Meter",
|
|
1140
|
+
"/TR",
|
|
1141
|
+
`"${paths.wrapper}"`
|
|
1142
|
+
]);
|
|
1143
|
+
return { enabled: true, kind: "schtasks", supported: true };
|
|
1144
|
+
default:
|
|
1145
|
+
return { enabled: false, kind: "none", supported: false };
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
async function removeSchedule(context) {
|
|
1149
|
+
if (!context.exec) return;
|
|
1150
|
+
const paths = schedulePaths(context);
|
|
1151
|
+
switch (context.platform) {
|
|
1152
|
+
case "darwin":
|
|
1153
|
+
await rm3(paths.plist, { force: true });
|
|
1154
|
+
await succeeds(context, "launchctl", [
|
|
1155
|
+
"bootout",
|
|
1156
|
+
`gui/${context.uid}/${label}`
|
|
1157
|
+
]);
|
|
1158
|
+
return;
|
|
1159
|
+
case "linux": {
|
|
1160
|
+
await succeeds(context, "systemctl", [
|
|
1161
|
+
"--user",
|
|
1162
|
+
"disable",
|
|
1163
|
+
"--now",
|
|
1164
|
+
timer
|
|
1165
|
+
]);
|
|
1166
|
+
await rm3(paths.service, { force: true });
|
|
1167
|
+
await rm3(paths.timer, { force: true });
|
|
1168
|
+
await succeeds(context, "systemctl", ["--user", "daemon-reload"]);
|
|
1169
|
+
const previous = await crontab(context);
|
|
1170
|
+
const remaining = withoutMarker(previous);
|
|
1171
|
+
if (remaining !== previous)
|
|
1172
|
+
await context.exec("crontab", ["-"], {
|
|
1173
|
+
input: remaining.trim() ? remaining : ""
|
|
1174
|
+
});
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
case "win32":
|
|
1178
|
+
await succeeds(context, "schtasks", [
|
|
1179
|
+
"/Delete",
|
|
1180
|
+
"/F",
|
|
1181
|
+
"/TN",
|
|
1182
|
+
"MadeFeed Meter"
|
|
1183
|
+
]);
|
|
1184
|
+
await rm3(paths.wrapper, { force: true });
|
|
1185
|
+
return;
|
|
1186
|
+
default:
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
async function scheduleStatus(context) {
|
|
1191
|
+
const paths = schedulePaths(context);
|
|
1192
|
+
switch (context.platform) {
|
|
1193
|
+
case "darwin":
|
|
1194
|
+
if (await fileText(paths.plist) !== void 0 || await succeeds(context, "launchctl", [
|
|
1195
|
+
"print",
|
|
1196
|
+
`gui/${context.uid}/${label}`
|
|
1197
|
+
]))
|
|
1198
|
+
return { enabled: true, kind: "launchd" };
|
|
1199
|
+
break;
|
|
1200
|
+
case "linux":
|
|
1201
|
+
if (await fileText(paths.timer) !== void 0 && (!context.exec || await succeeds(context, "systemctl", [
|
|
1202
|
+
"--user",
|
|
1203
|
+
"is-enabled",
|
|
1204
|
+
timer
|
|
1205
|
+
])))
|
|
1206
|
+
return { enabled: true, kind: "systemd" };
|
|
1207
|
+
if ((await crontab(context)).split("\n").some((line) => line.trimEnd().endsWith(marker)))
|
|
1208
|
+
return { enabled: true, kind: "cron" };
|
|
1209
|
+
break;
|
|
1210
|
+
case "win32":
|
|
1211
|
+
if (context.exec ? await succeeds(context, "schtasks", [
|
|
1212
|
+
"/Query",
|
|
1213
|
+
"/TN",
|
|
1214
|
+
"MadeFeed Meter"
|
|
1215
|
+
]) : await fileText(paths.wrapper) !== void 0)
|
|
1216
|
+
return { enabled: true, kind: "schtasks" };
|
|
1217
|
+
break;
|
|
1218
|
+
default:
|
|
1219
|
+
break;
|
|
1220
|
+
}
|
|
1221
|
+
return { enabled: false, kind: "none" };
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// src/auto.ts
|
|
1225
|
+
function automatic(options) {
|
|
1226
|
+
const { runtime, home, env, diagnostic } = options;
|
|
1227
|
+
const active = runtime.exec !== void 0 && runtime.self !== void 0;
|
|
1228
|
+
const context = {
|
|
1229
|
+
platform: runtime.platform ?? process.platform,
|
|
1230
|
+
home,
|
|
1231
|
+
uid: runtime.uid,
|
|
1232
|
+
node: process.execPath,
|
|
1233
|
+
agent: agentPath(home),
|
|
1234
|
+
env,
|
|
1235
|
+
...active ? { exec: runtime.exec } : {}
|
|
1236
|
+
};
|
|
1237
|
+
async function safely(action, message) {
|
|
1238
|
+
try {
|
|
1239
|
+
await action();
|
|
1240
|
+
} catch (error) {
|
|
1241
|
+
if (error instanceof Error) diagnostic(message);
|
|
1242
|
+
else throw error;
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
return {
|
|
1246
|
+
async status() {
|
|
1247
|
+
try {
|
|
1248
|
+
return await scheduleStatus(context);
|
|
1249
|
+
} catch (error) {
|
|
1250
|
+
if (!(error instanceof Error)) throw error;
|
|
1251
|
+
diagnostic(setupFailure);
|
|
1252
|
+
return { enabled: false, kind: "none" };
|
|
1253
|
+
}
|
|
1254
|
+
},
|
|
1255
|
+
async install(config) {
|
|
1256
|
+
const self = runtime.self;
|
|
1257
|
+
if (!active || !self) return;
|
|
1258
|
+
await safely(async () => {
|
|
1259
|
+
await installAgent(self, home);
|
|
1260
|
+
const result = await installSchedule(context);
|
|
1261
|
+
if (!result.supported) {
|
|
1262
|
+
diagnostic(setupFailure);
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
await saveConfig(home, { ...config, auto: "on" });
|
|
1266
|
+
if (config.auto !== "on")
|
|
1267
|
+
for (const line of autoEnabled) diagnostic(line);
|
|
1268
|
+
}, setupFailure);
|
|
1269
|
+
},
|
|
1270
|
+
async remove(scope) {
|
|
1271
|
+
const failure2 = cleanupFailure(scope);
|
|
1272
|
+
if (active) {
|
|
1273
|
+
await safely(() => removeAgent(home), failure2);
|
|
1274
|
+
await safely(() => removeLog(home), failure2);
|
|
1275
|
+
}
|
|
1276
|
+
try {
|
|
1277
|
+
if (scope === "device") await logout(home);
|
|
1278
|
+
} finally {
|
|
1279
|
+
if (active) await safely(() => removeSchedule(context), failure2);
|
|
1280
|
+
}
|
|
1281
|
+
},
|
|
1282
|
+
async trim() {
|
|
1283
|
+
await safely(() => trimLog(home), setupFailure);
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
async function autoCommand(action, config, options) {
|
|
1288
|
+
const auto = automatic(options);
|
|
1289
|
+
switch (action) {
|
|
1290
|
+
case "on":
|
|
1291
|
+
if (!config) throw new MeterError(connectionRequired);
|
|
1292
|
+
await auto.install(config);
|
|
1293
|
+
break;
|
|
1294
|
+
case "off":
|
|
1295
|
+
await auto.remove("auto");
|
|
1296
|
+
if (config) await saveConfig(options.home, { ...config, auto: "off" });
|
|
1297
|
+
break;
|
|
1298
|
+
case "status":
|
|
1299
|
+
break;
|
|
1300
|
+
default:
|
|
1301
|
+
throw new MeterError(invalidAuto);
|
|
1302
|
+
}
|
|
1303
|
+
return auto.status();
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
// src/cli-options.ts
|
|
1307
|
+
import { parseArgs } from "node:util";
|
|
1308
|
+
var VERSION = "0.3.0";
|
|
1309
|
+
var help = helpText(VERSION);
|
|
1310
|
+
function cliOptions(args) {
|
|
496
1311
|
try {
|
|
497
|
-
|
|
1312
|
+
return parseArgs({
|
|
498
1313
|
args: [...args],
|
|
499
1314
|
allowPositionals: true,
|
|
500
1315
|
options: {
|
|
501
1316
|
"dry-run": { type: "boolean" },
|
|
1317
|
+
"no-auto": { type: "boolean" },
|
|
1318
|
+
scheduled: { type: "boolean" },
|
|
502
1319
|
days: { type: "string" },
|
|
503
1320
|
url: { type: "string" },
|
|
504
1321
|
json: { type: "boolean" },
|
|
@@ -507,12 +1324,54 @@ async function runCli(args, runtime = {}) {
|
|
|
507
1324
|
}
|
|
508
1325
|
});
|
|
509
1326
|
} catch (error) {
|
|
510
|
-
if (error instanceof Error)
|
|
511
|
-
throw new MeterError(
|
|
512
|
-
"\uBA85\uB839 \uC635\uC158\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694. --help\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694."
|
|
513
|
-
);
|
|
1327
|
+
if (error instanceof Error) throw new MeterError(invalidOptions);
|
|
514
1328
|
throw error;
|
|
515
1329
|
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// src/disconnect.ts
|
|
1333
|
+
async function runLogout(session) {
|
|
1334
|
+
let config;
|
|
1335
|
+
try {
|
|
1336
|
+
config = await readConfig(session.home);
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
if (!(error instanceof Error)) throw error;
|
|
1339
|
+
}
|
|
1340
|
+
const server = config ? await revokeDevice(
|
|
1341
|
+
{ url: config.url, fetch: session.fetch },
|
|
1342
|
+
config.deviceToken
|
|
1343
|
+
) : "none";
|
|
1344
|
+
await session.auto.remove("device");
|
|
1345
|
+
let message;
|
|
1346
|
+
switch (server) {
|
|
1347
|
+
case "revoked":
|
|
1348
|
+
message = logoutRevoked;
|
|
1349
|
+
break;
|
|
1350
|
+
case "already":
|
|
1351
|
+
case "none":
|
|
1352
|
+
message = logoutLocal;
|
|
1353
|
+
break;
|
|
1354
|
+
case "unreachable":
|
|
1355
|
+
message = logoutUnreachable(config?.url ?? "");
|
|
1356
|
+
break;
|
|
1357
|
+
default: {
|
|
1358
|
+
const exhaustive = server;
|
|
1359
|
+
throw exhaustive;
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
session.output(
|
|
1363
|
+
session.json ? JSON.stringify({ loggedIn: false, server }) : message
|
|
1364
|
+
);
|
|
1365
|
+
}
|
|
1366
|
+
async function cleanDisconnected(session, options) {
|
|
1367
|
+
if (options.scheduled) session.output(scheduledDisconnected(options.now));
|
|
1368
|
+
await session.auto.remove("device");
|
|
1369
|
+
if (!options.scheduled) throw new MeterError(disconnected);
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
// src/cli.ts
|
|
1373
|
+
async function runCli(args, runtime = {}) {
|
|
1374
|
+
const parsed = cliOptions(args);
|
|
516
1375
|
const { values, positionals } = parsed;
|
|
517
1376
|
const output = runtime.output ?? console.log;
|
|
518
1377
|
const diagnostic = runtime.diagnostic ?? console.error;
|
|
@@ -521,43 +1380,81 @@ async function runCli(args, runtime = {}) {
|
|
|
521
1380
|
return;
|
|
522
1381
|
}
|
|
523
1382
|
if (values["version"]) {
|
|
524
|
-
output(
|
|
1383
|
+
output(VERSION);
|
|
525
1384
|
return;
|
|
526
1385
|
}
|
|
527
1386
|
const days = Number(values["days"] ?? 14);
|
|
528
1387
|
if (!Number.isInteger(days) || days < 1 || days > 35)
|
|
529
|
-
throw new MeterError(
|
|
1388
|
+
throw new MeterError(invalidDays);
|
|
530
1389
|
const command = positionals[0] ?? "upload";
|
|
531
|
-
if (positionals.length > 1 || !["login", "upload", "logout", "status"].includes(command))
|
|
532
|
-
throw new MeterError(
|
|
1390
|
+
if (positionals.length > (command === "auto" ? 2 : 1) || !["login", "upload", "logout", "status", "auto"].includes(command))
|
|
1391
|
+
throw new MeterError(unknownCommand);
|
|
533
1392
|
if (values["dry-run"] && command !== "upload")
|
|
534
|
-
throw new MeterError(
|
|
535
|
-
|
|
536
|
-
);
|
|
1393
|
+
throw new MeterError(invalidDryRun);
|
|
1394
|
+
if (values["scheduled"] && command !== "upload")
|
|
1395
|
+
throw new MeterError(invalidScheduled);
|
|
537
1396
|
const home = runtime.home ?? homedir();
|
|
1397
|
+
const env = runtime.env ?? process.env;
|
|
1398
|
+
const autoOptions = { runtime, home, env, diagnostic };
|
|
1399
|
+
const auto = automatic(autoOptions);
|
|
1400
|
+
const session = {
|
|
1401
|
+
home,
|
|
1402
|
+
auto,
|
|
1403
|
+
output,
|
|
1404
|
+
json: values["json"] ?? false,
|
|
1405
|
+
fetch: runtime.fetch ?? fetch
|
|
1406
|
+
};
|
|
1407
|
+
if (values["scheduled"]) await auto.trim();
|
|
538
1408
|
if (command === "logout") {
|
|
539
|
-
await
|
|
540
|
-
|
|
541
|
-
|
|
1409
|
+
await runLogout(session);
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
let config;
|
|
1413
|
+
try {
|
|
1414
|
+
config = await readConfig(home);
|
|
1415
|
+
} catch (error) {
|
|
1416
|
+
if (command === "login" && error instanceof Error) config = void 0;
|
|
1417
|
+
else {
|
|
1418
|
+
if (values["scheduled"] && error instanceof MeterError) {
|
|
1419
|
+
output(scheduledSkip);
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
throw error;
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
if (command === "auto") {
|
|
1426
|
+
const state = await autoCommand(
|
|
1427
|
+
positionals[1] ?? "status",
|
|
1428
|
+
config,
|
|
1429
|
+
autoOptions
|
|
542
1430
|
);
|
|
1431
|
+
output(values["json"] ? JSON.stringify(state) : autoLine(state));
|
|
543
1432
|
return;
|
|
544
1433
|
}
|
|
545
|
-
const
|
|
546
|
-
const chosen = values["url"] ?? process.env["MADEFEED_URL"] ?? config?.url ?? "https://madefeed.dev";
|
|
547
|
-
if (typeof chosen !== "string")
|
|
548
|
-
throw new MeterError("\uC11C\uBC84 URL\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC544\uC694.");
|
|
1434
|
+
const chosen = values["url"] ?? env["MADEFEED_URL"] ?? config?.url ?? "https://madefeed.dev";
|
|
549
1435
|
const url = serviceUrl(chosen);
|
|
550
1436
|
const configured = config?.url === url ? config : void 0;
|
|
1437
|
+
if (values["scheduled"] && !configured) {
|
|
1438
|
+
output(scheduledSkip);
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
551
1441
|
const deviceName = configured?.deviceName ?? hostname().replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 80);
|
|
552
1442
|
if (command === "status") {
|
|
553
|
-
const
|
|
1443
|
+
const state = await auto.status();
|
|
1444
|
+
const status = {
|
|
1445
|
+
loggedIn: Boolean(configured),
|
|
1446
|
+
url,
|
|
1447
|
+
deviceName,
|
|
1448
|
+
auto: state
|
|
1449
|
+
};
|
|
554
1450
|
output(
|
|
555
|
-
values["json"] ? JSON.stringify(status) : configured
|
|
1451
|
+
values["json"] ? JSON.stringify(status) : connectionLine(configured)
|
|
556
1452
|
);
|
|
1453
|
+
if (!values["json"]) output(autoLine(state));
|
|
557
1454
|
return;
|
|
558
1455
|
}
|
|
559
1456
|
const now = runtime.now ?? Date.now();
|
|
560
|
-
const options = { home, sinceMs: windowStart(now, days) };
|
|
1457
|
+
const options = { home, sinceMs: windowStart(now, days), env };
|
|
561
1458
|
const api = {
|
|
562
1459
|
url,
|
|
563
1460
|
fetch: runtime.fetch ?? fetch,
|
|
@@ -566,7 +1463,8 @@ async function runCli(args, runtime = {}) {
|
|
|
566
1463
|
const sources = command === "upload" ? await Promise.all([
|
|
567
1464
|
readClaude(options),
|
|
568
1465
|
readCodex(options),
|
|
569
|
-
readOpenCode(options)
|
|
1466
|
+
readOpenCode(options),
|
|
1467
|
+
readGemini(options)
|
|
570
1468
|
]) : [];
|
|
571
1469
|
for (const source of sources) if (source.reason) diagnostic(source.reason);
|
|
572
1470
|
const rows = aggregate(
|
|
@@ -575,8 +1473,8 @@ async function runCli(args, runtime = {}) {
|
|
|
575
1473
|
const body = payload(deviceName, rows);
|
|
576
1474
|
if (values["dry-run"]) {
|
|
577
1475
|
if (!values["json"]) {
|
|
578
|
-
output(
|
|
579
|
-
output(
|
|
1476
|
+
output(dryRunHeader);
|
|
1477
|
+
output(dryRunColumns);
|
|
580
1478
|
for (const row of rows)
|
|
581
1479
|
output(
|
|
582
1480
|
`${row.date} ${row.tool.padEnd(11)} ${row.model.padEnd(28)} ${row.tokens}`
|
|
@@ -585,25 +1483,45 @@ async function runCli(args, runtime = {}) {
|
|
|
585
1483
|
output(JSON.stringify(body, null, values["json"] ? void 0 : 2));
|
|
586
1484
|
return;
|
|
587
1485
|
}
|
|
588
|
-
let
|
|
589
|
-
|
|
1486
|
+
let token2 = configured?.deviceToken;
|
|
1487
|
+
let saved = configured;
|
|
1488
|
+
if (!values["scheduled"] && (command === "login" || !token2)) {
|
|
590
1489
|
const device = await requestDevice(api, deviceName);
|
|
591
1490
|
const instructions = values["json"] ? diagnostic : output;
|
|
592
|
-
instructions(
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
1491
|
+
for (const line of approval(device)) instructions(line);
|
|
1492
|
+
token2 = await pollToken(api, device);
|
|
1493
|
+
saved = {
|
|
1494
|
+
url,
|
|
1495
|
+
deviceName,
|
|
1496
|
+
deviceToken: token2,
|
|
1497
|
+
...config?.auto ? { auto: config.auto } : {}
|
|
1498
|
+
};
|
|
1499
|
+
await saveConfig(home, saved);
|
|
1500
|
+
if (command !== "login") instructions(connected(deviceName));
|
|
597
1501
|
}
|
|
1502
|
+
if (!values["scheduled"] && !values["no-auto"] && env["MADEFEED_NO_AUTO"] !== "1" && saved && saved.auto !== "off")
|
|
1503
|
+
await auto.install(saved);
|
|
598
1504
|
if (command === "login") {
|
|
1505
|
+
if (values["json"]) diagnostic(connected(deviceName));
|
|
599
1506
|
output(
|
|
600
|
-
values["json"] ? JSON.stringify({ loggedIn: true }) :
|
|
1507
|
+
values["json"] ? JSON.stringify({ loggedIn: true }) : connected(deviceName)
|
|
601
1508
|
);
|
|
602
1509
|
return;
|
|
603
1510
|
}
|
|
604
|
-
|
|
1511
|
+
if (!token2) return;
|
|
1512
|
+
let result;
|
|
1513
|
+
try {
|
|
1514
|
+
result = await uploadUsage(api, token2, body);
|
|
1515
|
+
} catch (error) {
|
|
1516
|
+
if (!(error instanceof DisconnectedError)) throw error;
|
|
1517
|
+
await cleanDisconnected(session, {
|
|
1518
|
+
scheduled: values["scheduled"] ?? false,
|
|
1519
|
+
now
|
|
1520
|
+
});
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
605
1523
|
output(
|
|
606
|
-
values["json"] ? JSON.stringify(result) :
|
|
1524
|
+
values["scheduled"] ? scheduledUpload(now, result.accepted) : values["json"] ? JSON.stringify(result) : uploadResult(result)
|
|
607
1525
|
);
|
|
608
1526
|
}
|
|
609
1527
|
function invokedDirectly() {
|
|
@@ -617,8 +1535,27 @@ function invokedDirectly() {
|
|
|
617
1535
|
}
|
|
618
1536
|
}
|
|
619
1537
|
if (invokedDirectly()) {
|
|
620
|
-
|
|
621
|
-
|
|
1538
|
+
const entry = process.argv[1];
|
|
1539
|
+
const exec = (file, args, options) => new Promise((resolve2, reject) => {
|
|
1540
|
+
const child = execFile(
|
|
1541
|
+
file,
|
|
1542
|
+
[...args],
|
|
1543
|
+
{ encoding: "utf8" },
|
|
1544
|
+
(error, stdout) => {
|
|
1545
|
+
if (error) reject(error);
|
|
1546
|
+
else resolve2({ stdout });
|
|
1547
|
+
}
|
|
1548
|
+
);
|
|
1549
|
+
child.stdin?.on("error", (error) => reject(error));
|
|
1550
|
+
child.stdin?.end(options?.input);
|
|
1551
|
+
});
|
|
1552
|
+
runCli(process.argv.slice(2), {
|
|
1553
|
+
exec,
|
|
1554
|
+
...entry ? { self: realpathSync(entry) } : {},
|
|
1555
|
+
platform: process.platform,
|
|
1556
|
+
...process.getuid ? { uid: process.getuid() } : {}
|
|
1557
|
+
}).catch((error) => {
|
|
1558
|
+
const message = error instanceof MeterError ? error.message : localFailure;
|
|
622
1559
|
if (process.argv.includes("--json"))
|
|
623
1560
|
console.error(JSON.stringify({ error: message }));
|
|
624
1561
|
else console.error(message);
|