agycraft-mcp 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/LICENSE +21 -0
- package/README.md +189 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +4693 -0
- package/dist/index.js.map +1 -0
- package/package.json +50 -4
- package/snapshots/chronicle.json +326 -0
- package/snapshots/diagnosis.json +661 -0
- package/snapshots/models.json +1464 -0
- package/snapshots/quotas.json +280 -0
- package/snapshots/status.json +186 -0
- package/snapshots/updates.json +722 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4693 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli/doctor.ts
|
|
4
|
+
import { access, readFile, stat } from "fs/promises";
|
|
5
|
+
import { constants as fsConstants } from "fs";
|
|
6
|
+
import { homedir } from "os";
|
|
7
|
+
import { join } from "path";
|
|
8
|
+
import { execFile } from "child_process";
|
|
9
|
+
import { promisify } from "util";
|
|
10
|
+
var execFileAsync = promisify(execFile);
|
|
11
|
+
var SENSITIVE_KEY_RE = /(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH)/i;
|
|
12
|
+
var GIT_SAFETY_GUARDRAIL_SNIPPET = `# Git Safety Guardrail (add to AGENTS.md or GEMINI.md)
|
|
13
|
+
- NEVER run destructive git commands (\`git push --force\`, \`git reset --hard\`, \`git clean -fd\`, \`git checkout -- .\`) without explicit user confirmation.
|
|
14
|
+
- NEVER delete files outside the current workspace or run \`rm -rf\` on broad paths.
|
|
15
|
+
- Always run \`git status\` and \`git diff --stat\` before committing or staging changes.`;
|
|
16
|
+
var GEMINIIGNORE_TEMPLATE = `# Recommended .geminiignore to prevent context bloat & 504 timeouts
|
|
17
|
+
# JS/TS & Web
|
|
18
|
+
node_modules/
|
|
19
|
+
dist/
|
|
20
|
+
build/
|
|
21
|
+
.next/
|
|
22
|
+
.astro/
|
|
23
|
+
coverage/
|
|
24
|
+
*.lock
|
|
25
|
+
package-lock.json
|
|
26
|
+
pnpm-lock.yaml
|
|
27
|
+
yarn.lock
|
|
28
|
+
*.min.js
|
|
29
|
+
*.map
|
|
30
|
+
|
|
31
|
+
# Python & Data Engineering
|
|
32
|
+
.venv/
|
|
33
|
+
venv/
|
|
34
|
+
__pycache__/
|
|
35
|
+
.pytest_cache/
|
|
36
|
+
.mypy_cache/
|
|
37
|
+
.ruff_cache/
|
|
38
|
+
data/
|
|
39
|
+
logs/
|
|
40
|
+
tmp/
|
|
41
|
+
*.parquet
|
|
42
|
+
*.sqlite
|
|
43
|
+
*.db
|
|
44
|
+
*.log
|
|
45
|
+
|
|
46
|
+
# VCS
|
|
47
|
+
.git/
|
|
48
|
+
`;
|
|
49
|
+
async function fileExists(filePath) {
|
|
50
|
+
try {
|
|
51
|
+
await access(filePath, fsConstants.R_OK);
|
|
52
|
+
return true;
|
|
53
|
+
} catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async function detectBinaryVersion(cmd, args = ["--version"]) {
|
|
58
|
+
try {
|
|
59
|
+
const { stdout } = await execFileAsync(cmd, args, { timeout: 2500 });
|
|
60
|
+
const firstLine = stdout.trim().split("\n")[0]?.trim() ?? "";
|
|
61
|
+
return firstLine.slice(0, 64) || null;
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async function inspectJsonConfig(filePath, kind) {
|
|
67
|
+
const checks = [];
|
|
68
|
+
if (!await fileExists(filePath)) {
|
|
69
|
+
return checks;
|
|
70
|
+
}
|
|
71
|
+
let parsed;
|
|
72
|
+
try {
|
|
73
|
+
const raw = await readFile(filePath, "utf8");
|
|
74
|
+
parsed = JSON.parse(raw);
|
|
75
|
+
} catch (err) {
|
|
76
|
+
const msg = err instanceof Error ? err.message : "Invalid JSON syntax";
|
|
77
|
+
checks.push({
|
|
78
|
+
id: `${kind}_syntax_error`,
|
|
79
|
+
category: "mcp_config",
|
|
80
|
+
severity: "error",
|
|
81
|
+
title: `Invalid JSON syntax in ${kind === "mcp_config" ? "mcp_config.json" : "settings.json"}`,
|
|
82
|
+
detail: `Parse error: ${msg.slice(0, 120)}`,
|
|
83
|
+
fix_hint: "Validate trailing commas, quotes, and braces with `jq . <file>`."
|
|
84
|
+
});
|
|
85
|
+
return checks;
|
|
86
|
+
}
|
|
87
|
+
checks.push({
|
|
88
|
+
id: `${kind}_syntax_ok`,
|
|
89
|
+
category: "mcp_config",
|
|
90
|
+
severity: "ok",
|
|
91
|
+
title: `${kind === "mcp_config" ? "mcp_config.json" : "settings.json"} JSON syntax valid`,
|
|
92
|
+
detail: "Parsed cleanly."
|
|
93
|
+
});
|
|
94
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
95
|
+
return checks;
|
|
96
|
+
}
|
|
97
|
+
const root = parsed;
|
|
98
|
+
const serversObj = root["mcpServers"];
|
|
99
|
+
if (serversObj && typeof serversObj === "object" && !Array.isArray(serversObj)) {
|
|
100
|
+
const serverEntries = Object.entries(serversObj);
|
|
101
|
+
const serverCount = serverEntries.length;
|
|
102
|
+
if (serverCount > 8) {
|
|
103
|
+
checks.push({
|
|
104
|
+
id: "mcp_server_bloat",
|
|
105
|
+
category: "context_hygiene",
|
|
106
|
+
severity: "warn",
|
|
107
|
+
title: `High mounted MCP server count (${serverCount})`,
|
|
108
|
+
detail: `${serverCount} MCP servers inject many tool schemas into every turn, accelerating 5h/7d quota burn.`,
|
|
109
|
+
fix_hint: "Disable unused MCP servers or split specialized workflows into on-demand SKILL.md files."
|
|
110
|
+
});
|
|
111
|
+
} else {
|
|
112
|
+
checks.push({
|
|
113
|
+
id: "mcp_server_count_ok",
|
|
114
|
+
category: "context_hygiene",
|
|
115
|
+
severity: "ok",
|
|
116
|
+
title: `Mounted MCP server count healthy (${serverCount})`,
|
|
117
|
+
detail: `${serverCount} configured MCP server(s).`
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
for (const [serverName, cfg] of serverEntries) {
|
|
121
|
+
if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const serverCfg = cfg;
|
|
125
|
+
const safeName = serverName.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 32);
|
|
126
|
+
const hasUrl = typeof serverCfg["url"] === "string";
|
|
127
|
+
const hasHttpUrl = typeof serverCfg["httpUrl"] === "string";
|
|
128
|
+
if (hasUrl && hasHttpUrl) {
|
|
129
|
+
checks.push({
|
|
130
|
+
id: `mcp_transport_conflict_${safeName}`,
|
|
131
|
+
category: "mcp_config",
|
|
132
|
+
severity: "error",
|
|
133
|
+
title: `MCP server "${safeName}" sets both "url" and "httpUrl"`,
|
|
134
|
+
detail: "Use 'url' for SSE transport OR 'httpUrl' for Streamable HTTP, never both.",
|
|
135
|
+
fix_hint: `Remove one of 'url' or 'httpUrl' in mcpServers.${safeName} and verify with \`gemini mcp list\`.`
|
|
136
|
+
});
|
|
137
|
+
} else if (hasUrl) {
|
|
138
|
+
const urlStr = String(serverCfg["url"]);
|
|
139
|
+
if (urlStr.includes("/mcp") && !urlStr.includes("/sse")) {
|
|
140
|
+
checks.push({
|
|
141
|
+
id: `mcp_url_mismatch_${safeName}`,
|
|
142
|
+
category: "mcp_config",
|
|
143
|
+
severity: "warn",
|
|
144
|
+
title: `Possible url vs httpUrl mismatch on "${safeName}"`,
|
|
145
|
+
detail: "Endpoint looks like Streamable HTTP (/mcp) but uses legacy SSE key 'url'.",
|
|
146
|
+
fix_hint: `Rename key "url" -> "httpUrl" in mcpServers.${safeName} if the server uses Streamable HTTP.`
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
} else if (hasHttpUrl) {
|
|
150
|
+
const httpUrlStr = String(serverCfg["httpUrl"]);
|
|
151
|
+
if (httpUrlStr.includes("/sse")) {
|
|
152
|
+
checks.push({
|
|
153
|
+
id: `mcp_httpurl_mismatch_${safeName}`,
|
|
154
|
+
category: "mcp_config",
|
|
155
|
+
severity: "warn",
|
|
156
|
+
title: `Possible httpUrl vs url mismatch on "${safeName}"`,
|
|
157
|
+
detail: "Endpoint looks like SSE (/sse) but uses Streamable HTTP key 'httpUrl'.",
|
|
158
|
+
fix_hint: `Rename key "httpUrl" -> "url" in mcpServers.${safeName} if the server uses SSE.`
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const envBlock = serverCfg["env"];
|
|
163
|
+
if (envBlock && typeof envBlock === "object" && !Array.isArray(envBlock)) {
|
|
164
|
+
const sensitiveKeyCount = Object.keys(envBlock).filter(
|
|
165
|
+
(k) => SENSITIVE_KEY_RE.test(k)
|
|
166
|
+
).length;
|
|
167
|
+
if (sensitiveKeyCount > 0) {
|
|
168
|
+
checks.push({
|
|
169
|
+
id: `mcp_env_explicit_${safeName}`,
|
|
170
|
+
category: "mcp_config",
|
|
171
|
+
severity: "info",
|
|
172
|
+
title: `MCP server "${safeName}" defines ${sensitiveKeyCount} explicit credential env key(s)`,
|
|
173
|
+
detail: "Explicit env keys are present (values not inspected or logged)."
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return checks;
|
|
180
|
+
}
|
|
181
|
+
async function runDoctor(options) {
|
|
182
|
+
const cwd = options?.cwd ?? process.cwd();
|
|
183
|
+
const home = options?.homeDir ?? homedir();
|
|
184
|
+
const env = options?.env ?? process.env;
|
|
185
|
+
const checks = [];
|
|
186
|
+
const nodeVersion = process.version;
|
|
187
|
+
const major = Number(nodeVersion.replace(/^v/, "").split(".")[0] ?? "0");
|
|
188
|
+
checks.push({
|
|
189
|
+
id: "node_version",
|
|
190
|
+
category: "runtime",
|
|
191
|
+
severity: major >= 20 ? "ok" : "warn",
|
|
192
|
+
title: `Node.js ${nodeVersion}`,
|
|
193
|
+
detail: major >= 22 ? "Node 22+ runtime detected." : major >= 20 ? "Node 20+ runtime supported (Node 22+ LTS recommended for latest Gemini CLI)." : "Node.js >= 20.0.0 is required for agycraft-mcp (Node 22+ LTS recommended).",
|
|
194
|
+
fix_hint: major >= 20 ? void 0 : "Upgrade Node.js to v20 LTS or v22 LTS."
|
|
195
|
+
});
|
|
196
|
+
if (!options?.skipBinaryChecks) {
|
|
197
|
+
const [geminiVer, agyVer] = await Promise.all([
|
|
198
|
+
detectBinaryVersion("gemini", ["--version"]),
|
|
199
|
+
detectBinaryVersion("agy", ["--version"])
|
|
200
|
+
]);
|
|
201
|
+
checks.push({
|
|
202
|
+
id: "gemini_cli_version",
|
|
203
|
+
category: "runtime",
|
|
204
|
+
severity: geminiVer ? "ok" : "info",
|
|
205
|
+
title: geminiVer ? `Gemini CLI detected (${geminiVer})` : "Gemini CLI not found on PATH",
|
|
206
|
+
detail: geminiVer ? "Gemini CLI binary is reachable." : "Optional (Enterprise / paid API key workflows only; personal tier sunset Jun 2026 \u2014 use Antigravity CLI `agy` for personal workflows): install with `npm i -g @google/gemini-cli`."
|
|
207
|
+
});
|
|
208
|
+
checks.push({
|
|
209
|
+
id: "agy_cli_version",
|
|
210
|
+
category: "runtime",
|
|
211
|
+
severity: agyVer ? "ok" : "info",
|
|
212
|
+
title: agyVer ? `Antigravity CLI detected (${agyVer})` : "Antigravity CLI (`agy`) not found on PATH",
|
|
213
|
+
detail: agyVer ? "Antigravity CLI binary is reachable." : "If using Antigravity IDE only, CLI binary on PATH is optional."
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
const mcpPaths = options?.mcpConfigPaths ?? [
|
|
217
|
+
join(home, ".gemini", "antigravity", "mcp_config.json"),
|
|
218
|
+
join(cwd, "mcp_config.json")
|
|
219
|
+
];
|
|
220
|
+
const settingsPaths = options?.settingsJsonPaths ?? [
|
|
221
|
+
join(home, ".gemini", "settings.json"),
|
|
222
|
+
join(cwd, ".gemini", "settings.json")
|
|
223
|
+
];
|
|
224
|
+
let foundAnyConfig = false;
|
|
225
|
+
for (const p of mcpPaths) {
|
|
226
|
+
const res = await inspectJsonConfig(p, "mcp_config");
|
|
227
|
+
if (res.length > 0) {
|
|
228
|
+
foundAnyConfig = true;
|
|
229
|
+
checks.push(...res);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
for (const p of settingsPaths) {
|
|
233
|
+
const res = await inspectJsonConfig(p, "settings");
|
|
234
|
+
if (res.length > 0) {
|
|
235
|
+
foundAnyConfig = true;
|
|
236
|
+
checks.push(...res);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (!foundAnyConfig) {
|
|
240
|
+
checks.push({
|
|
241
|
+
id: "no_mcp_config_found",
|
|
242
|
+
category: "mcp_config",
|
|
243
|
+
severity: "info",
|
|
244
|
+
title: "No local mcp_config.json or settings.json found in default locations",
|
|
245
|
+
detail: "Run `npx agycraft-mcp setup` to view copyable MCP & OTel setup snippets."
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
const hasGeminiApiKey = Boolean(env["GEMINI_API_KEY"] || env["GOOGLE_API_KEY"]);
|
|
249
|
+
const hasGcpProject = Boolean(env["GOOGLE_CLOUD_PROJECT"]);
|
|
250
|
+
if (hasGeminiApiKey && hasGcpProject) {
|
|
251
|
+
checks.push({
|
|
252
|
+
id: "auth_env_dual_set",
|
|
253
|
+
category: "auth_env",
|
|
254
|
+
severity: "warn",
|
|
255
|
+
title: "Both API Key env and GOOGLE_CLOUD_PROJECT are set",
|
|
256
|
+
detail: "Mixing API Key auth with Vertex/OAuth project env can trigger 403 Permission Denied or ACCESS_TOKEN_TYPE_UNSUPPORTED.",
|
|
257
|
+
fix_hint: "Unset the unused auth method in your shell profile (`unset GEMINI_API_KEY` or `unset GOOGLE_CLOUD_PROJECT`)."
|
|
258
|
+
});
|
|
259
|
+
} else {
|
|
260
|
+
checks.push({
|
|
261
|
+
id: "auth_env_boolean_ok",
|
|
262
|
+
category: "auth_env",
|
|
263
|
+
severity: "ok",
|
|
264
|
+
title: "Auth environment variables checked (boolean presence only)",
|
|
265
|
+
detail: `GEMINI_API_KEY/GOOGLE_API_KEY set: ${hasGeminiApiKey}, GOOGLE_CLOUD_PROJECT set: ${hasGcpProject}.`
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
const sensitiveEnvCount = Object.keys(env).filter(
|
|
269
|
+
(k) => SENSITIVE_KEY_RE.test(k)
|
|
270
|
+
).length;
|
|
271
|
+
if (sensitiveEnvCount > 0) {
|
|
272
|
+
checks.push({
|
|
273
|
+
id: "env_stripping_warning",
|
|
274
|
+
category: "auth_env",
|
|
275
|
+
severity: "info",
|
|
276
|
+
title: `Detected ${sensitiveEnvCount} shell env var(s) matching *TOKEN*/*KEY*/*SECRET*`,
|
|
277
|
+
detail: "Gemini CLI & AGY sanitize/strip *TOKEN*/*KEY*/*SECRET* env vars from child MCP servers by default (values not inspected).",
|
|
278
|
+
fix_hint: "If an MCP server requires a specific variable, pass it explicitly in that server's `env` block in mcp_config.json / settings.json."
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
const hasProxy = Boolean(
|
|
282
|
+
env["HTTP_PROXY"] || env["HTTPS_PROXY"] || env["http_proxy"] || env["https_proxy"]
|
|
283
|
+
);
|
|
284
|
+
const caCertPath = env["NODE_EXTRA_CA_CERTS"];
|
|
285
|
+
const hasCaCert = Boolean(caCertPath);
|
|
286
|
+
if (hasProxy && !hasCaCert) {
|
|
287
|
+
checks.push({
|
|
288
|
+
id: "proxy_without_ca_certs",
|
|
289
|
+
category: "network_ssl",
|
|
290
|
+
severity: "warn",
|
|
291
|
+
title: "HTTP(S)_PROXY is set without NODE_EXTRA_CA_CERTS",
|
|
292
|
+
detail: "Corporate SSL-inspecting proxies often cause `UNABLE_TO_GET_ISSUER_CERT_LOCALLY` in Node.js.",
|
|
293
|
+
fix_hint: "If behind a corporate TLS proxy, export `NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem`."
|
|
294
|
+
});
|
|
295
|
+
} else if (hasCaCert && caCertPath) {
|
|
296
|
+
const readable = await fileExists(caCertPath);
|
|
297
|
+
checks.push({
|
|
298
|
+
id: "node_extra_ca_certs_check",
|
|
299
|
+
category: "network_ssl",
|
|
300
|
+
severity: readable ? "ok" : "error",
|
|
301
|
+
title: readable ? "NODE_EXTRA_CA_CERTS is set and readable" : "NODE_EXTRA_CA_CERTS points to an unreadable or missing file",
|
|
302
|
+
detail: readable ? "Custom CA bundle is readable by Node.js." : "Node.js will ignore or fail TLS verification when NODE_EXTRA_CA_CERTS is unreadable.",
|
|
303
|
+
fix_hint: readable ? void 0 : "Verify the CA certificate path and file permissions (`chmod 644`)."
|
|
304
|
+
});
|
|
305
|
+
} else {
|
|
306
|
+
checks.push({
|
|
307
|
+
id: "network_ssl_ok",
|
|
308
|
+
category: "network_ssl",
|
|
309
|
+
severity: "ok",
|
|
310
|
+
title: "No proxy/SSL misconfiguration detected",
|
|
311
|
+
detail: "Direct HTTPS connection environment."
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
const hasGeminiIgnore = await fileExists(join(cwd, ".geminiignore"));
|
|
315
|
+
checks.push({
|
|
316
|
+
id: "geminiignore_check",
|
|
317
|
+
category: "context_hygiene",
|
|
318
|
+
severity: hasGeminiIgnore ? "ok" : "warn",
|
|
319
|
+
title: hasGeminiIgnore ? ".geminiignore found in workspace" : "Missing .geminiignore in current workspace",
|
|
320
|
+
detail: hasGeminiIgnore ? "Workspace ignore rules help prevent lockfile/build-artifact context bloat." : "Without .geminiignore, lockfiles and build outputs can bloat context and trigger 504 timeouts or quota burn.",
|
|
321
|
+
fix_hint: hasGeminiIgnore ? void 0 : "Create a `.geminiignore` file using the recommended template below."
|
|
322
|
+
});
|
|
323
|
+
const ruleCandidates = [
|
|
324
|
+
{ label: "~/.gemini/GEMINI.md", path: join(home, ".gemini", "GEMINI.md") },
|
|
325
|
+
{ label: "./GEMINI.md", path: join(cwd, "GEMINI.md") },
|
|
326
|
+
{ label: "./AGENTS.md", path: join(cwd, "AGENTS.md") }
|
|
327
|
+
];
|
|
328
|
+
let totalRuleBytes = 0;
|
|
329
|
+
let foundRuleFiles = 0;
|
|
330
|
+
for (const candidate of ruleCandidates) {
|
|
331
|
+
try {
|
|
332
|
+
const s = await stat(candidate.path);
|
|
333
|
+
if (s.isFile()) {
|
|
334
|
+
totalRuleBytes += s.size;
|
|
335
|
+
foundRuleFiles += 1;
|
|
336
|
+
}
|
|
337
|
+
} catch {
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const estimatedRuleTokens = Math.ceil(totalRuleBytes / 4);
|
|
341
|
+
if (estimatedRuleTokens > 3e3) {
|
|
342
|
+
checks.push({
|
|
343
|
+
id: "global_rules_bloat",
|
|
344
|
+
category: "context_hygiene",
|
|
345
|
+
severity: "warn",
|
|
346
|
+
title: `Global rules token bloat (~${estimatedRuleTokens} tokens across ${foundRuleFiles} file(s))`,
|
|
347
|
+
detail: "Large always-loaded rule files are re-sent on every single turn and inflate 5h/7d token consumption.",
|
|
348
|
+
fix_hint: "Keep global rules under ~2,000 tokens and move domain-specific instructions into on-demand SKILL.md files."
|
|
349
|
+
});
|
|
350
|
+
} else {
|
|
351
|
+
checks.push({
|
|
352
|
+
id: "global_rules_ok",
|
|
353
|
+
category: "context_hygiene",
|
|
354
|
+
severity: "ok",
|
|
355
|
+
title: `Global rules size healthy (~${estimatedRuleTokens} tokens across ${foundRuleFiles} file(s))`,
|
|
356
|
+
detail: "Baseline instruction overhead is lean."
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
checks.push({
|
|
360
|
+
id: "git_safety_guardrail",
|
|
361
|
+
category: "safety_guardrail",
|
|
362
|
+
severity: "info",
|
|
363
|
+
title: "Git safety guardrail template available",
|
|
364
|
+
detail: "Add the non-destructive Git safety snippet below to GEMINI.md / AGENTS.md to prevent accidental force-pushes or hard resets."
|
|
365
|
+
});
|
|
366
|
+
const summary = {
|
|
367
|
+
ok: checks.filter((c) => c.severity === "ok").length,
|
|
368
|
+
warn: checks.filter((c) => c.severity === "warn").length,
|
|
369
|
+
error: checks.filter((c) => c.severity === "error").length,
|
|
370
|
+
info: checks.filter((c) => c.severity === "info").length
|
|
371
|
+
};
|
|
372
|
+
return {
|
|
373
|
+
generated_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
374
|
+
node_version: nodeVersion,
|
|
375
|
+
checks,
|
|
376
|
+
summary,
|
|
377
|
+
git_safety_guardrail_snippet: GIT_SAFETY_GUARDRAIL_SNIPPET,
|
|
378
|
+
geminiignore_template: GEMINIIGNORE_TEMPLATE
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
function formatDoctorReport(report) {
|
|
382
|
+
const icon = {
|
|
383
|
+
ok: "[OK]",
|
|
384
|
+
warn: "[WARN]",
|
|
385
|
+
error: "[ERR]",
|
|
386
|
+
info: "[INFO]"
|
|
387
|
+
};
|
|
388
|
+
const lines = [
|
|
389
|
+
"agycraft-mcp doctor (100% local, zero secret values inspected)",
|
|
390
|
+
"================================================================"
|
|
391
|
+
];
|
|
392
|
+
for (const check of report.checks) {
|
|
393
|
+
lines.push(`${icon[check.severity]} ${check.title}`);
|
|
394
|
+
lines.push(` ${check.detail}`);
|
|
395
|
+
if (check.fix_hint) {
|
|
396
|
+
lines.push(` Fix: ${check.fix_hint}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
lines.push("");
|
|
400
|
+
lines.push(
|
|
401
|
+
`Summary: ${report.summary.ok} ok, ${report.summary.warn} warn, ${report.summary.error} error, ${report.summary.info} info`
|
|
402
|
+
);
|
|
403
|
+
lines.push("");
|
|
404
|
+
lines.push("--- Recommended Git Safety Guardrail Snippet ---");
|
|
405
|
+
lines.push(report.git_safety_guardrail_snippet);
|
|
406
|
+
const missingIgnore = report.checks.some(
|
|
407
|
+
(c) => c.id === "geminiignore_check" && c.severity === "warn"
|
|
408
|
+
);
|
|
409
|
+
if (missingIgnore) {
|
|
410
|
+
lines.push("");
|
|
411
|
+
lines.push("--- Recommended .geminiignore Template ---");
|
|
412
|
+
lines.push(report.geminiignore_template.trimEnd());
|
|
413
|
+
}
|
|
414
|
+
return lines.join("\n");
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// src/cli/preflight.ts
|
|
418
|
+
var DEFAULT_DATA_URL = "https://modelcraft.dev/data/v1";
|
|
419
|
+
function resolvePreflightStatusUrl(options) {
|
|
420
|
+
if (options?.statusUrl && options.statusUrl.trim().length > 0) {
|
|
421
|
+
return options.statusUrl.trim();
|
|
422
|
+
}
|
|
423
|
+
const env = options?.env ?? process.env;
|
|
424
|
+
const statusUrl = env.MODELCRAFT_STATUS_URL?.trim();
|
|
425
|
+
if (statusUrl) {
|
|
426
|
+
return statusUrl;
|
|
427
|
+
}
|
|
428
|
+
const dataUrl = env.MODELCRAFT_DATA_URL?.trim();
|
|
429
|
+
const base = (dataUrl || DEFAULT_DATA_URL).replace(/\/+$/, "");
|
|
430
|
+
return `${base}/status.json`;
|
|
431
|
+
}
|
|
432
|
+
function isRateOrCapacityError(status, errorText) {
|
|
433
|
+
if (status === 429 || status === 503 || status === "429" || status === "503") {
|
|
434
|
+
return true;
|
|
435
|
+
}
|
|
436
|
+
if (typeof errorText === "string" && /\b(429|503)\b/.test(errorText)) {
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
async function runPreflight(options) {
|
|
442
|
+
const url = resolvePreflightStatusUrl(options);
|
|
443
|
+
const fetchFn = options?.fetchFn ?? globalThis.fetch;
|
|
444
|
+
const timeoutMs = options?.timeoutMs ?? 5e3;
|
|
445
|
+
const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
446
|
+
const controller = new AbortController();
|
|
447
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
448
|
+
let data;
|
|
449
|
+
try {
|
|
450
|
+
const resp = await fetchFn(url, {
|
|
451
|
+
method: "GET",
|
|
452
|
+
headers: { Accept: "application/json" },
|
|
453
|
+
signal: controller.signal
|
|
454
|
+
});
|
|
455
|
+
if (!resp.ok) {
|
|
456
|
+
const reason = `HTTP ${resp.status} ${resp.statusText || ""}`.trim();
|
|
457
|
+
return {
|
|
458
|
+
ok: false,
|
|
459
|
+
exit_code: 1,
|
|
460
|
+
url,
|
|
461
|
+
checked_at: checkedAt,
|
|
462
|
+
overall_status: "unknown",
|
|
463
|
+
active_incidents_count: 0,
|
|
464
|
+
degraded_surfaces: [],
|
|
465
|
+
flagged_sources: [],
|
|
466
|
+
reasons: [`Failed to fetch status.json (${reason})`],
|
|
467
|
+
error: reason
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
data = await resp.json();
|
|
471
|
+
} catch (err) {
|
|
472
|
+
const msg = err instanceof Error ? err.name === "AbortError" ? `Request timed out after ${timeoutMs}ms` : err.message : String(err);
|
|
473
|
+
return {
|
|
474
|
+
ok: false,
|
|
475
|
+
exit_code: 1,
|
|
476
|
+
url,
|
|
477
|
+
checked_at: checkedAt,
|
|
478
|
+
overall_status: "unknown",
|
|
479
|
+
active_incidents_count: 0,
|
|
480
|
+
degraded_surfaces: [],
|
|
481
|
+
flagged_sources: [],
|
|
482
|
+
reasons: [`Failed to fetch status.json: ${msg}`],
|
|
483
|
+
error: msg
|
|
484
|
+
};
|
|
485
|
+
} finally {
|
|
486
|
+
clearTimeout(timer);
|
|
487
|
+
}
|
|
488
|
+
const reasons = [];
|
|
489
|
+
const overallStatus = typeof data?.overall_status === "string" ? data.overall_status : "unknown";
|
|
490
|
+
if (overallStatus !== "operational") {
|
|
491
|
+
reasons.push(
|
|
492
|
+
`overall_status is "${overallStatus}" (expected "operational")`
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
const incidents = Array.isArray(data?.active_incidents) ? data.active_incidents : [];
|
|
496
|
+
if (incidents.length > 0) {
|
|
497
|
+
const titles = incidents.map((inc) => inc?.title || inc?.id || "unnamed incident").slice(0, 3).join("; ");
|
|
498
|
+
reasons.push(
|
|
499
|
+
`${incidents.length} active incident(s) reported: ${titles}`
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
const surfaces = Array.isArray(data?.surfaces) ? data.surfaces : [];
|
|
503
|
+
const degradedSurfaces = surfaces.filter((s) => s && s.status !== "operational").map((s) => ({
|
|
504
|
+
id: String(s.id ?? "unknown"),
|
|
505
|
+
name: String(s.name ?? s.id ?? "unknown"),
|
|
506
|
+
status: String(s.status ?? "unknown")
|
|
507
|
+
}));
|
|
508
|
+
for (const s of degradedSurfaces) {
|
|
509
|
+
reasons.push(`surface "${s.id}" is "${s.status}"`);
|
|
510
|
+
}
|
|
511
|
+
const sources = Array.isArray(data?.sources_checked) ? data.sources_checked : [];
|
|
512
|
+
const flaggedSources = [];
|
|
513
|
+
for (const src of sources) {
|
|
514
|
+
if (typeof src === "string") {
|
|
515
|
+
if (/\b(429|503)\b/.test(src)) {
|
|
516
|
+
flaggedSources.push({ id: src, http_status: null, error: src });
|
|
517
|
+
reasons.push(`source "${src}" reported 429/503`);
|
|
518
|
+
}
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (src && typeof src === "object") {
|
|
522
|
+
const rec = src;
|
|
523
|
+
const id = String(rec["id"] ?? rec["url"] ?? "unknown");
|
|
524
|
+
const httpStatus = typeof rec["http_status"] === "number" || typeof rec["http_status"] === "string" ? rec["http_status"] : null;
|
|
525
|
+
const errStr = typeof rec["error"] === "string" ? rec["error"] : null;
|
|
526
|
+
if (isRateOrCapacityError(httpStatus, errStr)) {
|
|
527
|
+
flaggedSources.push({ id, http_status: httpStatus, error: errStr });
|
|
528
|
+
reasons.push(
|
|
529
|
+
`source "${id}" reported ${httpStatus !== null ? `HTTP ${httpStatus}` : errStr ?? "429/503"}`
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const ok = reasons.length === 0;
|
|
535
|
+
return {
|
|
536
|
+
ok,
|
|
537
|
+
exit_code: ok ? 0 : 1,
|
|
538
|
+
url,
|
|
539
|
+
checked_at: checkedAt,
|
|
540
|
+
overall_status: overallStatus,
|
|
541
|
+
active_incidents_count: incidents.length,
|
|
542
|
+
degraded_surfaces: degradedSurfaces,
|
|
543
|
+
flagged_sources: flaggedSources,
|
|
544
|
+
reasons
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
function formatPreflightReport(result) {
|
|
548
|
+
const lines = [
|
|
549
|
+
`agycraft-mcp preflight (${result.url})`,
|
|
550
|
+
"================================================================",
|
|
551
|
+
`Status: ${result.ok ? "[PASS]" : "[FAIL]"} overall_status=${result.overall_status} active_incidents=${result.active_incidents_count}`
|
|
552
|
+
];
|
|
553
|
+
if (result.reasons.length > 0) {
|
|
554
|
+
lines.push("Blocking checks:");
|
|
555
|
+
for (const reason of result.reasons) {
|
|
556
|
+
lines.push(` - ${reason}`);
|
|
557
|
+
}
|
|
558
|
+
} else {
|
|
559
|
+
lines.push("All surfaces operational; no active incidents or 429/503 source errors.");
|
|
560
|
+
}
|
|
561
|
+
return lines.join("\n");
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// src/paths.ts
|
|
565
|
+
import { homedir as homedir2 } from "os";
|
|
566
|
+
import { join as join2, resolve } from "path";
|
|
567
|
+
function getConfigDir() {
|
|
568
|
+
const override = process.env.AGYCRAFT_CONFIG_DIR;
|
|
569
|
+
if (override && override.trim().length > 0) {
|
|
570
|
+
return resolve(override.trim());
|
|
571
|
+
}
|
|
572
|
+
const xdg = process.env.XDG_CONFIG_HOME;
|
|
573
|
+
if (xdg && xdg.trim().length > 0) {
|
|
574
|
+
return join2(resolve(xdg.trim()), "agycraft");
|
|
575
|
+
}
|
|
576
|
+
return join2(homedir2(), ".config", "agycraft");
|
|
577
|
+
}
|
|
578
|
+
function getUsageLogPath() {
|
|
579
|
+
return join2(getConfigDir(), "usage.jsonl");
|
|
580
|
+
}
|
|
581
|
+
function getCacheDir() {
|
|
582
|
+
return join2(getConfigDir(), "cache");
|
|
583
|
+
}
|
|
584
|
+
function getRollupsDir() {
|
|
585
|
+
return join2(getConfigDir(), "rollups");
|
|
586
|
+
}
|
|
587
|
+
function getSaltFilePath() {
|
|
588
|
+
return join2(getConfigDir(), ".salt");
|
|
589
|
+
}
|
|
590
|
+
function getDefaultGeminiTelemetryPath() {
|
|
591
|
+
const override = process.env.AGYCRAFT_GEMINI_OTEL_PATH;
|
|
592
|
+
if (override && override.trim().length > 0) {
|
|
593
|
+
return resolve(override.trim());
|
|
594
|
+
}
|
|
595
|
+
return join2(homedir2(), ".gemini", "telemetry_stats.jsonl");
|
|
596
|
+
}
|
|
597
|
+
var BRAIN_SCAN_DISABLED_VALUES = /* @__PURE__ */ new Set(["none", "off", "false"]);
|
|
598
|
+
function isBrainScanDisabledValue(value) {
|
|
599
|
+
return BRAIN_SCAN_DISABLED_VALUES.has(value.trim().toLowerCase());
|
|
600
|
+
}
|
|
601
|
+
function getAgyBrainDir() {
|
|
602
|
+
const override = process.env.AGYCRAFT_BRAIN_DIR;
|
|
603
|
+
if (override && override.trim().length > 0) {
|
|
604
|
+
const trimmed = override.trim();
|
|
605
|
+
if (isBrainScanDisabledValue(trimmed)) {
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
return resolve(trimmed);
|
|
609
|
+
}
|
|
610
|
+
const configOverride = process.env.AGYCRAFT_CONFIG_DIR;
|
|
611
|
+
if (configOverride && configOverride.trim().length > 0) {
|
|
612
|
+
return null;
|
|
613
|
+
}
|
|
614
|
+
return join2(homedir2(), ".gemini", "antigravity-cli", "brain");
|
|
615
|
+
}
|
|
616
|
+
function getAgyHistoryPath() {
|
|
617
|
+
const override = process.env.AGYCRAFT_HISTORY_PATH;
|
|
618
|
+
if (override && override.trim().length > 0) {
|
|
619
|
+
const trimmed = override.trim();
|
|
620
|
+
if (isBrainScanDisabledValue(trimmed)) {
|
|
621
|
+
return null;
|
|
622
|
+
}
|
|
623
|
+
return resolve(trimmed);
|
|
624
|
+
}
|
|
625
|
+
const configOverride = process.env.AGYCRAFT_CONFIG_DIR;
|
|
626
|
+
if (configOverride && configOverride.trim().length > 0) {
|
|
627
|
+
return null;
|
|
628
|
+
}
|
|
629
|
+
return join2(homedir2(), ".gemini", "antigravity-cli", "history.jsonl");
|
|
630
|
+
}
|
|
631
|
+
function getSnapshotsDir() {
|
|
632
|
+
const override = process.env.AGYCRAFT_SNAPSHOTS_DIR;
|
|
633
|
+
if (override && override.trim().length > 0) {
|
|
634
|
+
return resolve(override.trim());
|
|
635
|
+
}
|
|
636
|
+
return resolve(new URL("../snapshots", import.meta.url).pathname);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// src/cli/setup.ts
|
|
640
|
+
function buildSetupInstructions() {
|
|
641
|
+
const usagePath = getUsageLogPath();
|
|
642
|
+
return [
|
|
643
|
+
"agycraft-mcp setup (non-destructive, opt-in instructions)",
|
|
644
|
+
"================================================================",
|
|
645
|
+
"No files have been modified automatically. Copy and paste only what you want.",
|
|
646
|
+
"",
|
|
647
|
+
"1. Register agycraft MCP Server:",
|
|
648
|
+
"",
|
|
649
|
+
" Option A \u2014 Antigravity CLI (`agy`) one-liner:",
|
|
650
|
+
" agy mcp add agycraft npx -y agycraft-mcp",
|
|
651
|
+
"",
|
|
652
|
+
" (Local dev testing against a local ModelCraft server):",
|
|
653
|
+
" agy mcp add --env MODELCRAFT_DATA_URL=http://127.0.0.1:4321/data/v1 agycraft agycraft-mcp",
|
|
654
|
+
"",
|
|
655
|
+
" Option B \u2014 Antigravity IDE (~/.gemini/antigravity/mcp_config.json)",
|
|
656
|
+
" or Gemini CLI (~/.gemini/settings.json):",
|
|
657
|
+
"",
|
|
658
|
+
JSON.stringify(
|
|
659
|
+
{
|
|
660
|
+
mcpServers: {
|
|
661
|
+
agycraft: {
|
|
662
|
+
command: "npx",
|
|
663
|
+
args: ["-y", "agycraft-mcp"]
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
},
|
|
667
|
+
null,
|
|
668
|
+
2
|
|
669
|
+
),
|
|
670
|
+
"",
|
|
671
|
+
"2. (Optional) Enable Privacy-Safe Gemini CLI OpenTelemetry outfile (exact token & model metrics)",
|
|
672
|
+
" Add to ~/.gemini/settings.json (logPrompts MUST remain false):",
|
|
673
|
+
"",
|
|
674
|
+
JSON.stringify(
|
|
675
|
+
{
|
|
676
|
+
telemetry: {
|
|
677
|
+
enabled: true,
|
|
678
|
+
target: "local",
|
|
679
|
+
otlpEndpoint: "",
|
|
680
|
+
logPrompts: false,
|
|
681
|
+
outfile: "~/.gemini/telemetry_stats.jsonl"
|
|
682
|
+
}
|
|
683
|
+
},
|
|
684
|
+
null,
|
|
685
|
+
2
|
|
686
|
+
),
|
|
687
|
+
"",
|
|
688
|
+
"3. (Optional) Antigravity CLI Hook Recorder (numeric metadata ONLY)",
|
|
689
|
+
" Add to ~/.gemini/config/hooks.json (leaves statusLine untouched):",
|
|
690
|
+
"",
|
|
691
|
+
JSON.stringify(
|
|
692
|
+
{
|
|
693
|
+
hooks: {
|
|
694
|
+
PostInvocation: [
|
|
695
|
+
{
|
|
696
|
+
matcher: ".*",
|
|
697
|
+
hooks: [
|
|
698
|
+
{
|
|
699
|
+
type: "command",
|
|
700
|
+
command: "npx -y agycraft-mcp record",
|
|
701
|
+
timeout: 3e3
|
|
702
|
+
}
|
|
703
|
+
]
|
|
704
|
+
}
|
|
705
|
+
]
|
|
706
|
+
}
|
|
707
|
+
},
|
|
708
|
+
null,
|
|
709
|
+
2
|
|
710
|
+
),
|
|
711
|
+
"",
|
|
712
|
+
` Whitelisted numeric records are stored locally at: ${usagePath}`,
|
|
713
|
+
" (Strict whitelist: ts, provider, product, session_hash, model, input_tokens,",
|
|
714
|
+
" output_tokens, context_used_pct, tool_calls, turn_index, error_code.",
|
|
715
|
+
" Prompts, code, paths, and emails are NEVER written or uploaded.)",
|
|
716
|
+
" Note: AGY PostInvocation hooks may only capture invocation timestamps/counts",
|
|
717
|
+
" if token/model fields aren't emitted, whereas Gemini CLI OTel (step 2)",
|
|
718
|
+
" provides exact token/model metrics.",
|
|
719
|
+
"",
|
|
720
|
+
"4. (Optional) Project-Scoped Sandbox Isolation (zero global ~/.config/agycraft writes):",
|
|
721
|
+
" Set AGYCRAFT_CONFIG_DIR to isolate usage.jsonl, .salt, and cache/ inside your repo/sandbox:",
|
|
722
|
+
" export AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft",
|
|
723
|
+
"",
|
|
724
|
+
" CLI one-liners:",
|
|
725
|
+
" Gemini CLI (supports --scope project):",
|
|
726
|
+
" gemini mcp add --scope project --env AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft agycraft npx -y agycraft-mcp",
|
|
727
|
+
" Antigravity CLI:",
|
|
728
|
+
" agy mcp add --env AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft agycraft npx -y agycraft-mcp",
|
|
729
|
+
"",
|
|
730
|
+
" Example sandboxed settings.json / mcp_config.json:",
|
|
731
|
+
JSON.stringify(
|
|
732
|
+
{
|
|
733
|
+
mcpServers: {
|
|
734
|
+
agycraft: {
|
|
735
|
+
command: "npx",
|
|
736
|
+
args: ["-y", "agycraft-mcp"],
|
|
737
|
+
env: {
|
|
738
|
+
AGYCRAFT_CONFIG_DIR: "./sandbox_repo/.agycraft"
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
},
|
|
742
|
+
toolPermission: "proceed-in-sandbox"
|
|
743
|
+
},
|
|
744
|
+
null,
|
|
745
|
+
2
|
|
746
|
+
),
|
|
747
|
+
' Note: "toolPermission": "proceed-in-sandbox" is an Antigravity top-level settings.json',
|
|
748
|
+
' permission field (sibling to "mcpServers"). `agy mcp add` / `gemini mcp add` do not',
|
|
749
|
+
" write this field automatically; add it manually at the top level if needed.",
|
|
750
|
+
"",
|
|
751
|
+
"5. Verify & Clear Local Data Anytime:",
|
|
752
|
+
" npx agycraft-mcp doctor",
|
|
753
|
+
" npx agycraft-mcp preflight",
|
|
754
|
+
" npx agycraft-mcp clear-local-data"
|
|
755
|
+
].join("\n");
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// src/cli/clear-local-data.ts
|
|
759
|
+
import { rm } from "fs/promises";
|
|
760
|
+
|
|
761
|
+
// src/collectors/agy-hook.ts
|
|
762
|
+
import { appendFile, mkdir as mkdir2, readFile as readFile3 } from "fs/promises";
|
|
763
|
+
import { dirname as dirname2 } from "path";
|
|
764
|
+
|
|
765
|
+
// src/privacy.ts
|
|
766
|
+
import { createHash, randomBytes } from "crypto";
|
|
767
|
+
import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
|
|
768
|
+
import { dirname, resolve as resolve2 } from "path";
|
|
769
|
+
var ALLOWED_PROVIDERS = /* @__PURE__ */ new Set(["google", "antigravity", "other"]);
|
|
770
|
+
var ALLOWED_PRODUCTS = /* @__PURE__ */ new Set(["agy", "gemini-cli", "api", "web"]);
|
|
771
|
+
var ALLOWED_AUTH_MODES = /* @__PURE__ */ new Set([
|
|
772
|
+
"google_oauth",
|
|
773
|
+
"gcp_adc",
|
|
774
|
+
"api_key",
|
|
775
|
+
"unknown"
|
|
776
|
+
]);
|
|
777
|
+
var SAFE_MODEL_RE = /^[a-zA-Z0-9._:-]{1,64}$/;
|
|
778
|
+
var SAFE_ERROR_CODE_RE = /^[A-Z0-9_:-]{1,48}$/;
|
|
779
|
+
var cachedSalts = /* @__PURE__ */ new Map();
|
|
780
|
+
async function getOrCreateLocalSalt(saltPath = getSaltFilePath()) {
|
|
781
|
+
const key = resolve2(saltPath);
|
|
782
|
+
const cached = cachedSalts.get(key);
|
|
783
|
+
if (cached) {
|
|
784
|
+
return cached;
|
|
785
|
+
}
|
|
786
|
+
try {
|
|
787
|
+
const existing = (await readFile2(key, "utf8")).trim();
|
|
788
|
+
if (existing.length >= 16) {
|
|
789
|
+
cachedSalts.set(key, existing);
|
|
790
|
+
return existing;
|
|
791
|
+
}
|
|
792
|
+
} catch {
|
|
793
|
+
}
|
|
794
|
+
const fresh = randomBytes(16).toString("hex");
|
|
795
|
+
await mkdir(dirname(key), { recursive: true });
|
|
796
|
+
await writeFile(key, fresh, { mode: 384 });
|
|
797
|
+
cachedSalts.set(key, fresh);
|
|
798
|
+
return fresh;
|
|
799
|
+
}
|
|
800
|
+
function resetSaltCache(saltPath) {
|
|
801
|
+
if (saltPath !== void 0) {
|
|
802
|
+
cachedSalts.delete(resolve2(saltPath));
|
|
803
|
+
} else {
|
|
804
|
+
cachedSalts.clear();
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
function hashSessionId(rawSessionId, salt) {
|
|
808
|
+
return createHash("sha256").update(`${salt}:${rawSessionId}`).digest("hex").slice(0, 12);
|
|
809
|
+
}
|
|
810
|
+
function hashProjectPath(workspaceDir, salt) {
|
|
811
|
+
return createHash("sha256").update(`${salt}:${resolve2(workspaceDir)}`).digest("hex").slice(0, 12);
|
|
812
|
+
}
|
|
813
|
+
function clampNonNegativeInt(val) {
|
|
814
|
+
const n = typeof val === "number" ? val : Number(val);
|
|
815
|
+
if (!Number.isFinite(n) || n < 0) {
|
|
816
|
+
return 0;
|
|
817
|
+
}
|
|
818
|
+
return Math.floor(n);
|
|
819
|
+
}
|
|
820
|
+
function clampPct(val) {
|
|
821
|
+
if (val === null || val === void 0 || val === "") {
|
|
822
|
+
return null;
|
|
823
|
+
}
|
|
824
|
+
const n = typeof val === "number" ? val : Number(val);
|
|
825
|
+
if (!Number.isFinite(n)) {
|
|
826
|
+
return null;
|
|
827
|
+
}
|
|
828
|
+
return Math.round(Math.min(100, Math.max(0, n)) * 10) / 10;
|
|
829
|
+
}
|
|
830
|
+
function sanitizeModelName(raw) {
|
|
831
|
+
if (typeof raw !== "string") {
|
|
832
|
+
return "unknown";
|
|
833
|
+
}
|
|
834
|
+
const trimmed = raw.trim();
|
|
835
|
+
if (trimmed.includes("/") || trimmed.includes("\\") || trimmed.includes("@") || trimmed.includes(" ") || !SAFE_MODEL_RE.test(trimmed)) {
|
|
836
|
+
return "unknown";
|
|
837
|
+
}
|
|
838
|
+
return trimmed;
|
|
839
|
+
}
|
|
840
|
+
function sanitizeErrorCode(raw) {
|
|
841
|
+
if (raw === null || raw === void 0 || raw === "") {
|
|
842
|
+
return null;
|
|
843
|
+
}
|
|
844
|
+
const str = String(raw).trim().toUpperCase();
|
|
845
|
+
if (SAFE_ERROR_CODE_RE.test(str)) {
|
|
846
|
+
return str;
|
|
847
|
+
}
|
|
848
|
+
const httpMatch = str.match(/\b(400|401|403|404|408|429|500|502|503|504)\b/);
|
|
849
|
+
if (httpMatch?.[1]) {
|
|
850
|
+
return httpMatch[1];
|
|
851
|
+
}
|
|
852
|
+
return "UNKNOWN_ERROR";
|
|
853
|
+
}
|
|
854
|
+
function sanitizeAuthMode(raw) {
|
|
855
|
+
if (typeof raw === "string") {
|
|
856
|
+
const normalized = raw.trim().toLowerCase();
|
|
857
|
+
if (ALLOWED_AUTH_MODES.has(normalized)) {
|
|
858
|
+
return normalized;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
return "unknown";
|
|
862
|
+
}
|
|
863
|
+
function sanitizeIsoTimestamp(raw) {
|
|
864
|
+
if (typeof raw === "string") {
|
|
865
|
+
const parsed = Date.parse(raw);
|
|
866
|
+
if (!Number.isNaN(parsed)) {
|
|
867
|
+
return new Date(parsed).toISOString();
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
if (typeof raw === "number" && Number.isFinite(raw)) {
|
|
871
|
+
const ms = raw > 1e12 ? raw : raw * 1e3;
|
|
872
|
+
return new Date(ms).toISOString();
|
|
873
|
+
}
|
|
874
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
875
|
+
}
|
|
876
|
+
function sanitizeUsagePayload(raw, salt) {
|
|
877
|
+
const ctx = raw.context_window && typeof raw.context_window === "object" ? raw.context_window : {};
|
|
878
|
+
const providerRaw = typeof raw.provider === "string" ? raw.provider.toLowerCase() : "antigravity";
|
|
879
|
+
const provider = ALLOWED_PROVIDERS.has(providerRaw) ? providerRaw : "antigravity";
|
|
880
|
+
const productRaw = typeof raw.product === "string" ? raw.product.toLowerCase() : "agy";
|
|
881
|
+
const product = ALLOWED_PRODUCTS.has(productRaw) ? productRaw : "agy";
|
|
882
|
+
const sessionSource = typeof raw.session_hash === "string" && /^[a-f0-9]{8,16}$/.test(raw.session_hash) ? raw.session_hash : hashSessionId(
|
|
883
|
+
typeof raw.session_hash === "string" && raw.session_hash.trim().length > 0 ? raw.session_hash.trim() : typeof raw.session_id === "string" && raw.session_id.trim().length > 0 ? raw.session_id.trim() : typeof raw.conversation_id === "string" && raw.conversation_id.trim().length > 0 ? raw.conversation_id.trim() : "default-session",
|
|
884
|
+
salt
|
|
885
|
+
);
|
|
886
|
+
let projectHash = null;
|
|
887
|
+
if (typeof raw.project_hash === "string" && /^[a-f0-9]{8,16}$/.test(raw.project_hash)) {
|
|
888
|
+
projectHash = raw.project_hash;
|
|
889
|
+
} else if (typeof raw.workspace_dir === "string" && raw.workspace_dir.trim().length > 0) {
|
|
890
|
+
projectHash = hashProjectPath(raw.workspace_dir.trim(), salt);
|
|
891
|
+
} else if (typeof raw.cwd === "string" && raw.cwd.trim().length > 0) {
|
|
892
|
+
projectHash = hashProjectPath(raw.cwd.trim(), salt);
|
|
893
|
+
}
|
|
894
|
+
const inputTokens = clampNonNegativeInt(
|
|
895
|
+
raw.input_tokens ?? ctx.input_tokens ?? raw.prompt_tokens ?? 0
|
|
896
|
+
);
|
|
897
|
+
const cacheReadTokens = clampNonNegativeInt(
|
|
898
|
+
raw.cache_read_tokens ?? ctx.cache_read_tokens ?? raw.cached_content_token_count ?? 0
|
|
899
|
+
);
|
|
900
|
+
const outputTokens = clampNonNegativeInt(
|
|
901
|
+
raw.output_tokens ?? ctx.output_tokens ?? raw.completion_tokens ?? 0
|
|
902
|
+
);
|
|
903
|
+
const thinkingTokens = clampNonNegativeInt(
|
|
904
|
+
raw.thinking_tokens ?? ctx.thinking_tokens ?? raw.thoughts_token_count ?? 0
|
|
905
|
+
);
|
|
906
|
+
const contextUsedPct = clampPct(
|
|
907
|
+
raw.context_used_pct ?? ctx.used_pct ?? ctx.context_used_pct ?? null
|
|
908
|
+
);
|
|
909
|
+
return {
|
|
910
|
+
v: 1,
|
|
911
|
+
ts: sanitizeIsoTimestamp(raw.ts ?? raw.timestamp),
|
|
912
|
+
provider,
|
|
913
|
+
product,
|
|
914
|
+
session_hash: sessionSource,
|
|
915
|
+
model: sanitizeModelName(raw.model ?? ctx.model),
|
|
916
|
+
input_tokens: inputTokens,
|
|
917
|
+
cache_read_tokens: cacheReadTokens,
|
|
918
|
+
output_tokens: outputTokens,
|
|
919
|
+
thinking_tokens: thinkingTokens,
|
|
920
|
+
context_used_pct: contextUsedPct,
|
|
921
|
+
tool_calls: clampNonNegativeInt(raw.tool_calls ?? 0),
|
|
922
|
+
turn_index: clampNonNegativeInt(raw.turn_index ?? 0),
|
|
923
|
+
error_code: sanitizeErrorCode(raw.error_code ?? raw.status_code ?? null),
|
|
924
|
+
project_hash: projectHash,
|
|
925
|
+
auth_mode: sanitizeAuthMode(raw.auth_mode)
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// src/collectors/agy-hook.ts
|
|
930
|
+
async function appendUsageRecord(rawPayload, options) {
|
|
931
|
+
const logPath = options?.logPath ?? getUsageLogPath();
|
|
932
|
+
const salt = await getOrCreateLocalSalt(options?.saltPath);
|
|
933
|
+
const record = sanitizeUsagePayload(rawPayload, salt);
|
|
934
|
+
await mkdir2(dirname2(logPath), { recursive: true });
|
|
935
|
+
await appendFile(logPath, `${JSON.stringify(record)}
|
|
936
|
+
`, {
|
|
937
|
+
encoding: "utf8",
|
|
938
|
+
mode: 384
|
|
939
|
+
});
|
|
940
|
+
return record;
|
|
941
|
+
}
|
|
942
|
+
async function readUsageRecords(options) {
|
|
943
|
+
const logPath = options?.logPath ?? getUsageLogPath();
|
|
944
|
+
let content;
|
|
945
|
+
try {
|
|
946
|
+
content = await readFile3(logPath, "utf8");
|
|
947
|
+
} catch {
|
|
948
|
+
return [];
|
|
949
|
+
}
|
|
950
|
+
const salt = options?.salt ?? await getOrCreateLocalSalt(options?.saltPath);
|
|
951
|
+
const records = [];
|
|
952
|
+
const lines = content.split("\n");
|
|
953
|
+
for (const line of lines) {
|
|
954
|
+
const trimmed = line.trim();
|
|
955
|
+
if (!trimmed) {
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
try {
|
|
959
|
+
const parsed = JSON.parse(trimmed);
|
|
960
|
+
const safe = sanitizeUsagePayload(parsed, salt);
|
|
961
|
+
if (options?.sinceMs !== void 0 && Date.parse(safe.ts) < options.sinceMs) {
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
if (options?.product && options.product !== "all" && safe.product !== options.product) {
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
records.push(safe);
|
|
968
|
+
} catch {
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
return records;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// src/cli/clear-local-data.ts
|
|
975
|
+
async function clearLocalData(options) {
|
|
976
|
+
const usageLogPath = options?.usageLogPath ?? getUsageLogPath();
|
|
977
|
+
const cacheDir = options?.cacheDir ?? getCacheDir();
|
|
978
|
+
const rollupsDir = options?.rollupsDir ?? getRollupsDir();
|
|
979
|
+
const saltPath = options?.saltPath ?? getSaltFilePath();
|
|
980
|
+
const removed = [];
|
|
981
|
+
for (const target of [usageLogPath, saltPath]) {
|
|
982
|
+
try {
|
|
983
|
+
await rm(target, { force: true });
|
|
984
|
+
removed.push(target);
|
|
985
|
+
} catch {
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
for (const dir of [cacheDir, rollupsDir]) {
|
|
989
|
+
try {
|
|
990
|
+
await rm(dir, { recursive: true, force: true });
|
|
991
|
+
removed.push(dir);
|
|
992
|
+
} catch {
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
resetSaltCache();
|
|
996
|
+
return { removed };
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// src/server.ts
|
|
1000
|
+
import { access as access2 } from "fs/promises";
|
|
1001
|
+
import { join as join7 } from "path";
|
|
1002
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
1003
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
1004
|
+
import { z } from "zod";
|
|
1005
|
+
|
|
1006
|
+
// src/collectors/auth-detector.ts
|
|
1007
|
+
import { existsSync } from "fs";
|
|
1008
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
1009
|
+
import { homedir as homedir3 } from "os";
|
|
1010
|
+
import { join as join3 } from "path";
|
|
1011
|
+
function mapSelectedAuthType(raw) {
|
|
1012
|
+
if (typeof raw !== "string") {
|
|
1013
|
+
return null;
|
|
1014
|
+
}
|
|
1015
|
+
const lower = raw.trim().toLowerCase();
|
|
1016
|
+
if (!lower) {
|
|
1017
|
+
return null;
|
|
1018
|
+
}
|
|
1019
|
+
if (lower.includes("oauth")) {
|
|
1020
|
+
return "google_oauth";
|
|
1021
|
+
}
|
|
1022
|
+
if (lower.includes("api-key") || lower.includes("api_key") || lower === "gemini-api-key") {
|
|
1023
|
+
return "api_key";
|
|
1024
|
+
}
|
|
1025
|
+
if (lower.includes("vertex") || lower.includes("adc") || lower.includes("compute") || lower.includes("gcp")) {
|
|
1026
|
+
return "gcp_adc";
|
|
1027
|
+
}
|
|
1028
|
+
return null;
|
|
1029
|
+
}
|
|
1030
|
+
async function readSafeJsonObject(filePath) {
|
|
1031
|
+
try {
|
|
1032
|
+
const raw = await readFile4(filePath, "utf8");
|
|
1033
|
+
const parsed = JSON.parse(raw);
|
|
1034
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1035
|
+
return parsed;
|
|
1036
|
+
}
|
|
1037
|
+
} catch {
|
|
1038
|
+
}
|
|
1039
|
+
return null;
|
|
1040
|
+
}
|
|
1041
|
+
async function detectAuthContext(options) {
|
|
1042
|
+
const home = options?.homeDir ?? homedir3();
|
|
1043
|
+
const env = options?.env ?? process.env;
|
|
1044
|
+
const oauthCredsPath = options?.oauthCredsPath ?? join3(home, ".gemini", "oauth_creds.json");
|
|
1045
|
+
const adcPath = options?.adcPath ?? join3(home, ".config", "gcloud", "application_default_credentials.json");
|
|
1046
|
+
const geminiSettingsPath = options?.geminiSettingsPath ?? join3(home, ".gemini", "settings.json");
|
|
1047
|
+
const agySettingsPath = options?.agySettingsPath ?? join3(home, ".gemini", "antigravity-cli", "settings.json");
|
|
1048
|
+
const hasGeminiApiKey = Boolean(env.GEMINI_API_KEY && env.GEMINI_API_KEY.trim().length > 0);
|
|
1049
|
+
const hasGcpProject = Boolean(
|
|
1050
|
+
env.GOOGLE_CLOUD_PROJECT && env.GOOGLE_CLOUD_PROJECT.trim().length > 0
|
|
1051
|
+
);
|
|
1052
|
+
const hasGacEnv = Boolean(
|
|
1053
|
+
env.GOOGLE_APPLICATION_CREDENTIALS && env.GOOGLE_APPLICATION_CREDENTIALS.trim().length > 0
|
|
1054
|
+
);
|
|
1055
|
+
const hasOauthCredsFile = existsSync(oauthCredsPath);
|
|
1056
|
+
const hasAdcFile = existsSync(adcPath);
|
|
1057
|
+
const [geminiSettings, agySettings] = await Promise.all([
|
|
1058
|
+
readSafeJsonObject(geminiSettingsPath),
|
|
1059
|
+
readSafeJsonObject(agySettingsPath)
|
|
1060
|
+
]);
|
|
1061
|
+
let selectedAuthMode = null;
|
|
1062
|
+
if (geminiSettings) {
|
|
1063
|
+
const security = geminiSettings["security"];
|
|
1064
|
+
if (security && typeof security === "object" && !Array.isArray(security)) {
|
|
1065
|
+
const auth = security["auth"];
|
|
1066
|
+
if (auth && typeof auth === "object" && !Array.isArray(auth)) {
|
|
1067
|
+
selectedAuthMode = mapSelectedAuthType(
|
|
1068
|
+
auth["selectedType"]
|
|
1069
|
+
);
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
const hasAgyGcpConfig = Boolean(
|
|
1074
|
+
agySettings && "gcp" in agySettings && agySettings["gcp"] != null
|
|
1075
|
+
);
|
|
1076
|
+
const detectedSet = /* @__PURE__ */ new Set();
|
|
1077
|
+
if (hasOauthCredsFile || selectedAuthMode === "google_oauth") {
|
|
1078
|
+
detectedSet.add("google_oauth");
|
|
1079
|
+
}
|
|
1080
|
+
if (hasAdcFile || hasGacEnv || hasGcpProject || hasAgyGcpConfig || selectedAuthMode === "gcp_adc") {
|
|
1081
|
+
detectedSet.add("gcp_adc");
|
|
1082
|
+
}
|
|
1083
|
+
if (hasGeminiApiKey || selectedAuthMode === "api_key") {
|
|
1084
|
+
detectedSet.add("api_key");
|
|
1085
|
+
}
|
|
1086
|
+
const detectedModes = ["google_oauth", "gcp_adc", "api_key"].filter(
|
|
1087
|
+
(m) => detectedSet.has(m)
|
|
1088
|
+
);
|
|
1089
|
+
let activeAuthMode = "unknown";
|
|
1090
|
+
if (hasGeminiApiKey) {
|
|
1091
|
+
activeAuthMode = "api_key";
|
|
1092
|
+
} else if (selectedAuthMode) {
|
|
1093
|
+
activeAuthMode = selectedAuthMode;
|
|
1094
|
+
} else if (hasGacEnv || hasGcpProject || hasAgyGcpConfig) {
|
|
1095
|
+
activeAuthMode = "gcp_adc";
|
|
1096
|
+
} else if (hasOauthCredsFile) {
|
|
1097
|
+
activeAuthMode = "google_oauth";
|
|
1098
|
+
} else if (hasAdcFile) {
|
|
1099
|
+
activeAuthMode = "gcp_adc";
|
|
1100
|
+
}
|
|
1101
|
+
const hasMixedAuth = detectedModes.length > 1;
|
|
1102
|
+
const isolationNote = hasMixedAuth ? `Mixed auth contexts detected (${detectedModes.join(", ")}). Active mode inferred as ${activeAuthMode}; Google OAuth and GCP ADC quotas/credentials are isolated\u2014verify active auth before attributing 429/401 errors.` : activeAuthMode !== "unknown" ? `Single auth context detected (${activeAuthMode}); no cross-auth mixing.` : "No local auth credentials or env flags detected (active_auth_mode: unknown).";
|
|
1103
|
+
return {
|
|
1104
|
+
active_auth_mode: activeAuthMode,
|
|
1105
|
+
detected_modes: detectedModes,
|
|
1106
|
+
has_mixed_auth: hasMixedAuth,
|
|
1107
|
+
isolation_note: isolationNote
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
// src/collectors/gemini-otel.ts
|
|
1112
|
+
import { readFile as readFile5 } from "fs/promises";
|
|
1113
|
+
async function readGeminiOtelRecords(options) {
|
|
1114
|
+
const otelPath = options?.otelPath ?? getDefaultGeminiTelemetryPath();
|
|
1115
|
+
const salt = options?.salt ?? await getOrCreateLocalSalt(options?.saltPath);
|
|
1116
|
+
let content;
|
|
1117
|
+
try {
|
|
1118
|
+
content = await readFile5(otelPath, "utf8");
|
|
1119
|
+
} catch {
|
|
1120
|
+
return [];
|
|
1121
|
+
}
|
|
1122
|
+
const records = [];
|
|
1123
|
+
for (const line of content.split("\n")) {
|
|
1124
|
+
const trimmed = line.trim();
|
|
1125
|
+
if (!trimmed) {
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
try {
|
|
1129
|
+
const entry = JSON.parse(trimmed);
|
|
1130
|
+
const attrs = extractOtelAttributes(entry);
|
|
1131
|
+
const inputTokens = firstNumber(
|
|
1132
|
+
attrs["gen_ai.usage.input_tokens"],
|
|
1133
|
+
attrs["input_token_count"],
|
|
1134
|
+
attrs["prompt_tokens"],
|
|
1135
|
+
entry["input_tokens"],
|
|
1136
|
+
entry["prompt_tokens"]
|
|
1137
|
+
);
|
|
1138
|
+
const outputTokens = firstNumber(
|
|
1139
|
+
attrs["gen_ai.usage.output_tokens"],
|
|
1140
|
+
attrs["output_token_count"],
|
|
1141
|
+
attrs["completion_tokens"],
|
|
1142
|
+
entry["output_tokens"],
|
|
1143
|
+
entry["completion_tokens"]
|
|
1144
|
+
);
|
|
1145
|
+
const cacheReadTokens = firstNumber(
|
|
1146
|
+
attrs["gen_ai.usage.cache_read_input_tokens"],
|
|
1147
|
+
attrs["cache_read_tokens"],
|
|
1148
|
+
attrs["cached_content_token_count"],
|
|
1149
|
+
entry["cache_read_tokens"]
|
|
1150
|
+
);
|
|
1151
|
+
const thinkingTokens = firstNumber(
|
|
1152
|
+
attrs["gen_ai.usage.thinking_tokens"],
|
|
1153
|
+
attrs["thinking_tokens"],
|
|
1154
|
+
attrs["thoughts_token_count"],
|
|
1155
|
+
entry["thinking_tokens"]
|
|
1156
|
+
);
|
|
1157
|
+
const errorCode = attrs["error.type"] ?? attrs["http.response.status_code"] ?? entry["error_code"] ?? null;
|
|
1158
|
+
if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0 && !errorCode) {
|
|
1159
|
+
continue;
|
|
1160
|
+
}
|
|
1161
|
+
const rawSession = String(
|
|
1162
|
+
attrs["session.id"] ?? entry["session_id"] ?? "gemini-cli-session"
|
|
1163
|
+
);
|
|
1164
|
+
const record = sanitizeUsagePayload(
|
|
1165
|
+
{
|
|
1166
|
+
ts: entry["timestamp"] ?? entry["ts"] ?? entry["startTime"],
|
|
1167
|
+
provider: "google",
|
|
1168
|
+
product: "gemini-cli",
|
|
1169
|
+
session_hash: hashSessionId(rawSession, salt),
|
|
1170
|
+
model: attrs["gen_ai.request.model"] ?? attrs["gen_ai.response.model"] ?? attrs["model"] ?? entry["model"] ?? "unknown",
|
|
1171
|
+
input_tokens: inputTokens,
|
|
1172
|
+
cache_read_tokens: cacheReadTokens,
|
|
1173
|
+
output_tokens: outputTokens,
|
|
1174
|
+
thinking_tokens: thinkingTokens,
|
|
1175
|
+
context_used_pct: attrs["context_used_pct"] ?? null,
|
|
1176
|
+
tool_calls: firstNumber(attrs["tool_calls"], entry["tool_calls"]),
|
|
1177
|
+
turn_index: firstNumber(attrs["turn_index"], entry["turn_index"]),
|
|
1178
|
+
error_code: errorCode
|
|
1179
|
+
},
|
|
1180
|
+
salt
|
|
1181
|
+
);
|
|
1182
|
+
if (options?.sinceMs !== void 0 && Date.parse(record.ts) < options.sinceMs) {
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
records.push(record);
|
|
1186
|
+
} catch {
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
return records;
|
|
1190
|
+
}
|
|
1191
|
+
function extractOtelAttributes(entry) {
|
|
1192
|
+
const attrs = entry["attributes"];
|
|
1193
|
+
if (attrs && typeof attrs === "object" && !Array.isArray(attrs)) {
|
|
1194
|
+
return attrs;
|
|
1195
|
+
}
|
|
1196
|
+
return {};
|
|
1197
|
+
}
|
|
1198
|
+
function firstNumber(...candidates) {
|
|
1199
|
+
for (const val of candidates) {
|
|
1200
|
+
if (val === null || val === void 0 || val === "") {
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
const n = typeof val === "number" ? val : Number(val);
|
|
1204
|
+
if (Number.isFinite(n) && n >= 0) {
|
|
1205
|
+
return Math.floor(n);
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return 0;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// src/collectors/transcript-meta.ts
|
|
1212
|
+
import { readdir, readFile as readFile6 } from "fs/promises";
|
|
1213
|
+
import { join as join4, resolve as resolve3 } from "path";
|
|
1214
|
+
var SAFE_TOOL_NAME_RE = /^[a-zA-Z0-9._-]{1,48}$/;
|
|
1215
|
+
function sanitizeToolCategory(raw) {
|
|
1216
|
+
if (typeof raw !== "string") {
|
|
1217
|
+
return "unknown_tool";
|
|
1218
|
+
}
|
|
1219
|
+
const trimmed = raw.trim();
|
|
1220
|
+
if (SAFE_TOOL_NAME_RE.test(trimmed)) {
|
|
1221
|
+
return trimmed;
|
|
1222
|
+
}
|
|
1223
|
+
return "unknown_tool";
|
|
1224
|
+
}
|
|
1225
|
+
async function analyzeTranscriptStructure(transcriptPath, loopThreshold = 4) {
|
|
1226
|
+
let rawText;
|
|
1227
|
+
try {
|
|
1228
|
+
rawText = await readFile6(transcriptPath, "utf8");
|
|
1229
|
+
} catch {
|
|
1230
|
+
return emptyTranscriptMeta();
|
|
1231
|
+
}
|
|
1232
|
+
return parseTranscriptLines(rawText.split("\n"), loopThreshold);
|
|
1233
|
+
}
|
|
1234
|
+
function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
1235
|
+
let totalSteps = 0;
|
|
1236
|
+
let userTurns = 0;
|
|
1237
|
+
let assistantTurns = 0;
|
|
1238
|
+
let toolCallCount = 0;
|
|
1239
|
+
let toolErrorCount = 0;
|
|
1240
|
+
let hasCompactEvent = false;
|
|
1241
|
+
let stepsSinceLastCompact = 0;
|
|
1242
|
+
let currentStreak = 0;
|
|
1243
|
+
let currentStreakTool = null;
|
|
1244
|
+
let maxConsecutiveFailures = 0;
|
|
1245
|
+
let maxFailureTool = null;
|
|
1246
|
+
for (const line of lines) {
|
|
1247
|
+
const trimmed = line.trim();
|
|
1248
|
+
if (!trimmed) {
|
|
1249
|
+
continue;
|
|
1250
|
+
}
|
|
1251
|
+
let parsed;
|
|
1252
|
+
try {
|
|
1253
|
+
parsed = JSON.parse(trimmed);
|
|
1254
|
+
} catch {
|
|
1255
|
+
continue;
|
|
1256
|
+
}
|
|
1257
|
+
totalSteps += 1;
|
|
1258
|
+
stepsSinceLastCompact += 1;
|
|
1259
|
+
const role = typeof parsed.role === "string" ? parsed.role.toLowerCase() : "";
|
|
1260
|
+
const eventType = typeof parsed.type === "string" ? parsed.type.toLowerCase() : "";
|
|
1261
|
+
const source = typeof parsed.source === "string" ? parsed.source.toUpperCase() : "";
|
|
1262
|
+
if (eventType === "compact" || eventType === "compaction") {
|
|
1263
|
+
hasCompactEvent = true;
|
|
1264
|
+
stepsSinceLastCompact = 0;
|
|
1265
|
+
continue;
|
|
1266
|
+
}
|
|
1267
|
+
if (role === "user" || eventType === "user_message" || eventType === "user_input" || source === "USER_EXPLICIT") {
|
|
1268
|
+
userTurns += 1;
|
|
1269
|
+
currentStreak = 0;
|
|
1270
|
+
currentStreakTool = null;
|
|
1271
|
+
} else if (role === "assistant" || role === "model" || eventType === "assistant_message" || eventType === "planner_response") {
|
|
1272
|
+
assistantTurns += 1;
|
|
1273
|
+
}
|
|
1274
|
+
if (Array.isArray(parsed.tool_calls)) {
|
|
1275
|
+
toolCallCount += parsed.tool_calls.length;
|
|
1276
|
+
for (const tc of parsed.tool_calls) {
|
|
1277
|
+
if (!tc || typeof tc !== "object") {
|
|
1278
|
+
continue;
|
|
1279
|
+
}
|
|
1280
|
+
const tcObj = tc;
|
|
1281
|
+
const toolName = sanitizeToolCategory(tcObj.tool_name ?? tcObj.name);
|
|
1282
|
+
const failed = tcObj.is_error === true || tcObj.status === "error" || tcObj.status === "failed" || typeof tcObj.exit_code === "number" && tcObj.exit_code !== 0;
|
|
1283
|
+
if (failed) {
|
|
1284
|
+
toolErrorCount += 1;
|
|
1285
|
+
if (currentStreakTool === toolName) {
|
|
1286
|
+
currentStreak += 1;
|
|
1287
|
+
} else {
|
|
1288
|
+
currentStreak = 1;
|
|
1289
|
+
currentStreakTool = toolName;
|
|
1290
|
+
}
|
|
1291
|
+
if (currentStreak > maxConsecutiveFailures) {
|
|
1292
|
+
maxConsecutiveFailures = currentStreak;
|
|
1293
|
+
maxFailureTool = toolName;
|
|
1294
|
+
}
|
|
1295
|
+
} else {
|
|
1296
|
+
currentStreak = 0;
|
|
1297
|
+
currentStreakTool = null;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
} else if (typeof parsed.tool_calls === "number" && Number.isFinite(parsed.tool_calls)) {
|
|
1301
|
+
toolCallCount += Math.max(0, Math.floor(parsed.tool_calls));
|
|
1302
|
+
}
|
|
1303
|
+
const isToolEvent = role === "tool" || eventType === "tool_call" || eventType === "tool_result" || Boolean(parsed.tool_name);
|
|
1304
|
+
if (isToolEvent) {
|
|
1305
|
+
toolCallCount += 1;
|
|
1306
|
+
const toolName = sanitizeToolCategory(parsed.tool_name ?? parsed.name);
|
|
1307
|
+
const failed = parsed.is_error === true || parsed.status === "error" || parsed.status === "failed" || typeof parsed.exit_code === "number" && parsed.exit_code !== 0;
|
|
1308
|
+
if (failed) {
|
|
1309
|
+
toolErrorCount += 1;
|
|
1310
|
+
if (currentStreakTool === toolName) {
|
|
1311
|
+
currentStreak += 1;
|
|
1312
|
+
} else {
|
|
1313
|
+
currentStreak = 1;
|
|
1314
|
+
currentStreakTool = toolName;
|
|
1315
|
+
}
|
|
1316
|
+
if (currentStreak > maxConsecutiveFailures) {
|
|
1317
|
+
maxConsecutiveFailures = currentStreak;
|
|
1318
|
+
maxFailureTool = toolName;
|
|
1319
|
+
}
|
|
1320
|
+
} else {
|
|
1321
|
+
currentStreak = 0;
|
|
1322
|
+
currentStreakTool = null;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
return {
|
|
1327
|
+
total_steps: totalSteps,
|
|
1328
|
+
user_turns: userTurns,
|
|
1329
|
+
assistant_turns: assistantTurns,
|
|
1330
|
+
tool_call_count: toolCallCount,
|
|
1331
|
+
tool_error_count: toolErrorCount,
|
|
1332
|
+
max_consecutive_tool_failures: maxConsecutiveFailures,
|
|
1333
|
+
consecutive_failure_tool_type: maxFailureTool,
|
|
1334
|
+
has_compact_event: hasCompactEvent,
|
|
1335
|
+
steps_since_last_compact: stepsSinceLastCompact,
|
|
1336
|
+
loop_detected: maxConsecutiveFailures >= loopThreshold
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
function emptyTranscriptMeta() {
|
|
1340
|
+
return {
|
|
1341
|
+
total_steps: 0,
|
|
1342
|
+
user_turns: 0,
|
|
1343
|
+
assistant_turns: 0,
|
|
1344
|
+
tool_call_count: 0,
|
|
1345
|
+
tool_error_count: 0,
|
|
1346
|
+
max_consecutive_tool_failures: 0,
|
|
1347
|
+
consecutive_failure_tool_type: null,
|
|
1348
|
+
has_compact_event: false,
|
|
1349
|
+
steps_since_last_compact: 0,
|
|
1350
|
+
loop_detected: false
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1353
|
+
function extractStructuralTimestampMs(parsed) {
|
|
1354
|
+
const raw = parsed.created_at ?? parsed.timestamp ?? parsed.ts;
|
|
1355
|
+
if (typeof raw === "string") {
|
|
1356
|
+
const ms = Date.parse(raw);
|
|
1357
|
+
return Number.isNaN(ms) ? null : ms;
|
|
1358
|
+
}
|
|
1359
|
+
if (typeof raw === "number" && Number.isFinite(raw)) {
|
|
1360
|
+
return raw > 1e12 ? raw : raw * 1e3;
|
|
1361
|
+
}
|
|
1362
|
+
return null;
|
|
1363
|
+
}
|
|
1364
|
+
function formatLocalIsoish(ms, timezone) {
|
|
1365
|
+
const tz = timezone || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
1366
|
+
try {
|
|
1367
|
+
return new Intl.DateTimeFormat("en-US", {
|
|
1368
|
+
timeZone: tz,
|
|
1369
|
+
dateStyle: "medium",
|
|
1370
|
+
timeStyle: "short"
|
|
1371
|
+
}).format(new Date(ms));
|
|
1372
|
+
} catch {
|
|
1373
|
+
return new Date(ms).toISOString();
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
async function scanTranscriptActivity(options) {
|
|
1377
|
+
const explicitBrainDir = options?.brainDir;
|
|
1378
|
+
let brainDir;
|
|
1379
|
+
if (explicitBrainDir !== void 0) {
|
|
1380
|
+
const trimmed = explicitBrainDir.trim();
|
|
1381
|
+
brainDir = trimmed.length === 0 || isBrainScanDisabledValue(trimmed) ? null : resolve3(trimmed);
|
|
1382
|
+
} else {
|
|
1383
|
+
brainDir = getAgyBrainDir();
|
|
1384
|
+
}
|
|
1385
|
+
const nowMs = options?.nowMs ?? Date.now();
|
|
1386
|
+
const tz = options?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
1387
|
+
const cutoff5h = nowMs - 5 * 3600 * 1e3;
|
|
1388
|
+
const cutoff7d = nowMs - 7 * 86400 * 1e3;
|
|
1389
|
+
let sessions5h = 0;
|
|
1390
|
+
let turns5h = 0;
|
|
1391
|
+
let tools5h = 0;
|
|
1392
|
+
let earliest5h = null;
|
|
1393
|
+
let sessions7d = 0;
|
|
1394
|
+
let turns7d = 0;
|
|
1395
|
+
let tools7d = 0;
|
|
1396
|
+
let earliest7d = null;
|
|
1397
|
+
let sessionDirs = [];
|
|
1398
|
+
if (brainDir !== null) {
|
|
1399
|
+
try {
|
|
1400
|
+
const entries = await readdir(brainDir, { withFileTypes: true });
|
|
1401
|
+
sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
1402
|
+
} catch {
|
|
1403
|
+
sessionDirs = [];
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
for (const dirName of sessionDirs) {
|
|
1407
|
+
const transcriptPath = join4(brainDir, dirName, ".system_generated", "logs", "transcript.jsonl");
|
|
1408
|
+
let rawText;
|
|
1409
|
+
try {
|
|
1410
|
+
rawText = await readFile6(transcriptPath, "utf8");
|
|
1411
|
+
} catch {
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
let seenIn5h = false;
|
|
1415
|
+
let seenIn7d = false;
|
|
1416
|
+
for (const line of rawText.split("\n")) {
|
|
1417
|
+
const trimmed = line.trim();
|
|
1418
|
+
if (!trimmed) {
|
|
1419
|
+
continue;
|
|
1420
|
+
}
|
|
1421
|
+
let parsed;
|
|
1422
|
+
try {
|
|
1423
|
+
parsed = JSON.parse(trimmed);
|
|
1424
|
+
} catch {
|
|
1425
|
+
continue;
|
|
1426
|
+
}
|
|
1427
|
+
const tsMs = extractStructuralTimestampMs(parsed);
|
|
1428
|
+
if (tsMs === null || tsMs < cutoff7d || tsMs > nowMs + 6e4) {
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
const typeStr = typeof parsed.type === "string" ? parsed.type.toUpperCase() : "";
|
|
1432
|
+
const sourceStr = typeof parsed.source === "string" ? parsed.source.toUpperCase() : "";
|
|
1433
|
+
const roleStr = typeof parsed.role === "string" ? parsed.role.toLowerCase() : "";
|
|
1434
|
+
const isTurn = typeStr === "USER_INPUT" || typeStr === "PLANNER_RESPONSE" || typeStr === "USER_MESSAGE" || typeStr === "ASSISTANT_MESSAGE" || sourceStr === "USER_EXPLICIT" || sourceStr === "MODEL" || roleStr === "user" || roleStr === "assistant" || roleStr === "model" || typeof parsed.step_index === "number";
|
|
1435
|
+
const isTool = typeStr === "TOOL_CALL" || typeStr === "TOOL_RESULT" || roleStr === "tool" || Boolean(parsed.tool_name);
|
|
1436
|
+
if (tsMs >= cutoff7d) {
|
|
1437
|
+
seenIn7d = true;
|
|
1438
|
+
if (isTurn) turns7d += 1;
|
|
1439
|
+
if (isTool) tools7d += 1;
|
|
1440
|
+
if (earliest7d === null || tsMs < earliest7d) {
|
|
1441
|
+
earliest7d = tsMs;
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
if (tsMs >= cutoff5h) {
|
|
1445
|
+
seenIn5h = true;
|
|
1446
|
+
if (isTurn) turns5h += 1;
|
|
1447
|
+
if (isTool) tools5h += 1;
|
|
1448
|
+
if (earliest5h === null || tsMs < earliest5h) {
|
|
1449
|
+
earliest5h = tsMs;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
if (seenIn5h) sessions5h += 1;
|
|
1454
|
+
if (seenIn7d) sessions7d += 1;
|
|
1455
|
+
}
|
|
1456
|
+
const reset5hMs = earliest5h !== null ? earliest5h + 5 * 3600 * 1e3 : null;
|
|
1457
|
+
return {
|
|
1458
|
+
source: "transcript_timestamps",
|
|
1459
|
+
note: "Estimated from local AGY session timestamps; run agycraft-mcp setup for exact token counts.",
|
|
1460
|
+
timezone: tz,
|
|
1461
|
+
window_5h: {
|
|
1462
|
+
session_count: sessions5h,
|
|
1463
|
+
turn_count: turns5h,
|
|
1464
|
+
tool_call_count: tools5h,
|
|
1465
|
+
earliest_turn_at: earliest5h !== null ? new Date(earliest5h).toISOString() : null,
|
|
1466
|
+
estimated_5h_reset_at: reset5hMs !== null ? new Date(reset5hMs).toISOString() : null,
|
|
1467
|
+
estimated_5h_reset_local: reset5hMs !== null ? formatLocalIsoish(reset5hMs, tz) : null
|
|
1468
|
+
},
|
|
1469
|
+
window_7d: {
|
|
1470
|
+
session_count: sessions7d,
|
|
1471
|
+
turn_count: turns7d,
|
|
1472
|
+
tool_call_count: tools7d,
|
|
1473
|
+
earliest_turn_at: earliest7d !== null ? new Date(earliest7d).toISOString() : null
|
|
1474
|
+
},
|
|
1475
|
+
earliest_turn_5h_ms: earliest5h,
|
|
1476
|
+
earliest_turn_7d_ms: earliest7d
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1479
|
+
async function buildConversationProjectIndex(historyPath, salt) {
|
|
1480
|
+
const index = /* @__PURE__ */ new Map();
|
|
1481
|
+
if (!historyPath) {
|
|
1482
|
+
return index;
|
|
1483
|
+
}
|
|
1484
|
+
let rawText;
|
|
1485
|
+
try {
|
|
1486
|
+
rawText = await readFile6(historyPath, "utf8");
|
|
1487
|
+
} catch {
|
|
1488
|
+
return index;
|
|
1489
|
+
}
|
|
1490
|
+
for (const line of rawText.split("\n")) {
|
|
1491
|
+
const trimmed = line.trim();
|
|
1492
|
+
if (!trimmed) {
|
|
1493
|
+
continue;
|
|
1494
|
+
}
|
|
1495
|
+
try {
|
|
1496
|
+
const parsed = JSON.parse(trimmed);
|
|
1497
|
+
const convId = typeof parsed.conversationId === "string" ? parsed.conversationId.trim() : "";
|
|
1498
|
+
const workspace = typeof parsed.workspace === "string" ? parsed.workspace.trim() : "";
|
|
1499
|
+
if (convId.length > 0 && workspace.length > 0) {
|
|
1500
|
+
index.set(convId, hashProjectPath(workspace, salt));
|
|
1501
|
+
}
|
|
1502
|
+
} catch {
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
return index;
|
|
1506
|
+
}
|
|
1507
|
+
function firstNonNegInt(...candidates) {
|
|
1508
|
+
for (const val of candidates) {
|
|
1509
|
+
if (val === null || val === void 0 || val === "") {
|
|
1510
|
+
continue;
|
|
1511
|
+
}
|
|
1512
|
+
const n = typeof val === "number" ? val : Number(val);
|
|
1513
|
+
if (Number.isFinite(n) && n >= 0) {
|
|
1514
|
+
return Math.floor(n);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
return 0;
|
|
1518
|
+
}
|
|
1519
|
+
function resolveOptionalPath(explicit, fallbackFn) {
|
|
1520
|
+
if (explicit === null) {
|
|
1521
|
+
return null;
|
|
1522
|
+
}
|
|
1523
|
+
if (explicit !== void 0) {
|
|
1524
|
+
const trimmed = explicit.trim();
|
|
1525
|
+
if (trimmed.length === 0 || isBrainScanDisabledValue(trimmed)) {
|
|
1526
|
+
return null;
|
|
1527
|
+
}
|
|
1528
|
+
return resolve3(trimmed);
|
|
1529
|
+
}
|
|
1530
|
+
return fallbackFn();
|
|
1531
|
+
}
|
|
1532
|
+
async function collectTranscriptUsageRecords(options) {
|
|
1533
|
+
const brainDir = resolveOptionalPath(options?.brainDir, getAgyBrainDir);
|
|
1534
|
+
const historyPath = resolveOptionalPath(options?.historyPath, getAgyHistoryPath);
|
|
1535
|
+
const salt = options?.salt ?? await getOrCreateLocalSalt(options?.saltPath);
|
|
1536
|
+
const nowMs = options?.nowMs ?? Date.now();
|
|
1537
|
+
const sinceMs = options?.sinceMs;
|
|
1538
|
+
const projectIndex = await buildConversationProjectIndex(historyPath, salt);
|
|
1539
|
+
const records = [];
|
|
1540
|
+
let attributedSessionCount = 0;
|
|
1541
|
+
let unattributedSessionCount = 0;
|
|
1542
|
+
if (brainDir === null) {
|
|
1543
|
+
return {
|
|
1544
|
+
records,
|
|
1545
|
+
attributed_session_count: 0,
|
|
1546
|
+
unattributed_session_count: 0
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
let sessionDirs = [];
|
|
1550
|
+
try {
|
|
1551
|
+
const entries = await readdir(brainDir, { withFileTypes: true });
|
|
1552
|
+
sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
1553
|
+
} catch {
|
|
1554
|
+
return {
|
|
1555
|
+
records,
|
|
1556
|
+
attributed_session_count: 0,
|
|
1557
|
+
unattributed_session_count: 0
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
for (const sessionId of sessionDirs) {
|
|
1561
|
+
const transcriptPath = join4(
|
|
1562
|
+
brainDir,
|
|
1563
|
+
sessionId,
|
|
1564
|
+
".system_generated",
|
|
1565
|
+
"logs",
|
|
1566
|
+
"transcript.jsonl"
|
|
1567
|
+
);
|
|
1568
|
+
let rawText;
|
|
1569
|
+
try {
|
|
1570
|
+
rawText = await readFile6(transcriptPath, "utf8");
|
|
1571
|
+
} catch {
|
|
1572
|
+
continue;
|
|
1573
|
+
}
|
|
1574
|
+
const projectHash = projectIndex.get(sessionId) ?? null;
|
|
1575
|
+
let sessionHadRecord = false;
|
|
1576
|
+
for (const line of rawText.split("\n")) {
|
|
1577
|
+
const trimmed = line.trim();
|
|
1578
|
+
if (!trimmed) {
|
|
1579
|
+
continue;
|
|
1580
|
+
}
|
|
1581
|
+
let parsed;
|
|
1582
|
+
try {
|
|
1583
|
+
parsed = JSON.parse(trimmed);
|
|
1584
|
+
} catch {
|
|
1585
|
+
continue;
|
|
1586
|
+
}
|
|
1587
|
+
const tsMs = extractStructuralTimestampMs(parsed);
|
|
1588
|
+
if (tsMs === null || tsMs > nowMs + 6e4) {
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
if (sinceMs !== void 0 && tsMs < sinceMs) {
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
const typeStr = typeof parsed.type === "string" ? parsed.type.toUpperCase() : "";
|
|
1595
|
+
const usageObj = parsed.usage && typeof parsed.usage === "object" && !Array.isArray(parsed.usage) ? parsed.usage : {};
|
|
1596
|
+
const rawInput = firstNonNegInt(
|
|
1597
|
+
parsed.input_tokens,
|
|
1598
|
+
usageObj.input_tokens,
|
|
1599
|
+
usageObj.prompt_tokens
|
|
1600
|
+
);
|
|
1601
|
+
const rawCacheRead = firstNonNegInt(
|
|
1602
|
+
parsed.cache_read_tokens,
|
|
1603
|
+
usageObj.cache_read_tokens,
|
|
1604
|
+
usageObj.cached_content_token_count
|
|
1605
|
+
);
|
|
1606
|
+
const rawOutput = firstNonNegInt(
|
|
1607
|
+
parsed.output_tokens,
|
|
1608
|
+
usageObj.output_tokens,
|
|
1609
|
+
usageObj.completion_tokens
|
|
1610
|
+
);
|
|
1611
|
+
const totalInput = rawInput + rawCacheRead;
|
|
1612
|
+
if (typeStr !== "PLANNER_RESPONSE" && totalInput === 0 && rawOutput === 0) {
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
if (totalInput === 0 && rawOutput === 0) {
|
|
1616
|
+
continue;
|
|
1617
|
+
}
|
|
1618
|
+
const record = sanitizeUsagePayload(
|
|
1619
|
+
{
|
|
1620
|
+
ts: new Date(tsMs).toISOString(),
|
|
1621
|
+
provider: "antigravity",
|
|
1622
|
+
product: "agy",
|
|
1623
|
+
session_id: sessionId,
|
|
1624
|
+
model: parsed.model ?? usageObj.model ?? "unknown",
|
|
1625
|
+
input_tokens: rawInput,
|
|
1626
|
+
cache_read_tokens: rawCacheRead,
|
|
1627
|
+
output_tokens: rawOutput,
|
|
1628
|
+
thinking_tokens: 0,
|
|
1629
|
+
tool_calls: 0,
|
|
1630
|
+
turn_index: typeof parsed.step_index === "number" ? parsed.step_index : 0,
|
|
1631
|
+
project_hash: projectHash,
|
|
1632
|
+
auth_mode: options?.authMode ?? "unknown"
|
|
1633
|
+
},
|
|
1634
|
+
salt
|
|
1635
|
+
);
|
|
1636
|
+
records.push(record);
|
|
1637
|
+
sessionHadRecord = true;
|
|
1638
|
+
}
|
|
1639
|
+
if (sessionHadRecord) {
|
|
1640
|
+
if (projectHash !== null) {
|
|
1641
|
+
attributedSessionCount += 1;
|
|
1642
|
+
} else {
|
|
1643
|
+
unattributedSessionCount += 1;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
return {
|
|
1648
|
+
records,
|
|
1649
|
+
attributed_session_count: attributedSessionCount,
|
|
1650
|
+
unattributed_session_count: unattributedSessionCount
|
|
1651
|
+
};
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
// src/analyzers/token-window.ts
|
|
1655
|
+
var WINDOW_MS = {
|
|
1656
|
+
"5h": 5 * 60 * 60 * 1e3,
|
|
1657
|
+
"24h": 24 * 60 * 60 * 1e3,
|
|
1658
|
+
"7d": 7 * 24 * 60 * 60 * 1e3,
|
|
1659
|
+
"30d": 30 * 24 * 60 * 60 * 1e3
|
|
1660
|
+
};
|
|
1661
|
+
var DEFAULT_PRICING = {
|
|
1662
|
+
input_per_1m_usd: 1.25,
|
|
1663
|
+
output_per_1m_usd: 10
|
|
1664
|
+
};
|
|
1665
|
+
function findModelEntry(modelId, catalog) {
|
|
1666
|
+
const lower = modelId.toLowerCase();
|
|
1667
|
+
const exact = catalog.find(
|
|
1668
|
+
(m) => m.id.toLowerCase() === lower || m.api_model_id.toLowerCase() === lower || m.display_name.toLowerCase() === lower || m.codename && m.codename.toLowerCase() === lower
|
|
1669
|
+
);
|
|
1670
|
+
return exact ?? catalog.find(
|
|
1671
|
+
(m) => lower.includes(m.id.toLowerCase()) || m.id.toLowerCase().includes(lower) || lower.includes(m.api_model_id.toLowerCase()) || m.codename && lower.includes(m.codename.toLowerCase())
|
|
1672
|
+
);
|
|
1673
|
+
}
|
|
1674
|
+
function findModelPricing(modelId, catalog) {
|
|
1675
|
+
const partial = findModelEntry(modelId, catalog);
|
|
1676
|
+
if (partial?.pricing) {
|
|
1677
|
+
const input = partial.pricing.input_per_1m_usd;
|
|
1678
|
+
const cachedInput = typeof partial.pricing.cached_input_per_1m_usd === "number" ? partial.pricing.cached_input_per_1m_usd : input * 0.25;
|
|
1679
|
+
return {
|
|
1680
|
+
input,
|
|
1681
|
+
cachedInput,
|
|
1682
|
+
output: partial.pricing.output_per_1m_usd,
|
|
1683
|
+
tier: partial.quota_profile?.shared_bucket_cost_tier ?? "medium"
|
|
1684
|
+
};
|
|
1685
|
+
}
|
|
1686
|
+
const lower = modelId.toLowerCase();
|
|
1687
|
+
if (lower.includes("flash-lite") || lower.includes("lite")) {
|
|
1688
|
+
return { input: 0.1, cachedInput: 0.025, output: 0.4, tier: "low" };
|
|
1689
|
+
}
|
|
1690
|
+
if (lower.includes("flash") || lower.includes("hydrogen")) {
|
|
1691
|
+
return { input: 0.3, cachedInput: 0.075, output: 2.5, tier: "low" };
|
|
1692
|
+
}
|
|
1693
|
+
if (lower.includes("neon") || lower.includes("pro") || lower.includes("carbon")) {
|
|
1694
|
+
return { input: 2, cachedInput: 0.5, output: 12, tier: "high" };
|
|
1695
|
+
}
|
|
1696
|
+
return {
|
|
1697
|
+
input: DEFAULT_PRICING.input_per_1m_usd,
|
|
1698
|
+
cachedInput: DEFAULT_PRICING.input_per_1m_usd * 0.25,
|
|
1699
|
+
output: DEFAULT_PRICING.output_per_1m_usd,
|
|
1700
|
+
tier: "medium"
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
function estimateTokenCosts(params, catalog) {
|
|
1704
|
+
const pricing = findModelPricing(params.model, catalog);
|
|
1705
|
+
const inputUsd = params.uncachedInputTokens / 1e6 * pricing.input + params.cacheReadTokens / 1e6 * pricing.cachedInput;
|
|
1706
|
+
const cacheSavingsUsd = Math.max(
|
|
1707
|
+
0,
|
|
1708
|
+
params.cacheReadTokens / 1e6 * (pricing.input - pricing.cachedInput)
|
|
1709
|
+
);
|
|
1710
|
+
const outputUsd = params.outputTokens / 1e6 * pricing.output;
|
|
1711
|
+
return {
|
|
1712
|
+
pricing,
|
|
1713
|
+
inputUsd,
|
|
1714
|
+
cacheSavingsUsd,
|
|
1715
|
+
outputUsd,
|
|
1716
|
+
totalUsd: inputUsd + outputUsd
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
function analyzeTokenWindow(records, options) {
|
|
1720
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
1721
|
+
const cutoffMs = options.window === "all" ? Number.NEGATIVE_INFINITY : nowMs - WINDOW_MS[options.window];
|
|
1722
|
+
const catalog = options.models ?? [];
|
|
1723
|
+
const scope = options.scope ?? "global";
|
|
1724
|
+
const authModeFilter = options.authMode ?? "all";
|
|
1725
|
+
const baseFiltered = records.filter((r) => {
|
|
1726
|
+
const ts = Date.parse(r.ts);
|
|
1727
|
+
if (Number.isNaN(ts) || ts < cutoffMs) {
|
|
1728
|
+
return false;
|
|
1729
|
+
}
|
|
1730
|
+
if (options.product && options.product !== "all" && r.product !== options.product) {
|
|
1731
|
+
return false;
|
|
1732
|
+
}
|
|
1733
|
+
if (authModeFilter !== "all" && (r.auth_mode ?? "unknown") !== authModeFilter) {
|
|
1734
|
+
return false;
|
|
1735
|
+
}
|
|
1736
|
+
return true;
|
|
1737
|
+
});
|
|
1738
|
+
const unattributedSessionsInWindow = /* @__PURE__ */ new Set();
|
|
1739
|
+
for (const r of baseFiltered) {
|
|
1740
|
+
if (!r.project_hash) {
|
|
1741
|
+
const key = typeof r.session_hash === "string" && r.session_hash.trim().length > 0 ? r.session_hash.trim() : "default-session";
|
|
1742
|
+
unattributedSessionsInWindow.add(key);
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
const filtered = scope === "project" ? baseFiltered.filter(
|
|
1746
|
+
(r) => Boolean(options.projectHash) && r.project_hash === options.projectHash
|
|
1747
|
+
) : baseFiltered;
|
|
1748
|
+
let totalUncachedInput = 0;
|
|
1749
|
+
let totalCacheRead = 0;
|
|
1750
|
+
let totalOutput = 0;
|
|
1751
|
+
let errorCount = 0;
|
|
1752
|
+
let rateLimit429Count = 0;
|
|
1753
|
+
let peakCtxPct = null;
|
|
1754
|
+
let oldestMs = null;
|
|
1755
|
+
let belowKvCacheThresholdRequests = 0;
|
|
1756
|
+
const sessions = /* @__PURE__ */ new Set();
|
|
1757
|
+
const modelMap = /* @__PURE__ */ new Map();
|
|
1758
|
+
for (const r of filtered) {
|
|
1759
|
+
const uncached = r.input_tokens;
|
|
1760
|
+
const cacheRead = r.cache_read_tokens ?? 0;
|
|
1761
|
+
const reqTotalInput = uncached + cacheRead;
|
|
1762
|
+
totalUncachedInput += uncached;
|
|
1763
|
+
totalCacheRead += cacheRead;
|
|
1764
|
+
totalOutput += r.output_tokens;
|
|
1765
|
+
const sessionKey = typeof r.session_hash === "string" && r.session_hash.trim().length > 0 ? r.session_hash.trim() : "default-session";
|
|
1766
|
+
sessions.add(sessionKey);
|
|
1767
|
+
const matchedEntry = findModelEntry(r.model, catalog);
|
|
1768
|
+
const kvMinTokens = matchedEntry?.specs?.implicit_cache_min_tokens ?? 4096;
|
|
1769
|
+
if (kvMinTokens > 0 && reqTotalInput > 0 && reqTotalInput < kvMinTokens && cacheRead === 0) {
|
|
1770
|
+
belowKvCacheThresholdRequests += 1;
|
|
1771
|
+
}
|
|
1772
|
+
const ts = Date.parse(r.ts);
|
|
1773
|
+
if (!Number.isNaN(ts) && (oldestMs === null || ts < oldestMs)) {
|
|
1774
|
+
oldestMs = ts;
|
|
1775
|
+
}
|
|
1776
|
+
if (r.error_code) {
|
|
1777
|
+
errorCount += 1;
|
|
1778
|
+
if (r.error_code.includes("429") || r.error_code.includes("RESOURCE_EXHAUSTED")) {
|
|
1779
|
+
rateLimit429Count += 1;
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
if (r.context_used_pct !== null) {
|
|
1783
|
+
peakCtxPct = peakCtxPct === null ? r.context_used_pct : Math.max(peakCtxPct, r.context_used_pct);
|
|
1784
|
+
}
|
|
1785
|
+
const agg = modelMap.get(r.model) ?? {
|
|
1786
|
+
requests: 0,
|
|
1787
|
+
uncachedInput: 0,
|
|
1788
|
+
cacheRead: 0,
|
|
1789
|
+
output: 0
|
|
1790
|
+
};
|
|
1791
|
+
agg.requests += 1;
|
|
1792
|
+
agg.uncachedInput += uncached;
|
|
1793
|
+
agg.cacheRead += cacheRead;
|
|
1794
|
+
agg.output += r.output_tokens;
|
|
1795
|
+
modelMap.set(r.model, agg);
|
|
1796
|
+
}
|
|
1797
|
+
let totalInputUsd = 0;
|
|
1798
|
+
let totalCacheSavingsUsd = 0;
|
|
1799
|
+
let totalOutputUsd = 0;
|
|
1800
|
+
const byModel = [];
|
|
1801
|
+
for (const [model, agg] of modelMap.entries()) {
|
|
1802
|
+
const {
|
|
1803
|
+
pricing,
|
|
1804
|
+
inputUsd: inUsd,
|
|
1805
|
+
cacheSavingsUsd,
|
|
1806
|
+
outputUsd: outUsd
|
|
1807
|
+
} = estimateTokenCosts(
|
|
1808
|
+
{
|
|
1809
|
+
model,
|
|
1810
|
+
uncachedInputTokens: agg.uncachedInput,
|
|
1811
|
+
cacheReadTokens: agg.cacheRead,
|
|
1812
|
+
outputTokens: agg.output
|
|
1813
|
+
},
|
|
1814
|
+
catalog
|
|
1815
|
+
);
|
|
1816
|
+
totalInputUsd += inUsd;
|
|
1817
|
+
totalCacheSavingsUsd += cacheSavingsUsd;
|
|
1818
|
+
totalOutputUsd += outUsd;
|
|
1819
|
+
const modelInputTotal = agg.uncachedInput + agg.cacheRead;
|
|
1820
|
+
const modelCacheHitRate = modelInputTotal > 0 ? Math.round(agg.cacheRead / modelInputTotal * 1e3) / 10 : 0;
|
|
1821
|
+
byModel.push({
|
|
1822
|
+
model,
|
|
1823
|
+
requests: agg.requests,
|
|
1824
|
+
uncached_input_tokens: agg.uncachedInput,
|
|
1825
|
+
cache_read_tokens: agg.cacheRead,
|
|
1826
|
+
input_tokens: modelInputTotal,
|
|
1827
|
+
output_tokens: agg.output,
|
|
1828
|
+
total_tokens: modelInputTotal + agg.output,
|
|
1829
|
+
cache_hit_rate_pct: modelCacheHitRate,
|
|
1830
|
+
estimated_input_usd: round4(inUsd),
|
|
1831
|
+
estimated_cache_savings_usd: round4(cacheSavingsUsd),
|
|
1832
|
+
estimated_output_and_thinking_usd: round4(outUsd),
|
|
1833
|
+
estimated_total_usd: round4(inUsd + outUsd),
|
|
1834
|
+
shared_bucket_cost_tier: pricing.tier
|
|
1835
|
+
});
|
|
1836
|
+
}
|
|
1837
|
+
byModel.sort((a, b) => b.total_tokens - a.total_tokens);
|
|
1838
|
+
const totalInput = totalUncachedInput + totalCacheRead;
|
|
1839
|
+
const totalTokens = totalInput + totalOutput;
|
|
1840
|
+
const cacheHitRatePct = totalInput > 0 ? Math.round(totalCacheRead / totalInput * 1e3) / 10 : 0;
|
|
1841
|
+
const dataMode = resolveDataMode(
|
|
1842
|
+
filtered.length,
|
|
1843
|
+
totalTokens,
|
|
1844
|
+
options.dataModeOverride
|
|
1845
|
+
);
|
|
1846
|
+
const usageNote = dataMode === "hook_events_without_tokens" ? `Local hook events (${filtered.length} record(s)) were recorded without token or model fields. Refer to the official AGY/CLI quota UI for authoritative remaining %, or enable Gemini CLI OTel for exact local token counts.` : void 0;
|
|
1847
|
+
const excludedUnattributed = unattributedSessionsInWindow.size;
|
|
1848
|
+
const totalUsd = totalInputUsd + totalOutputUsd;
|
|
1849
|
+
const outputCostSharePct = totalUsd > 0 ? Math.round(totalOutputUsd / totalUsd * 1e3) / 10 : 0;
|
|
1850
|
+
const risk = assessSharedBucketRisk(
|
|
1851
|
+
options.window,
|
|
1852
|
+
totalTokens,
|
|
1853
|
+
rateLimit429Count,
|
|
1854
|
+
byModel
|
|
1855
|
+
);
|
|
1856
|
+
return {
|
|
1857
|
+
window: options.window,
|
|
1858
|
+
product_filter: options.product ?? "all",
|
|
1859
|
+
scope,
|
|
1860
|
+
...scope === "project" && options.projectHash ? { project_hash: options.projectHash } : {},
|
|
1861
|
+
auth_mode_filter: authModeFilter,
|
|
1862
|
+
...scope === "project" ? {
|
|
1863
|
+
unattributed_sessions_excluded: excludedUnattributed,
|
|
1864
|
+
unattributed_sessions_note: excludedUnattributed > 0 ? `${excludedUnattributed} unattributed/derived session(s) without workspace mapping in history.jsonl were excluded from project scope.` : "All attributed sessions for this project are included; any unattributed subagent sessions are excluded in project scope."
|
|
1865
|
+
} : {},
|
|
1866
|
+
data_mode: dataMode,
|
|
1867
|
+
...usageNote ? { usage_note: usageNote } : {},
|
|
1868
|
+
record_count: filtered.length,
|
|
1869
|
+
session_count: sessions.size,
|
|
1870
|
+
total_uncached_input_tokens: totalUncachedInput,
|
|
1871
|
+
total_cache_read_tokens: totalCacheRead,
|
|
1872
|
+
total_input_tokens: totalInput,
|
|
1873
|
+
total_output_tokens: totalOutput,
|
|
1874
|
+
total_tokens: totalTokens,
|
|
1875
|
+
cache_hit_rate_pct: cacheHitRatePct,
|
|
1876
|
+
error_count: errorCount,
|
|
1877
|
+
rate_limit_429_count: rateLimit429Count,
|
|
1878
|
+
peak_context_used_pct: peakCtxPct,
|
|
1879
|
+
oldest_event_ms: oldestMs,
|
|
1880
|
+
below_kv_cache_threshold_requests: belowKvCacheThresholdRequests,
|
|
1881
|
+
shared_bucket_risk: risk,
|
|
1882
|
+
thinking_cost_estimate: {
|
|
1883
|
+
estimated_input_usd: round4(totalInputUsd),
|
|
1884
|
+
estimated_cache_savings_usd: round4(totalCacheSavingsUsd),
|
|
1885
|
+
estimated_output_and_thinking_usd: round4(totalOutputUsd),
|
|
1886
|
+
estimated_total_usd: round4(totalUsd),
|
|
1887
|
+
output_cost_share_pct: outputCostSharePct,
|
|
1888
|
+
note: options.activeAuthMode === "google_oauth" || authModeFilter === "google_oauth" ? "API-equivalent shadow cost (measures shared 5h/7d subscription quota pressure, not direct cash billing). Thinking tokens are weighted at output rates (typically 4x\u20138x input cost); high output cost share signals a Thinking-budget or model-tier optimization opportunity." : "Estimated at API list rates (API-equivalent shadow cost under subscription plans). Thinking tokens are billed at output rates (typically 4x\u20138x input cost). High output cost share signals a Thinking-budget or model-tier optimization opportunity."
|
|
1889
|
+
},
|
|
1890
|
+
by_model: byModel
|
|
1891
|
+
};
|
|
1892
|
+
}
|
|
1893
|
+
function resolveDataMode(recordCount, totalTokens, override) {
|
|
1894
|
+
if (recordCount === 0) {
|
|
1895
|
+
return "transcript_timestamps_only";
|
|
1896
|
+
}
|
|
1897
|
+
if (totalTokens > 0 && override === "transcript_token_logs") {
|
|
1898
|
+
return "transcript_token_logs";
|
|
1899
|
+
}
|
|
1900
|
+
return totalTokens > 0 ? "exact_token_logs" : "hook_events_without_tokens";
|
|
1901
|
+
}
|
|
1902
|
+
function assessSharedBucketRisk(window, totalTokens, rateLimit429Count, byModel) {
|
|
1903
|
+
if (rateLimit429Count >= 3) {
|
|
1904
|
+
return "critical";
|
|
1905
|
+
}
|
|
1906
|
+
const heavyTokens = byModel.filter(
|
|
1907
|
+
(m) => m.shared_bucket_cost_tier === "high" || m.shared_bucket_cost_tier === "very_high"
|
|
1908
|
+
).reduce((sum, m) => sum + m.total_tokens, 0);
|
|
1909
|
+
const scale = window === "5h" ? 1 : window === "24h" ? 3 : window === "7d" ? 10 : window === "30d" ? 35 : 60;
|
|
1910
|
+
if (totalTokens > 8e6 * scale || heavyTokens > 4e6 * scale) {
|
|
1911
|
+
return "critical";
|
|
1912
|
+
}
|
|
1913
|
+
if (totalTokens > 3e6 * scale || heavyTokens > 15e5 * scale || rateLimit429Count > 0) {
|
|
1914
|
+
return "high";
|
|
1915
|
+
}
|
|
1916
|
+
if (totalTokens > 1e6 * scale) {
|
|
1917
|
+
return "moderate";
|
|
1918
|
+
}
|
|
1919
|
+
return "low";
|
|
1920
|
+
}
|
|
1921
|
+
function round4(n) {
|
|
1922
|
+
return Math.round(n * 1e4) / 1e4;
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
// src/storage/rollups.ts
|
|
1926
|
+
import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
|
|
1927
|
+
import {
|
|
1928
|
+
mkdir as mkdir3,
|
|
1929
|
+
open,
|
|
1930
|
+
readdir as readdir2,
|
|
1931
|
+
readFile as readFile7,
|
|
1932
|
+
rename,
|
|
1933
|
+
stat as stat2,
|
|
1934
|
+
unlink,
|
|
1935
|
+
writeFile as writeFile2
|
|
1936
|
+
} from "fs/promises";
|
|
1937
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
1938
|
+
var STALE_LOCK_MS = 1e4;
|
|
1939
|
+
var DEFAULT_COLD_BRAIN_DAYS = 30;
|
|
1940
|
+
function computeSaltFingerprint(salt) {
|
|
1941
|
+
return createHash2("sha256").update(salt).digest("hex").slice(0, 12);
|
|
1942
|
+
}
|
|
1943
|
+
function isReadonlyEnv(explicit) {
|
|
1944
|
+
if (explicit === true) {
|
|
1945
|
+
return true;
|
|
1946
|
+
}
|
|
1947
|
+
const envVal = process.env.AGYCRAFT_READONLY?.trim().toLowerCase();
|
|
1948
|
+
return envVal === "1" || envVal === "true";
|
|
1949
|
+
}
|
|
1950
|
+
function emptyCounters() {
|
|
1951
|
+
return {
|
|
1952
|
+
requests: 0,
|
|
1953
|
+
uncached_input_tokens: 0,
|
|
1954
|
+
cache_read_tokens: 0,
|
|
1955
|
+
input_tokens: 0,
|
|
1956
|
+
output_tokens: 0,
|
|
1957
|
+
thinking_tokens: 0,
|
|
1958
|
+
total_tokens: 0,
|
|
1959
|
+
error_count: 0,
|
|
1960
|
+
rate_limit_429_count: 0,
|
|
1961
|
+
below_kv_cache_threshold_requests: 0,
|
|
1962
|
+
estimated_total_usd: 0,
|
|
1963
|
+
estimated_cache_savings_usd: 0
|
|
1964
|
+
};
|
|
1965
|
+
}
|
|
1966
|
+
function round42(n) {
|
|
1967
|
+
return Math.round(n * 1e4) / 1e4;
|
|
1968
|
+
}
|
|
1969
|
+
function normalizeTimezone(tz) {
|
|
1970
|
+
if (!tz || tz.trim().length === 0) {
|
|
1971
|
+
return "UTC";
|
|
1972
|
+
}
|
|
1973
|
+
try {
|
|
1974
|
+
new Intl.DateTimeFormat("en-US", { timeZone: tz.trim() });
|
|
1975
|
+
return tz.trim();
|
|
1976
|
+
} catch {
|
|
1977
|
+
return "UTC";
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
function getDatePartsInTz(ms, timeZone) {
|
|
1981
|
+
if (timeZone === "UTC") {
|
|
1982
|
+
const d = new Date(ms);
|
|
1983
|
+
return {
|
|
1984
|
+
year: d.getUTCFullYear(),
|
|
1985
|
+
month: d.getUTCMonth() + 1,
|
|
1986
|
+
day: d.getUTCDate(),
|
|
1987
|
+
hour: d.getUTCHours()
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
const fmt = new Intl.DateTimeFormat("en-CA", {
|
|
1991
|
+
timeZone,
|
|
1992
|
+
year: "numeric",
|
|
1993
|
+
month: "2-digit",
|
|
1994
|
+
day: "2-digit",
|
|
1995
|
+
hour: "2-digit",
|
|
1996
|
+
hour12: false
|
|
1997
|
+
});
|
|
1998
|
+
const parts = fmt.formatToParts(new Date(ms));
|
|
1999
|
+
const map = {};
|
|
2000
|
+
for (const p of parts) {
|
|
2001
|
+
if (p.type !== "literal") {
|
|
2002
|
+
map[p.type] = Number(p.value);
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
return {
|
|
2006
|
+
year: map.year ?? 1970,
|
|
2007
|
+
month: map.month ?? 1,
|
|
2008
|
+
day: map.day ?? 1,
|
|
2009
|
+
hour: (map.hour ?? 0) === 24 ? 0 : map.hour ?? 0
|
|
2010
|
+
};
|
|
2011
|
+
}
|
|
2012
|
+
function pad2(n) {
|
|
2013
|
+
return String(n).padStart(2, "0");
|
|
2014
|
+
}
|
|
2015
|
+
function getIsoWeekKey(year, month, day) {
|
|
2016
|
+
const d = new Date(Date.UTC(year, month - 1, day));
|
|
2017
|
+
const dayNum = d.getUTCDay() || 7;
|
|
2018
|
+
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
|
|
2019
|
+
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
|
|
2020
|
+
const weekNo = Math.ceil(((d.getTime() - yearStart.getTime()) / 864e5 + 1) / 7);
|
|
2021
|
+
return `${d.getUTCFullYear()}-W${pad2(weekNo)}`;
|
|
2022
|
+
}
|
|
2023
|
+
function formatBucketKey(ms, granularity, timeZone = "UTC") {
|
|
2024
|
+
const p = getDatePartsInTz(ms, timeZone);
|
|
2025
|
+
if (granularity === "hourly") {
|
|
2026
|
+
const suffix = timeZone === "UTC" ? "Z" : "";
|
|
2027
|
+
return `${p.year}-${pad2(p.month)}-${pad2(p.day)}T${pad2(p.hour)}:00:00${suffix}`;
|
|
2028
|
+
}
|
|
2029
|
+
if (granularity === "daily") {
|
|
2030
|
+
return `${p.year}-${pad2(p.month)}-${pad2(p.day)}`;
|
|
2031
|
+
}
|
|
2032
|
+
if (granularity === "weekly") {
|
|
2033
|
+
return getIsoWeekKey(p.year, p.month, p.day);
|
|
2034
|
+
}
|
|
2035
|
+
return `${p.year}-${pad2(p.month)}`;
|
|
2036
|
+
}
|
|
2037
|
+
function getUtcHourKey(ms) {
|
|
2038
|
+
return formatBucketKey(ms, "hourly", "UTC");
|
|
2039
|
+
}
|
|
2040
|
+
function getUtcMonthKey(ms) {
|
|
2041
|
+
return formatBucketKey(ms, "monthly", "UTC");
|
|
2042
|
+
}
|
|
2043
|
+
async function atomicWriteJson(targetPath, data) {
|
|
2044
|
+
await mkdir3(dirname3(targetPath), { recursive: true });
|
|
2045
|
+
const tmpPath = `${targetPath}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
|
|
2046
|
+
await writeFile2(tmpPath, JSON.stringify(data, null, 2), {
|
|
2047
|
+
encoding: "utf8",
|
|
2048
|
+
mode: 384
|
|
2049
|
+
});
|
|
2050
|
+
await rename(tmpPath, targetPath);
|
|
2051
|
+
}
|
|
2052
|
+
async function safeReadJson(filePath) {
|
|
2053
|
+
let raw;
|
|
2054
|
+
try {
|
|
2055
|
+
raw = await readFile7(filePath, "utf8");
|
|
2056
|
+
} catch (err) {
|
|
2057
|
+
const code = err?.code;
|
|
2058
|
+
if (code === "ENOENT") {
|
|
2059
|
+
return { status: "missing" };
|
|
2060
|
+
}
|
|
2061
|
+
return { status: "corrupt" };
|
|
2062
|
+
}
|
|
2063
|
+
try {
|
|
2064
|
+
const parsed = JSON.parse(raw);
|
|
2065
|
+
if (!parsed || typeof parsed !== "object") {
|
|
2066
|
+
return { status: "corrupt" };
|
|
2067
|
+
}
|
|
2068
|
+
return { status: "ok", data: parsed };
|
|
2069
|
+
} catch {
|
|
2070
|
+
return { status: "corrupt" };
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
async function acquireRollupLock(rollupsDir, timeoutMs = 150) {
|
|
2074
|
+
await mkdir3(rollupsDir, { recursive: true });
|
|
2075
|
+
const lockPath = join5(rollupsDir, ".rollup.lock");
|
|
2076
|
+
const deadline = Date.now() + timeoutMs;
|
|
2077
|
+
while (true) {
|
|
2078
|
+
try {
|
|
2079
|
+
const fh = await open(lockPath, "wx", 384);
|
|
2080
|
+
await fh.writeFile(JSON.stringify({ pid: process.pid, ts: Date.now() }), "utf8");
|
|
2081
|
+
await fh.close();
|
|
2082
|
+
return lockPath;
|
|
2083
|
+
} catch (err) {
|
|
2084
|
+
const code = err?.code;
|
|
2085
|
+
if (code !== "EEXIST") {
|
|
2086
|
+
return null;
|
|
2087
|
+
}
|
|
2088
|
+
try {
|
|
2089
|
+
const st = await stat2(lockPath);
|
|
2090
|
+
let lockTs = st.mtimeMs;
|
|
2091
|
+
try {
|
|
2092
|
+
const raw = await readFile7(lockPath, "utf8");
|
|
2093
|
+
const parsed = JSON.parse(raw);
|
|
2094
|
+
if (typeof parsed.ts === "number") {
|
|
2095
|
+
lockTs = parsed.ts;
|
|
2096
|
+
}
|
|
2097
|
+
} catch {
|
|
2098
|
+
}
|
|
2099
|
+
if (Date.now() - lockTs > STALE_LOCK_MS) {
|
|
2100
|
+
await unlink(lockPath).catch(() => {
|
|
2101
|
+
});
|
|
2102
|
+
continue;
|
|
2103
|
+
}
|
|
2104
|
+
} catch {
|
|
2105
|
+
continue;
|
|
2106
|
+
}
|
|
2107
|
+
if (Date.now() >= deadline) {
|
|
2108
|
+
return null;
|
|
2109
|
+
}
|
|
2110
|
+
await new Promise((r) => setTimeout(r, 25));
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
async function releaseLock(lockPath) {
|
|
2115
|
+
if (!lockPath) {
|
|
2116
|
+
return;
|
|
2117
|
+
}
|
|
2118
|
+
await unlink(lockPath).catch(() => {
|
|
2119
|
+
});
|
|
2120
|
+
}
|
|
2121
|
+
async function readFileIncrementalLines(filePath, watermark) {
|
|
2122
|
+
let st;
|
|
2123
|
+
try {
|
|
2124
|
+
st = await stat2(filePath);
|
|
2125
|
+
} catch {
|
|
2126
|
+
return null;
|
|
2127
|
+
}
|
|
2128
|
+
if (watermark && st.size === watermark.byte_offset && st.mtimeMs === watermark.mtime_ms) {
|
|
2129
|
+
return { lines: [], newOffset: watermark.byte_offset, mtimeMs: st.mtimeMs, resetRequired: false };
|
|
2130
|
+
}
|
|
2131
|
+
const startOffset = watermark && st.size >= watermark.byte_offset ? watermark.byte_offset : 0;
|
|
2132
|
+
const resetRequired = Boolean(watermark && st.size < watermark.byte_offset);
|
|
2133
|
+
const bytesToRead = st.size - startOffset;
|
|
2134
|
+
if (bytesToRead <= 0) {
|
|
2135
|
+
return { lines: [], newOffset: st.size, mtimeMs: st.mtimeMs, resetRequired };
|
|
2136
|
+
}
|
|
2137
|
+
const fh = await open(filePath, "r");
|
|
2138
|
+
try {
|
|
2139
|
+
const buf = Buffer.alloc(bytesToRead);
|
|
2140
|
+
const { bytesRead } = await fh.read(buf, 0, bytesToRead, startOffset);
|
|
2141
|
+
const text = buf.subarray(0, bytesRead).toString("utf8");
|
|
2142
|
+
const lastNewline = text.lastIndexOf("\n");
|
|
2143
|
+
if (lastNewline === -1) {
|
|
2144
|
+
const trimmed = text.trim();
|
|
2145
|
+
if (!trimmed) {
|
|
2146
|
+
return { lines: [], newOffset: startOffset + bytesRead, mtimeMs: st.mtimeMs, resetRequired };
|
|
2147
|
+
}
|
|
2148
|
+
try {
|
|
2149
|
+
JSON.parse(trimmed);
|
|
2150
|
+
return { lines: [trimmed], newOffset: startOffset + bytesRead, mtimeMs: st.mtimeMs, resetRequired };
|
|
2151
|
+
} catch {
|
|
2152
|
+
return { lines: [], newOffset: startOffset, mtimeMs: st.mtimeMs, resetRequired };
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
const trailing = text.slice(lastNewline + 1);
|
|
2156
|
+
const trailingTrimmed = trailing.trim();
|
|
2157
|
+
if (trailingTrimmed.length > 0) {
|
|
2158
|
+
try {
|
|
2159
|
+
JSON.parse(trailingTrimmed);
|
|
2160
|
+
return {
|
|
2161
|
+
lines: text.split("\n"),
|
|
2162
|
+
newOffset: startOffset + bytesRead,
|
|
2163
|
+
mtimeMs: st.mtimeMs,
|
|
2164
|
+
resetRequired
|
|
2165
|
+
};
|
|
2166
|
+
} catch {
|
|
2167
|
+
const consumedBytes = Buffer.byteLength(text.slice(0, lastNewline + 1), "utf8");
|
|
2168
|
+
return {
|
|
2169
|
+
lines: text.slice(0, lastNewline + 1).split("\n"),
|
|
2170
|
+
newOffset: startOffset + consumedBytes,
|
|
2171
|
+
mtimeMs: st.mtimeMs,
|
|
2172
|
+
resetRequired
|
|
2173
|
+
};
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
return {
|
|
2177
|
+
lines: text.split("\n"),
|
|
2178
|
+
newOffset: startOffset + bytesRead,
|
|
2179
|
+
mtimeMs: st.mtimeMs,
|
|
2180
|
+
resetRequired
|
|
2181
|
+
};
|
|
2182
|
+
} finally {
|
|
2183
|
+
await fh.close();
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
function mergeRecordIntoBucket(bucketsMap, bucketKey, record, catalog) {
|
|
2187
|
+
let entries = bucketsMap[bucketKey];
|
|
2188
|
+
if (!entries) {
|
|
2189
|
+
entries = [];
|
|
2190
|
+
bucketsMap[bucketKey] = entries;
|
|
2191
|
+
}
|
|
2192
|
+
const authMode = record.auth_mode ?? "unknown";
|
|
2193
|
+
const projectHash = record.project_hash ?? null;
|
|
2194
|
+
const modelKey = record.model || "unknown";
|
|
2195
|
+
let target = entries.find(
|
|
2196
|
+
(e) => e.product === record.product && e.project_hash === projectHash && e.auth_mode === authMode && (e.model ?? "unknown") === modelKey
|
|
2197
|
+
);
|
|
2198
|
+
if (!target) {
|
|
2199
|
+
target = {
|
|
2200
|
+
product: record.product,
|
|
2201
|
+
project_hash: projectHash,
|
|
2202
|
+
auth_mode: authMode,
|
|
2203
|
+
model: modelKey,
|
|
2204
|
+
session_hashes: [],
|
|
2205
|
+
...emptyCounters()
|
|
2206
|
+
};
|
|
2207
|
+
entries.push(target);
|
|
2208
|
+
}
|
|
2209
|
+
const uncached = record.input_tokens;
|
|
2210
|
+
const cacheRead = record.cache_read_tokens ?? 0;
|
|
2211
|
+
const thinking = record.thinking_tokens ?? 0;
|
|
2212
|
+
const reqInput = uncached + cacheRead;
|
|
2213
|
+
const reqTotal = reqInput + record.output_tokens;
|
|
2214
|
+
const {
|
|
2215
|
+
inputUsd: inUsd,
|
|
2216
|
+
cacheSavingsUsd,
|
|
2217
|
+
outputUsd: outUsd
|
|
2218
|
+
} = estimateTokenCosts(
|
|
2219
|
+
{
|
|
2220
|
+
model: modelKey,
|
|
2221
|
+
uncachedInputTokens: uncached,
|
|
2222
|
+
cacheReadTokens: cacheRead,
|
|
2223
|
+
outputTokens: record.output_tokens
|
|
2224
|
+
},
|
|
2225
|
+
catalog
|
|
2226
|
+
);
|
|
2227
|
+
const matchedEntry = findModelEntry(record.model, catalog);
|
|
2228
|
+
const kvMinTokens = matchedEntry?.specs?.implicit_cache_min_tokens ?? 4096;
|
|
2229
|
+
const isColdBelowKv = kvMinTokens > 0 && reqInput > 0 && reqInput < kvMinTokens && cacheRead === 0;
|
|
2230
|
+
target.requests += 1;
|
|
2231
|
+
target.uncached_input_tokens += uncached;
|
|
2232
|
+
target.cache_read_tokens += cacheRead;
|
|
2233
|
+
target.input_tokens += reqInput;
|
|
2234
|
+
target.output_tokens += record.output_tokens;
|
|
2235
|
+
target.thinking_tokens += thinking;
|
|
2236
|
+
target.total_tokens += reqTotal;
|
|
2237
|
+
if (record.error_code) {
|
|
2238
|
+
target.error_count += 1;
|
|
2239
|
+
if (record.error_code.includes("429") || record.error_code.includes("RESOURCE_EXHAUSTED")) {
|
|
2240
|
+
target.rate_limit_429_count += 1;
|
|
2241
|
+
}
|
|
2242
|
+
}
|
|
2243
|
+
if (isColdBelowKv) {
|
|
2244
|
+
target.below_kv_cache_threshold_requests += 1;
|
|
2245
|
+
}
|
|
2246
|
+
target.estimated_total_usd = round42(target.estimated_total_usd + inUsd + outUsd);
|
|
2247
|
+
target.estimated_cache_savings_usd = round42(
|
|
2248
|
+
target.estimated_cache_savings_usd + cacheSavingsUsd
|
|
2249
|
+
);
|
|
2250
|
+
if (record.session_hash && !target.session_hashes.includes(record.session_hash)) {
|
|
2251
|
+
target.session_hashes.push(record.session_hash);
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
function parseUsageLogLine(line, salt) {
|
|
2255
|
+
const trimmed = line.trim();
|
|
2256
|
+
if (!trimmed) {
|
|
2257
|
+
return null;
|
|
2258
|
+
}
|
|
2259
|
+
try {
|
|
2260
|
+
const parsed = JSON.parse(trimmed);
|
|
2261
|
+
return sanitizeUsagePayload(parsed, salt);
|
|
2262
|
+
} catch {
|
|
2263
|
+
return null;
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
function parseOtelLine(line, salt) {
|
|
2267
|
+
const trimmed = line.trim();
|
|
2268
|
+
if (!trimmed) {
|
|
2269
|
+
return null;
|
|
2270
|
+
}
|
|
2271
|
+
try {
|
|
2272
|
+
const entry = JSON.parse(trimmed);
|
|
2273
|
+
const rawAttrs = entry["attributes"];
|
|
2274
|
+
const attrs = rawAttrs && typeof rawAttrs === "object" && !Array.isArray(rawAttrs) ? rawAttrs : {};
|
|
2275
|
+
const firstNum = (...cands) => {
|
|
2276
|
+
for (const v of cands) {
|
|
2277
|
+
if (v === null || v === void 0 || v === "") continue;
|
|
2278
|
+
const n = typeof v === "number" ? v : Number(v);
|
|
2279
|
+
if (Number.isFinite(n) && n >= 0) return Math.floor(n);
|
|
2280
|
+
}
|
|
2281
|
+
return 0;
|
|
2282
|
+
};
|
|
2283
|
+
const inputTokens = firstNum(
|
|
2284
|
+
attrs["gen_ai.usage.input_tokens"],
|
|
2285
|
+
attrs["input_token_count"],
|
|
2286
|
+
attrs["prompt_tokens"],
|
|
2287
|
+
entry["input_tokens"],
|
|
2288
|
+
entry["prompt_tokens"]
|
|
2289
|
+
);
|
|
2290
|
+
const cacheReadTokens = firstNum(
|
|
2291
|
+
attrs["gen_ai.usage.cache_read_input_tokens"],
|
|
2292
|
+
attrs["cache_read_tokens"],
|
|
2293
|
+
attrs["cached_content_token_count"],
|
|
2294
|
+
entry["cache_read_tokens"]
|
|
2295
|
+
);
|
|
2296
|
+
const outputTokens = firstNum(
|
|
2297
|
+
attrs["gen_ai.usage.output_tokens"],
|
|
2298
|
+
attrs["output_token_count"],
|
|
2299
|
+
attrs["completion_tokens"],
|
|
2300
|
+
entry["output_tokens"],
|
|
2301
|
+
entry["completion_tokens"]
|
|
2302
|
+
);
|
|
2303
|
+
const thinkingTokens = firstNum(
|
|
2304
|
+
attrs["gen_ai.usage.thinking_tokens"],
|
|
2305
|
+
attrs["thinking_tokens"],
|
|
2306
|
+
attrs["thoughts_token_count"],
|
|
2307
|
+
entry["thinking_tokens"]
|
|
2308
|
+
);
|
|
2309
|
+
const errorCode = attrs["error.type"] ?? attrs["http.response.status_code"] ?? entry["error_code"] ?? null;
|
|
2310
|
+
if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0 && !errorCode) {
|
|
2311
|
+
return null;
|
|
2312
|
+
}
|
|
2313
|
+
const rawSession = String(
|
|
2314
|
+
attrs["session.id"] ?? entry["session_id"] ?? "gemini-cli-session"
|
|
2315
|
+
);
|
|
2316
|
+
return sanitizeUsagePayload(
|
|
2317
|
+
{
|
|
2318
|
+
ts: entry["timestamp"] ?? entry["ts"] ?? entry["startTime"],
|
|
2319
|
+
provider: "google",
|
|
2320
|
+
product: "gemini-cli",
|
|
2321
|
+
session_hash: hashSessionId(rawSession, salt),
|
|
2322
|
+
model: attrs["gen_ai.request.model"] ?? attrs["gen_ai.response.model"] ?? attrs["model"] ?? entry["model"] ?? "unknown",
|
|
2323
|
+
input_tokens: inputTokens,
|
|
2324
|
+
cache_read_tokens: cacheReadTokens,
|
|
2325
|
+
output_tokens: outputTokens,
|
|
2326
|
+
thinking_tokens: thinkingTokens,
|
|
2327
|
+
context_used_pct: attrs["context_used_pct"] ?? null,
|
|
2328
|
+
tool_calls: firstNum(attrs["tool_calls"], entry["tool_calls"]),
|
|
2329
|
+
turn_index: firstNum(attrs["turn_index"], entry["turn_index"]),
|
|
2330
|
+
error_code: errorCode
|
|
2331
|
+
},
|
|
2332
|
+
salt
|
|
2333
|
+
);
|
|
2334
|
+
} catch {
|
|
2335
|
+
return null;
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
async function queryRollups(options) {
|
|
2339
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
2340
|
+
const readonly = isReadonlyEnv(options.readonly);
|
|
2341
|
+
const rollupsDir = options.rollupsDir ?? getRollupsDir();
|
|
2342
|
+
const hourlyDir = join5(rollupsDir, "hourly");
|
|
2343
|
+
const watermarksPath = join5(rollupsDir, "watermarks.json");
|
|
2344
|
+
const dailyPath = join5(rollupsDir, "daily.json");
|
|
2345
|
+
const weeklyPath = join5(rollupsDir, "weekly.json");
|
|
2346
|
+
const monthlyPath = join5(rollupsDir, "monthly.json");
|
|
2347
|
+
const catalog = options.models ?? [];
|
|
2348
|
+
const tz = normalizeTimezone(options.timezone);
|
|
2349
|
+
const maxBuckets = Math.max(1, Math.min(90, options.maxBuckets ?? 31));
|
|
2350
|
+
let salt = options.salt;
|
|
2351
|
+
if (!salt) {
|
|
2352
|
+
if (readonly) {
|
|
2353
|
+
try {
|
|
2354
|
+
salt = await getOrCreateLocalSalt(options.saltPath);
|
|
2355
|
+
} catch {
|
|
2356
|
+
salt = "readonly-ephemeral-salt";
|
|
2357
|
+
}
|
|
2358
|
+
} else {
|
|
2359
|
+
salt = await getOrCreateLocalSalt(options.saltPath);
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
let lockPath = null;
|
|
2363
|
+
let canWrite = !readonly;
|
|
2364
|
+
if (canWrite) {
|
|
2365
|
+
lockPath = await acquireRollupLock(rollupsDir, options.lockTimeoutMs ?? 150);
|
|
2366
|
+
if (!lockPath) {
|
|
2367
|
+
canWrite = false;
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
try {
|
|
2371
|
+
const saltFingerprint = computeSaltFingerprint(salt);
|
|
2372
|
+
const wmRes = await safeReadJson(watermarksPath);
|
|
2373
|
+
const dailyRes = await safeReadJson(dailyPath);
|
|
2374
|
+
const weeklyRes = await safeReadJson(weeklyPath);
|
|
2375
|
+
const monthlyRes = await safeReadJson(monthlyPath);
|
|
2376
|
+
let corruptDetected = wmRes.status === "corrupt" || dailyRes.status === "corrupt" || weeklyRes.status === "corrupt" || monthlyRes.status === "corrupt";
|
|
2377
|
+
let existingHourlyFiles = [];
|
|
2378
|
+
try {
|
|
2379
|
+
const files = await readdir2(hourlyDir);
|
|
2380
|
+
existingHourlyFiles = files.filter((f) => /^\d{4}-\d{2}\.json$/.test(f)).sort();
|
|
2381
|
+
} catch {
|
|
2382
|
+
existingHourlyFiles = [];
|
|
2383
|
+
}
|
|
2384
|
+
let legacySchemaDetected = false;
|
|
2385
|
+
if (!corruptDetected) {
|
|
2386
|
+
for (const f of existingHourlyFiles) {
|
|
2387
|
+
const hRes = await safeReadJson(join5(hourlyDir, f));
|
|
2388
|
+
if (hRes.status === "corrupt") {
|
|
2389
|
+
corruptDetected = true;
|
|
2390
|
+
break;
|
|
2391
|
+
}
|
|
2392
|
+
if (hRes.status === "ok" && hRes.data.v !== 2) {
|
|
2393
|
+
legacySchemaDetected = true;
|
|
2394
|
+
}
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
const hasExistingDiskRollups = wmRes.status === "ok" || dailyRes.status === "ok" || weeklyRes.status === "ok" || monthlyRes.status === "ok" || existingHourlyFiles.length > 0;
|
|
2398
|
+
const saltMismatch = hasExistingDiskRollups && (wmRes.status !== "ok" || wmRes.data.v !== 2 || wmRes.data.salt_fingerprint !== saltFingerprint);
|
|
2399
|
+
const rebuildRequired = corruptDetected || saltMismatch || legacySchemaDetected;
|
|
2400
|
+
const usageLogPath = options.usageLogPath ?? getUsageLogPath();
|
|
2401
|
+
const otelPath = options.geminiOtelPath ?? getDefaultGeminiTelemetryPath();
|
|
2402
|
+
const brainDir = options.brainDir === void 0 ? getAgyBrainDir() : options.brainDir;
|
|
2403
|
+
const historyPath = options.historyPath === void 0 ? getAgyHistoryPath() : options.historyPath;
|
|
2404
|
+
const runIngestionPass = async (useDiskRollups) => {
|
|
2405
|
+
const watermarks2 = useDiskRollups && wmRes.status === "ok" && wmRes.data.sources ? {
|
|
2406
|
+
v: 2,
|
|
2407
|
+
salt_fingerprint: saltFingerprint,
|
|
2408
|
+
sources: { ...wmRes.data.sources }
|
|
2409
|
+
} : { v: 2, salt_fingerprint: saltFingerprint, sources: {} };
|
|
2410
|
+
const hourlyCache2 = /* @__PURE__ */ new Map();
|
|
2411
|
+
const dirtyHourlyMonths2 = /* @__PURE__ */ new Set();
|
|
2412
|
+
const diskSessionHashes = /* @__PURE__ */ new Set();
|
|
2413
|
+
const loadHourlyMonth = async (monthKey) => {
|
|
2414
|
+
const cached = hourlyCache2.get(monthKey);
|
|
2415
|
+
if (cached) {
|
|
2416
|
+
return cached;
|
|
2417
|
+
}
|
|
2418
|
+
if (useDiskRollups) {
|
|
2419
|
+
const filePath = join5(hourlyDir, `${monthKey}.json`);
|
|
2420
|
+
const res = await safeReadJson(filePath);
|
|
2421
|
+
if (res.status === "ok" && res.data.buckets) {
|
|
2422
|
+
for (const entries of Object.values(res.data.buckets)) {
|
|
2423
|
+
for (const entry of entries) {
|
|
2424
|
+
for (const sh of entry.session_hashes) {
|
|
2425
|
+
diskSessionHashes.add(sh);
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
hourlyCache2.set(monthKey, res.data);
|
|
2430
|
+
return res.data;
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
const empty = {
|
|
2434
|
+
v: 2,
|
|
2435
|
+
month: monthKey,
|
|
2436
|
+
updated_at: new Date(nowMs).toISOString(),
|
|
2437
|
+
buckets: {}
|
|
2438
|
+
};
|
|
2439
|
+
hourlyCache2.set(monthKey, empty);
|
|
2440
|
+
return empty;
|
|
2441
|
+
};
|
|
2442
|
+
if (useDiskRollups) {
|
|
2443
|
+
for (const file of existingHourlyFiles) {
|
|
2444
|
+
const monthKey = file.replace(/\.json$/, "");
|
|
2445
|
+
await loadHourlyMonth(monthKey);
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
const dailyData2 = useDiskRollups && dailyRes.status === "ok" && dailyRes.data.buckets ? dailyRes.data : { v: 2, granularity: "daily", updated_at: new Date(nowMs).toISOString(), buckets: {} };
|
|
2449
|
+
const weeklyData2 = useDiskRollups && weeklyRes.status === "ok" && weeklyRes.data.buckets ? weeklyRes.data : { v: 2, granularity: "weekly", updated_at: new Date(nowMs).toISOString(), buckets: {} };
|
|
2450
|
+
const monthlyData2 = useDiskRollups && monthlyRes.status === "ok" && monthlyRes.data.buckets ? monthlyRes.data : { v: 2, granularity: "monthly", updated_at: new Date(nowMs).toISOString(), buckets: {} };
|
|
2451
|
+
let anyNewData2 = !useDiskRollups && rebuildRequired;
|
|
2452
|
+
const ingestRecords = async (newRecords) => {
|
|
2453
|
+
for (const r of newRecords) {
|
|
2454
|
+
const tsMs = Date.parse(r.ts);
|
|
2455
|
+
if (Number.isNaN(tsMs)) {
|
|
2456
|
+
continue;
|
|
2457
|
+
}
|
|
2458
|
+
const monthKey = getUtcMonthKey(tsMs);
|
|
2459
|
+
const hourKey = getUtcHourKey(tsMs);
|
|
2460
|
+
const dayKey = formatBucketKey(tsMs, "daily", "UTC");
|
|
2461
|
+
const weekKey = formatBucketKey(tsMs, "weekly", "UTC");
|
|
2462
|
+
const hourlyFile = await loadHourlyMonth(monthKey);
|
|
2463
|
+
mergeRecordIntoBucket(hourlyFile.buckets, hourKey, r, catalog);
|
|
2464
|
+
hourlyFile.updated_at = new Date(nowMs).toISOString();
|
|
2465
|
+
dirtyHourlyMonths2.add(monthKey);
|
|
2466
|
+
mergeRecordIntoBucket(dailyData2.buckets, dayKey, r, catalog);
|
|
2467
|
+
mergeRecordIntoBucket(weeklyData2.buckets, weekKey, r, catalog);
|
|
2468
|
+
mergeRecordIntoBucket(monthlyData2.buckets, monthKey, r, catalog);
|
|
2469
|
+
anyNewData2 = true;
|
|
2470
|
+
}
|
|
2471
|
+
};
|
|
2472
|
+
const prevUsageWm = useDiskRollups ? watermarks2.sources["usage_log"] : void 0;
|
|
2473
|
+
const usageInc = await readFileIncrementalLines(usageLogPath, prevUsageWm);
|
|
2474
|
+
if (usageInc && usageInc.lines.length > 0) {
|
|
2475
|
+
const parsedRecords = [];
|
|
2476
|
+
for (const line of usageInc.lines) {
|
|
2477
|
+
const rec = parseUsageLogLine(line, salt);
|
|
2478
|
+
if (rec) parsedRecords.push(rec);
|
|
2479
|
+
}
|
|
2480
|
+
if (!canWrite && useDiskRollups && hasExistingDiskRollups && parsedRecords.length > 0 && (!prevUsageWm || usageInc.resetRequired)) {
|
|
2481
|
+
return {
|
|
2482
|
+
fallbackToCleanMemory: true,
|
|
2483
|
+
watermarks: watermarks2,
|
|
2484
|
+
hourlyCache: hourlyCache2,
|
|
2485
|
+
dirtyHourlyMonths: dirtyHourlyMonths2,
|
|
2486
|
+
dailyData: dailyData2,
|
|
2487
|
+
weeklyData: weeklyData2,
|
|
2488
|
+
monthlyData: monthlyData2,
|
|
2489
|
+
anyNewData: anyNewData2
|
|
2490
|
+
};
|
|
2491
|
+
}
|
|
2492
|
+
await ingestRecords(parsedRecords);
|
|
2493
|
+
watermarks2.sources["usage_log"] = {
|
|
2494
|
+
mtime_ms: usageInc.mtimeMs,
|
|
2495
|
+
byte_offset: usageInc.newOffset,
|
|
2496
|
+
updated_at: new Date(nowMs).toISOString()
|
|
2497
|
+
};
|
|
2498
|
+
anyNewData2 = true;
|
|
2499
|
+
}
|
|
2500
|
+
const prevOtelWm = useDiskRollups ? watermarks2.sources["gemini_otel"] : void 0;
|
|
2501
|
+
const otelInc = await readFileIncrementalLines(otelPath, prevOtelWm);
|
|
2502
|
+
if (otelInc && otelInc.lines.length > 0) {
|
|
2503
|
+
const parsedRecords = [];
|
|
2504
|
+
for (const line of otelInc.lines) {
|
|
2505
|
+
const rec = parseOtelLine(line, salt);
|
|
2506
|
+
if (rec) parsedRecords.push(rec);
|
|
2507
|
+
}
|
|
2508
|
+
if (!canWrite && useDiskRollups && hasExistingDiskRollups && parsedRecords.length > 0 && (!prevOtelWm || otelInc.resetRequired)) {
|
|
2509
|
+
return {
|
|
2510
|
+
fallbackToCleanMemory: true,
|
|
2511
|
+
watermarks: watermarks2,
|
|
2512
|
+
hourlyCache: hourlyCache2,
|
|
2513
|
+
dirtyHourlyMonths: dirtyHourlyMonths2,
|
|
2514
|
+
dailyData: dailyData2,
|
|
2515
|
+
weeklyData: weeklyData2,
|
|
2516
|
+
monthlyData: monthlyData2,
|
|
2517
|
+
anyNewData: anyNewData2
|
|
2518
|
+
};
|
|
2519
|
+
}
|
|
2520
|
+
await ingestRecords(parsedRecords);
|
|
2521
|
+
watermarks2.sources["gemini_otel"] = {
|
|
2522
|
+
mtime_ms: otelInc.mtimeMs,
|
|
2523
|
+
byte_offset: otelInc.newOffset,
|
|
2524
|
+
updated_at: new Date(nowMs).toISOString()
|
|
2525
|
+
};
|
|
2526
|
+
anyNewData2 = true;
|
|
2527
|
+
}
|
|
2528
|
+
if (brainDir) {
|
|
2529
|
+
const coldThresholdMs = nowMs - (options.coldBrainDays ?? DEFAULT_COLD_BRAIN_DAYS) * 864e5;
|
|
2530
|
+
const projectIndex = await buildConversationProjectIndex(historyPath, salt);
|
|
2531
|
+
let sessionDirs = [];
|
|
2532
|
+
try {
|
|
2533
|
+
const entries = await readdir2(brainDir, { withFileTypes: true });
|
|
2534
|
+
sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
2535
|
+
} catch {
|
|
2536
|
+
sessionDirs = [];
|
|
2537
|
+
}
|
|
2538
|
+
for (const sessionId of sessionDirs) {
|
|
2539
|
+
const transcriptPath = join5(
|
|
2540
|
+
brainDir,
|
|
2541
|
+
sessionId,
|
|
2542
|
+
".system_generated",
|
|
2543
|
+
"logs",
|
|
2544
|
+
"transcript.jsonl"
|
|
2545
|
+
);
|
|
2546
|
+
let st;
|
|
2547
|
+
try {
|
|
2548
|
+
st = await stat2(transcriptPath);
|
|
2549
|
+
} catch {
|
|
2550
|
+
continue;
|
|
2551
|
+
}
|
|
2552
|
+
if (st.mtimeMs < coldThresholdMs) {
|
|
2553
|
+
continue;
|
|
2554
|
+
}
|
|
2555
|
+
const sessionHash = hashSessionId(sessionId, salt);
|
|
2556
|
+
const wmKey = `transcript:${sessionHash}`;
|
|
2557
|
+
const prevWm = useDiskRollups ? watermarks2.sources[wmKey] : void 0;
|
|
2558
|
+
const inc = await readFileIncrementalLines(transcriptPath, prevWm);
|
|
2559
|
+
if (!inc || inc.lines.length === 0) {
|
|
2560
|
+
continue;
|
|
2561
|
+
}
|
|
2562
|
+
if (!canWrite && useDiskRollups && (!prevWm || inc.resetRequired) && diskSessionHashes.has(sessionHash)) {
|
|
2563
|
+
return {
|
|
2564
|
+
fallbackToCleanMemory: true,
|
|
2565
|
+
watermarks: watermarks2,
|
|
2566
|
+
hourlyCache: hourlyCache2,
|
|
2567
|
+
dirtyHourlyMonths: dirtyHourlyMonths2,
|
|
2568
|
+
dailyData: dailyData2,
|
|
2569
|
+
weeklyData: weeklyData2,
|
|
2570
|
+
monthlyData: monthlyData2,
|
|
2571
|
+
anyNewData: anyNewData2
|
|
2572
|
+
};
|
|
2573
|
+
}
|
|
2574
|
+
const projectHash = projectIndex.get(sessionId) ?? null;
|
|
2575
|
+
let maxStepIndex = prevWm?.last_step_index ?? -1;
|
|
2576
|
+
const parsedRecords = [];
|
|
2577
|
+
for (const line of inc.lines) {
|
|
2578
|
+
const trimmed = line.trim();
|
|
2579
|
+
if (!trimmed) continue;
|
|
2580
|
+
let parsed;
|
|
2581
|
+
try {
|
|
2582
|
+
parsed = JSON.parse(trimmed);
|
|
2583
|
+
} catch {
|
|
2584
|
+
continue;
|
|
2585
|
+
}
|
|
2586
|
+
const stepIdx = typeof parsed.step_index === "number" ? parsed.step_index : void 0;
|
|
2587
|
+
if (stepIdx !== void 0 && prevWm?.last_step_index !== void 0 && stepIdx <= prevWm.last_step_index) {
|
|
2588
|
+
continue;
|
|
2589
|
+
}
|
|
2590
|
+
const tsMs = extractStructuralTimestampMs(parsed);
|
|
2591
|
+
if (tsMs === null || tsMs > nowMs + 6e4) continue;
|
|
2592
|
+
const typeStr = typeof parsed.type === "string" ? parsed.type.toUpperCase() : "";
|
|
2593
|
+
const usageObj = parsed.usage && typeof parsed.usage === "object" && !Array.isArray(parsed.usage) ? parsed.usage : {};
|
|
2594
|
+
const num = (...vals) => {
|
|
2595
|
+
for (const v of vals) {
|
|
2596
|
+
if (v === null || v === void 0 || v === "") continue;
|
|
2597
|
+
const n = typeof v === "number" ? v : Number(v);
|
|
2598
|
+
if (Number.isFinite(n) && n >= 0) return Math.floor(n);
|
|
2599
|
+
}
|
|
2600
|
+
return 0;
|
|
2601
|
+
};
|
|
2602
|
+
const rawInput = num(parsed.input_tokens, usageObj.input_tokens, usageObj.prompt_tokens);
|
|
2603
|
+
const rawCacheRead = num(
|
|
2604
|
+
parsed.cache_read_tokens,
|
|
2605
|
+
usageObj.cache_read_tokens,
|
|
2606
|
+
usageObj.cached_content_token_count
|
|
2607
|
+
);
|
|
2608
|
+
const rawOutput = num(
|
|
2609
|
+
parsed.output_tokens,
|
|
2610
|
+
usageObj.output_tokens,
|
|
2611
|
+
usageObj.completion_tokens
|
|
2612
|
+
);
|
|
2613
|
+
if (typeStr !== "PLANNER_RESPONSE" && rawInput + rawCacheRead === 0 && rawOutput === 0) {
|
|
2614
|
+
continue;
|
|
2615
|
+
}
|
|
2616
|
+
if (rawInput + rawCacheRead === 0 && rawOutput === 0) {
|
|
2617
|
+
continue;
|
|
2618
|
+
}
|
|
2619
|
+
if (stepIdx !== void 0 && stepIdx > maxStepIndex) {
|
|
2620
|
+
maxStepIndex = stepIdx;
|
|
2621
|
+
}
|
|
2622
|
+
parsedRecords.push(
|
|
2623
|
+
sanitizeUsagePayload(
|
|
2624
|
+
{
|
|
2625
|
+
ts: new Date(tsMs).toISOString(),
|
|
2626
|
+
provider: "antigravity",
|
|
2627
|
+
product: "agy",
|
|
2628
|
+
session_id: sessionId,
|
|
2629
|
+
model: parsed.model ?? usageObj.model ?? "unknown",
|
|
2630
|
+
input_tokens: rawInput,
|
|
2631
|
+
cache_read_tokens: rawCacheRead,
|
|
2632
|
+
output_tokens: rawOutput,
|
|
2633
|
+
thinking_tokens: 0,
|
|
2634
|
+
tool_calls: 0,
|
|
2635
|
+
turn_index: stepIdx ?? 0,
|
|
2636
|
+
project_hash: projectHash,
|
|
2637
|
+
auth_mode: options.transcriptAuthMode ?? "unknown"
|
|
2638
|
+
},
|
|
2639
|
+
salt
|
|
2640
|
+
)
|
|
2641
|
+
);
|
|
2642
|
+
}
|
|
2643
|
+
await ingestRecords(parsedRecords);
|
|
2644
|
+
watermarks2.sources[wmKey] = {
|
|
2645
|
+
mtime_ms: inc.mtimeMs,
|
|
2646
|
+
byte_offset: inc.newOffset,
|
|
2647
|
+
...maxStepIndex >= 0 ? { last_step_index: maxStepIndex } : {},
|
|
2648
|
+
updated_at: new Date(nowMs).toISOString()
|
|
2649
|
+
};
|
|
2650
|
+
anyNewData2 = true;
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
return {
|
|
2654
|
+
fallbackToCleanMemory: false,
|
|
2655
|
+
watermarks: watermarks2,
|
|
2656
|
+
hourlyCache: hourlyCache2,
|
|
2657
|
+
dirtyHourlyMonths: dirtyHourlyMonths2,
|
|
2658
|
+
dailyData: dailyData2,
|
|
2659
|
+
weeklyData: weeklyData2,
|
|
2660
|
+
monthlyData: monthlyData2,
|
|
2661
|
+
anyNewData: anyNewData2
|
|
2662
|
+
};
|
|
2663
|
+
};
|
|
2664
|
+
let passResult = await runIngestionPass(!rebuildRequired);
|
|
2665
|
+
if (passResult.fallbackToCleanMemory) {
|
|
2666
|
+
passResult = await runIngestionPass(false);
|
|
2667
|
+
}
|
|
2668
|
+
const {
|
|
2669
|
+
watermarks,
|
|
2670
|
+
hourlyCache,
|
|
2671
|
+
dirtyHourlyMonths,
|
|
2672
|
+
dailyData,
|
|
2673
|
+
weeklyData,
|
|
2674
|
+
monthlyData,
|
|
2675
|
+
anyNewData
|
|
2676
|
+
} = passResult;
|
|
2677
|
+
if (canWrite && anyNewData) {
|
|
2678
|
+
if (rebuildRequired) {
|
|
2679
|
+
for (const oldFile of existingHourlyFiles) {
|
|
2680
|
+
const oldMonth = oldFile.replace(/\.json$/, "");
|
|
2681
|
+
if (!dirtyHourlyMonths.has(oldMonth)) {
|
|
2682
|
+
await unlink(join5(hourlyDir, oldFile)).catch(() => void 0);
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
for (const monthKey of dirtyHourlyMonths) {
|
|
2687
|
+
const hf = hourlyCache.get(monthKey);
|
|
2688
|
+
if (hf) {
|
|
2689
|
+
await atomicWriteJson(join5(hourlyDir, `${monthKey}.json`), hf);
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
dailyData.updated_at = new Date(nowMs).toISOString();
|
|
2693
|
+
weeklyData.updated_at = new Date(nowMs).toISOString();
|
|
2694
|
+
monthlyData.updated_at = new Date(nowMs).toISOString();
|
|
2695
|
+
await atomicWriteJson(dailyPath, dailyData);
|
|
2696
|
+
await atomicWriteJson(weeklyPath, weeklyData);
|
|
2697
|
+
await atomicWriteJson(monthlyPath, monthlyData);
|
|
2698
|
+
await atomicWriteJson(watermarksPath, watermarks);
|
|
2699
|
+
}
|
|
2700
|
+
const cutoffMs = options.window === "all" ? Number.NEGATIVE_INFINITY : nowMs - WINDOW_MS[options.window];
|
|
2701
|
+
const aggregated = /* @__PURE__ */ new Map();
|
|
2702
|
+
const totalSessions = /* @__PURE__ */ new Set();
|
|
2703
|
+
const unattributedSessions = /* @__PURE__ */ new Set();
|
|
2704
|
+
const totals = emptyCounters();
|
|
2705
|
+
const productFilter = options.product ?? "all";
|
|
2706
|
+
const scope = options.scope ?? "global";
|
|
2707
|
+
const authFilter = options.authMode ?? "all";
|
|
2708
|
+
for (const hf of hourlyCache.values()) {
|
|
2709
|
+
for (const [hourUtcKey, entries] of Object.entries(hf.buckets)) {
|
|
2710
|
+
const hourMs = Date.parse(hourUtcKey);
|
|
2711
|
+
if (Number.isNaN(hourMs) || hourMs + 36e5 <= cutoffMs || hourMs > nowMs + 36e5) {
|
|
2712
|
+
continue;
|
|
2713
|
+
}
|
|
2714
|
+
const targetBucketKey = formatBucketKey(hourMs, options.granularity, tz);
|
|
2715
|
+
for (const entry of entries) {
|
|
2716
|
+
if (productFilter !== "all" && entry.product !== productFilter) {
|
|
2717
|
+
continue;
|
|
2718
|
+
}
|
|
2719
|
+
if (authFilter !== "all" && entry.auth_mode !== authFilter) {
|
|
2720
|
+
continue;
|
|
2721
|
+
}
|
|
2722
|
+
if (!entry.project_hash) {
|
|
2723
|
+
for (const sh of entry.session_hashes) {
|
|
2724
|
+
unattributedSessions.add(sh);
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
if (scope === "project") {
|
|
2728
|
+
if (!options.projectHash || entry.project_hash !== options.projectHash) {
|
|
2729
|
+
continue;
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
let bucketAgg = aggregated.get(targetBucketKey);
|
|
2733
|
+
if (!bucketAgg) {
|
|
2734
|
+
bucketAgg = { counters: emptyCounters(), sessions: /* @__PURE__ */ new Set() };
|
|
2735
|
+
aggregated.set(targetBucketKey, bucketAgg);
|
|
2736
|
+
}
|
|
2737
|
+
const repriced = entry.model ? estimateTokenCosts(
|
|
2738
|
+
{
|
|
2739
|
+
model: entry.model,
|
|
2740
|
+
uncachedInputTokens: entry.uncached_input_tokens,
|
|
2741
|
+
cacheReadTokens: entry.cache_read_tokens,
|
|
2742
|
+
outputTokens: entry.output_tokens
|
|
2743
|
+
},
|
|
2744
|
+
catalog
|
|
2745
|
+
) : null;
|
|
2746
|
+
const entryTotalUsd = repriced ? repriced.totalUsd : entry.estimated_total_usd;
|
|
2747
|
+
const entryCacheSavingsUsd = repriced ? repriced.cacheSavingsUsd : entry.estimated_cache_savings_usd;
|
|
2748
|
+
const c = bucketAgg.counters;
|
|
2749
|
+
c.requests += entry.requests;
|
|
2750
|
+
c.uncached_input_tokens += entry.uncached_input_tokens;
|
|
2751
|
+
c.cache_read_tokens += entry.cache_read_tokens;
|
|
2752
|
+
c.input_tokens += entry.input_tokens;
|
|
2753
|
+
c.output_tokens += entry.output_tokens;
|
|
2754
|
+
c.thinking_tokens += entry.thinking_tokens;
|
|
2755
|
+
c.total_tokens += entry.total_tokens;
|
|
2756
|
+
c.error_count += entry.error_count;
|
|
2757
|
+
c.rate_limit_429_count += entry.rate_limit_429_count;
|
|
2758
|
+
c.below_kv_cache_threshold_requests += entry.below_kv_cache_threshold_requests;
|
|
2759
|
+
c.estimated_total_usd += entryTotalUsd;
|
|
2760
|
+
c.estimated_cache_savings_usd += entryCacheSavingsUsd;
|
|
2761
|
+
totals.requests += entry.requests;
|
|
2762
|
+
totals.uncached_input_tokens += entry.uncached_input_tokens;
|
|
2763
|
+
totals.cache_read_tokens += entry.cache_read_tokens;
|
|
2764
|
+
totals.input_tokens += entry.input_tokens;
|
|
2765
|
+
totals.output_tokens += entry.output_tokens;
|
|
2766
|
+
totals.thinking_tokens += entry.thinking_tokens;
|
|
2767
|
+
totals.total_tokens += entry.total_tokens;
|
|
2768
|
+
totals.error_count += entry.error_count;
|
|
2769
|
+
totals.rate_limit_429_count += entry.rate_limit_429_count;
|
|
2770
|
+
totals.below_kv_cache_threshold_requests += entry.below_kv_cache_threshold_requests;
|
|
2771
|
+
totals.estimated_total_usd += entryTotalUsd;
|
|
2772
|
+
totals.estimated_cache_savings_usd += entryCacheSavingsUsd;
|
|
2773
|
+
for (const sh of entry.session_hashes) {
|
|
2774
|
+
bucketAgg.sessions.add(sh);
|
|
2775
|
+
totalSessions.add(sh);
|
|
2776
|
+
}
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
totals.estimated_total_usd = round42(totals.estimated_total_usd);
|
|
2781
|
+
totals.estimated_cache_savings_usd = round42(totals.estimated_cache_savings_usd);
|
|
2782
|
+
const allBuckets = [...aggregated.entries()].filter(([, v]) => v.counters.requests > 0).sort(([a], [b]) => a.localeCompare(b)).map(([bucket, v]) => ({
|
|
2783
|
+
bucket,
|
|
2784
|
+
...v.counters,
|
|
2785
|
+
estimated_total_usd: round42(v.counters.estimated_total_usd),
|
|
2786
|
+
estimated_cache_savings_usd: round42(v.counters.estimated_cache_savings_usd),
|
|
2787
|
+
session_count: v.sessions.size,
|
|
2788
|
+
cache_hit_rate_pct: v.counters.input_tokens > 0 ? Math.round(v.counters.cache_read_tokens / v.counters.input_tokens * 1e3) / 10 : 0
|
|
2789
|
+
}));
|
|
2790
|
+
const truncated = allBuckets.length > maxBuckets;
|
|
2791
|
+
const returned = truncated ? allBuckets.slice(-maxBuckets) : allBuckets;
|
|
2792
|
+
return {
|
|
2793
|
+
time_series: returned,
|
|
2794
|
+
time_series_meta: {
|
|
2795
|
+
granularity: options.granularity,
|
|
2796
|
+
timezone: tz,
|
|
2797
|
+
total_buckets: allBuckets.length,
|
|
2798
|
+
returned_buckets: returned.length,
|
|
2799
|
+
max_buckets: maxBuckets,
|
|
2800
|
+
truncated,
|
|
2801
|
+
source: canWrite ? "rollups" : "memory_fallback"
|
|
2802
|
+
},
|
|
2803
|
+
summary_totals: {
|
|
2804
|
+
...totals,
|
|
2805
|
+
session_count: totalSessions.size,
|
|
2806
|
+
cache_hit_rate_pct: totals.input_tokens > 0 ? Math.round(totals.cache_read_tokens / totals.input_tokens * 1e3) / 10 : 0,
|
|
2807
|
+
unattributed_sessions_excluded: unattributedSessions.size
|
|
2808
|
+
}
|
|
2809
|
+
};
|
|
2810
|
+
} finally {
|
|
2811
|
+
await releaseLock(lockPath);
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
// src/analyzers/antipatterns.ts
|
|
2816
|
+
var HEAVY_MODEL_RE = /(neon|carbon|pro|ultra|opus)/i;
|
|
2817
|
+
function analyzeAntipatterns(records, options) {
|
|
2818
|
+
const window = options?.window ?? "24h";
|
|
2819
|
+
const scope = options?.scope ?? "global";
|
|
2820
|
+
const nowMs = options?.nowMs ?? Date.now();
|
|
2821
|
+
const cutoffMs = nowMs - (window === "24h" ? 864e5 : 7 * 864e5);
|
|
2822
|
+
const windowRecords = records.filter((r) => {
|
|
2823
|
+
const ts = Date.parse(r.ts);
|
|
2824
|
+
return !Number.isNaN(ts) && ts >= cutoffMs;
|
|
2825
|
+
});
|
|
2826
|
+
const filtered = scope === "project" ? windowRecords.filter(
|
|
2827
|
+
(r) => Boolean(options?.projectHash) && r.project_hash === options?.projectHash
|
|
2828
|
+
) : windowRecords;
|
|
2829
|
+
const recs = [];
|
|
2830
|
+
let totalUncachedInput = 0;
|
|
2831
|
+
let totalCacheRead = 0;
|
|
2832
|
+
for (const r of filtered) {
|
|
2833
|
+
totalUncachedInput += r.input_tokens;
|
|
2834
|
+
totalCacheRead += r.cache_read_tokens ?? 0;
|
|
2835
|
+
}
|
|
2836
|
+
const totalInputWithCache = totalUncachedInput + totalCacheRead;
|
|
2837
|
+
const cacheHitRatePct = totalInputWithCache > 0 ? totalCacheRead / totalInputWithCache * 100 : 0;
|
|
2838
|
+
const longSessions = /* @__PURE__ */ new Map();
|
|
2839
|
+
for (const r of filtered) {
|
|
2840
|
+
const cur = longSessions.get(r.session_hash) ?? {
|
|
2841
|
+
maxTurn: 0,
|
|
2842
|
+
maxCtxPct: null,
|
|
2843
|
+
totalInput: 0,
|
|
2844
|
+
turns: 0
|
|
2845
|
+
};
|
|
2846
|
+
cur.maxTurn = Math.max(cur.maxTurn, r.turn_index);
|
|
2847
|
+
if (typeof r.context_used_pct === "number") {
|
|
2848
|
+
cur.maxCtxPct = cur.maxCtxPct === null ? r.context_used_pct : Math.max(cur.maxCtxPct, r.context_used_pct);
|
|
2849
|
+
}
|
|
2850
|
+
cur.totalInput += r.input_tokens + (r.cache_read_tokens ?? 0);
|
|
2851
|
+
cur.turns += 1;
|
|
2852
|
+
longSessions.set(r.session_hash, cur);
|
|
2853
|
+
}
|
|
2854
|
+
const snowballSessions = [...longSessions.values()].filter(
|
|
2855
|
+
(s) => s.maxTurn >= 20 || s.maxCtxPct !== null && s.maxCtxPct >= 70 || s.turns >= 25 && (s.maxTurn > 0 || s.maxCtxPct !== null && s.maxCtxPct > 0)
|
|
2856
|
+
);
|
|
2857
|
+
const transcriptUncompacted = options?.transcriptMeta && options.transcriptMeta.steps_since_last_compact >= 30;
|
|
2858
|
+
if (snowballSessions.length > 0 || transcriptUncompacted) {
|
|
2859
|
+
const ctxValues = snowballSessions.map((s) => s.maxCtxPct).filter((v) => v !== null);
|
|
2860
|
+
const peakCtx = ctxValues.length > 0 ? Math.max(...ctxValues) : null;
|
|
2861
|
+
const peakTurn = Math.max(0, ...snowballSessions.map((s) => s.maxTurn));
|
|
2862
|
+
const snowballTotalInput = snowballSessions.reduce((s, v) => s + v.totalInput, 0);
|
|
2863
|
+
const snowballTotalTurns = snowballSessions.reduce((s, v) => s + v.turns, 0);
|
|
2864
|
+
const snowballAvgInput = snowballTotalTurns > 0 ? Math.round(snowballTotalInput / snowballTotalTurns) : 0;
|
|
2865
|
+
const avgInputLabel = snowballAvgInput >= 1e3 ? `~${Math.round(snowballAvgInput / 1e3)}K` : `${snowballAvgInput}`;
|
|
2866
|
+
const highCacheHit = totalInputWithCache > 0 && cacheHitRatePct >= 85;
|
|
2867
|
+
const roundedHit = Math.round(cacheHitRatePct * 10) / 10;
|
|
2868
|
+
recs.push({
|
|
2869
|
+
id: "long_session_snowball",
|
|
2870
|
+
severity: "high",
|
|
2871
|
+
category: "long_session_snowball",
|
|
2872
|
+
title: "Long-session context snowball detected",
|
|
2873
|
+
evidence: snowballSessions.length > 0 ? peakCtx !== null ? `${snowballSessions.length} session(s) reached turn ${peakTurn} / ${peakCtx}% context utilization without compacting.` : `${snowballSessions.length} session(s) reached turn ${peakTurn} (context % unavailable, avg ${avgInputLabel} input tokens/req) without compacting.` : `Transcript has ${options?.transcriptMeta?.steps_since_last_compact} steps since last /compact.`,
|
|
2874
|
+
action: highCacheHit ? `With ${roundedHit}% KV cache hit rate, avoid mechanical \`/compact\` every 12\u201315 turns (which breaks prefix caching); run \`/compact\` or start a fresh thread at phase milestones or when per-request input approaches 150K\u2013200K tokens.` : "Run `/compact` (or `/compress`) every 12\u201315 turns or start a fresh thread per subtask. Uncompacted histories re-bill growing prefixes every turn.",
|
|
2875
|
+
estimated_savings_pct: highCacheHit ? "15\u201330%" : "35\u201360%"
|
|
2876
|
+
});
|
|
2877
|
+
}
|
|
2878
|
+
const heavyTurns = filtered.filter((r) => HEAVY_MODEL_RE.test(r.model));
|
|
2879
|
+
const lightweightOnHeavy = heavyTurns.filter(
|
|
2880
|
+
(r) => r.output_tokens > 0 && r.output_tokens < 350 && r.tool_calls <= 1
|
|
2881
|
+
);
|
|
2882
|
+
if (heavyTurns.length >= 4 && lightweightOnHeavy.length / heavyTurns.length >= 0.45) {
|
|
2883
|
+
const pct = Math.round(lightweightOnHeavy.length / heavyTurns.length * 100);
|
|
2884
|
+
recs.push({
|
|
2885
|
+
id: "heavy_model_mismatch",
|
|
2886
|
+
severity: "high",
|
|
2887
|
+
category: "heavy_model_mismatch",
|
|
2888
|
+
title: "Heavy flagship model used for lightweight turns",
|
|
2889
|
+
evidence: `${lightweightOnHeavy.length}/${heavyTurns.length} (${pct}%) heavy-model turns produced <350 output tokens with <=1 tool call.`,
|
|
2890
|
+
action: "Adopt an Orchestrator workflow: use Gemini 4 Neon for architecture/planning, then route routine edits, tests, and greps to Gemini 4 Hydrogen or Gemini 3.8 Flash.",
|
|
2891
|
+
estimated_savings_pct: "50\u201375%"
|
|
2892
|
+
});
|
|
2893
|
+
}
|
|
2894
|
+
const totalHeavyInput = heavyTurns.reduce((s, r) => s + r.input_tokens, 0);
|
|
2895
|
+
const totalHeavyOutput = heavyTurns.reduce((s, r) => s + r.output_tokens, 0);
|
|
2896
|
+
if (heavyTurns.length >= 3 && totalHeavyOutput > 15e3 && (totalHeavyInput === 0 || totalHeavyOutput / Math.max(1, totalHeavyInput) >= 0.15)) {
|
|
2897
|
+
recs.push({
|
|
2898
|
+
id: "thinking_downgrade",
|
|
2899
|
+
severity: "medium",
|
|
2900
|
+
category: "thinking_downgrade",
|
|
2901
|
+
title: "High Thinking/output token burn on flagship models",
|
|
2902
|
+
evidence: `${totalHeavyOutput.toLocaleString()} output/thinking tokens on heavy models (billed at 4x\u20138x input rate in shared 5h/7d buckets).`,
|
|
2903
|
+
action: "Lower Thinking level (e.g. Medium/Low) for boilerplate coding & log parsing, reserving High Thinking strictly for multi-file debugging or architecture.",
|
|
2904
|
+
estimated_savings_pct: "25\u201345%"
|
|
2905
|
+
});
|
|
2906
|
+
}
|
|
2907
|
+
if (options?.transcriptMeta?.loop_detected) {
|
|
2908
|
+
const tool = options.transcriptMeta.consecutive_failure_tool_type ?? "tool";
|
|
2909
|
+
const streak = options.transcriptMeta.max_consecutive_tool_failures;
|
|
2910
|
+
recs.push({
|
|
2911
|
+
id: "infinite_loop_warning",
|
|
2912
|
+
severity: "high",
|
|
2913
|
+
category: "infinite_loop_warning",
|
|
2914
|
+
title: `Autonomous failure loop detected (${streak} consecutive "${tool}" errors)`,
|
|
2915
|
+
evidence: `Transcript recorded ${streak} consecutive failures on "${tool}" (${options.transcriptMeta.tool_error_count} total tool errors).`,
|
|
2916
|
+
action: "Stop the agent immediately, inspect the failing command manually, fix the root cause or environment, and resume with a concise summary.",
|
|
2917
|
+
estimated_savings_pct: "40\u201380% on runaway turns"
|
|
2918
|
+
});
|
|
2919
|
+
}
|
|
2920
|
+
if (options?.hasGeminiIgnore === false) {
|
|
2921
|
+
recs.push({
|
|
2922
|
+
id: "missing_geminiignore",
|
|
2923
|
+
severity: "medium",
|
|
2924
|
+
category: "missing_geminiignore",
|
|
2925
|
+
title: "Missing .geminiignore in workspace",
|
|
2926
|
+
evidence: "No .geminiignore file was found in the provided workspace_dir.",
|
|
2927
|
+
action: "Create a `.geminiignore` file (excluding `node_modules/`, `dist/`, `.venv/`, `__pycache__/`, `data/`, `logs/`, `tmp/`, `*.parquet`, `*.lock`) or run `npx agycraft-mcp doctor` for a recommended template.",
|
|
2928
|
+
estimated_savings_pct: "15\u201335%"
|
|
2929
|
+
});
|
|
2930
|
+
}
|
|
2931
|
+
const hasLongTurns = snowballSessions.length > 0 || [...longSessions.values()].some((s) => s.turns >= 5);
|
|
2932
|
+
if (filtered.length >= 4 && totalInputWithCache >= 16384 && cacheHitRatePct < 30 && (totalCacheRead > 0 || hasLongTurns)) {
|
|
2933
|
+
recs.push({
|
|
2934
|
+
id: "low_kv_cache_efficiency",
|
|
2935
|
+
severity: "medium",
|
|
2936
|
+
category: "low_kv_cache_efficiency",
|
|
2937
|
+
title: "Low KV cache hit efficiency",
|
|
2938
|
+
evidence: `KV cache hit rate is ${Math.round(cacheHitRatePct * 10) / 10}% (${totalCacheRead.toLocaleString()} cached / ${totalInputWithCache.toLocaleString()} total input tokens).`,
|
|
2939
|
+
action: "Keep system instructions, tool schemas, and file prefixes stable across turns to maximize implicit KV cache hits instead of re-paying full uncached input rates.",
|
|
2940
|
+
estimated_savings_pct: "20\u201350% on input cost"
|
|
2941
|
+
});
|
|
2942
|
+
}
|
|
2943
|
+
const tz = normalizeTimezone(options?.timezone);
|
|
2944
|
+
const hourlyMap = /* @__PURE__ */ new Map();
|
|
2945
|
+
if (options?.hourlyBuckets && options.hourlyBuckets.length > 0) {
|
|
2946
|
+
for (const b of options.hourlyBuckets) {
|
|
2947
|
+
hourlyMap.set(b.bucket, {
|
|
2948
|
+
tokens: b.total_tokens,
|
|
2949
|
+
count429: b.rate_limit_429_count,
|
|
2950
|
+
requests: b.requests ?? 0,
|
|
2951
|
+
uncachedInput: 0,
|
|
2952
|
+
cacheRead: 0,
|
|
2953
|
+
cacheHitRatePct: b.cache_hit_rate_pct
|
|
2954
|
+
});
|
|
2955
|
+
}
|
|
2956
|
+
} else {
|
|
2957
|
+
for (const r of filtered) {
|
|
2958
|
+
const tsMs = Date.parse(r.ts);
|
|
2959
|
+
if (Number.isNaN(tsMs)) continue;
|
|
2960
|
+
const hourKey = formatBucketKey(tsMs, "hourly", tz);
|
|
2961
|
+
const cur = hourlyMap.get(hourKey) ?? {
|
|
2962
|
+
tokens: 0,
|
|
2963
|
+
count429: 0,
|
|
2964
|
+
requests: 0,
|
|
2965
|
+
uncachedInput: 0,
|
|
2966
|
+
cacheRead: 0
|
|
2967
|
+
};
|
|
2968
|
+
const cacheRead = r.cache_read_tokens ?? 0;
|
|
2969
|
+
cur.requests += 1;
|
|
2970
|
+
cur.uncachedInput += r.input_tokens;
|
|
2971
|
+
cur.cacheRead += cacheRead;
|
|
2972
|
+
cur.tokens += r.input_tokens + cacheRead + r.output_tokens;
|
|
2973
|
+
if (r.error_code && (r.error_code.includes("429") || r.error_code.includes("RESOURCE_EXHAUSTED"))) {
|
|
2974
|
+
cur.count429 += 1;
|
|
2975
|
+
}
|
|
2976
|
+
hourlyMap.set(hourKey, cur);
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
const hourlyValues = [...hourlyMap.values()];
|
|
2980
|
+
const totalHourlyTokens = hourlyValues.reduce((s, v) => s + v.tokens, 0);
|
|
2981
|
+
const total429 = hourlyValues.reduce((s, v) => s + v.count429, 0);
|
|
2982
|
+
if (hourlyValues.length >= 3 && totalHourlyTokens > 0 && total429 > 0) {
|
|
2983
|
+
const sortedTokens = hourlyValues.map((v) => v.tokens).sort((a, b) => b - a);
|
|
2984
|
+
const top3Tokens = sortedTokens.slice(0, 3).reduce((s, t) => s + t, 0);
|
|
2985
|
+
const top3SharePct = Math.round(top3Tokens / totalHourlyTokens * 1e3) / 10;
|
|
2986
|
+
if (top3SharePct >= 70) {
|
|
2987
|
+
recs.push({
|
|
2988
|
+
id: "peak_window_misalignment",
|
|
2989
|
+
severity: "medium",
|
|
2990
|
+
category: "peak_window_misalignment",
|
|
2991
|
+
title: "Peak window concentration causing 429 rate limits",
|
|
2992
|
+
evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s).`,
|
|
2993
|
+
action: "Stagger heavy batch runs across 5h rolling windows and align daily quota resets with PT midnight (America/Los_Angeles 00:00) to avoid burst exhaustion.",
|
|
2994
|
+
estimated_savings_pct: "15\u201330% fewer 429 retries"
|
|
2995
|
+
});
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
const hasTelemetry = filtered.some(
|
|
2999
|
+
(r) => r.input_tokens > 0 || (r.cache_read_tokens ?? 0) > 0 || r.output_tokens > 0 || r.turn_index > 0 || r.context_used_pct !== null && r.context_used_pct > 0
|
|
3000
|
+
);
|
|
3001
|
+
const note = filtered.length > 0 && !hasTelemetry && !options?.transcriptMeta ? "Local hook events lack token, turn, and context telemetry. Antipattern recommendations require token/turn telemetry (e.g. Gemini CLI OTel) or a local transcript_path." : void 0;
|
|
3002
|
+
const catalog = options?.models ?? [];
|
|
3003
|
+
const totalOutput = filtered.reduce((s, r) => s + r.output_tokens, 0);
|
|
3004
|
+
const totalTokens = totalInputWithCache + totalOutput;
|
|
3005
|
+
const totalRequests = filtered.length;
|
|
3006
|
+
const avgInputTokensPerRequest = totalRequests > 0 ? Math.round(totalInputWithCache / totalRequests) : 0;
|
|
3007
|
+
const roundedCacheHitRatePct = totalInputWithCache > 0 ? Math.round(cacheHitRatePct * 10) / 10 : 0;
|
|
3008
|
+
const modelAgg = /* @__PURE__ */ new Map();
|
|
3009
|
+
for (const r of filtered) {
|
|
3010
|
+
const cur = modelAgg.get(r.model) ?? {
|
|
3011
|
+
requests: 0,
|
|
3012
|
+
uncachedInput: 0,
|
|
3013
|
+
cacheRead: 0,
|
|
3014
|
+
output: 0
|
|
3015
|
+
};
|
|
3016
|
+
cur.requests += 1;
|
|
3017
|
+
cur.uncachedInput += r.input_tokens;
|
|
3018
|
+
cur.cacheRead += r.cache_read_tokens ?? 0;
|
|
3019
|
+
cur.output += r.output_tokens;
|
|
3020
|
+
modelAgg.set(r.model, cur);
|
|
3021
|
+
}
|
|
3022
|
+
let estimatedCacheSavingsUsd = 0;
|
|
3023
|
+
let lightModelRequests = 0;
|
|
3024
|
+
let heavyModelRequests = 0;
|
|
3025
|
+
const modelEntries = [];
|
|
3026
|
+
for (const [model, agg] of modelAgg.entries()) {
|
|
3027
|
+
const { pricing, cacheSavingsUsd } = estimateTokenCosts(
|
|
3028
|
+
{
|
|
3029
|
+
model,
|
|
3030
|
+
uncachedInputTokens: agg.uncachedInput,
|
|
3031
|
+
cacheReadTokens: agg.cacheRead,
|
|
3032
|
+
outputTokens: agg.output
|
|
3033
|
+
},
|
|
3034
|
+
catalog
|
|
3035
|
+
);
|
|
3036
|
+
estimatedCacheSavingsUsd += cacheSavingsUsd;
|
|
3037
|
+
if (pricing.tier === "low" || pricing.tier === "minimal") {
|
|
3038
|
+
lightModelRequests += agg.requests;
|
|
3039
|
+
} else if (pricing.tier === "high" || pricing.tier === "very-high" || pricing.tier === "very_high") {
|
|
3040
|
+
heavyModelRequests += agg.requests;
|
|
3041
|
+
}
|
|
3042
|
+
const modelTotalTokens = agg.uncachedInput + agg.cacheRead + agg.output;
|
|
3043
|
+
modelEntries.push({
|
|
3044
|
+
model,
|
|
3045
|
+
requests: agg.requests,
|
|
3046
|
+
total_tokens: modelTotalTokens
|
|
3047
|
+
});
|
|
3048
|
+
}
|
|
3049
|
+
modelEntries.sort(
|
|
3050
|
+
(a, b) => b.total_tokens - a.total_tokens || b.requests - a.requests
|
|
3051
|
+
);
|
|
3052
|
+
const topModels = modelEntries.slice(0, 3).map((m) => ({
|
|
3053
|
+
model: m.model,
|
|
3054
|
+
requests: m.requests,
|
|
3055
|
+
token_share_pct: totalTokens > 0 ? Math.round(m.total_tokens / totalTokens * 1e3) / 10 : totalRequests > 0 ? Math.round(m.requests / totalRequests * 1e3) / 10 : 0,
|
|
3056
|
+
total_tokens: m.total_tokens
|
|
3057
|
+
}));
|
|
3058
|
+
const lightModelRequestSharePct = totalRequests > 0 ? Math.round(lightModelRequests / totalRequests * 1e3) / 10 : 0;
|
|
3059
|
+
const heavyModelRequestSharePct = totalRequests > 0 ? Math.round(heavyModelRequests / totalRequests * 1e3) / 10 : 0;
|
|
3060
|
+
const hasBucketRequests = Boolean(
|
|
3061
|
+
options?.hourlyBuckets?.some((b) => typeof b.requests === "number")
|
|
3062
|
+
);
|
|
3063
|
+
const peakHoursSource = options?.hourlyBuckets && options.hourlyBuckets.length > 0 && hasBucketRequests ? options.hourlyBuckets.map((b) => ({
|
|
3064
|
+
bucket: b.bucket,
|
|
3065
|
+
requests: b.requests ?? 0,
|
|
3066
|
+
total_tokens: b.total_tokens,
|
|
3067
|
+
cache_hit_rate_pct: b.cache_hit_rate_pct ?? 0
|
|
3068
|
+
})) : [...hourlyMap.entries()].map(([bucket, v]) => {
|
|
3069
|
+
const inputTotal = v.uncachedInput + v.cacheRead;
|
|
3070
|
+
const hitPct = typeof v.cacheHitRatePct === "number" ? v.cacheHitRatePct : inputTotal > 0 ? Math.round(v.cacheRead / inputTotal * 1e3) / 10 : 0;
|
|
3071
|
+
return {
|
|
3072
|
+
bucket,
|
|
3073
|
+
requests: v.requests,
|
|
3074
|
+
total_tokens: v.tokens,
|
|
3075
|
+
cache_hit_rate_pct: hitPct
|
|
3076
|
+
};
|
|
3077
|
+
});
|
|
3078
|
+
const peakHours = peakHoursSource.filter((b) => b.requests > 0 || b.total_tokens > 0).sort((a, b) => b.total_tokens - a.total_tokens || b.requests - a.requests).slice(0, 3);
|
|
3079
|
+
const globalTotalTokens = windowRecords.reduce(
|
|
3080
|
+
(s, r) => s + r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens,
|
|
3081
|
+
0
|
|
3082
|
+
);
|
|
3083
|
+
const projectShareOfGlobalPct = scope === "project" ? globalTotalTokens > 0 ? Math.round(totalTokens / globalTotalTokens * 1e3) / 10 : 0 : null;
|
|
3084
|
+
const roundedSavingsUsd = Math.round(estimatedCacheSavingsUsd * 1e4) / 1e4;
|
|
3085
|
+
const authSummary = {
|
|
3086
|
+
active_auth_mode: options?.authContext?.active_auth_mode ?? "unknown",
|
|
3087
|
+
has_mixed_auth: options?.authContext?.has_mixed_auth ?? false
|
|
3088
|
+
};
|
|
3089
|
+
const behaviorSummary = {
|
|
3090
|
+
avg_input_tokens_per_request: avgInputTokensPerRequest,
|
|
3091
|
+
cache_hit_rate_pct: roundedCacheHitRatePct,
|
|
3092
|
+
estimated_cache_savings_usd: roundedSavingsUsd,
|
|
3093
|
+
light_model_request_share_pct: lightModelRequestSharePct,
|
|
3094
|
+
heavy_model_request_share_pct: heavyModelRequestSharePct,
|
|
3095
|
+
top_models: topModels,
|
|
3096
|
+
peak_hours: peakHours,
|
|
3097
|
+
project_share_of_global_pct: projectShareOfGlobalPct,
|
|
3098
|
+
auth_context: authSummary
|
|
3099
|
+
};
|
|
3100
|
+
const executiveSummary = buildExecutiveSummary({
|
|
3101
|
+
window,
|
|
3102
|
+
scope,
|
|
3103
|
+
requests: totalRequests,
|
|
3104
|
+
totalTokens,
|
|
3105
|
+
avgInputTokensPerRequest,
|
|
3106
|
+
cacheHitRatePct: roundedCacheHitRatePct,
|
|
3107
|
+
estimatedCacheSavingsUsd: roundedSavingsUsd,
|
|
3108
|
+
projectShareOfGlobalPct,
|
|
3109
|
+
activeAuthMode: authSummary.active_auth_mode,
|
|
3110
|
+
recommendations: recs,
|
|
3111
|
+
hasMissingTelemetryNote: Boolean(note)
|
|
3112
|
+
});
|
|
3113
|
+
return {
|
|
3114
|
+
window,
|
|
3115
|
+
...options?.scope ? { scope } : {},
|
|
3116
|
+
...scope === "project" && options?.projectHash ? { project_hash: options.projectHash } : {},
|
|
3117
|
+
analyzed_records: filtered.length,
|
|
3118
|
+
recommendations: recs,
|
|
3119
|
+
healthy: recs.length === 0,
|
|
3120
|
+
...note ? { note } : {},
|
|
3121
|
+
behavior_summary: behaviorSummary,
|
|
3122
|
+
executive_summary: executiveSummary
|
|
3123
|
+
};
|
|
3124
|
+
}
|
|
3125
|
+
function buildExecutiveSummary(params) {
|
|
3126
|
+
const {
|
|
3127
|
+
window,
|
|
3128
|
+
scope,
|
|
3129
|
+
requests,
|
|
3130
|
+
totalTokens,
|
|
3131
|
+
avgInputTokensPerRequest,
|
|
3132
|
+
cacheHitRatePct,
|
|
3133
|
+
estimatedCacheSavingsUsd,
|
|
3134
|
+
projectShareOfGlobalPct,
|
|
3135
|
+
activeAuthMode,
|
|
3136
|
+
recommendations,
|
|
3137
|
+
hasMissingTelemetryNote
|
|
3138
|
+
} = params;
|
|
3139
|
+
if (requests === 0) {
|
|
3140
|
+
return `No usage records found in the ${window} ${scope} window; run active sessions or enable Gemini CLI OTel to capture token telemetry.`;
|
|
3141
|
+
}
|
|
3142
|
+
const shareText = scope === "project" && projectShareOfGlobalPct !== null ? ` (${projectShareOfGlobalPct}% of global volume)` : "";
|
|
3143
|
+
const costLabel = activeAuthMode === "google_oauth" ? `$${estimatedCacheSavingsUsd.toFixed(2)} API-equivalent shadow cost saved` : `$${estimatedCacheSavingsUsd.toFixed(2)} saved`;
|
|
3144
|
+
const usagePart = `${window} ${scope} summary: ${requests.toLocaleString()} requests totaling ${totalTokens.toLocaleString()} tokens${shareText}, averaging ${avgInputTokensPerRequest.toLocaleString()} input tokens/req with ${cacheHitRatePct}% KV cache hit rate (${costLabel}).`;
|
|
3145
|
+
if (recommendations.length === 0) {
|
|
3146
|
+
if (hasMissingTelemetryNote) {
|
|
3147
|
+
return `${usagePart} Token telemetry is incomplete; enable Gemini CLI OTel or pass transcript_path for deeper antipattern diagnostics.`;
|
|
3148
|
+
}
|
|
3149
|
+
return `${usagePart} Status: healthy with no quota-burning antipatterns detected; maintain stable prefixes and current model tier routing.`;
|
|
3150
|
+
}
|
|
3151
|
+
const rank = {
|
|
3152
|
+
high: 0,
|
|
3153
|
+
medium: 1,
|
|
3154
|
+
low: 2
|
|
3155
|
+
};
|
|
3156
|
+
const sorted = [...recommendations].sort(
|
|
3157
|
+
(a, b) => rank[a.severity] - rank[b.severity]
|
|
3158
|
+
);
|
|
3159
|
+
const top = sorted[0];
|
|
3160
|
+
return `${usagePart} Primary bottleneck: ${top.title} (${recommendations.length} issue(s) flagged). Top action: ${top.action}`;
|
|
3161
|
+
}
|
|
3162
|
+
|
|
3163
|
+
// src/analyzers/error-diagnoser.ts
|
|
3164
|
+
var EXTERNAL_GCP_DATA_PLANE_403_RE = /\bbigquery\b|Access\s+Denied:\s*BigQuery|bigquery\.tables\.|BigQuery\s+job\s+failed|Access\s+Denied:\s*(?:Table|Dataset)|\b(?:dataset|table)\b.*\b(?:permission|denied|403|not\s+found)\b|gs:\/\/|storage\.objects\.|pubsub\.topics\.|compute\.instances\./i;
|
|
3165
|
+
var MODEL_AUTH_CONFLICT_RE = /cloudaicompanion|generativelanguage|aiplatform|gemini|antigravity|ACCESS_TOKEN_TYPE_UNSUPPORTED|API_KEY_INVALID|GEMINI_API_KEY|GOOGLE_CLOUD_PROJECT/i;
|
|
3166
|
+
function isExternalGcpDataPlane403(text) {
|
|
3167
|
+
return EXTERNAL_GCP_DATA_PLANE_403_RE.test(text) && !MODEL_AUTH_CONFLICT_RE.test(text);
|
|
3168
|
+
}
|
|
3169
|
+
var SPECIFIC_GCP_RULE_IDS = /* @__PURE__ */ new Set([
|
|
3170
|
+
"gcp-vertex-api-disabled",
|
|
3171
|
+
"gcp-adc-expired",
|
|
3172
|
+
"gcp-vertex-iam-or-location",
|
|
3173
|
+
"gcp-vpc-sc-blocked"
|
|
3174
|
+
]);
|
|
3175
|
+
var BUILTIN_RULES = [
|
|
3176
|
+
{
|
|
3177
|
+
id: "weekly-cap",
|
|
3178
|
+
domain: "quota",
|
|
3179
|
+
regex: /weekly\s*(?:cap|limit)|WEEKLY_LIMIT_EXCEEDED|5-?hour|rolling\s*(?:5h|7d)|reached\s+your\s+usage\s+limit/i,
|
|
3180
|
+
fallback: {
|
|
3181
|
+
id: "weekly-cap",
|
|
3182
|
+
slug: "weekly-cap",
|
|
3183
|
+
provider: "antigravity",
|
|
3184
|
+
route_provider: "agy",
|
|
3185
|
+
domain: "quota",
|
|
3186
|
+
title: "Shared 5h / 7d Weekly Quota Cap Reached",
|
|
3187
|
+
severity: "high",
|
|
3188
|
+
products: ["agy", "cli", "web"],
|
|
3189
|
+
error_codes: ["429", "WEEKLY_LIMIT_EXCEEDED", "RATE_LIMIT_EXCEEDED"],
|
|
3190
|
+
error_patterns: ["weekly limit", "5-hour", "Try again later", "reached your usage limit"],
|
|
3191
|
+
root_cause: "You have exhausted the shared 5-hour or 7-day rolling quota bucket across Antigravity / Gemini CLI.",
|
|
3192
|
+
steps: [
|
|
3193
|
+
"Check `get_ecosystem_status` for local 5h/7d rolling window estimates and the official AGY/CLI quota UI for authoritative remaining %.",
|
|
3194
|
+
"Switch to a lighter model (Gemini 4 Hydrogen or Gemini 3.8 Flash) or run `/compact` to reduce per-turn token burn."
|
|
3195
|
+
],
|
|
3196
|
+
commands: [
|
|
3197
|
+
{ label: "Switch Gemini CLI to Flash", os: "all", command: "gemini --model gemini-3.8-flash" }
|
|
3198
|
+
],
|
|
3199
|
+
verify_command: "gemini --version && npx agycraft-mcp doctor",
|
|
3200
|
+
dont_dos: [
|
|
3201
|
+
"Do NOT hammer retry in a tight loop while capped."
|
|
3202
|
+
],
|
|
3203
|
+
deep_link: "https://modelcraft.dev/fix/quota/weekly-cap"
|
|
3204
|
+
}
|
|
3205
|
+
},
|
|
3206
|
+
{
|
|
3207
|
+
id: "429-desync",
|
|
3208
|
+
domain: "quota",
|
|
3209
|
+
regex: /\b429\b|RESOURCE_EXHAUSTED|quotaMetric|limit:\s*0|rate\s*limit/i,
|
|
3210
|
+
fallback: {
|
|
3211
|
+
id: "429-desync",
|
|
3212
|
+
slug: "429-desync",
|
|
3213
|
+
provider: "antigravity",
|
|
3214
|
+
route_provider: "agy",
|
|
3215
|
+
domain: "quota",
|
|
3216
|
+
title: "429 RESOURCE_EXHAUSTED / Quota Desync or Shared Bucket Cap",
|
|
3217
|
+
severity: "high",
|
|
3218
|
+
products: ["agy", "cli", "api"],
|
|
3219
|
+
error_codes: ["429", "RESOURCE_EXHAUSTED"],
|
|
3220
|
+
error_patterns: ["429", "RESOURCE_EXHAUSTED", "limit: 0"],
|
|
3221
|
+
root_cause: "Either the shared 5h/7d quota bucket is exhausted, or local account/billing state is desynced (showing high remaining % while returning 429 or limit: 0).",
|
|
3222
|
+
steps: [
|
|
3223
|
+
"Compare local 5h token consumption against the error to separate real cap vs entitlement/billing desync.",
|
|
3224
|
+
"If desynced: run Reset Onboarding in Antigravity or verify Google Cloud Billing / AI Pro subscription binding.",
|
|
3225
|
+
"If real cap: switch to Gemini 4 Hydrogen or Gemini 3.8 Flash, run `/compact`, and wait for the rolling 5h window relief."
|
|
3226
|
+
],
|
|
3227
|
+
commands: [
|
|
3228
|
+
{ label: "Run local preflight doctor", os: "all", command: "npx agycraft-mcp doctor" },
|
|
3229
|
+
{ label: "Switch Gemini CLI to lighter Flash model", os: "all", command: "gemini --model gemini-3.8-flash" }
|
|
3230
|
+
],
|
|
3231
|
+
verify_command: "gemini --version && npx agycraft-mcp doctor",
|
|
3232
|
+
dont_dos: [
|
|
3233
|
+
"Do NOT hammer retry in a tight loop \u2014 repeated 429 bursts can trigger automated abuse cooldowns.",
|
|
3234
|
+
"Do NOT rotate multiple personal API keys to bypass free-tier limits."
|
|
3235
|
+
],
|
|
3236
|
+
deep_link: "https://modelcraft.dev/fix/quota/429-desync"
|
|
3237
|
+
}
|
|
3238
|
+
},
|
|
3239
|
+
{
|
|
3240
|
+
id: "gcp-vertex-api-disabled",
|
|
3241
|
+
domain: "auth",
|
|
3242
|
+
regex: /\bSERVICE_DISABLED\b|aiplatform\.googleapis\.com.*(?:has\s+not\s+been\s+used|disabled)|cloudaicompanion\.googleapis\.com.*(?:has\s+not\s+been\s+used|disabled)|Vertex\s+AI\s+API\s+has\s+not\s+been\s+used/i,
|
|
3243
|
+
fallback: {
|
|
3244
|
+
id: "gcp-vertex-api-disabled",
|
|
3245
|
+
slug: "gcp-vertex-api-disabled",
|
|
3246
|
+
provider: "google",
|
|
3247
|
+
route_provider: "google",
|
|
3248
|
+
domain: "auth",
|
|
3249
|
+
title: "GCP Vertex AI / Companion API Disabled (SERVICE_DISABLED)",
|
|
3250
|
+
severity: "high",
|
|
3251
|
+
products: ["agy", "cli", "api"],
|
|
3252
|
+
error_codes: ["403", "PERMISSION_DENIED", "SERVICE_DISABLED"],
|
|
3253
|
+
error_patterns: [
|
|
3254
|
+
"SERVICE_DISABLED",
|
|
3255
|
+
"aiplatform.googleapis.com",
|
|
3256
|
+
"cloudaicompanion.googleapis.com",
|
|
3257
|
+
"Vertex AI API has not been used"
|
|
3258
|
+
],
|
|
3259
|
+
root_cause: "The target GCP project does not have the Vertex AI API (`aiplatform.googleapis.com`) or Gemini Code Assist API (`cloudaicompanion.googleapis.com`) enabled.",
|
|
3260
|
+
steps: [
|
|
3261
|
+
"Enable `aiplatform.googleapis.com` on your active `GOOGLE_CLOUD_PROJECT`.",
|
|
3262
|
+
"If using Gemini CLI / Code Assist enterprise seats, also enable `cloudaicompanion.googleapis.com` as needed.",
|
|
3263
|
+
"Wait 1-2 minutes for GCP service enablement propagation, then retry."
|
|
3264
|
+
],
|
|
3265
|
+
commands: [
|
|
3266
|
+
{
|
|
3267
|
+
label: "Enable Vertex AI API",
|
|
3268
|
+
os: "all",
|
|
3269
|
+
command: "gcloud services enable aiplatform.googleapis.com --project=${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id}"
|
|
3270
|
+
},
|
|
3271
|
+
{
|
|
3272
|
+
label: "Enable Gemini Code Assist API (if needed)",
|
|
3273
|
+
os: "all",
|
|
3274
|
+
command: "gcloud services enable cloudaicompanion.googleapis.com --project=${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id}"
|
|
3275
|
+
}
|
|
3276
|
+
],
|
|
3277
|
+
verify_command: 'gcloud services list --enabled --filter="config.name:(aiplatform.googleapis.com OR cloudaicompanion.googleapis.com)"',
|
|
3278
|
+
dont_dos: [
|
|
3279
|
+
"Do NOT switch to an unrelated personal API key to work around a disabled project API."
|
|
3280
|
+
],
|
|
3281
|
+
deep_link: "https://modelcraft.dev/fix/auth/gcp-vertex-api-disabled"
|
|
3282
|
+
}
|
|
3283
|
+
},
|
|
3284
|
+
{
|
|
3285
|
+
id: "gcp-adc-expired",
|
|
3286
|
+
domain: "auth",
|
|
3287
|
+
regex: /\binvalid_grant\b|reauth\s+related\s+error|Refreshing\s+credentials\s+failed|Getting\s+metadata\s+from\s+plugin\s+failed|application-default\s+login/i,
|
|
3288
|
+
fallback: {
|
|
3289
|
+
id: "gcp-adc-expired",
|
|
3290
|
+
slug: "gcp-adc-expired",
|
|
3291
|
+
provider: "google",
|
|
3292
|
+
route_provider: "google",
|
|
3293
|
+
domain: "auth",
|
|
3294
|
+
title: "GCP Application Default Credentials (ADC) Expired / Reauth Required",
|
|
3295
|
+
severity: "high",
|
|
3296
|
+
products: ["agy", "cli", "api"],
|
|
3297
|
+
error_codes: ["401", "403", "UNAUTHENTICATED", "invalid_grant"],
|
|
3298
|
+
error_patterns: [
|
|
3299
|
+
"invalid_grant",
|
|
3300
|
+
"reauth related error",
|
|
3301
|
+
"Refreshing credentials failed",
|
|
3302
|
+
"Getting metadata from plugin failed",
|
|
3303
|
+
"application-default login"
|
|
3304
|
+
],
|
|
3305
|
+
root_cause: "Local Google Application Default Credentials (ADC) or OAuth refresh token has expired, been revoked, or `GOOGLE_APPLICATION_CREDENTIALS` points to an invalid/stale credential file.",
|
|
3306
|
+
steps: [
|
|
3307
|
+
"Re-authenticate Application Default Credentials via `gcloud auth application-default login`.",
|
|
3308
|
+
"Check whether `GOOGLE_APPLICATION_CREDENTIALS` is set to a stale or deleted file path (without printing secret contents)."
|
|
3309
|
+
],
|
|
3310
|
+
commands: [
|
|
3311
|
+
{
|
|
3312
|
+
label: "Refresh Application Default Credentials",
|
|
3313
|
+
os: "all",
|
|
3314
|
+
command: "gcloud auth application-default login"
|
|
3315
|
+
},
|
|
3316
|
+
{
|
|
3317
|
+
label: "Check GOOGLE_APPLICATION_CREDENTIALS path existence",
|
|
3318
|
+
os: "unix",
|
|
3319
|
+
command: 'test -n "$GOOGLE_APPLICATION_CREDENTIALS" && ls -l "$GOOGLE_APPLICATION_CREDENTIALS" || echo "unset"'
|
|
3320
|
+
}
|
|
3321
|
+
],
|
|
3322
|
+
verify_command: "gcloud auth application-default print-access-token >/dev/null && echo OK",
|
|
3323
|
+
dont_dos: [
|
|
3324
|
+
"Do NOT read, print, or paste raw service account JSON keys or OAuth refresh tokens."
|
|
3325
|
+
],
|
|
3326
|
+
deep_link: "https://modelcraft.dev/fix/auth/gcp-adc-expired"
|
|
3327
|
+
}
|
|
3328
|
+
},
|
|
3329
|
+
{
|
|
3330
|
+
id: "gcp-vertex-iam-or-location",
|
|
3331
|
+
domain: "auth",
|
|
3332
|
+
regex: /roles\/aiplatform\.user|aiplatform\.endpoints\.predict|not\s+found\s+in\s+location|Publisher\s+Model.*(?:not\s+found|permission)/i,
|
|
3333
|
+
fallback: {
|
|
3334
|
+
id: "gcp-vertex-iam-or-location",
|
|
3335
|
+
slug: "gcp-vertex-iam-or-location",
|
|
3336
|
+
provider: "google",
|
|
3337
|
+
route_provider: "google",
|
|
3338
|
+
domain: "auth",
|
|
3339
|
+
title: "Vertex AI IAM Role (roles/aiplatform.user) or Location Mismatch",
|
|
3340
|
+
severity: "high",
|
|
3341
|
+
products: ["agy", "cli", "api"],
|
|
3342
|
+
error_codes: ["403", "404", "PERMISSION_DENIED", "NOT_FOUND"],
|
|
3343
|
+
error_patterns: [
|
|
3344
|
+
"roles/aiplatform.user",
|
|
3345
|
+
"aiplatform.endpoints.predict",
|
|
3346
|
+
"not found in location",
|
|
3347
|
+
"Publisher Model"
|
|
3348
|
+
],
|
|
3349
|
+
root_cause: "The active GCP principal lacks `roles/aiplatform.user` (which includes `aiplatform.endpoints.predict`), or `GOOGLE_CLOUD_LOCATION` points to a region where the requested Publisher Model is unavailable.",
|
|
3350
|
+
steps: [
|
|
3351
|
+
"Verify `GOOGLE_CLOUD_LOCATION` matches a supported region for the target model (e.g. `us-central1` or `global`).",
|
|
3352
|
+
"Confirm your user or service account has `roles/aiplatform.user` (including `aiplatform.endpoints.predict`) on the target project."
|
|
3353
|
+
],
|
|
3354
|
+
commands: [
|
|
3355
|
+
{
|
|
3356
|
+
label: "Set supported Vertex AI location",
|
|
3357
|
+
os: "unix",
|
|
3358
|
+
command: "export GOOGLE_CLOUD_LOCATION=us-central1"
|
|
3359
|
+
},
|
|
3360
|
+
{
|
|
3361
|
+
label: "Inspect project IAM policy for active account",
|
|
3362
|
+
os: "all",
|
|
3363
|
+
command: 'gcloud projects get-iam-policy ${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id} --flatten="bindings[].members" --format="table(bindings.role,bindings.members)"'
|
|
3364
|
+
}
|
|
3365
|
+
],
|
|
3366
|
+
verify_command: 'echo "GOOGLE_CLOUD_LOCATION=${GOOGLE_CLOUD_LOCATION:-unset}"',
|
|
3367
|
+
dont_dos: [
|
|
3368
|
+
"Do NOT grant `roles/owner` when `roles/aiplatform.user` is sufficient."
|
|
3369
|
+
],
|
|
3370
|
+
deep_link: "https://modelcraft.dev/fix/auth/gcp-vertex-iam-or-location"
|
|
3371
|
+
}
|
|
3372
|
+
},
|
|
3373
|
+
{
|
|
3374
|
+
id: "gcp-vpc-sc-blocked",
|
|
3375
|
+
domain: "network",
|
|
3376
|
+
regex: /VPC\s+Service\s+Controls|prohibited\s+by\s+organization(?:'s)?\s+policy|vpcServiceControlsUniqueIdentifier|Request\s+is\s+prohibited\s+by\s+organization/i,
|
|
3377
|
+
fallback: {
|
|
3378
|
+
id: "gcp-vpc-sc-blocked",
|
|
3379
|
+
slug: "gcp-vpc-sc-blocked",
|
|
3380
|
+
provider: "google",
|
|
3381
|
+
route_provider: "google",
|
|
3382
|
+
domain: "network",
|
|
3383
|
+
title: "Blocked by GCP VPC Service Controls / Organization Policy",
|
|
3384
|
+
severity: "high",
|
|
3385
|
+
products: ["agy", "cli", "api"],
|
|
3386
|
+
error_codes: ["403", "PERMISSION_DENIED", "VPC_SERVICE_CONTROLS"],
|
|
3387
|
+
error_patterns: [
|
|
3388
|
+
"VPC Service Controls",
|
|
3389
|
+
"prohibited by organization's policy",
|
|
3390
|
+
"vpcServiceControlsUniqueIdentifier",
|
|
3391
|
+
"Request is prohibited by organization"
|
|
3392
|
+
],
|
|
3393
|
+
root_cause: "The request was blocked at the enterprise GCP VPC Service Controls perimeter or organization policy boundary.",
|
|
3394
|
+
steps: [
|
|
3395
|
+
"Record the `vpcServiceControlsUniqueIdentifier` (if present) from the error payload.",
|
|
3396
|
+
"Contact your GCP security/network administrator to review VPC-SC ingress/egress rules, or run from an authorized corporate network/perimeter."
|
|
3397
|
+
],
|
|
3398
|
+
commands: [
|
|
3399
|
+
{
|
|
3400
|
+
label: "Verify active gcloud account and project",
|
|
3401
|
+
os: "all",
|
|
3402
|
+
command: 'gcloud config list --format="table(core.account,core.project)"'
|
|
3403
|
+
}
|
|
3404
|
+
],
|
|
3405
|
+
verify_command: "gcloud config get-value project",
|
|
3406
|
+
dont_dos: [
|
|
3407
|
+
"Do NOT attempt to bypass corporate VPC Service Controls with unapproved proxies or personal projects."
|
|
3408
|
+
],
|
|
3409
|
+
deep_link: "https://modelcraft.dev/fix/network/gcp-vpc-sc-blocked"
|
|
3410
|
+
}
|
|
3411
|
+
},
|
|
3412
|
+
{
|
|
3413
|
+
id: "403-auth-mismatch",
|
|
3414
|
+
domain: "auth",
|
|
3415
|
+
regex: /\b401\b|\b403\b|UNAUTHENTICATED|Permission\s*Denied|cloudaicompanion.*denied|ACCESS_TOKEN_TYPE_UNSUPPORTED|API_KEY_INVALID/i,
|
|
3416
|
+
fallback: {
|
|
3417
|
+
id: "403-auth-mismatch",
|
|
3418
|
+
slug: "403-auth-mismatch",
|
|
3419
|
+
provider: "google",
|
|
3420
|
+
route_provider: "google",
|
|
3421
|
+
domain: "auth",
|
|
3422
|
+
title: "401/403 Auth & Entitlement Mismatch",
|
|
3423
|
+
severity: "high",
|
|
3424
|
+
products: ["agy", "cli", "api"],
|
|
3425
|
+
error_codes: ["401", "403", "UNAUTHENTICATED", "PERMISSION_DENIED"],
|
|
3426
|
+
error_patterns: ["401", "403", "UNAUTHENTICATED", "ACCESS_TOKEN_TYPE_UNSUPPORTED"],
|
|
3427
|
+
root_cause: "Mixed authentication state (e.g., GEMINI_API_KEY colliding with GOOGLE_CLOUD_PROJECT OAuth) or stale local OAuth consent/ADC cache.",
|
|
3428
|
+
steps: [
|
|
3429
|
+
"Unset conflicting env vars so only ONE auth mode (API Key OR Google Cloud OAuth) is active.",
|
|
3430
|
+
"Revoke stale third-party authorization at https://myaccount.google.com/connections if OAuth is stuck.",
|
|
3431
|
+
"Clear local auth cache and re-authenticate cleanly."
|
|
3432
|
+
],
|
|
3433
|
+
commands: [
|
|
3434
|
+
{ label: "Unset conflicting API key vars", os: "unix", command: "unset GEMINI_API_KEY GOOGLE_API_KEY" },
|
|
3435
|
+
{ label: "Set GCP project for OAuth/Vertex", os: "unix", command: "export GOOGLE_CLOUD_PROJECT=your-gcp-project-id" },
|
|
3436
|
+
{ label: "Refresh Application Default Credentials", os: "all", command: "gcloud auth application-default login" }
|
|
3437
|
+
],
|
|
3438
|
+
verify_command: "gcloud auth application-default print-access-token >/dev/null && echo OK",
|
|
3439
|
+
dont_dos: [
|
|
3440
|
+
"Do NOT paste OAuth tokens or API keys into public issue trackers or MCP logs.",
|
|
3441
|
+
"Do NOT mix Vertex AI GOOGLE_CLOUD_PROJECT with AI Studio GEMINI_API_KEY in the same shell."
|
|
3442
|
+
],
|
|
3443
|
+
deep_link: "https://modelcraft.dev/fix/auth/403-auth-mismatch"
|
|
3444
|
+
}
|
|
3445
|
+
},
|
|
3446
|
+
{
|
|
3447
|
+
id: "503-504-stall",
|
|
3448
|
+
domain: "capacity",
|
|
3449
|
+
regex: /\b503\b|\b504\b|No\s*capacity|DEADLINE_EXCEEDED|UNAVAILABLE|antigravity-unleash\.goog|overloaded/i,
|
|
3450
|
+
fallback: {
|
|
3451
|
+
id: "503-504-stall",
|
|
3452
|
+
slug: "503-504-stall",
|
|
3453
|
+
provider: "google",
|
|
3454
|
+
route_provider: "google",
|
|
3455
|
+
domain: "capacity",
|
|
3456
|
+
title: "503 No Capacity / 504 DEADLINE_EXCEEDED / Stall",
|
|
3457
|
+
severity: "high",
|
|
3458
|
+
products: ["agy", "cli", "api"],
|
|
3459
|
+
error_codes: ["503", "504", "UNAVAILABLE", "DEADLINE_EXCEEDED"],
|
|
3460
|
+
error_patterns: ["503", "504", "DEADLINE_EXCEEDED", "No capacity"],
|
|
3461
|
+
root_cause: "Upstream model capacity saturation (503) or oversized uncompacted prompt context exceeding backend deadline (504).",
|
|
3462
|
+
steps: [
|
|
3463
|
+
"Check ModelCraft live upstream status to confirm whether a global 503 wave is active.",
|
|
3464
|
+
"If upstream is healthy and you hit 504: add a `.geminiignore` file, run `/compact`, and split the task.",
|
|
3465
|
+
"Temporarily switch from flagship Neon to Hydrogen or Flash until capacity recovers."
|
|
3466
|
+
],
|
|
3467
|
+
commands: [
|
|
3468
|
+
{ label: "Check context hygiene & .geminiignore", os: "all", command: "npx agycraft-mcp doctor" }
|
|
3469
|
+
],
|
|
3470
|
+
verify_command: "curl -sI https://modelcraft.dev/data/v1/status.json | head -n 1",
|
|
3471
|
+
dont_dos: [
|
|
3472
|
+
"Do NOT keep retrying massive 500k+ token prompts on 504 without compacting context first."
|
|
3473
|
+
],
|
|
3474
|
+
deep_link: "https://modelcraft.dev/fix/capacity/503-504-stall"
|
|
3475
|
+
}
|
|
3476
|
+
},
|
|
3477
|
+
{
|
|
3478
|
+
id: "mcp-disconnected",
|
|
3479
|
+
domain: "mcp",
|
|
3480
|
+
regex: /MCP.*Disconnected|MCP\s*(?:error\s*)?-32000|-32000\s*:\s*Connection\s+closed|MCP.*Connection\s+closed|EADDRINUSE|httpUrl|streamable.*http|gemini\s+trust|transport.*closed|ENOENT.*npx/i,
|
|
3481
|
+
fallback: {
|
|
3482
|
+
id: "mcp-disconnected",
|
|
3483
|
+
slug: "mcp-disconnected",
|
|
3484
|
+
provider: "antigravity",
|
|
3485
|
+
route_provider: "agy",
|
|
3486
|
+
domain: "mcp",
|
|
3487
|
+
title: "MCP Disconnected / Transport Mismatch / Env Stripped",
|
|
3488
|
+
severity: "high",
|
|
3489
|
+
products: ["agy", "cli"],
|
|
3490
|
+
error_codes: ["EADDRINUSE", "MCP_DISCONNECTED"],
|
|
3491
|
+
error_patterns: ["MCP Disconnected", "EADDRINUSE", "httpUrl"],
|
|
3492
|
+
root_cause: "Untrusted workspace directory, `url` (SSE) vs `httpUrl` (Streamable HTTP) key mismatch, port conflict (EADDRINUSE), or `*TOKEN*`/`*KEY*`/`*SECRET*` env vars stripped from MCP child process.",
|
|
3493
|
+
steps: [
|
|
3494
|
+
"Trust the workspace directory with `gemini trust`.",
|
|
3495
|
+
"Run `npx agycraft-mcp doctor` to check JSON syntax, `url` vs `httpUrl`, and env key stripping.",
|
|
3496
|
+
"Pass required credentials explicitly inside the server's `env` block in mcp_config.json / settings.json."
|
|
3497
|
+
],
|
|
3498
|
+
commands: [
|
|
3499
|
+
{ label: "Trust workspace", os: "all", command: "gemini trust" },
|
|
3500
|
+
{ label: "Run offline config doctor", os: "all", command: "npx agycraft-mcp doctor" },
|
|
3501
|
+
{ label: "List active MCP servers", os: "all", command: "gemini mcp list" }
|
|
3502
|
+
],
|
|
3503
|
+
verify_command: "gemini mcp list",
|
|
3504
|
+
dont_dos: [
|
|
3505
|
+
"Do NOT log debug text to stdout in stdio MCP servers \u2014 stdout is reserved for JSON-RPC frames.",
|
|
3506
|
+
"Do NOT set both `url` and `httpUrl` on the same MCP server entry."
|
|
3507
|
+
],
|
|
3508
|
+
deep_link: "https://modelcraft.dev/fix/mcp/mcp-disconnected"
|
|
3509
|
+
}
|
|
3510
|
+
},
|
|
3511
|
+
{
|
|
3512
|
+
id: "ssl-proxy",
|
|
3513
|
+
domain: "network",
|
|
3514
|
+
regex: /UNABLE_TO_GET_ISSUER_CERT_LOCALLY|UNABLE_TO_VERIFY_LEAF_SIGNATURE|SELF_SIGNED_CERT_IN_CHAIN|CERT_HAS_EXPIRED|ECONNRESET|ETIMEDOUT|ECONNREFUSED/i,
|
|
3515
|
+
fallback: {
|
|
3516
|
+
id: "ssl-proxy",
|
|
3517
|
+
slug: "ssl-proxy",
|
|
3518
|
+
provider: "google",
|
|
3519
|
+
route_provider: "google",
|
|
3520
|
+
domain: "network",
|
|
3521
|
+
title: "Corporate Proxy / SSL Certificate Verification Failure",
|
|
3522
|
+
severity: "medium",
|
|
3523
|
+
products: ["agy", "cli", "api"],
|
|
3524
|
+
error_codes: ["UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "SELF_SIGNED_CERT_IN_CHAIN"],
|
|
3525
|
+
error_patterns: ["UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "SELF_SIGNED_CERT_IN_CHAIN"],
|
|
3526
|
+
root_cause: "Node.js does not automatically trust corporate TLS-inspecting proxy root certificates unless NODE_EXTRA_CA_CERTS is configured.",
|
|
3527
|
+
steps: [
|
|
3528
|
+
"Export your corporate root CA bundle in PEM format.",
|
|
3529
|
+
"Set `NODE_EXTRA_CA_CERTS` in your shell profile and verify the file is readable.",
|
|
3530
|
+
"Verify `HTTP_PROXY` / `HTTPS_PROXY` URLs are reachable."
|
|
3531
|
+
],
|
|
3532
|
+
commands: [
|
|
3533
|
+
{ label: "Configure Node extra CA bundle", os: "unix", command: "export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem" },
|
|
3534
|
+
{ label: "Verify SSL & proxy setup", os: "all", command: "npx agycraft-mcp doctor" }
|
|
3535
|
+
],
|
|
3536
|
+
verify_command: `node -e "fetch('https://modelcraft.dev/data/v1/status.json').then(r => console.log(r.status))"`,
|
|
3537
|
+
dont_dos: [
|
|
3538
|
+
"Do NOT permanently set `NODE_TLS_REJECT_UNAUTHORIZED=0` \u2014 it disables all TLS verification."
|
|
3539
|
+
],
|
|
3540
|
+
deep_link: "https://modelcraft.dev/fix/network/ssl-proxy"
|
|
3541
|
+
}
|
|
3542
|
+
},
|
|
3543
|
+
{
|
|
3544
|
+
id: "function-calling-state",
|
|
3545
|
+
domain: "protocol",
|
|
3546
|
+
regex: /thought_signature|function[\s_]+call|function[\s_]+response|FunctionCall|MALFORMED_FUNCTION_CALL|INVALID_ARGUMENT.*turn|tool_call_id/i,
|
|
3547
|
+
fallback: {
|
|
3548
|
+
id: "function-calling-state",
|
|
3549
|
+
slug: "function-calling-state",
|
|
3550
|
+
provider: "google",
|
|
3551
|
+
route_provider: "google",
|
|
3552
|
+
domain: "protocol",
|
|
3553
|
+
title: "Function Calling Turn Alignment / Missing thought_signature",
|
|
3554
|
+
severity: "medium",
|
|
3555
|
+
products: ["api", "cli", "agy"],
|
|
3556
|
+
error_codes: ["INVALID_ARGUMENT"],
|
|
3557
|
+
error_patterns: ["thought_signature", "function_call", "function_response"],
|
|
3558
|
+
root_cause: "Tool call/response turn sequence is misaligned, or Thinking-model `thought_signature` was stripped when replaying assistant tool calls.",
|
|
3559
|
+
steps: [
|
|
3560
|
+
"Preserve the exact `thought_signature` field on model `functionCall` parts when sending back `functionResponse` turns.",
|
|
3561
|
+
"Ensure every `functionCall` turn is immediately followed by matching `functionResponse` parts in the next user/tool turn.",
|
|
3562
|
+
"Upgrade `@google/genai` or `@google/gemini-cli` to the latest release."
|
|
3563
|
+
],
|
|
3564
|
+
commands: [
|
|
3565
|
+
{ label: "Check latest Gemini CLI version", os: "all", command: "npm view @google/gemini-cli version" }
|
|
3566
|
+
],
|
|
3567
|
+
verify_command: "Replay a single 2-turn tool call with unmodified model parts including thought_signature.",
|
|
3568
|
+
dont_dos: [
|
|
3569
|
+
"Do NOT manually reconstruct or strip unknown fields from model `parts` during multi-turn tool calling."
|
|
3570
|
+
],
|
|
3571
|
+
deep_link: "https://modelcraft.dev/fix/protocol/function-calling-state"
|
|
3572
|
+
}
|
|
3573
|
+
},
|
|
3574
|
+
{
|
|
3575
|
+
id: "structured-output-schema",
|
|
3576
|
+
domain: "protocol",
|
|
3577
|
+
regex: /(?:response_schema|responseJsonSchema|nesting\s*depth|too\s*many\s*states|additionalProperties|constrained\s*decoding|INVALID_ARGUMENT.*(?:response_?schema|json\s*schema|nesting|states|\$ref))/i,
|
|
3578
|
+
fallback: {
|
|
3579
|
+
id: "structured-output-schema",
|
|
3580
|
+
slug: "structured-output-schema",
|
|
3581
|
+
provider: "google",
|
|
3582
|
+
route_provider: "google",
|
|
3583
|
+
domain: "protocol",
|
|
3584
|
+
title: "Structured Output JSON Schema Too Deep or Unsupported Keyword",
|
|
3585
|
+
severity: "medium",
|
|
3586
|
+
products: ["api", "cli"],
|
|
3587
|
+
error_codes: ["INVALID_ARGUMENT"],
|
|
3588
|
+
error_patterns: ["response_schema", "nesting depth", "too many states"],
|
|
3589
|
+
root_cause: "Gemini constrained decoding rejects deeply nested schemas, recursive `$ref` cycles, or excessive union branches ('too many states').",
|
|
3590
|
+
steps: [
|
|
3591
|
+
"Flatten nested objects to <= 4 levels and remove recursive `$ref` definitions.",
|
|
3592
|
+
"Replace large `oneOf`/`anyOf` unions with a flat discriminator string enum + optional fields.",
|
|
3593
|
+
"Keep property descriptions concise so grammar compilation stays within state limits."
|
|
3594
|
+
],
|
|
3595
|
+
commands: [
|
|
3596
|
+
{ label: "Run doctor preflight", os: "all", command: "npx agycraft-mcp doctor" }
|
|
3597
|
+
],
|
|
3598
|
+
verify_command: "Re-run the API call with flattened JSON schema (depth <= 4, no recursive $ref).",
|
|
3599
|
+
dont_dos: [
|
|
3600
|
+
"Do NOT pass unconstrained TypeScript ASTs or OpenAPI specs directly as `response_schema`."
|
|
3601
|
+
],
|
|
3602
|
+
deep_link: "https://modelcraft.dev/fix/protocol/structured-output-schema"
|
|
3603
|
+
}
|
|
3604
|
+
}
|
|
3605
|
+
];
|
|
3606
|
+
function extractSignals(errorText) {
|
|
3607
|
+
const httpMatch = errorText.match(/\b(400|401|403|404|408|429|500|502|503|504)\b/);
|
|
3608
|
+
const retryMatch = errorText.match(/retryDelay["']?\s*[:=]\s*["']?([0-9.]+s?)/i);
|
|
3609
|
+
const metricMatch = errorText.match(/quotaMetric["']?\s*[:=]\s*["']?([a-zA-Z0-9._/-]+)/i);
|
|
3610
|
+
return {
|
|
3611
|
+
http_status: httpMatch?.[1] ?? null,
|
|
3612
|
+
retry_delay: retryMatch?.[1] ?? null,
|
|
3613
|
+
quota_metric: metricMatch?.[1] ?? null
|
|
3614
|
+
};
|
|
3615
|
+
}
|
|
3616
|
+
function diagnoseError(options) {
|
|
3617
|
+
const text = options.errorText;
|
|
3618
|
+
const lowerText = text.toLowerCase();
|
|
3619
|
+
const signals = extractSignals(text);
|
|
3620
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
3621
|
+
const upstreamStatus = options.statusSnapshot?.overall_status ?? "unknown";
|
|
3622
|
+
const hasActiveIncident = upstreamStatus === "degraded" || upstreamStatus === "outage" || (options.statusSnapshot?.active_incidents?.some(
|
|
3623
|
+
(i) => i.status !== "resolved"
|
|
3624
|
+
) ?? false);
|
|
3625
|
+
const skip403AuthMismatch = isExternalGcpDataPlane403(text);
|
|
3626
|
+
let matchedRule = null;
|
|
3627
|
+
for (const rule of BUILTIN_RULES) {
|
|
3628
|
+
if (skip403AuthMismatch && rule.id === "403-auth-mismatch") {
|
|
3629
|
+
continue;
|
|
3630
|
+
}
|
|
3631
|
+
if (rule.regex.test(text)) {
|
|
3632
|
+
matchedRule = rule;
|
|
3633
|
+
break;
|
|
3634
|
+
}
|
|
3635
|
+
}
|
|
3636
|
+
const GENERIC_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
3637
|
+
"400",
|
|
3638
|
+
"401",
|
|
3639
|
+
"403",
|
|
3640
|
+
"404",
|
|
3641
|
+
"500",
|
|
3642
|
+
"502",
|
|
3643
|
+
"503",
|
|
3644
|
+
"504",
|
|
3645
|
+
"invalid_argument"
|
|
3646
|
+
]);
|
|
3647
|
+
const skipGeneric403 = skip403AuthMismatch || matchedRule !== null && SPECIFIC_GCP_RULE_IDS.has(matchedRule.id);
|
|
3648
|
+
let remoteMatch = null;
|
|
3649
|
+
let bestScore = 0;
|
|
3650
|
+
for (const entry of options.diagnosisEntries ?? []) {
|
|
3651
|
+
if (skipGeneric403 && (entry.id === "google-403-auth-mismatch" || entry.slug === "403-auth-mismatch")) {
|
|
3652
|
+
continue;
|
|
3653
|
+
}
|
|
3654
|
+
let score = 0;
|
|
3655
|
+
let hasSpecificSignal = false;
|
|
3656
|
+
const codeSet = new Set((entry.error_codes ?? []).map((c) => c.toLowerCase()));
|
|
3657
|
+
for (const p of entry.error_patterns ?? []) {
|
|
3658
|
+
const lp = p.toLowerCase();
|
|
3659
|
+
if (lowerText.includes(lp)) {
|
|
3660
|
+
if (codeSet.has(lp) || GENERIC_ERROR_CODES.has(lp)) {
|
|
3661
|
+
score += 2;
|
|
3662
|
+
} else {
|
|
3663
|
+
score += 10;
|
|
3664
|
+
hasSpecificSignal = true;
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
3668
|
+
for (const c of entry.error_codes ?? []) {
|
|
3669
|
+
const lc = c.toLowerCase();
|
|
3670
|
+
if (lowerText.includes(lc)) {
|
|
3671
|
+
score += 2;
|
|
3672
|
+
if (!GENERIC_ERROR_CODES.has(lc)) {
|
|
3673
|
+
hasSpecificSignal = true;
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
3676
|
+
}
|
|
3677
|
+
if (matchedRule && (entry.id === matchedRule.id || entry.slug === matchedRule.id)) {
|
|
3678
|
+
score += 25;
|
|
3679
|
+
hasSpecificSignal = true;
|
|
3680
|
+
}
|
|
3681
|
+
if (hasSpecificSignal && score > bestScore) {
|
|
3682
|
+
bestScore = score;
|
|
3683
|
+
remoteMatch = entry;
|
|
3684
|
+
}
|
|
3685
|
+
}
|
|
3686
|
+
const chosen = remoteMatch ?? matchedRule?.fallback ?? null;
|
|
3687
|
+
if (!chosen) {
|
|
3688
|
+
return {
|
|
3689
|
+
matched: false,
|
|
3690
|
+
domain: "unknown",
|
|
3691
|
+
diagnosis_id: "unclassified",
|
|
3692
|
+
title: "Unclassified Error",
|
|
3693
|
+
confidence: "low",
|
|
3694
|
+
attribution: hasActiveIncident ? `Upstream status is currently "${upstreamStatus}" \u2014 this may be related to an active provider incident.` : "No known fault signature matched. Run `npx agycraft-mcp doctor` to check local environment hygiene.",
|
|
3695
|
+
root_cause: "Error text did not match the 5 primary fault domains (quota, auth, capacity, mcp, network) or protocol signatures.",
|
|
3696
|
+
steps: [
|
|
3697
|
+
"Run `npx agycraft-mcp doctor` to inspect local config syntax, auth env booleans, and proxy settings.",
|
|
3698
|
+
"Check https://modelcraft.dev/fix for the latest community-verified troubleshooting guides."
|
|
3699
|
+
],
|
|
3700
|
+
commands: [
|
|
3701
|
+
{ label: "Run local preflight doctor", os: "all", command: "npx agycraft-mcp doctor" }
|
|
3702
|
+
],
|
|
3703
|
+
verify_command: "npx agycraft-mcp doctor",
|
|
3704
|
+
dont_dos: [
|
|
3705
|
+
"Do NOT paste raw API keys, OAuth tokens, or private code when asking for help."
|
|
3706
|
+
],
|
|
3707
|
+
deep_link: "https://modelcraft.dev/fix",
|
|
3708
|
+
official_source_url: "https://aistudio.google.com/docs/troubleshooting",
|
|
3709
|
+
upstream_status: upstreamStatus,
|
|
3710
|
+
extracted_signals: signals
|
|
3711
|
+
};
|
|
3712
|
+
}
|
|
3713
|
+
let attribution = `Matched fault domain: ${chosen.domain}.`;
|
|
3714
|
+
if (chosen.domain === "quota") {
|
|
3715
|
+
const fiveHoursAgo = nowMs - 5 * 3600 * 1e3;
|
|
3716
|
+
const recentRecords = (options.localRecords ?? []).filter(
|
|
3717
|
+
(r) => Date.parse(r.ts) >= fiveHoursAgo
|
|
3718
|
+
);
|
|
3719
|
+
const recentTokens = recentRecords.reduce(
|
|
3720
|
+
(sum, r) => sum + r.input_tokens + r.output_tokens,
|
|
3721
|
+
0
|
|
3722
|
+
);
|
|
3723
|
+
if (lowerText.includes("limit: 0") || recentRecords.length > 0 && recentTokens < 5e4) {
|
|
3724
|
+
attribution = "LIKELY FALSE EXHAUSTION / ENTITLEMENT DESYNC: Local 5h usage is very low (<50k tokens) or `limit: 0` was returned. Check billing/account sync or Reset Onboarding before waiting.";
|
|
3725
|
+
} else if (recentTokens >= 5e5) {
|
|
3726
|
+
attribution = `REAL QUOTA CAP: Local 5h usage is high (${recentTokens.toLocaleString()} tokens across ${recentRecords.length} turns). Switch to a lighter model (Hydrogen/Flash) and wait for rolling 5h relief.`;
|
|
3727
|
+
} else if (hasActiveIncident) {
|
|
3728
|
+
attribution = `POSSIBLE UPSTREAM INCIDENT: Upstream status is "${upstreamStatus}" \u2014 429s may be caused by upstream throttling.`;
|
|
3729
|
+
} else {
|
|
3730
|
+
attribution = "QUOTA / RATE LIMIT HIT: Enable local numeric usage logging (`npx agycraft-mcp setup`) to distinguish real 5h/7d exhaustion from entitlement desync.";
|
|
3731
|
+
}
|
|
3732
|
+
} else if (chosen.domain === "capacity") {
|
|
3733
|
+
attribution = hasActiveIncident ? `UPSTREAM OUTAGE/DEGRADATION CONFIRMED (${upstreamStatus}): Not a local machine issue. Wait for recovery or temporarily switch to Flash/Hydrogen.` : "LOCAL CONTEXT OR TRANSIENT CAPACITY SPIKE: Upstream status appears operational; check for oversized context (>200k tokens) and add `.geminiignore`.";
|
|
3734
|
+
}
|
|
3735
|
+
return {
|
|
3736
|
+
matched: true,
|
|
3737
|
+
domain: chosen.domain,
|
|
3738
|
+
diagnosis_id: chosen.id,
|
|
3739
|
+
title: chosen.title,
|
|
3740
|
+
confidence: "high",
|
|
3741
|
+
attribution,
|
|
3742
|
+
root_cause: chosen.root_cause,
|
|
3743
|
+
steps: chosen.steps,
|
|
3744
|
+
commands: chosen.commands,
|
|
3745
|
+
verify_command: chosen.verify_command,
|
|
3746
|
+
dont_dos: chosen.dont_dos,
|
|
3747
|
+
deep_link: chosen.deep_link.startsWith("/") ? `https://modelcraft.dev${chosen.deep_link}` : chosen.deep_link,
|
|
3748
|
+
official_source_url: chosen.official_source_url ?? null,
|
|
3749
|
+
upstream_status: upstreamStatus,
|
|
3750
|
+
extracted_signals: signals
|
|
3751
|
+
};
|
|
3752
|
+
}
|
|
3753
|
+
|
|
3754
|
+
// src/analyzers/countdown.ts
|
|
3755
|
+
var ROLLING_ESTIMATE_NOTE = "Approximated solely from the earliest local event timestamp in this window; does not reflect server-side multi-device usage or official remaining quota percentages.";
|
|
3756
|
+
function formatDuration(seconds) {
|
|
3757
|
+
const clamped = Math.max(0, Math.floor(seconds));
|
|
3758
|
+
const days = Math.floor(clamped / 86400);
|
|
3759
|
+
const hours = Math.floor(clamped % 86400 / 3600);
|
|
3760
|
+
const mins = Math.floor(clamped % 3600 / 60);
|
|
3761
|
+
if (days > 0) {
|
|
3762
|
+
return `${days}d ${hours}h ${mins}m`;
|
|
3763
|
+
}
|
|
3764
|
+
if (hours > 0) {
|
|
3765
|
+
return `${hours}h ${mins}m`;
|
|
3766
|
+
}
|
|
3767
|
+
return `${mins}m`;
|
|
3768
|
+
}
|
|
3769
|
+
function validateTimezone(tz) {
|
|
3770
|
+
if (!tz) {
|
|
3771
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
3772
|
+
}
|
|
3773
|
+
try {
|
|
3774
|
+
Intl.DateTimeFormat("en-US", { timeZone: tz });
|
|
3775
|
+
return tz;
|
|
3776
|
+
} catch {
|
|
3777
|
+
return "UTC";
|
|
3778
|
+
}
|
|
3779
|
+
}
|
|
3780
|
+
function getPtDateParts(now) {
|
|
3781
|
+
const fmt = new Intl.DateTimeFormat("en-US", {
|
|
3782
|
+
timeZone: "America/Los_Angeles",
|
|
3783
|
+
year: "numeric",
|
|
3784
|
+
month: "2-digit",
|
|
3785
|
+
day: "2-digit",
|
|
3786
|
+
hour: "2-digit",
|
|
3787
|
+
minute: "2-digit",
|
|
3788
|
+
second: "2-digit",
|
|
3789
|
+
hour12: false
|
|
3790
|
+
});
|
|
3791
|
+
const parts = fmt.formatToParts(now);
|
|
3792
|
+
const get = (type) => Number(parts.find((p) => p.type === type)?.value ?? "0");
|
|
3793
|
+
return {
|
|
3794
|
+
year: get("year"),
|
|
3795
|
+
month: get("month"),
|
|
3796
|
+
day: get("day"),
|
|
3797
|
+
hour: get("hour") === 24 ? 0 : get("hour"),
|
|
3798
|
+
minute: get("minute"),
|
|
3799
|
+
second: get("second")
|
|
3800
|
+
};
|
|
3801
|
+
}
|
|
3802
|
+
function computeNextPtMidnight(now) {
|
|
3803
|
+
const pt = getPtDateParts(now);
|
|
3804
|
+
const remainingTodaySec = (23 - pt.hour) * 3600 + (59 - pt.minute) * 60 + (60 - pt.second);
|
|
3805
|
+
let candidate = new Date(now.getTime() + remainingTodaySec * 1e3);
|
|
3806
|
+
for (let i = 0; i < 3; i++) {
|
|
3807
|
+
const check = getPtDateParts(candidate);
|
|
3808
|
+
if (check.hour === 0 && check.minute === 0 && check.second === 0) {
|
|
3809
|
+
break;
|
|
3810
|
+
}
|
|
3811
|
+
if (check.hour >= 22) {
|
|
3812
|
+
candidate = new Date(
|
|
3813
|
+
candidate.getTime() + ((24 - check.hour) * 3600 - check.minute * 60 - check.second) * 1e3
|
|
3814
|
+
);
|
|
3815
|
+
} else if (check.hour <= 2) {
|
|
3816
|
+
candidate = new Date(
|
|
3817
|
+
candidate.getTime() - (check.hour * 3600 + check.minute * 60 + check.second) * 1e3
|
|
3818
|
+
);
|
|
3819
|
+
}
|
|
3820
|
+
}
|
|
3821
|
+
return candidate;
|
|
3822
|
+
}
|
|
3823
|
+
function computeResetCountdown(options) {
|
|
3824
|
+
const now = options?.now ?? /* @__PURE__ */ new Date();
|
|
3825
|
+
const tz = validateTimezone(options?.timezone);
|
|
3826
|
+
const nextPt = computeNextPtMidnight(now);
|
|
3827
|
+
const ptRemainingSec = Math.max(
|
|
3828
|
+
0,
|
|
3829
|
+
Math.floor((nextPt.getTime() - now.getTime()) / 1e3)
|
|
3830
|
+
);
|
|
3831
|
+
const nextPtLocal = new Intl.DateTimeFormat("en-US", {
|
|
3832
|
+
timeZone: tz,
|
|
3833
|
+
dateStyle: "medium",
|
|
3834
|
+
timeStyle: "short"
|
|
3835
|
+
}).format(nextPt);
|
|
3836
|
+
const fiveHoursMs = 5 * 3600 * 1e3;
|
|
3837
|
+
const sevenDaysMs = 7 * 86400 * 1e3;
|
|
3838
|
+
let relief5hIso = null;
|
|
3839
|
+
let relief5hLocal = null;
|
|
3840
|
+
let relief5hSec = null;
|
|
3841
|
+
if (options?.oldestEventIn5hMs) {
|
|
3842
|
+
const reliefMs = options.oldestEventIn5hMs + fiveHoursMs;
|
|
3843
|
+
relief5hIso = new Date(reliefMs).toISOString();
|
|
3844
|
+
relief5hLocal = new Intl.DateTimeFormat("en-US", {
|
|
3845
|
+
timeZone: tz,
|
|
3846
|
+
dateStyle: "medium",
|
|
3847
|
+
timeStyle: "short"
|
|
3848
|
+
}).format(new Date(reliefMs));
|
|
3849
|
+
relief5hSec = Math.max(0, Math.floor((reliefMs - now.getTime()) / 1e3));
|
|
3850
|
+
}
|
|
3851
|
+
let relief7dIso = null;
|
|
3852
|
+
let relief7dLocal = null;
|
|
3853
|
+
let relief7dSec = null;
|
|
3854
|
+
if (options?.oldestEventIn7dMs) {
|
|
3855
|
+
const reliefMs = options.oldestEventIn7dMs + sevenDaysMs;
|
|
3856
|
+
relief7dIso = new Date(reliefMs).toISOString();
|
|
3857
|
+
relief7dLocal = new Intl.DateTimeFormat("en-US", {
|
|
3858
|
+
timeZone: tz,
|
|
3859
|
+
dateStyle: "medium",
|
|
3860
|
+
timeStyle: "short"
|
|
3861
|
+
}).format(new Date(reliefMs));
|
|
3862
|
+
relief7dSec = Math.max(0, Math.floor((reliefMs - now.getTime()) / 1e3));
|
|
3863
|
+
}
|
|
3864
|
+
return {
|
|
3865
|
+
timezone: tz,
|
|
3866
|
+
now_iso: now.toISOString(),
|
|
3867
|
+
pt_midnight: {
|
|
3868
|
+
next_reset_iso: nextPt.toISOString(),
|
|
3869
|
+
next_reset_local: nextPtLocal,
|
|
3870
|
+
remaining_seconds: ptRemainingSec,
|
|
3871
|
+
remaining_human: formatDuration(ptRemainingSec)
|
|
3872
|
+
},
|
|
3873
|
+
rolling_5h: {
|
|
3874
|
+
window_hours: 5,
|
|
3875
|
+
is_local_estimate: true,
|
|
3876
|
+
estimate_note: ROLLING_ESTIMATE_NOTE,
|
|
3877
|
+
oldest_active_event_iso: options?.oldestEventIn5hMs ? new Date(options.oldestEventIn5hMs).toISOString() : null,
|
|
3878
|
+
estimated_relief_iso: relief5hIso,
|
|
3879
|
+
estimated_relief_local: relief5hLocal,
|
|
3880
|
+
remaining_seconds: relief5hSec,
|
|
3881
|
+
remaining_human: relief5hSec !== null ? formatDuration(relief5hSec) : "No active usage recorded in last 5h"
|
|
3882
|
+
},
|
|
3883
|
+
rolling_7d: {
|
|
3884
|
+
window_days: 7,
|
|
3885
|
+
is_local_estimate: true,
|
|
3886
|
+
estimate_note: ROLLING_ESTIMATE_NOTE,
|
|
3887
|
+
oldest_active_event_iso: options?.oldestEventIn7dMs ? new Date(options.oldestEventIn7dMs).toISOString() : null,
|
|
3888
|
+
estimated_relief_iso: relief7dIso,
|
|
3889
|
+
estimated_relief_local: relief7dLocal,
|
|
3890
|
+
remaining_seconds: relief7dSec,
|
|
3891
|
+
remaining_human: relief7dSec !== null ? formatDuration(relief7dSec) : "No active usage recorded in last 7d"
|
|
3892
|
+
}
|
|
3893
|
+
};
|
|
3894
|
+
}
|
|
3895
|
+
|
|
3896
|
+
// src/remote/snapshot-client.ts
|
|
3897
|
+
import { mkdir as mkdir4, readFile as readFile8, writeFile as writeFile3 } from "fs/promises";
|
|
3898
|
+
import { join as join6 } from "path";
|
|
3899
|
+
var DEFAULT_DATA_URL2 = "https://modelcraft.dev/data/v1";
|
|
3900
|
+
var TTL_MS = {
|
|
3901
|
+
status: 5 * 60 * 1e3,
|
|
3902
|
+
updates: 15 * 60 * 1e3,
|
|
3903
|
+
models: 6 * 60 * 60 * 1e3,
|
|
3904
|
+
chronicle: 6 * 60 * 60 * 1e3,
|
|
3905
|
+
diagnosis: 6 * 60 * 60 * 1e3,
|
|
3906
|
+
quotas: 6 * 60 * 60 * 1e3
|
|
3907
|
+
};
|
|
3908
|
+
var SnapshotClient = class {
|
|
3909
|
+
baseUrl;
|
|
3910
|
+
cacheDir;
|
|
3911
|
+
snapshotsDir;
|
|
3912
|
+
fetchFn;
|
|
3913
|
+
offlineOnly;
|
|
3914
|
+
timeoutMs;
|
|
3915
|
+
constructor(options) {
|
|
3916
|
+
const envUrl = process.env.MODELCRAFT_DATA_URL?.trim();
|
|
3917
|
+
this.baseUrl = (options?.baseUrl || envUrl || DEFAULT_DATA_URL2).replace(
|
|
3918
|
+
/\/+$/,
|
|
3919
|
+
""
|
|
3920
|
+
);
|
|
3921
|
+
this.cacheDir = options?.cacheDir ?? getCacheDir();
|
|
3922
|
+
this.snapshotsDir = options?.snapshotsDir ?? getSnapshotsDir();
|
|
3923
|
+
this.fetchFn = options?.fetchFn ?? globalThis.fetch;
|
|
3924
|
+
this.offlineOnly = options?.offlineOnly ?? process.env.AGYCRAFT_OFFLINE === "1";
|
|
3925
|
+
this.timeoutMs = options?.timeoutMs ?? 4e3;
|
|
3926
|
+
}
|
|
3927
|
+
async get(name) {
|
|
3928
|
+
const cacheFile = join6(this.cacheDir, `${name}.json`);
|
|
3929
|
+
const metaFile = join6(this.cacheDir, `${name}.meta.json`);
|
|
3930
|
+
const ttl = TTL_MS[name];
|
|
3931
|
+
const cached = await this.readCache(cacheFile, metaFile);
|
|
3932
|
+
const now = Date.now();
|
|
3933
|
+
if (cached && now - cached.meta.fetched_at_ms < ttl) {
|
|
3934
|
+
return { data: cached.data, source: "cache" };
|
|
3935
|
+
}
|
|
3936
|
+
if (!this.offlineOnly) {
|
|
3937
|
+
const remoteResult = await this.fetchRemote(
|
|
3938
|
+
name,
|
|
3939
|
+
cached?.meta.etag ?? null,
|
|
3940
|
+
cacheFile,
|
|
3941
|
+
metaFile,
|
|
3942
|
+
cached?.data ?? null
|
|
3943
|
+
);
|
|
3944
|
+
if (remoteResult) {
|
|
3945
|
+
return remoteResult;
|
|
3946
|
+
}
|
|
3947
|
+
}
|
|
3948
|
+
if (cached) {
|
|
3949
|
+
return { data: cached.data, source: "cache" };
|
|
3950
|
+
}
|
|
3951
|
+
const fallback = await this.readBundledFallback(name);
|
|
3952
|
+
return { data: fallback, source: "bundled_fallback" };
|
|
3953
|
+
}
|
|
3954
|
+
async readCache(cacheFile, metaFile) {
|
|
3955
|
+
try {
|
|
3956
|
+
const [rawJson, rawMeta] = await Promise.all([
|
|
3957
|
+
readFile8(cacheFile, "utf8"),
|
|
3958
|
+
readFile8(metaFile, "utf8")
|
|
3959
|
+
]);
|
|
3960
|
+
const data = JSON.parse(rawJson);
|
|
3961
|
+
const meta = JSON.parse(rawMeta);
|
|
3962
|
+
return { data, meta };
|
|
3963
|
+
} catch {
|
|
3964
|
+
return null;
|
|
3965
|
+
}
|
|
3966
|
+
}
|
|
3967
|
+
async writeCache(cacheFile, metaFile, data, etag) {
|
|
3968
|
+
try {
|
|
3969
|
+
await mkdir4(this.cacheDir, { recursive: true });
|
|
3970
|
+
const meta = { etag, fetched_at_ms: Date.now() };
|
|
3971
|
+
await Promise.all([
|
|
3972
|
+
writeFile3(cacheFile, JSON.stringify(data), "utf8"),
|
|
3973
|
+
writeFile3(metaFile, JSON.stringify(meta), "utf8")
|
|
3974
|
+
]);
|
|
3975
|
+
} catch {
|
|
3976
|
+
}
|
|
3977
|
+
}
|
|
3978
|
+
async fetchRemote(name, etag, cacheFile, metaFile, cachedData) {
|
|
3979
|
+
const url = `${this.baseUrl}/${name}.json`;
|
|
3980
|
+
const headers = {
|
|
3981
|
+
Accept: "application/json"
|
|
3982
|
+
};
|
|
3983
|
+
if (etag) {
|
|
3984
|
+
headers["If-None-Match"] = etag;
|
|
3985
|
+
}
|
|
3986
|
+
const controller = new AbortController();
|
|
3987
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
3988
|
+
try {
|
|
3989
|
+
const resp = await this.fetchFn(url, {
|
|
3990
|
+
method: "GET",
|
|
3991
|
+
headers,
|
|
3992
|
+
signal: controller.signal
|
|
3993
|
+
});
|
|
3994
|
+
if (resp.status === 304 && cachedData !== null) {
|
|
3995
|
+
await this.writeCache(cacheFile, metaFile, cachedData, etag);
|
|
3996
|
+
return { data: cachedData, source: "cache" };
|
|
3997
|
+
}
|
|
3998
|
+
if (!resp.ok) {
|
|
3999
|
+
return null;
|
|
4000
|
+
}
|
|
4001
|
+
const data = await resp.json();
|
|
4002
|
+
const newEtag = resp.headers.get("etag");
|
|
4003
|
+
await this.writeCache(cacheFile, metaFile, data, newEtag);
|
|
4004
|
+
return { data, source: "remote" };
|
|
4005
|
+
} catch {
|
|
4006
|
+
return null;
|
|
4007
|
+
} finally {
|
|
4008
|
+
clearTimeout(timer);
|
|
4009
|
+
}
|
|
4010
|
+
}
|
|
4011
|
+
async readBundledFallback(name) {
|
|
4012
|
+
const filePath = join6(this.snapshotsDir, `${name}.json`);
|
|
4013
|
+
const raw = await readFile8(filePath, "utf8");
|
|
4014
|
+
return JSON.parse(raw);
|
|
4015
|
+
}
|
|
4016
|
+
};
|
|
4017
|
+
|
|
4018
|
+
// src/server.ts
|
|
4019
|
+
async function resolveSaltForServer(deps) {
|
|
4020
|
+
if (isReadonlyEnv(deps.readonly)) {
|
|
4021
|
+
try {
|
|
4022
|
+
return await getOrCreateLocalSalt(deps.saltPath);
|
|
4023
|
+
} catch {
|
|
4024
|
+
return "readonly-ephemeral-salt";
|
|
4025
|
+
}
|
|
4026
|
+
}
|
|
4027
|
+
return getOrCreateLocalSalt(deps.saltPath);
|
|
4028
|
+
}
|
|
4029
|
+
async function resolveScopeProjectHash(scope, workspaceDir, deps) {
|
|
4030
|
+
if (scope !== "project") {
|
|
4031
|
+
return void 0;
|
|
4032
|
+
}
|
|
4033
|
+
const targetDir = workspaceDir && workspaceDir.trim().length > 0 ? workspaceDir.trim() : process.cwd();
|
|
4034
|
+
const salt = await resolveSaltForServer(deps);
|
|
4035
|
+
return hashProjectPath(targetDir, salt);
|
|
4036
|
+
}
|
|
4037
|
+
function filterRecordsByScopeAndAuth(records, scope, projectHash, authMode) {
|
|
4038
|
+
return records.filter((r) => {
|
|
4039
|
+
if (authMode !== "all" && (r.auth_mode ?? "unknown") !== authMode) {
|
|
4040
|
+
return false;
|
|
4041
|
+
}
|
|
4042
|
+
if (scope === "project") {
|
|
4043
|
+
return Boolean(projectHash) && r.project_hash === projectHash;
|
|
4044
|
+
}
|
|
4045
|
+
return true;
|
|
4046
|
+
});
|
|
4047
|
+
}
|
|
4048
|
+
async function loadCombinedLocalRecords(deps, sinceMs) {
|
|
4049
|
+
const salt = await resolveSaltForServer(deps);
|
|
4050
|
+
const [agyRecords, otelRecords] = await Promise.all([
|
|
4051
|
+
readUsageRecords({ logPath: deps.usageLogPath, sinceMs, salt }),
|
|
4052
|
+
readGeminiOtelRecords({ otelPath: deps.geminiOtelPath, sinceMs, salt })
|
|
4053
|
+
]);
|
|
4054
|
+
return [...agyRecords, ...otelRecords];
|
|
4055
|
+
}
|
|
4056
|
+
async function loadMergedUsageRecords(deps, options) {
|
|
4057
|
+
const salt = await resolveSaltForServer(deps);
|
|
4058
|
+
const [agyHookRecords, otelRecords] = await Promise.all([
|
|
4059
|
+
readUsageRecords({ logPath: deps.usageLogPath, sinceMs: options.sinceMs, salt }),
|
|
4060
|
+
readGeminiOtelRecords({ otelPath: deps.geminiOtelPath, sinceMs: options.sinceMs, salt })
|
|
4061
|
+
]);
|
|
4062
|
+
const agyOnlyHooks = agyHookRecords.filter((r) => r.product === "agy");
|
|
4063
|
+
const nonAgyHooks = agyHookRecords.filter((r) => r.product !== "agy");
|
|
4064
|
+
const agyHasTokens = agyOnlyHooks.some(
|
|
4065
|
+
(r) => r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens > 0
|
|
4066
|
+
);
|
|
4067
|
+
if (options.product === "gemini-cli") {
|
|
4068
|
+
return { records: [...otelRecords, ...nonAgyHooks] };
|
|
4069
|
+
}
|
|
4070
|
+
let transcriptRecords = [];
|
|
4071
|
+
if (!agyHasTokens) {
|
|
4072
|
+
const collected = await collectTranscriptUsageRecords({
|
|
4073
|
+
brainDir: deps.brainDir,
|
|
4074
|
+
historyPath: deps.historyPath,
|
|
4075
|
+
salt,
|
|
4076
|
+
sinceMs: options.sinceMs,
|
|
4077
|
+
nowMs: options.nowMs,
|
|
4078
|
+
authMode: options.activeAuthMode
|
|
4079
|
+
});
|
|
4080
|
+
transcriptRecords = collected.records;
|
|
4081
|
+
}
|
|
4082
|
+
const agySide = agyHasTokens ? agyOnlyHooks : transcriptRecords.length > 0 ? transcriptRecords : agyOnlyHooks;
|
|
4083
|
+
const usedTranscriptOnly = !agyHasTokens && transcriptRecords.length > 0 && (options.product === "agy" || otelRecords.length === 0);
|
|
4084
|
+
if (options.product === "agy") {
|
|
4085
|
+
return {
|
|
4086
|
+
records: agySide,
|
|
4087
|
+
...usedTranscriptOnly ? { dataModeOverride: "transcript_token_logs" } : {}
|
|
4088
|
+
};
|
|
4089
|
+
}
|
|
4090
|
+
return {
|
|
4091
|
+
records: [...agySide, ...nonAgyHooks, ...otelRecords],
|
|
4092
|
+
...usedTranscriptOnly ? { dataModeOverride: "transcript_token_logs" } : {}
|
|
4093
|
+
};
|
|
4094
|
+
}
|
|
4095
|
+
function buildActivitySummary(fallback, windowLabel) {
|
|
4096
|
+
const stats = windowLabel === "5h" ? fallback.window_5h : fallback.window_7d;
|
|
4097
|
+
if (stats.session_count === 0 && stats.turn_count === 0) {
|
|
4098
|
+
return void 0;
|
|
4099
|
+
}
|
|
4100
|
+
const resetPart = fallback.window_5h.estimated_5h_reset_local ? `; estimated 5h rolling reset at ${fallback.window_5h.estimated_5h_reset_local}` : "";
|
|
4101
|
+
return `${stats.session_count} active AGY session(s) (${stats.turn_count.toLocaleString()} turns) in last ${windowLabel} window${resetPart} (exact token counts require running agycraft-mcp setup).`;
|
|
4102
|
+
}
|
|
4103
|
+
function createAgycraftServer(deps = {}) {
|
|
4104
|
+
const client = deps.snapshotClient ?? new SnapshotClient();
|
|
4105
|
+
const server = new McpServer({
|
|
4106
|
+
name: "agycraft-mcp",
|
|
4107
|
+
version: "0.2.0"
|
|
4108
|
+
});
|
|
4109
|
+
server.tool(
|
|
4110
|
+
"analyze_token_usage",
|
|
4111
|
+
"Analyze local 5h/24h/7d/30d/all token usage, KV cache efficiency, shared-bucket exhaustion risk, and optional hourly/daily/weekly/monthly time series. 100% local numeric metadata only.",
|
|
4112
|
+
{
|
|
4113
|
+
window: z.enum(["5h", "24h", "7d", "30d", "all"]).default("5h"),
|
|
4114
|
+
granularity: z.enum(["summary", "hourly", "daily", "weekly", "monthly"]).default("summary"),
|
|
4115
|
+
timezone: z.string().optional().describe("IANA timezone for time-series bucketing (default: UTC)."),
|
|
4116
|
+
max_buckets: z.number().int().min(1).max(90).default(31).describe("Maximum number of time-series buckets to return (1..90, default: 31)."),
|
|
4117
|
+
product: z.enum(["agy", "gemini-cli", "all"]).default("all"),
|
|
4118
|
+
scope: z.enum(["global", "project"]).default("global"),
|
|
4119
|
+
workspace_dir: z.string().optional().describe(
|
|
4120
|
+
"Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned)."
|
|
4121
|
+
),
|
|
4122
|
+
auth_mode: z.enum(["all", "google_oauth", "gcp_adc", "api_key", "unknown"]).default("all")
|
|
4123
|
+
},
|
|
4124
|
+
async ({ window, granularity, timezone, max_buckets, product, scope, workspace_dir, auth_mode }) => {
|
|
4125
|
+
const [modelsSnap, authContext, projectHash] = await Promise.all([
|
|
4126
|
+
client.get("models"),
|
|
4127
|
+
deps.authContext ? Promise.resolve(deps.authContext) : detectAuthContext(),
|
|
4128
|
+
resolveScopeProjectHash(scope, workspace_dir, deps)
|
|
4129
|
+
]);
|
|
4130
|
+
if (granularity !== "summary") {
|
|
4131
|
+
const salt = await resolveSaltForServer(deps);
|
|
4132
|
+
const rollupRes = await queryRollups({
|
|
4133
|
+
rollupsDir: deps.rollupsDir,
|
|
4134
|
+
usageLogPath: deps.usageLogPath,
|
|
4135
|
+
geminiOtelPath: deps.geminiOtelPath,
|
|
4136
|
+
brainDir: deps.brainDir,
|
|
4137
|
+
historyPath: deps.historyPath,
|
|
4138
|
+
saltPath: deps.saltPath,
|
|
4139
|
+
salt,
|
|
4140
|
+
models: modelsSnap.data.models,
|
|
4141
|
+
window,
|
|
4142
|
+
granularity,
|
|
4143
|
+
product,
|
|
4144
|
+
scope,
|
|
4145
|
+
projectHash,
|
|
4146
|
+
authMode: auth_mode,
|
|
4147
|
+
timezone,
|
|
4148
|
+
maxBuckets: max_buckets,
|
|
4149
|
+
readonly: deps.readonly,
|
|
4150
|
+
transcriptAuthMode: authContext.active_auth_mode
|
|
4151
|
+
});
|
|
4152
|
+
const tot = rollupRes.summary_totals;
|
|
4153
|
+
const isSpecificAuthEmpty2 = auth_mode !== "all" && tot.requests === 0;
|
|
4154
|
+
const dataMode = resolveDataMode(tot.requests, tot.total_tokens);
|
|
4155
|
+
const usageNote = isSpecificAuthEmpty2 ? `No usage records matched auth_mode="${auth_mode}" in the ${window} window (active local auth mode is "${authContext.active_auth_mode}").` : dataMode === "hook_events_without_tokens" ? `Local hook events (${tot.requests} record(s)) were recorded without token or model fields. Refer to the official AGY/CLI quota UI for authoritative remaining %, or enable Gemini CLI OTel for exact local token counts.` : void 0;
|
|
4156
|
+
return {
|
|
4157
|
+
content: [
|
|
4158
|
+
{
|
|
4159
|
+
type: "text",
|
|
4160
|
+
text: JSON.stringify(
|
|
4161
|
+
{
|
|
4162
|
+
window,
|
|
4163
|
+
granularity,
|
|
4164
|
+
product_filter: product,
|
|
4165
|
+
scope,
|
|
4166
|
+
...scope === "project" && projectHash ? {
|
|
4167
|
+
project_hash: projectHash,
|
|
4168
|
+
unattributed_sessions_excluded: tot.unattributed_sessions_excluded
|
|
4169
|
+
} : {},
|
|
4170
|
+
auth_mode_filter: auth_mode,
|
|
4171
|
+
data_mode: dataMode,
|
|
4172
|
+
...usageNote ? { usage_note: usageNote } : {},
|
|
4173
|
+
record_count: tot.requests,
|
|
4174
|
+
session_count: isSpecificAuthEmpty2 ? 0 : tot.session_count,
|
|
4175
|
+
total_uncached_input_tokens: tot.uncached_input_tokens,
|
|
4176
|
+
total_cache_read_tokens: tot.cache_read_tokens,
|
|
4177
|
+
total_input_tokens: tot.input_tokens,
|
|
4178
|
+
total_output_tokens: tot.output_tokens,
|
|
4179
|
+
total_tokens: tot.total_tokens,
|
|
4180
|
+
cache_hit_rate_pct: tot.cache_hit_rate_pct,
|
|
4181
|
+
error_count: tot.error_count,
|
|
4182
|
+
rate_limit_429_count: tot.rate_limit_429_count,
|
|
4183
|
+
below_kv_cache_threshold_requests: tot.below_kv_cache_threshold_requests,
|
|
4184
|
+
estimated_total_usd: tot.estimated_total_usd,
|
|
4185
|
+
estimated_cache_savings_usd: tot.estimated_cache_savings_usd,
|
|
4186
|
+
time_series: rollupRes.time_series,
|
|
4187
|
+
time_series_meta: rollupRes.time_series_meta,
|
|
4188
|
+
models_snapshot_source: modelsSnap.source,
|
|
4189
|
+
privacy_note: "100% local numeric aggregation; zero user data uploaded."
|
|
4190
|
+
},
|
|
4191
|
+
null,
|
|
4192
|
+
2
|
|
4193
|
+
)
|
|
4194
|
+
}
|
|
4195
|
+
]
|
|
4196
|
+
};
|
|
4197
|
+
}
|
|
4198
|
+
const merged = await loadMergedUsageRecords(deps, {
|
|
4199
|
+
product,
|
|
4200
|
+
activeAuthMode: authContext.active_auth_mode
|
|
4201
|
+
});
|
|
4202
|
+
const analysis = analyzeTokenWindow(merged.records, {
|
|
4203
|
+
window,
|
|
4204
|
+
product,
|
|
4205
|
+
models: modelsSnap.data.models,
|
|
4206
|
+
scope,
|
|
4207
|
+
projectHash,
|
|
4208
|
+
authMode: auth_mode,
|
|
4209
|
+
activeAuthMode: authContext.active_auth_mode,
|
|
4210
|
+
dataModeOverride: merged.dataModeOverride
|
|
4211
|
+
});
|
|
4212
|
+
const isSpecificAuthEmpty = auth_mode !== "all" && analysis.record_count === 0;
|
|
4213
|
+
const transcriptFallback = !isSpecificAuthEmpty && analysis.record_count === 0 && scope === "global" ? await scanTranscriptActivity({ brainDir: deps.brainDir }) : void 0;
|
|
4214
|
+
const summaryWindow = window === "5h" ? "5h" : "7d";
|
|
4215
|
+
const activitySummary = transcriptFallback ? buildActivitySummary(transcriptFallback, summaryWindow) : void 0;
|
|
4216
|
+
const effectiveSessionCount = isSpecificAuthEmpty ? 0 : analysis.record_count > 0 ? analysis.session_count : summaryWindow === "5h" ? transcriptFallback?.window_5h.session_count ?? 0 : transcriptFallback?.window_7d.session_count ?? 0;
|
|
4217
|
+
const finalAnalysis = isSpecificAuthEmpty ? {
|
|
4218
|
+
...analysis,
|
|
4219
|
+
usage_note: `No usage records matched auth_mode="${auth_mode}" in the ${window} window (active local auth mode is "${authContext.active_auth_mode}").`
|
|
4220
|
+
} : analysis;
|
|
4221
|
+
return {
|
|
4222
|
+
content: [
|
|
4223
|
+
{
|
|
4224
|
+
type: "text",
|
|
4225
|
+
text: JSON.stringify(
|
|
4226
|
+
{
|
|
4227
|
+
...activitySummary ? { activity_summary: activitySummary } : {},
|
|
4228
|
+
...finalAnalysis,
|
|
4229
|
+
session_count: effectiveSessionCount,
|
|
4230
|
+
...transcriptFallback ? { transcript_activity_fallback: transcriptFallback } : {},
|
|
4231
|
+
models_snapshot_source: modelsSnap.source,
|
|
4232
|
+
privacy_note: "100% local numeric aggregation; zero user data uploaded."
|
|
4233
|
+
},
|
|
4234
|
+
null,
|
|
4235
|
+
2
|
|
4236
|
+
)
|
|
4237
|
+
}
|
|
4238
|
+
]
|
|
4239
|
+
};
|
|
4240
|
+
}
|
|
4241
|
+
);
|
|
4242
|
+
server.tool(
|
|
4243
|
+
"get_saving_recommendations",
|
|
4244
|
+
"Detect quota-burning antipatterns (long-session snowball, heavy model mismatch, Thinking downgrade opportunity, KV cache inefficiency, peak burst 429s, and autonomous failure loops) from local numeric usage and optional structural transcript metadata.",
|
|
4245
|
+
{
|
|
4246
|
+
window: z.enum(["24h", "7d"]).default("24h"),
|
|
4247
|
+
scope: z.enum(["global", "project"]).default("global"),
|
|
4248
|
+
transcript_path: z.string().optional().describe("Optional local transcript.jsonl path for structural step/loop counting only (never reads prompt/content)."),
|
|
4249
|
+
loopThreshold: z.number().int().positive().default(4).describe("Consecutive tool-failure streak threshold for infinite-loop detection (default: 4)."),
|
|
4250
|
+
workspace_dir: z.string().optional().describe("Optional workspace directory path for .geminiignore check and project-scoped filtering."),
|
|
4251
|
+
timezone: z.string().optional().describe("IANA timezone for peak_hours bucketing (default: UTC).")
|
|
4252
|
+
},
|
|
4253
|
+
async ({ window, scope, transcript_path, loopThreshold, workspace_dir, timezone }) => {
|
|
4254
|
+
const [modelsSnap, authContext, projectHash, transcriptMeta, hasGeminiIgnore] = await Promise.all([
|
|
4255
|
+
client.get("models"),
|
|
4256
|
+
deps.authContext ? Promise.resolve(deps.authContext) : detectAuthContext(),
|
|
4257
|
+
resolveScopeProjectHash(scope, workspace_dir, deps),
|
|
4258
|
+
transcript_path ? analyzeTranscriptStructure(transcript_path, loopThreshold) : Promise.resolve(null),
|
|
4259
|
+
workspace_dir ? access2(join7(workspace_dir, ".geminiignore")).then(() => true).catch(() => false) : Promise.resolve(void 0)
|
|
4260
|
+
]);
|
|
4261
|
+
const merged = await loadMergedUsageRecords(deps, {
|
|
4262
|
+
product: "all",
|
|
4263
|
+
activeAuthMode: authContext.active_auth_mode
|
|
4264
|
+
});
|
|
4265
|
+
const salt = await resolveSaltForServer(deps);
|
|
4266
|
+
const rollupHourly = await queryRollups({
|
|
4267
|
+
rollupsDir: deps.rollupsDir,
|
|
4268
|
+
usageLogPath: deps.usageLogPath,
|
|
4269
|
+
geminiOtelPath: deps.geminiOtelPath,
|
|
4270
|
+
brainDir: deps.brainDir,
|
|
4271
|
+
historyPath: deps.historyPath,
|
|
4272
|
+
saltPath: deps.saltPath,
|
|
4273
|
+
salt,
|
|
4274
|
+
models: modelsSnap.data.models,
|
|
4275
|
+
window,
|
|
4276
|
+
granularity: "hourly",
|
|
4277
|
+
product: "all",
|
|
4278
|
+
scope,
|
|
4279
|
+
projectHash,
|
|
4280
|
+
timezone,
|
|
4281
|
+
maxBuckets: 90,
|
|
4282
|
+
readonly: deps.readonly,
|
|
4283
|
+
transcriptAuthMode: authContext.active_auth_mode
|
|
4284
|
+
}).catch(() => null);
|
|
4285
|
+
const report = analyzeAntipatterns(merged.records, {
|
|
4286
|
+
window,
|
|
4287
|
+
scope,
|
|
4288
|
+
projectHash,
|
|
4289
|
+
transcriptMeta,
|
|
4290
|
+
hasGeminiIgnore,
|
|
4291
|
+
hourlyBuckets: rollupHourly?.time_series,
|
|
4292
|
+
models: modelsSnap.data.models,
|
|
4293
|
+
timezone,
|
|
4294
|
+
authContext: {
|
|
4295
|
+
active_auth_mode: authContext.active_auth_mode,
|
|
4296
|
+
has_mixed_auth: authContext.has_mixed_auth
|
|
4297
|
+
}
|
|
4298
|
+
});
|
|
4299
|
+
return {
|
|
4300
|
+
content: [
|
|
4301
|
+
{
|
|
4302
|
+
type: "text",
|
|
4303
|
+
text: JSON.stringify(
|
|
4304
|
+
{
|
|
4305
|
+
...report,
|
|
4306
|
+
transcript_structure: transcriptMeta,
|
|
4307
|
+
more_tips_url: "https://modelcraft.dev/quotas"
|
|
4308
|
+
},
|
|
4309
|
+
null,
|
|
4310
|
+
2
|
|
4311
|
+
)
|
|
4312
|
+
}
|
|
4313
|
+
]
|
|
4314
|
+
};
|
|
4315
|
+
}
|
|
4316
|
+
);
|
|
4317
|
+
server.tool(
|
|
4318
|
+
"diagnose_error",
|
|
4319
|
+
"Diagnose AGY / Gemini CLI / API errors across 5 fault domains (quota, auth, capacity, mcp, network) plus Structured Output & Function Calling protocol issues. Cross-references local usage & upstream status to provide root cause, copyable fix commands, verify command, don't-dos, and a modelcraft.dev Deep Link.",
|
|
4320
|
+
{
|
|
4321
|
+
error_text: z.string().min(1).describe("Raw error message or JSON snippet."),
|
|
4322
|
+
product: z.enum(["agy", "cli", "api", "web"]).optional(),
|
|
4323
|
+
doctor_summary: z.string().optional()
|
|
4324
|
+
},
|
|
4325
|
+
async ({ error_text, product }) => {
|
|
4326
|
+
const [records, statusSnap, diagnosisSnap] = await Promise.all([
|
|
4327
|
+
loadCombinedLocalRecords(deps),
|
|
4328
|
+
client.get("status"),
|
|
4329
|
+
client.get("diagnosis")
|
|
4330
|
+
]);
|
|
4331
|
+
const result = diagnoseError({
|
|
4332
|
+
errorText: error_text,
|
|
4333
|
+
product,
|
|
4334
|
+
localRecords: records,
|
|
4335
|
+
statusSnapshot: statusSnap.data,
|
|
4336
|
+
diagnosisEntries: diagnosisSnap.data.entries
|
|
4337
|
+
});
|
|
4338
|
+
return {
|
|
4339
|
+
content: [
|
|
4340
|
+
{
|
|
4341
|
+
type: "text",
|
|
4342
|
+
text: JSON.stringify(
|
|
4343
|
+
{
|
|
4344
|
+
...result,
|
|
4345
|
+
data_sources: {
|
|
4346
|
+
status: statusSnap.source,
|
|
4347
|
+
diagnosis: diagnosisSnap.source
|
|
4348
|
+
}
|
|
4349
|
+
},
|
|
4350
|
+
null,
|
|
4351
|
+
2
|
|
4352
|
+
)
|
|
4353
|
+
}
|
|
4354
|
+
]
|
|
4355
|
+
};
|
|
4356
|
+
}
|
|
4357
|
+
);
|
|
4358
|
+
server.tool(
|
|
4359
|
+
"lookup_model_guide",
|
|
4360
|
+
"Recommend the right Gemini / Antigravity model or Orchestrator pairing for a task, check deprecation status & shared-bucket cost tier, and optionally inspect official before->after chronicle history.",
|
|
4361
|
+
{
|
|
4362
|
+
task: z.string().optional().describe("Task description (e.g. 'architecture', 'multi-file refactor', 'quick qa', 'batch')."),
|
|
4363
|
+
model_id: z.string().optional().describe("Specific model id, api_model_id, or codename (e.g. 'neon', 'hydrogen', 'argon', 'gemini-3.8-flash')."),
|
|
4364
|
+
provider: z.enum(["google", "antigravity", "all"]).default("all"),
|
|
4365
|
+
include_history: z.boolean().default(false)
|
|
4366
|
+
},
|
|
4367
|
+
async ({ task, model_id, provider, include_history }) => {
|
|
4368
|
+
const [modelsSnap, chronicleSnap] = await Promise.all([
|
|
4369
|
+
client.get("models"),
|
|
4370
|
+
include_history ? client.get("chronicle") : Promise.resolve(null)
|
|
4371
|
+
]);
|
|
4372
|
+
let models = modelsSnap.data.models;
|
|
4373
|
+
if (provider === "antigravity") {
|
|
4374
|
+
models = models.filter(
|
|
4375
|
+
(m) => m.provider === "antigravity" || Boolean(m.availability?.products?.includes("agy"))
|
|
4376
|
+
);
|
|
4377
|
+
} else if (provider !== "all") {
|
|
4378
|
+
models = models.filter((m) => m.provider === provider);
|
|
4379
|
+
}
|
|
4380
|
+
let matched = models;
|
|
4381
|
+
if (model_id) {
|
|
4382
|
+
const needle = model_id.toLowerCase();
|
|
4383
|
+
matched = models.filter(
|
|
4384
|
+
(m) => m.id.toLowerCase().includes(needle) || m.api_model_id.toLowerCase().includes(needle) || m.display_name.toLowerCase().includes(needle) || m.codename && m.codename.toLowerCase().includes(needle)
|
|
4385
|
+
);
|
|
4386
|
+
} else if (task) {
|
|
4387
|
+
const needle = task.toLowerCase();
|
|
4388
|
+
const scored = models.filter((m) => m.lifecycle !== "deprecated" && m.lifecycle !== "removed").map((m) => {
|
|
4389
|
+
let score = 0;
|
|
4390
|
+
if (m.best_for.some((b) => b.toLowerCase().includes(needle) || needle.includes(b.toLowerCase()))) {
|
|
4391
|
+
score += 3;
|
|
4392
|
+
}
|
|
4393
|
+
if (m.summary.toLowerCase().includes(needle)) {
|
|
4394
|
+
score += 2;
|
|
4395
|
+
}
|
|
4396
|
+
if (needle.includes("plan") || needle.includes("architect") || needle.includes("debug")) {
|
|
4397
|
+
if (m.specs.reasoning_tier === "flagship" || m.id.includes("neon")) score += 4;
|
|
4398
|
+
}
|
|
4399
|
+
if (needle.includes("fast") || needle.includes("cheap") || needle.includes("edit") || needle.includes("test") || needle.includes("refactor")) {
|
|
4400
|
+
if (m.quota_profile.shared_bucket_cost_tier === "low" || m.id.includes("hydrogen") || m.id.includes("flash")) score += 4;
|
|
4401
|
+
}
|
|
4402
|
+
if (needle.includes("batch") || needle.includes("bulk") || needle.includes("high-volume")) {
|
|
4403
|
+
if (m.id.includes("flash-lite") || m.id.includes("flash")) score += 4;
|
|
4404
|
+
}
|
|
4405
|
+
return { model: m, score };
|
|
4406
|
+
}).sort((a, b) => b.score - a.score);
|
|
4407
|
+
matched = scored.slice(0, 3).map((s) => s.model);
|
|
4408
|
+
}
|
|
4409
|
+
const history = include_history && chronicleSnap ? chronicleSnap.data.entries.filter((e) => {
|
|
4410
|
+
if (!model_id) return true;
|
|
4411
|
+
const needle = model_id.toLowerCase();
|
|
4412
|
+
return e.entity_ids.some((id) => id.toLowerCase().includes(needle)) || e.title.toLowerCase().includes(needle);
|
|
4413
|
+
}) : void 0;
|
|
4414
|
+
const deprecationWarnings = matched.filter((m) => m.lifecycle === "deprecated" || m.lifecycle === "removed").map((m) => ({
|
|
4415
|
+
model: m.id,
|
|
4416
|
+
lifecycle: m.lifecycle,
|
|
4417
|
+
deprecated_date: m.deprecated_date,
|
|
4418
|
+
replacement_model_id: m.replacement_model_id
|
|
4419
|
+
}));
|
|
4420
|
+
return {
|
|
4421
|
+
content: [
|
|
4422
|
+
{
|
|
4423
|
+
type: "text",
|
|
4424
|
+
text: JSON.stringify(
|
|
4425
|
+
{
|
|
4426
|
+
models: matched,
|
|
4427
|
+
orchestrator_recipes: modelsSnap.data.orchestrator_recipes,
|
|
4428
|
+
deprecation_warnings: deprecationWarnings,
|
|
4429
|
+
chronicle_history: history,
|
|
4430
|
+
guide_url: "https://modelcraft.dev/models",
|
|
4431
|
+
official_source_urls: [
|
|
4432
|
+
...new Set(matched.flatMap((m) => m.official_source_urls ?? []))
|
|
4433
|
+
],
|
|
4434
|
+
snapshot_source: modelsSnap.source
|
|
4435
|
+
},
|
|
4436
|
+
null,
|
|
4437
|
+
2
|
|
4438
|
+
)
|
|
4439
|
+
}
|
|
4440
|
+
]
|
|
4441
|
+
};
|
|
4442
|
+
}
|
|
4443
|
+
);
|
|
4444
|
+
server.tool(
|
|
4445
|
+
"get_ecosystem_status",
|
|
4446
|
+
"Get live Gemini & Antigravity upstream status, latest CLI/SDK versions, recent official updates, quota rules, and local PT midnight + 5h/7d rolling reset countdowns.",
|
|
4447
|
+
{
|
|
4448
|
+
plan: z.enum(["free", "pro", "ultra"]).optional(),
|
|
4449
|
+
product: z.enum(["agy", "cli", "api", "web"]).optional(),
|
|
4450
|
+
timezone: z.string().optional().describe("IANA timezone (e.g. 'Asia/Shanghai', 'America/Los_Angeles')."),
|
|
4451
|
+
scope: z.enum(["global", "project"]).default("global"),
|
|
4452
|
+
workspace_dir: z.string().optional().describe(
|
|
4453
|
+
"Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned)."
|
|
4454
|
+
),
|
|
4455
|
+
auth_mode: z.enum(["all", "google_oauth", "gcp_adc", "api_key", "unknown"]).default("all")
|
|
4456
|
+
},
|
|
4457
|
+
async ({ plan, product, timezone, scope, workspace_dir, auth_mode }) => {
|
|
4458
|
+
const nowMs = Date.now();
|
|
4459
|
+
const since7d = nowMs - 7 * 86400 * 1e3;
|
|
4460
|
+
const [statusSnap, quotasSnap, updatesSnap, authContext, projectHash] = await Promise.all([
|
|
4461
|
+
client.get("status"),
|
|
4462
|
+
client.get("quotas"),
|
|
4463
|
+
client.get("updates"),
|
|
4464
|
+
deps.authContext ? Promise.resolve(deps.authContext) : detectAuthContext(),
|
|
4465
|
+
resolveScopeProjectHash(scope, workspace_dir, deps)
|
|
4466
|
+
]);
|
|
4467
|
+
const merged = await loadMergedUsageRecords(deps, {
|
|
4468
|
+
product: "all",
|
|
4469
|
+
activeAuthMode: authContext.active_auth_mode,
|
|
4470
|
+
sinceMs: since7d,
|
|
4471
|
+
nowMs
|
|
4472
|
+
});
|
|
4473
|
+
const effectiveBase = filterRecordsByScopeAndAuth(
|
|
4474
|
+
merged.records,
|
|
4475
|
+
"global",
|
|
4476
|
+
void 0,
|
|
4477
|
+
auth_mode
|
|
4478
|
+
);
|
|
4479
|
+
const effectiveRecords = filterRecordsByScopeAndAuth(
|
|
4480
|
+
merged.records,
|
|
4481
|
+
scope,
|
|
4482
|
+
projectHash,
|
|
4483
|
+
auth_mode
|
|
4484
|
+
);
|
|
4485
|
+
const effectiveTotalTokens7d = effectiveRecords.reduce(
|
|
4486
|
+
(sum, r) => sum + r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens,
|
|
4487
|
+
0
|
|
4488
|
+
);
|
|
4489
|
+
const usingTranscriptTokenLogs = merged.dataModeOverride === "transcript_token_logs";
|
|
4490
|
+
const unattributedExcluded = new Set(
|
|
4491
|
+
effectiveBase.filter((r) => !r.project_hash).map((r) => r.session_hash || "default-session")
|
|
4492
|
+
).size;
|
|
4493
|
+
const fiveHoursAgo = nowMs - 5 * 3600 * 1e3;
|
|
4494
|
+
const in5h = effectiveRecords.map((r) => Date.parse(r.ts)).filter((t) => !Number.isNaN(t) && t >= fiveHoursAgo);
|
|
4495
|
+
const in7d = effectiveRecords.map((r) => Date.parse(r.ts)).filter((t) => !Number.isNaN(t));
|
|
4496
|
+
const isSpecificAuthEmpty = auth_mode !== "all" && effectiveRecords.length === 0;
|
|
4497
|
+
const transcriptFallback = !isSpecificAuthEmpty && effectiveRecords.length === 0 && scope === "global" ? await scanTranscriptActivity({
|
|
4498
|
+
brainDir: deps.brainDir,
|
|
4499
|
+
nowMs,
|
|
4500
|
+
timezone
|
|
4501
|
+
}) : void 0;
|
|
4502
|
+
const countdown = computeResetCountdown({
|
|
4503
|
+
now: new Date(nowMs),
|
|
4504
|
+
timezone,
|
|
4505
|
+
oldestEventIn5hMs: in5h.length > 0 ? Math.min(...in5h) : transcriptFallback?.earliest_turn_5h_ms ?? null,
|
|
4506
|
+
oldestEventIn7dMs: in7d.length > 0 ? Math.min(...in7d) : transcriptFallback?.earliest_turn_7d_ms ?? null
|
|
4507
|
+
});
|
|
4508
|
+
const filteredPlans = plan ? quotasSnap.data.plans.filter(
|
|
4509
|
+
(p) => p.id.toLowerCase().includes(plan) || p.name.toLowerCase().includes(plan)
|
|
4510
|
+
) : quotasSnap.data.plans;
|
|
4511
|
+
const filteredUpdates = product ? updatesSnap.data.items.filter(
|
|
4512
|
+
(u) => u.product === product || u.product === "all"
|
|
4513
|
+
) : updatesSnap.data.items;
|
|
4514
|
+
const statusActivitySummary = transcriptFallback ? buildActivitySummary(transcriptFallback, "5h") : void 0;
|
|
4515
|
+
const statusDataMode = resolveDataMode(
|
|
4516
|
+
effectiveRecords.length,
|
|
4517
|
+
effectiveTotalTokens7d,
|
|
4518
|
+
usingTranscriptTokenLogs ? "transcript_token_logs" : void 0
|
|
4519
|
+
);
|
|
4520
|
+
const statusUsageNote = isSpecificAuthEmpty ? `No usage records matched auth_mode="${auth_mode}" in the 7d window (active local auth mode is "${authContext.active_auth_mode}").` : statusDataMode === "hook_events_without_tokens" ? `Local hook events (${effectiveRecords.length} record(s)) were recorded without token or model fields. Refer to the official AGY/CLI quota UI for authoritative remaining %, or enable Gemini CLI OTel for exact local token counts.` : void 0;
|
|
4521
|
+
return {
|
|
4522
|
+
content: [
|
|
4523
|
+
{
|
|
4524
|
+
type: "text",
|
|
4525
|
+
text: JSON.stringify(
|
|
4526
|
+
{
|
|
4527
|
+
...statusActivitySummary ? { activity_summary: statusActivitySummary } : {},
|
|
4528
|
+
scope,
|
|
4529
|
+
...scope === "project" && projectHash ? {
|
|
4530
|
+
project_hash: projectHash,
|
|
4531
|
+
unattributed_sessions_excluded: unattributedExcluded
|
|
4532
|
+
} : {},
|
|
4533
|
+
auth_mode_filter: auth_mode,
|
|
4534
|
+
auth_context: authContext,
|
|
4535
|
+
data_mode: statusDataMode,
|
|
4536
|
+
...statusUsageNote ? { usage_note: statusUsageNote } : {},
|
|
4537
|
+
session_count: isSpecificAuthEmpty ? 0 : effectiveRecords.length > 0 ? new Set(effectiveRecords.map((r) => r.session_hash)).size : transcriptFallback?.window_5h.session_count ?? 0,
|
|
4538
|
+
overall_status: statusSnap.data.overall_status,
|
|
4539
|
+
surfaces: statusSnap.data.surfaces,
|
|
4540
|
+
active_incidents: statusSnap.data.active_incidents,
|
|
4541
|
+
latest_versions: statusSnap.data.latest_versions,
|
|
4542
|
+
countdown,
|
|
4543
|
+
...transcriptFallback ? { transcript_activity_fallback: transcriptFallback } : {},
|
|
4544
|
+
quota_rules: quotasSnap.data.reset_rules,
|
|
4545
|
+
plans: filteredPlans,
|
|
4546
|
+
recent_updates: filteredUpdates.slice(0, 8),
|
|
4547
|
+
dashboard_url: "https://modelcraft.dev",
|
|
4548
|
+
official_source_urls: quotasSnap.data.official_source_urls ?? [],
|
|
4549
|
+
snapshot_sources: {
|
|
4550
|
+
status: statusSnap.source,
|
|
4551
|
+
quotas: quotasSnap.source,
|
|
4552
|
+
updates: updatesSnap.source
|
|
4553
|
+
}
|
|
4554
|
+
},
|
|
4555
|
+
null,
|
|
4556
|
+
2
|
|
4557
|
+
)
|
|
4558
|
+
}
|
|
4559
|
+
]
|
|
4560
|
+
};
|
|
4561
|
+
}
|
|
4562
|
+
);
|
|
4563
|
+
return server;
|
|
4564
|
+
}
|
|
4565
|
+
async function startStdioServer(deps = {}) {
|
|
4566
|
+
const server = createAgycraftServer(deps);
|
|
4567
|
+
const transport = new StdioServerTransport();
|
|
4568
|
+
await server.connect(transport);
|
|
4569
|
+
}
|
|
4570
|
+
|
|
4571
|
+
// src/index.ts
|
|
4572
|
+
async function readStdinText() {
|
|
4573
|
+
const chunks = [];
|
|
4574
|
+
for await (const chunk of process.stdin) {
|
|
4575
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
|
|
4576
|
+
}
|
|
4577
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
4578
|
+
}
|
|
4579
|
+
function printPreflightHelp() {
|
|
4580
|
+
console.log(
|
|
4581
|
+
[
|
|
4582
|
+
"agycraft-mcp preflight \u2014 Live ModelCraft cloud status guard",
|
|
4583
|
+
"",
|
|
4584
|
+
"Usage:",
|
|
4585
|
+
" agycraft-mcp preflight [--json]",
|
|
4586
|
+
"",
|
|
4587
|
+
"Environment:",
|
|
4588
|
+
" MODELCRAFT_STATUS_URL Full URL override for status.json",
|
|
4589
|
+
" MODELCRAFT_DATA_URL Base URL override (default: https://modelcraft.dev/data/v1)",
|
|
4590
|
+
"",
|
|
4591
|
+
"Exit codes:",
|
|
4592
|
+
" 0 overall_status is operational, no active_incidents, all surfaces operational, no 429/503 sources",
|
|
4593
|
+
" 1 degraded, active incident, 429/503 source error, or network/timeout failure"
|
|
4594
|
+
].join("\n")
|
|
4595
|
+
);
|
|
4596
|
+
}
|
|
4597
|
+
function printHelp() {
|
|
4598
|
+
console.log(
|
|
4599
|
+
[
|
|
4600
|
+
"agycraft-mcp \u2014 Privacy-first local MCP server & CLI doctor for Antigravity (AGY) & Gemini CLI",
|
|
4601
|
+
"",
|
|
4602
|
+
"Usage:",
|
|
4603
|
+
" agycraft-mcp Start Stdio MCP Server (default)",
|
|
4604
|
+
" agycraft-mcp doctor [--json] Run offline preflight & hygiene check (zero secret values read)",
|
|
4605
|
+
" agycraft-mcp preflight [--json] Check live ModelCraft status.json (exits 1 if degraded/429/503)",
|
|
4606
|
+
" agycraft-mcp setup Print non-destructive, opt-in AGY / Gemini CLI setup snippets",
|
|
4607
|
+
" agycraft-mcp record Read hook JSON from stdin and append strictly whitelisted numeric metrics",
|
|
4608
|
+
" agycraft-mcp clear-local-data Safely delete ~/.config/agycraft/usage.jsonl and cache",
|
|
4609
|
+
" agycraft-mcp --help Show this help message",
|
|
4610
|
+
"",
|
|
4611
|
+
"Independent community project (ModelCraft). Not affiliated with or endorsed by Google."
|
|
4612
|
+
].join("\n")
|
|
4613
|
+
);
|
|
4614
|
+
}
|
|
4615
|
+
async function main(argv = process.argv.slice(2)) {
|
|
4616
|
+
const cmd = argv[0];
|
|
4617
|
+
if (!cmd) {
|
|
4618
|
+
await startStdioServer();
|
|
4619
|
+
return;
|
|
4620
|
+
}
|
|
4621
|
+
switch (cmd) {
|
|
4622
|
+
case "doctor": {
|
|
4623
|
+
const asJson = argv.includes("--json");
|
|
4624
|
+
const report = await runDoctor();
|
|
4625
|
+
if (asJson) {
|
|
4626
|
+
console.log(JSON.stringify(report, null, 2));
|
|
4627
|
+
} else {
|
|
4628
|
+
console.log(formatDoctorReport(report));
|
|
4629
|
+
}
|
|
4630
|
+
return;
|
|
4631
|
+
}
|
|
4632
|
+
case "preflight": {
|
|
4633
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
4634
|
+
printPreflightHelp();
|
|
4635
|
+
return;
|
|
4636
|
+
}
|
|
4637
|
+
const asJson = argv.includes("--json");
|
|
4638
|
+
const result = await runPreflight();
|
|
4639
|
+
if (asJson) {
|
|
4640
|
+
console.log(JSON.stringify(result, null, 2));
|
|
4641
|
+
} else {
|
|
4642
|
+
console.log(formatPreflightReport(result));
|
|
4643
|
+
}
|
|
4644
|
+
process.exitCode = result.exit_code;
|
|
4645
|
+
return;
|
|
4646
|
+
}
|
|
4647
|
+
case "setup": {
|
|
4648
|
+
console.log(buildSetupInstructions());
|
|
4649
|
+
return;
|
|
4650
|
+
}
|
|
4651
|
+
case "clear-local-data": {
|
|
4652
|
+
const result = await clearLocalData();
|
|
4653
|
+
console.log(
|
|
4654
|
+
`Cleared local agycraft data (${result.removed.length} path(s) processed).`
|
|
4655
|
+
);
|
|
4656
|
+
return;
|
|
4657
|
+
}
|
|
4658
|
+
case "record": {
|
|
4659
|
+
const raw = (await readStdinText()).trim();
|
|
4660
|
+
if (!raw) {
|
|
4661
|
+
return;
|
|
4662
|
+
}
|
|
4663
|
+
try {
|
|
4664
|
+
const parsed = JSON.parse(raw);
|
|
4665
|
+
await appendUsageRecord(parsed);
|
|
4666
|
+
} catch {
|
|
4667
|
+
}
|
|
4668
|
+
return;
|
|
4669
|
+
}
|
|
4670
|
+
case "-h":
|
|
4671
|
+
case "--help":
|
|
4672
|
+
case "help": {
|
|
4673
|
+
printHelp();
|
|
4674
|
+
return;
|
|
4675
|
+
}
|
|
4676
|
+
default: {
|
|
4677
|
+
console.error(`Unknown subcommand: ${cmd}`);
|
|
4678
|
+
printHelp();
|
|
4679
|
+
process.exitCode = 1;
|
|
4680
|
+
}
|
|
4681
|
+
}
|
|
4682
|
+
}
|
|
4683
|
+
var isDirectRun = process.argv[1] && (process.argv[1].endsWith("index.js") || process.argv[1].endsWith("index.ts") || process.argv[1].endsWith("agycraft-mcp"));
|
|
4684
|
+
if (isDirectRun) {
|
|
4685
|
+
main().catch((err) => {
|
|
4686
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
4687
|
+
process.exitCode = 1;
|
|
4688
|
+
});
|
|
4689
|
+
}
|
|
4690
|
+
export {
|
|
4691
|
+
main
|
|
4692
|
+
};
|
|
4693
|
+
//# sourceMappingURL=index.js.map
|