agycraft-mcp 0.2.2 → 0.2.3
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/dist/index.js +2220 -122
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/doctor.ts","../src/collectors/auth-detector.ts","../src/collectors/channel-registry.ts","../src/paths.ts","../src/collectors/cli-log.ts","../src/analyzers/token-window.ts","../src/privacy.ts","../src/i18n.ts","../src/storage/rollups.ts","../src/collectors/transcript-meta.ts","../src/cli/preflight.ts","../src/cli/setup.ts","../src/cli/clear-local-data.ts","../src/collectors/agy-hook.ts","../src/server.ts","../src/collectors/gemini-otel.ts","../src/analyzers/antipatterns.ts","../src/analyzers/channel-diagnosis.ts","../src/analyzers/error-diagnoser.ts","../src/analyzers/countdown.ts","../src/remote/snapshot-client.ts","../src/index.ts"],"sourcesContent":["import { access, readFile, stat } from \"node:fs/promises\";\nimport { constants as fsConstants } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { detectAuthContext } from \"../collectors/auth-detector.js\";\nimport {\n ChannelRegistry,\n loadBundledChannelRegistry,\n} from \"../collectors/channel-registry.js\";\nimport { getLocalizedBehavior, resolveLocale } from \"../i18n.js\";\nimport { getSnapshotsDir } from \"../paths.js\";\nimport {\n queryRollups,\n readRollupCostSummary,\n type AuthChannelCostGroup,\n type CostSummaryWindow,\n type DeprecatedModelInUse,\n type ModelAuthCostRow,\n type RollupWindowCostSummary,\n} from \"../storage/rollups.js\";\nimport type {\n AuthMode,\n ChannelsSnapshot,\n ModelEntry,\n ModelsSnapshot,\n} from \"../types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type CheckSeverity = \"ok\" | \"warn\" | \"error\" | \"info\";\n\nexport interface DoctorCheckItem {\n id: string;\n category:\n | \"runtime\"\n | \"mcp_config\"\n | \"auth_env\"\n | \"network_ssl\"\n | \"context_hygiene\"\n | \"cost_usage\"\n | \"safety_guardrail\";\n severity: CheckSeverity;\n title: string;\n detail: string;\n fix_hint?: string;\n}\n\nexport interface DoctorReport {\n generated_at: string;\n node_version: string;\n checks: DoctorCheckItem[];\n summary: {\n ok: number;\n warn: number;\n error: number;\n info: number;\n };\n git_safety_guardrail_snippet: string;\n geminiignore_template: string;\n}\n\nexport interface DoctorOptions {\n cwd?: string;\n homeDir?: string;\n env?: NodeJS.ProcessEnv;\n mcpConfigPaths?: string[];\n settingsJsonPaths?: string[];\n skipBinaryChecks?: boolean;\n rollupsDir?: string;\n snapshotsDir?: string;\n authMode?: AuthMode;\n channels?: ChannelsSnapshot | ChannelRegistry;\n nowMs?: number;\n lang?: string;\n}\n\nexport interface DoctorCostOptions {\n window?: CostSummaryWindow;\n cwd?: string;\n homeDir?: string;\n env?: NodeJS.ProcessEnv;\n rollupsDir?: string;\n usageLogPath?: string;\n geminiOtelPath?: string;\n brainDir?: string | null;\n historyPath?: string | null;\n cliLogDir?: string | null;\n saltPath?: string;\n snapshotsDir?: string;\n nowMs?: number;\n}\n\nexport interface DoctorCostReport {\n generated_at: string;\n window: CostSummaryWindow;\n data_source: \"rollups\" | \"memory_fallback\";\n auth_groups: AuthChannelCostGroup[];\n by_model_auth: ModelAuthCostRow[];\n deprecated_models_in_use: DeprecatedModelInUse[];\n rate_limit_429_count: number;\n total_requests: number;\n total_tokens: number;\n notes: string[];\n}\n\nconst SENSITIVE_KEY_RE = /(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH)/i;\n\nexport const GIT_SAFETY_GUARDRAIL_SNIPPET = `# Git Safety Guardrail (add to AGENTS.md or GEMINI.md)\n- NEVER run destructive git commands (\\`git push --force\\`, \\`git reset --hard\\`, \\`git clean -fd\\`, \\`git checkout -- .\\`) without explicit user confirmation.\n- NEVER delete files outside the current workspace or run \\`rm -rf\\` on broad paths.\n- Always run \\`git status\\` and \\`git diff --stat\\` before committing or staging changes.`;\n\nexport const GEMINIIGNORE_TEMPLATE = `# Recommended .geminiignore to prevent context bloat & 504 timeouts\n# JS/TS & Web\nnode_modules/\ndist/\nbuild/\n.next/\n.astro/\ncoverage/\n*.lock\npackage-lock.json\npnpm-lock.yaml\nyarn.lock\n*.min.js\n*.map\n\n# Python & Data Engineering\n.venv/\nvenv/\n__pycache__/\n.pytest_cache/\n.mypy_cache/\n.ruff_cache/\ndata/\nlogs/\ntmp/\n*.parquet\n*.sqlite\n*.db\n*.log\n\n# VCS\n.git/\n`;\n\nasync function loadOfflineModelsSnapshot(\n snapshotsDir?: string,\n): Promise<{ models: ModelEntry[]; normalization_rules?: ModelsSnapshot[\"normalization_rules\"] }> {\n const dir = snapshotsDir ?? getSnapshotsDir();\n try {\n const raw = await readFile(join(dir, \"models.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as ModelsSnapshot;\n return {\n models: Array.isArray(parsed.models) ? parsed.models : [],\n normalization_rules: parsed.normalization_rules,\n };\n } catch {\n return { models: [] };\n }\n}\n\nfunction formatChannelSummaryText(winSummary: RollupWindowCostSummary): string {\n if (winSummary.by_auth_channel.length === 0) {\n return \"no usage recorded\";\n }\n return winSummary.by_auth_channel\n .map((g) => {\n const usd = `$${g.estimated_total_usd.toFixed(2)}`;\n if (g.auth_mode === \"google_oauth\") {\n return `Shadow Cost (Shared Quota Pressure): ~${usd} equiv`;\n }\n if (g.auth_mode === \"gcp_adc\" || g.auth_mode === \"api_key\") {\n return `Estimated GCP / API Spend: ~${usd} est.`;\n }\n return `Unattributed Est.: ~${usd}`;\n })\n .join(\" | \");\n}\n\nasync function fileExists(filePath: string): Promise<boolean> {\n try {\n await access(filePath, fsConstants.R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function detectBinaryVersion(\n cmd: string,\n args: string[] = [\"--version\"],\n): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync(cmd, args, { timeout: 2500 });\n const firstLine = stdout.trim().split(\"\\n\")[0]?.trim() ?? \"\";\n return firstLine.slice(0, 64) || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Inspects JSON config structure ONLY. Never reads or echoes secret/token/key values.\n */\nasync function inspectJsonConfig(\n filePath: string,\n kind: \"mcp_config\" | \"settings\",\n): Promise<DoctorCheckItem[]> {\n const checks: DoctorCheckItem[] = [];\n if (!(await fileExists(filePath))) {\n return checks;\n }\n\n let parsed: unknown;\n try {\n const raw = await readFile(filePath, \"utf8\");\n parsed = JSON.parse(raw);\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Invalid JSON syntax\";\n checks.push({\n id: `${kind}_syntax_error`,\n category: \"mcp_config\",\n severity: \"error\",\n title: `Invalid JSON syntax in ${kind === \"mcp_config\" ? \"mcp_config.json\" : \"settings.json\"}`,\n detail: `Parse error: ${msg.slice(0, 120)}`,\n fix_hint: \"Validate trailing commas, quotes, and braces with `jq . <file>`.\",\n });\n return checks;\n }\n\n checks.push({\n id: `${kind}_syntax_ok`,\n category: \"mcp_config\",\n severity: \"ok\",\n title: `${kind === \"mcp_config\" ? \"mcp_config.json\" : \"settings.json\"} JSON syntax valid`,\n detail: \"Parsed cleanly.\",\n });\n\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return checks;\n }\n\n const root = parsed as Record<string, unknown>;\n const serversObj = root[\"mcpServers\"];\n if (serversObj && typeof serversObj === \"object\" && !Array.isArray(serversObj)) {\n const serverEntries = Object.entries(serversObj as Record<string, unknown>);\n const serverCount = serverEntries.length;\n\n if (serverCount > 8) {\n checks.push({\n id: \"mcp_server_bloat\",\n category: \"context_hygiene\",\n severity: \"warn\",\n title: `High mounted MCP server count (${serverCount})`,\n detail: `${serverCount} MCP servers inject many tool schemas into every turn, accelerating 5h/7d quota burn.`,\n fix_hint: \"Disable unused MCP servers or split specialized workflows into on-demand SKILL.md files.\",\n });\n } else {\n checks.push({\n id: \"mcp_server_count_ok\",\n category: \"context_hygiene\",\n severity: \"ok\",\n title: `Mounted MCP server count healthy (${serverCount})`,\n detail: `${serverCount} configured MCP server(s).`,\n });\n }\n\n for (const [serverName, cfg] of serverEntries) {\n if (!cfg || typeof cfg !== \"object\" || Array.isArray(cfg)) {\n continue;\n }\n const serverCfg = cfg as Record<string, unknown>;\n const safeName = serverName.replace(/[^a-zA-Z0-9._-]/g, \"_\").slice(0, 32);\n\n // Check url vs httpUrl mismatch\n const hasUrl = typeof serverCfg[\"url\"] === \"string\";\n const hasHttpUrl = typeof serverCfg[\"httpUrl\"] === \"string\";\n if (hasUrl && hasHttpUrl) {\n checks.push({\n id: `mcp_transport_conflict_${safeName}`,\n category: \"mcp_config\",\n severity: \"error\",\n title: `MCP server \"${safeName}\" sets both \"url\" and \"httpUrl\"`,\n detail: \"Use 'url' for SSE transport OR 'httpUrl' for Streamable HTTP, never both.\",\n fix_hint: `Remove one of 'url' or 'httpUrl' in mcpServers.${safeName} and verify with \\`gemini mcp list\\`.`,\n });\n } else if (hasUrl) {\n const urlStr = String(serverCfg[\"url\"]);\n if (urlStr.includes(\"/mcp\") && !urlStr.includes(\"/sse\")) {\n checks.push({\n id: `mcp_url_mismatch_${safeName}`,\n category: \"mcp_config\",\n severity: \"warn\",\n title: `Possible url vs httpUrl mismatch on \"${safeName}\"`,\n detail: \"Endpoint looks like Streamable HTTP (/mcp) but uses legacy SSE key 'url'.\",\n fix_hint: `Rename key \"url\" -> \"httpUrl\" in mcpServers.${safeName} if the server uses Streamable HTTP.`,\n });\n }\n } else if (hasHttpUrl) {\n const httpUrlStr = String(serverCfg[\"httpUrl\"]);\n if (httpUrlStr.includes(\"/sse\")) {\n checks.push({\n id: `mcp_httpurl_mismatch_${safeName}`,\n category: \"mcp_config\",\n severity: \"warn\",\n title: `Possible httpUrl vs url mismatch on \"${safeName}\"`,\n detail: \"Endpoint looks like SSE (/sse) but uses Streamable HTTP key 'httpUrl'.\",\n fix_hint: `Rename key \"httpUrl\" -> \"url\" in mcpServers.${safeName} if the server uses SSE.`,\n });\n }\n }\n\n // Check env keys for *TOKEN*/*KEY*/*SECRET* stripping risk (NAMES ONLY, NEVER VALUES)\n const envBlock = serverCfg[\"env\"];\n if (envBlock && typeof envBlock === \"object\" && !Array.isArray(envBlock)) {\n const sensitiveKeyCount = Object.keys(envBlock as Record<string, unknown>).filter(\n (k) => SENSITIVE_KEY_RE.test(k),\n ).length;\n if (sensitiveKeyCount > 0) {\n checks.push({\n id: `mcp_env_explicit_${safeName}`,\n category: \"mcp_config\",\n severity: \"info\",\n title: `MCP server \"${safeName}\" defines ${sensitiveKeyCount} explicit credential env key(s)`,\n detail: \"Explicit env keys are present (values not inspected or logged).\",\n });\n }\n }\n }\n }\n\n return checks;\n}\n\n/**\n * Runs offline preflight & hygiene checks.\n * PRIVACY RED LINE: Only inspects boolean existence, structural syntax, and byte counts.\n * NEVER reads, retains, or prints secret/token/key values or credential files.\n */\nexport async function runDoctor(options?: DoctorOptions): Promise<DoctorReport> {\n const cwd = options?.cwd ?? process.cwd();\n const home = options?.homeDir ?? homedir();\n const env = options?.env ?? process.env;\n const locale = resolveLocale(options?.lang, env);\n const registry =\n options?.channels instanceof ChannelRegistry\n ? options.channels\n : options?.channels\n ? ChannelRegistry.fromSnapshot(options.channels)\n : loadBundledChannelRegistry(options?.snapshotsDir);\n const authContext = await detectAuthContext({\n homeDir: home,\n env,\n registry,\n nowMs: options?.nowMs,\n });\n const targetChannelId =\n options?.authMode && options.authMode !== \"unknown\"\n ? registry.resolveChannelId(options.authMode)\n : (authContext.active_channel_id ?? registry.resolveChannelId(authContext.active_auth_mode));\n const activeChannel =\n targetChannelId && targetChannelId !== \"unknown\"\n ? registry.getChannel(targetChannelId)\n : undefined;\n const checks: DoctorCheckItem[] = [];\n\n // 1. Node.js version check (Node 20+ supported, Node 22+ LTS recommended)\n const nodeVersion = process.version;\n const major = Number(nodeVersion.replace(/^v/, \"\").split(\".\")[0] ?? \"0\");\n checks.push({\n id: \"node_version\",\n category: \"runtime\",\n severity: major >= 20 ? \"ok\" : \"warn\",\n title: `Node.js ${nodeVersion}`,\n detail:\n major >= 22\n ? \"Node 22+ runtime detected.\"\n : major >= 20\n ? \"Node 20+ runtime supported (Node 22+ LTS recommended for latest Gemini CLI).\"\n : \"Node.js >= 20.0.0 is required for agycraft-mcp (Node 22+ LTS recommended).\",\n fix_hint: major >= 20 ? undefined : \"Upgrade Node.js to v20 LTS or v22 LTS.\",\n });\n\n // 2. AGY & Gemini CLI binary presence\n if (!options?.skipBinaryChecks) {\n const [geminiVer, agyVer] = await Promise.all([\n detectBinaryVersion(\"gemini\", [\"--version\"]),\n detectBinaryVersion(\"agy\", [\"--version\"]),\n ]);\n checks.push({\n id: \"gemini_cli_version\",\n category: \"runtime\",\n severity: geminiVer ? \"ok\" : \"info\",\n title: geminiVer ? `Gemini CLI detected (${geminiVer})` : \"Gemini CLI not found on PATH\",\n detail: geminiVer\n ? \"Gemini CLI binary is reachable.\"\n : \"Optional (Enterprise / paid API key workflows only; personal tier sunset Jun 2026 — use Antigravity CLI `agy` for personal workflows): install with `npm i -g @google/gemini-cli`.\",\n });\n checks.push({\n id: \"agy_cli_version\",\n category: \"runtime\",\n severity: agyVer ? \"ok\" : \"info\",\n title: agyVer ? `Antigravity CLI detected (${agyVer})` : \"Antigravity CLI (`agy`) not found on PATH\",\n detail: agyVer\n ? \"Antigravity CLI binary is reachable.\"\n : \"If using Antigravity IDE only, CLI binary on PATH is optional.\",\n });\n }\n\n // 3. mcp_config.json & settings.json syntax / transport checks\n const mcpPaths = options?.mcpConfigPaths ?? [\n join(home, \".gemini\", \"antigravity\", \"mcp_config.json\"),\n join(cwd, \"mcp_config.json\"),\n ];\n const settingsPaths = options?.settingsJsonPaths ?? [\n join(home, \".gemini\", \"settings.json\"),\n join(cwd, \".gemini\", \"settings.json\"),\n ];\n\n let foundAnyConfig = false;\n for (const p of mcpPaths) {\n const res = await inspectJsonConfig(p, \"mcp_config\");\n if (res.length > 0) {\n foundAnyConfig = true;\n checks.push(...res);\n }\n }\n for (const p of settingsPaths) {\n const res = await inspectJsonConfig(p, \"settings\");\n if (res.length > 0) {\n foundAnyConfig = true;\n checks.push(...res);\n }\n }\n if (!foundAnyConfig) {\n checks.push({\n id: \"no_mcp_config_found\",\n category: \"mcp_config\",\n severity: \"info\",\n title: \"No local mcp_config.json or settings.json found in default locations\",\n detail: \"Run `npx agycraft-mcp setup` to view copyable MCP & OTel setup snippets.\",\n });\n }\n\n // 4. Environment variable hygiene (BOOLEAN EXISTENCE ONLY — NEVER READ/PRINT VALUES)\n const hasGeminiApiKey = Boolean(env[\"GEMINI_API_KEY\"] || env[\"GOOGLE_API_KEY\"]);\n const hasGcpProject = Boolean(env[\"GOOGLE_CLOUD_PROJECT\"]);\n if (hasGeminiApiKey && hasGcpProject) {\n checks.push({\n id: \"auth_env_dual_set\",\n category: \"auth_env\",\n severity: \"warn\",\n title: \"Both API Key env and GOOGLE_CLOUD_PROJECT are set\",\n detail:\n \"Mixing API Key auth with Vertex/OAuth project env can trigger 403 Permission Denied or ACCESS_TOKEN_TYPE_UNSUPPORTED.\",\n fix_hint:\n \"Unset the unused auth method in your shell profile (`unset GEMINI_API_KEY` or `unset GOOGLE_CLOUD_PROJECT`).\",\n });\n } else {\n checks.push({\n id: \"auth_env_boolean_ok\",\n category: \"auth_env\",\n severity: \"ok\",\n title: \"Auth environment variables checked (boolean presence only)\",\n detail: `GEMINI_API_KEY/GOOGLE_API_KEY set: ${hasGeminiApiKey}, GOOGLE_CLOUD_PROJECT set: ${hasGcpProject}.`,\n });\n }\n\n // 4b. Multi-channel auth isolation check (driven by ChannelRegistry)\n const detectedChannelIds = authContext.detected_channels ?? authContext.detected_modes;\n if (authContext.has_mixed_auth) {\n const channelHints = detectedChannelIds\n .map((id) => {\n const ch = registry.getChannel(id);\n const conflicts = authContext.env_conflicts?.[id] ?? [];\n const iso = ch?.definition.recommended_behaviors.isolation_commands.join(\" && \");\n return ch\n ? `${id}${conflicts.length > 0 ? ` (conflicts: ${conflicts.join(\", \")})` : \"\"}${iso ? ` -> ${iso}` : \"\"}`\n : id;\n })\n .join(\" | \");\n const verifyHint = activeChannel?.definition.recommended_behaviors.verify_command;\n checks.push({\n id: \"auth_mixed_isolation\",\n category: \"auth_env\",\n severity: \"warn\",\n title: `Mixed auth channels detected (${detectedChannelIds.join(\", \")})`,\n detail: authContext.isolation_note,\n fix_hint: `Isolate active channel: ${channelHints}${verifyHint ? ` | Verify: ${verifyHint}` : \"\"}`,\n });\n } else if (activeChannel) {\n checks.push({\n id: \"auth_mixed_isolation\",\n category: \"auth_env\",\n severity: \"ok\",\n title: `Auth channel isolated (${activeChannel.channelId})`,\n detail: `${activeChannel.definition.display_name} (${activeChannel.definition.billing_model}, window: ${activeChannel.definition.quota_reset_policy.window_type}).`,\n fix_hint: activeChannel.definition.recommended_behaviors.verify_command,\n });\n } else {\n checks.push({\n id: \"auth_mixed_isolation\",\n category: \"auth_env\",\n severity: \"info\",\n title: \"No active local auth channel detected\",\n detail: authContext.isolation_note,\n });\n }\n\n // Check for *TOKEN*/*KEY*/*SECRET* env stripping warning in CLI subprocesses\n const sensitiveEnvCount = Object.keys(env).filter((k) =>\n SENSITIVE_KEY_RE.test(k),\n ).length;\n if (sensitiveEnvCount > 0) {\n checks.push({\n id: \"env_stripping_warning\",\n category: \"auth_env\",\n severity: \"info\",\n title: `Detected ${sensitiveEnvCount} shell env var(s) matching *TOKEN*/*KEY*/*SECRET*`,\n detail:\n \"Gemini CLI & AGY sanitize/strip *TOKEN*/*KEY*/*SECRET* env vars from child MCP servers by default (values not inspected).\",\n fix_hint:\n \"If an MCP server requires a specific variable, pass it explicitly in that server's `env` block in mcp_config.json / settings.json.\",\n });\n }\n\n // 5. Proxy & NODE_EXTRA_CA_CERTS presence (BOOLEAN & READABILITY ONLY)\n const hasProxy = Boolean(\n env[\"HTTP_PROXY\"] ||\n env[\"HTTPS_PROXY\"] ||\n env[\"http_proxy\"] ||\n env[\"https_proxy\"],\n );\n const caCertPath = env[\"NODE_EXTRA_CA_CERTS\"];\n const hasCaCert = Boolean(caCertPath);\n\n if (hasProxy && !hasCaCert) {\n checks.push({\n id: \"proxy_without_ca_certs\",\n category: \"network_ssl\",\n severity: \"warn\",\n title: \"HTTP(S)_PROXY is set without NODE_EXTRA_CA_CERTS\",\n detail:\n \"Corporate SSL-inspecting proxies often cause `UNABLE_TO_GET_ISSUER_CERT_LOCALLY` in Node.js.\",\n fix_hint:\n \"If behind a corporate TLS proxy, export `NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem`.\",\n });\n } else if (hasCaCert && caCertPath) {\n const readable = await fileExists(caCertPath);\n checks.push({\n id: \"node_extra_ca_certs_check\",\n category: \"network_ssl\",\n severity: readable ? \"ok\" : \"error\",\n title: readable\n ? \"NODE_EXTRA_CA_CERTS is set and readable\"\n : \"NODE_EXTRA_CA_CERTS points to an unreadable or missing file\",\n detail: readable\n ? \"Custom CA bundle is readable by Node.js.\"\n : \"Node.js will ignore or fail TLS verification when NODE_EXTRA_CA_CERTS is unreadable.\",\n fix_hint: readable\n ? undefined\n : \"Verify the CA certificate path and file permissions (`chmod 644`).\",\n });\n } else {\n checks.push({\n id: \"network_ssl_ok\",\n category: \"network_ssl\",\n severity: \"ok\",\n title: \"No proxy/SSL misconfiguration detected\",\n detail: \"Direct HTTPS connection environment.\",\n });\n }\n\n // 6. Context hygiene: .geminiignore check\n const hasGeminiIgnore = await fileExists(join(cwd, \".geminiignore\"));\n checks.push({\n id: \"geminiignore_check\",\n category: \"context_hygiene\",\n severity: hasGeminiIgnore ? \"ok\" : \"warn\",\n title: hasGeminiIgnore\n ? \".geminiignore found in workspace\"\n : \"Missing .geminiignore in current workspace\",\n detail: hasGeminiIgnore\n ? \"Workspace ignore rules help prevent lockfile/build-artifact context bloat.\"\n : \"Without .geminiignore, lockfiles and build outputs can bloat context and trigger 504 timeouts or quota burn.\",\n fix_hint: hasGeminiIgnore\n ? undefined\n : \"Create a `.geminiignore` file using the recommended template below.\",\n });\n\n // 7. Global rules token bloat estimate (byte size -> ~chars/4, never reads/prints contents)\n const ruleCandidates = [\n { label: \"~/.gemini/GEMINI.md\", path: join(home, \".gemini\", \"GEMINI.md\") },\n { label: \"./GEMINI.md\", path: join(cwd, \"GEMINI.md\") },\n { label: \"./AGENTS.md\", path: join(cwd, \"AGENTS.md\") },\n ];\n let totalRuleBytes = 0;\n let foundRuleFiles = 0;\n for (const candidate of ruleCandidates) {\n try {\n const s = await stat(candidate.path);\n if (s.isFile()) {\n totalRuleBytes += s.size;\n foundRuleFiles += 1;\n }\n } catch {\n // ignore missing\n }\n }\n const estimatedRuleTokens = Math.ceil(totalRuleBytes / 4);\n if (estimatedRuleTokens > 3000) {\n const channelHint = activeChannel\n ? ` Active channel (${activeChannel.channelId}): ${getLocalizedBehavior(activeChannel.definition.recommended_behaviors, \"kv_cache_guidance\", locale) ?? activeChannel.definition.recommended_behaviors.kv_cache_guidance}`\n : \"\";\n checks.push({\n id: \"global_rules_bloat\",\n category: \"context_hygiene\",\n severity: \"warn\",\n title: `Global rules token bloat (~${estimatedRuleTokens} tokens across ${foundRuleFiles} file(s))`,\n detail:\n activeChannel?.definition.quota_reset_policy.window_type === \"rolling_5h_7d\"\n ? \"Large always-loaded rule files are re-sent on every single turn and inflate 5h/7d token consumption.\"\n : \"Large always-loaded rule files are re-sent on every single turn and increase per-turn input token spend.\",\n fix_hint: `Keep global rules under ~2,000 tokens and move domain-specific instructions into on-demand SKILL.md files.${channelHint}`,\n });\n } else {\n checks.push({\n id: \"global_rules_ok\",\n category: \"context_hygiene\",\n severity: \"ok\",\n title: `Global rules size healthy (~${estimatedRuleTokens} tokens across ${foundRuleFiles} file(s))`,\n detail: \"Baseline instruction overhead is lean.\",\n });\n }\n\n // 8. Offline, zero-write, lock-free rollup cost_summary & deprecated model alerts\n const modelsSnapshot = await loadOfflineModelsSnapshot(options?.snapshotsDir);\n const costSummary = await readRollupCostSummary({\n rollupsDir: options?.rollupsDir,\n models: modelsSnapshot.models,\n normalizationRules: modelsSnapshot.normalization_rules,\n nowMs: options?.nowMs,\n });\n\n if (!costSummary.has_cache) {\n checks.push({\n id: \"cost_summary\",\n category: \"cost_usage\",\n severity: \"info\",\n title: \"Cost summary: no local rollups cache yet\",\n detail:\n \"No cached rollups/hourly/*.json found (zero-scan fast path). Run 'agycraft-mcp doctor --cost' or call MCP usage tools to warm local stats.\",\n });\n } else {\n const w5h = costSummary.windows[\"5h\"];\n const w24h = costSummary.windows[\"24h\"];\n const has429 = w5h.rate_limit_429_count > 0;\n checks.push({\n id: \"cost_summary\",\n category: \"cost_usage\",\n severity: has429 ? \"warn\" : \"ok\",\n title: has429\n ? `Cost summary (5h: ${w5h.total_requests} reqs, ${w5h.rate_limit_429_count} x 429; 24h: ${w24h.total_requests} reqs)`\n : `Cost summary (5h: ${w5h.total_requests} reqs | 24h: ${w24h.total_requests} reqs)`,\n detail: `5h -> ${formatChannelSummaryText(w5h)} || 24h -> ${formatChannelSummaryText(w24h)}`,\n ...(has429\n ? {\n fix_hint: activeChannel\n ? `429 rate limits detected in last 5h (${activeChannel.channelId}): ${getLocalizedBehavior(activeChannel.definition.recommended_behaviors, \"throttling_guidance\", locale) ?? activeChannel.definition.recommended_behaviors.throttling_guidance}`\n : \"429 rate limits detected in last 5h. Run `npx agycraft-mcp preflight` to inspect live upstream status.json.\",\n }\n : {}),\n });\n\n if (w24h.deprecated_models_in_use.length > 0) {\n const depList = w24h.deprecated_models_in_use\n .map(\n (d) =>\n `${d.model} (${d.lifecycle}${d.deprecated_date ? `, deprecated ${d.deprecated_date}` : \"\"})`,\n )\n .join(\"; \");\n const hints = w24h.deprecated_models_in_use\n .map((d) =>\n d.replacement_model_id\n ? `${d.model} -> ${d.replacement_model_id}`\n : `${d.model} -> migrate to active model`,\n )\n .join(\"; \");\n checks.push({\n id: \"deprecated_model_in_use\",\n category: \"cost_usage\",\n severity: \"warn\",\n title: `Deprecated/removed model(s) detected in last 24h (${w24h.deprecated_models_in_use.length})`,\n detail: `Used recently: ${depList}.`,\n fix_hint: `Migrate to recommended replacements: ${hints}.`,\n });\n }\n }\n\n // 9. Safety guardrail check\n checks.push({\n id: \"git_safety_guardrail\",\n category: \"safety_guardrail\",\n severity: \"info\",\n title: \"Git safety guardrail template available\",\n detail:\n \"Add the non-destructive Git safety snippet below to GEMINI.md / AGENTS.md to prevent accidental force-pushes or hard resets.\",\n });\n\n const summary = {\n ok: checks.filter((c) => c.severity === \"ok\").length,\n warn: checks.filter((c) => c.severity === \"warn\").length,\n error: checks.filter((c) => c.severity === \"error\").length,\n info: checks.filter((c) => c.severity === \"info\").length,\n };\n\n return {\n generated_at: new Date().toISOString(),\n node_version: nodeVersion,\n checks,\n summary,\n git_safety_guardrail_snippet: GIT_SAFETY_GUARDRAIL_SNIPPET,\n geminiignore_template: GEMINIIGNORE_TEMPLATE,\n };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n const icon: Record<CheckSeverity, string> = {\n ok: \"[OK]\",\n warn: \"[WARN]\",\n error: \"[ERR]\",\n info: \"[INFO]\",\n };\n const lines: string[] = [\n \"agycraft-mcp doctor (100% local, zero secret values inspected)\",\n \"================================================================\",\n ];\n\n for (const check of report.checks) {\n lines.push(`${icon[check.severity]} ${check.title}`);\n lines.push(` ${check.detail}`);\n if (check.fix_hint) {\n lines.push(` Fix: ${check.fix_hint}`);\n }\n }\n\n lines.push(\"\");\n lines.push(\n `Summary: ${report.summary.ok} ok, ${report.summary.warn} warn, ${report.summary.error} error, ${report.summary.info} info`,\n );\n lines.push(\"\");\n lines.push(\"--- Recommended Git Safety Guardrail Snippet ---\");\n lines.push(report.git_safety_guardrail_snippet);\n\n const missingIgnore = report.checks.some(\n (c) => c.id === \"geminiignore_check\" && c.severity === \"warn\",\n );\n if (missingIgnore) {\n lines.push(\"\");\n lines.push(\"--- Recommended .geminiignore Template ---\");\n lines.push(report.geminiignore_template.trimEnd());\n }\n\n return lines.join(\"\\n\");\n}\n\nexport async function runDoctorCost(\n options?: DoctorCostOptions,\n): Promise<DoctorCostReport> {\n const window: CostSummaryWindow = options?.window ?? \"24h\";\n const nowMs = options?.nowMs ?? Date.now();\n const [modelsSnapshot, authContext] = await Promise.all([\n loadOfflineModelsSnapshot(options?.snapshotsDir),\n detectAuthContext({\n homeDir: options?.homeDir,\n env: options?.env,\n }),\n ]);\n\n const rollupRes = await queryRollups({\n rollupsDir: options?.rollupsDir,\n usageLogPath: options?.usageLogPath,\n geminiOtelPath: options?.geminiOtelPath,\n brainDir: options?.brainDir,\n historyPath: options?.historyPath,\n cliLogDir: options?.cliLogDir,\n saltPath: options?.saltPath,\n models: modelsSnapshot.models,\n normalizationRules: modelsSnapshot.normalization_rules,\n window,\n granularity: \"hourly\",\n product: \"all\",\n scope: \"global\",\n authMode: \"all\",\n readonly: true,\n coldBrainDays: 1,\n transcriptAuthMode: authContext.active_auth_mode,\n hasMixedAuth: authContext.has_mixed_auth,\n nowMs,\n });\n\n const breakdown: RollupWindowCostSummary = rollupRes.cost_breakdown ?? {\n window,\n by_model_auth: [],\n by_auth_channel: [],\n deprecated_models_in_use: [],\n rate_limit_429_count: 0,\n total_requests: 0,\n total_tokens: 0,\n };\n\n const notes: string[] = [\n \"Shadow Cost (google_oauth) measures shared subscription quota pressure only and is strictly separated from Estimated GCP / API Spend.\",\n \"100% local readonly calculation; zero session hashes, project hashes, or local paths exposed.\",\n ];\n if (breakdown.rate_limit_429_count > 0) {\n notes.push(\n `Detected ${breakdown.rate_limit_429_count} rate-limit (429) event(s). Run \\`npx agycraft-mcp preflight\\` to check live upstream status.json.`,\n );\n }\n if (breakdown.deprecated_models_in_use.length > 0) {\n const replacements = breakdown.deprecated_models_in_use\n .map((d) => `${d.model} -> ${d.replacement_model_id ?? \"active model\"}`)\n .join(\"; \");\n notes.push(`Deprecated/removed model(s) in window: ${replacements}.`);\n }\n\n return {\n generated_at: new Date(nowMs).toISOString(),\n window,\n data_source: rollupRes.time_series_meta.source,\n auth_groups: breakdown.by_auth_channel,\n by_model_auth: breakdown.by_model_auth,\n deprecated_models_in_use: breakdown.deprecated_models_in_use,\n rate_limit_429_count: breakdown.rate_limit_429_count,\n total_requests: breakdown.total_requests,\n total_tokens: breakdown.total_tokens,\n notes,\n };\n}\n\nexport function formatDoctorCostReport(report: DoctorCostReport): string {\n const lines: string[] = [\n `agycraft-mcp doctor --cost (window: ${report.window}, source: ${report.data_source}, readonly)`,\n \"================================================================\",\n ];\n\n if (report.auth_groups.length === 0) {\n lines.push(\"No token usage recorded in this window.\");\n } else {\n lines.push(\"Channel Cost Summary (strictly isolated by auth_mode):\");\n for (const g of report.auth_groups) {\n const suffix = g.auth_mode === \"google_oauth\" ? \"equiv\" : \"est.\";\n lines.push(\n ` - ${g.label} [${g.auth_mode}]: ~$${g.estimated_total_usd.toFixed(4)} ${suffix} (${g.requests} reqs, ${g.total_tokens.toLocaleString()} tokens, saved ~$${g.estimated_cache_savings_usd.toFixed(4)})`,\n );\n }\n\n lines.push(\"\");\n lines.push(\"Breakdown by Canonical Model x Auth Mode:\");\n for (const row of report.by_model_auth) {\n const estTag =\n row.estimated_requests > 0\n ? ` [est_from_cli_log:${row.estimated_requests}]`\n : \"\";\n const depTag =\n row.lifecycle === \"deprecated\" || row.lifecycle === \"removed\"\n ? ` [${row.lifecycle.toUpperCase()} -> ${row.replacement_model_id ?? \"migrate\"}]`\n : \"\";\n lines.push(\n ` * ${row.model} (${row.auth_mode})${depTag}${estTag}: ${row.requests} reqs | ${row.total_tokens.toLocaleString()} tok | cache ${row.cache_hit_rate_pct}% | ~$${row.estimated_total_usd.toFixed(4)} (saved ~$${row.estimated_cache_savings_usd.toFixed(4)})`,\n );\n }\n }\n\n lines.push(\"\");\n for (const note of report.notes) {\n lines.push(`Note: ${note}`);\n }\n return lines.join(\"\\n\");\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AuthContext, AuthMode, ChannelsSnapshot } from \"../types.js\";\nimport {\n ChannelRegistry,\n loadBundledChannelRegistry,\n type CompiledAuthChannel,\n} from \"./channel-registry.js\";\nimport { collectCliLogSignals, type CliLogAuthEvent } from \"./cli-log.js\";\n\nexport interface DetectAuthContextOptions {\n homeDir?: string;\n env?: NodeJS.ProcessEnv;\n geminiSettingsPath?: string;\n agySettingsPath?: string;\n oauthCredsPath?: string;\n adcPath?: string;\n cliLogDir?: string | null;\n cliLogEvents?: CliLogAuthEvent[];\n nowMs?: number;\n registry?: ChannelRegistry;\n channelsSnapshot?: ChannelsSnapshot;\n}\n\nasync function readSafeJsonObject(filePath: string): Promise<Record<string, unknown> | null> {\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // Missing or malformed settings file\n }\n return null;\n}\n\nfunction expandHomePath(pattern: string, home: string): string {\n if (pattern.startsWith(\"~/\")) {\n return join(home, pattern.slice(2));\n }\n return pattern;\n}\n\nfunction resolveLocalConfigPath(\n pattern: string,\n home: string,\n oauthOverride?: string,\n adcOverride?: string,\n): string {\n if (oauthOverride && pattern.endsWith(\"oauth_creds.json\")) {\n return oauthOverride;\n }\n if (adcOverride && pattern.endsWith(\"application_default_credentials.json\")) {\n return adcOverride;\n }\n return expandHomePath(pattern, home);\n}\n\nfunction hasNonEmptySettingsKey(\n settings: Record<string, unknown> | null,\n key: string,\n): boolean {\n if (!settings) {\n return false;\n }\n const val = settings[key];\n return Boolean(\n val &&\n (typeof val !== \"object\" ||\n (!Array.isArray(val) && Object.keys(val as Record<string, unknown>).length > 0)),\n );\n}\n\n/**\n * Readonly detector for local Auth Channels (OAuth / Vertex ADC / AI Studio Key / Express / Custom).\n * PRIVACY RED LINE:\n * - Credential files (oauth_creds.json, application_default_credentials.json, etc.) are ONLY checked via existsSync.\n * - NEVER reads, parses, or logs credential file contents or env var values.\n * - 100% data-driven by ChannelRegistry (zero hardcoded auth channel if/else branches).\n */\nexport async function detectAuthContext(\n options?: DetectAuthContextOptions,\n): Promise<AuthContext> {\n const home = options?.homeDir ?? homedir();\n const env = options?.env ?? process.env;\n const nowMs = options?.nowMs ?? Date.now();\n const registry =\n options?.registry ??\n (options?.channelsSnapshot\n ? ChannelRegistry.fromSnapshot(options.channelsSnapshot)\n : loadBundledChannelRegistry());\n\n const geminiSettingsPath =\n options?.geminiSettingsPath ?? join(home, \".gemini\", \"settings.json\");\n const agySettingsPath =\n options?.agySettingsPath ??\n join(home, \".gemini\", \"antigravity-cli\", \"settings.json\");\n const oauthCredsPath =\n options?.oauthCredsPath ?? join(home, \".gemini\", \"oauth_creds.json\");\n const adcPath =\n options?.adcPath ??\n join(home, \".config\", \"gcloud\", \"application_default_credentials.json\");\n const hasDefaultOauthCredsFile = existsSync(oauthCredsPath);\n const hasDefaultAdcFile = existsSync(adcPath);\n\n const [geminiSettings, agySettings] = await Promise.all([\n readSafeJsonObject(geminiSettingsPath),\n readSafeJsonObject(agySettingsPath),\n ]);\n\n let selectedChannel: CompiledAuthChannel | undefined;\n if (geminiSettings) {\n const security = geminiSettings[\"security\"];\n if (security && typeof security === \"object\" && !Array.isArray(security)) {\n const auth = (security as Record<string, unknown>)[\"auth\"];\n if (auth && typeof auth === \"object\" && !Array.isArray(auth)) {\n selectedChannel = registry.matchSettingsAuthType(\n (auth as Record<string, unknown>)[\"selectedType\"],\n );\n }\n }\n }\n\n // Optional Stage 1: runtime cli-*.log events (last 12h) when cliLogDir or cliLogEvents provided\n let runtimeChannel: CompiledAuthChannel | undefined;\n const runtimeEvents =\n options?.cliLogEvents ??\n (options?.cliLogDir\n ? (\n await collectCliLogSignals({\n cliLogDir: options.cliLogDir,\n nowMs,\n registry,\n })\n ).authEvents\n : []);\n if (runtimeEvents.length > 0) {\n const maxStaleMs = 12 * 3600_000;\n for (let i = runtimeEvents.length - 1; i >= 0; i -= 1) {\n const ev = runtimeEvents[i]!;\n if (ev.tsMs <= nowMs && nowMs - ev.tsMs <= maxStaleMs) {\n const ch = registry.getChannel(ev.authMode);\n if (ch) {\n runtimeChannel = ch;\n break;\n }\n }\n }\n }\n\n const channelsInOrder = registry.getChannels();\n const channelsByPriority = registry.getChannelsByPriorityDesc();\n\n const envHitSet = new Set<string>();\n const fileHitSet = new Set<string>();\n const agyConfigHitSet = new Set<string>();\n const detectedChannelIds: string[] = [];\n const envConflicts: Record<string, string[]> = {};\n\n for (const ch of channelsInOrder) {\n const hasEnv = registry.checkEnvPresence(ch, env);\n const hasFile = ch.localConfigFiles.some((p) => {\n const targetPath = resolveLocalConfigPath(p, home, oauthCredsPath, adcPath);\n if (targetPath === oauthCredsPath) {\n return hasDefaultOauthCredsFile;\n }\n if (targetPath === adcPath) {\n return hasDefaultAdcFile;\n }\n return existsSync(targetPath);\n });\n const hasAgyKey = ch.agySettingsKeys.some((k) =>\n hasNonEmptySettingsKey(agySettings, k),\n );\n const hasSelected = selectedChannel?.channelId === ch.channelId;\n const hasRuntime = runtimeChannel?.channelId === ch.channelId;\n\n if (hasEnv) {\n envHitSet.add(ch.channelId);\n }\n if (hasFile) {\n fileHitSet.add(ch.channelId);\n }\n if (hasAgyKey) {\n agyConfigHitSet.add(ch.channelId);\n }\n\n if (hasEnv || hasFile || hasAgyKey || hasSelected || hasRuntime) {\n detectedChannelIds.push(ch.channelId);\n const conflicts = registry.getMatchedEnvConflicts(ch, env);\n if (conflicts.length > 0) {\n envConflicts[ch.channelId] = conflicts;\n }\n }\n }\n\n // Precedence: L1 runtime cli-*.log > L2 env (priority desc) > AGY settings key > Gemini selectedType > L3 local credential files\n let activeChannelId: string = \"unknown\";\n if (runtimeChannel) {\n activeChannelId = runtimeChannel.channelId;\n } else {\n const envWinner = channelsByPriority.find((ch) => envHitSet.has(ch.channelId));\n if (envWinner) {\n activeChannelId = envWinner.channelId;\n } else {\n const agyWinner = channelsByPriority.find((ch) => agyConfigHitSet.has(ch.channelId));\n if (agyWinner) {\n activeChannelId = agyWinner.channelId;\n } else if (selectedChannel) {\n activeChannelId = selectedChannel.channelId;\n } else {\n const fileWinner = channelsInOrder.find((ch) => fileHitSet.has(ch.channelId));\n if (fileWinner) {\n activeChannelId = fileWinner.channelId;\n }\n }\n }\n }\n\n const activeAuthMode: AuthMode =\n activeChannelId === \"unknown\" ? \"unknown\" : registry.toLegacyAuthMode(activeChannelId);\n const detectedModes: AuthMode[] = detectedChannelIds.map((id) =>\n registry.toLegacyAuthMode(id),\n );\n\n const hasMixedAuth = detectedChannelIds.length > 1;\n const isolationNote = hasMixedAuth\n ? `Mixed auth contexts detected (${detectedModes.join(\", \")}). Active mode inferred as ${activeAuthMode}; auth channel quotas and credentials are isolated—verify active auth before attributing 429/401/403 errors.`\n : activeAuthMode !== \"unknown\"\n ? `Single auth context detected (${activeAuthMode}); no cross-auth mixing.`\n : \"No local auth credentials or env flags detected (active_auth_mode: unknown).\";\n\n return {\n active_auth_mode: activeAuthMode,\n detected_modes: detectedModes,\n has_mixed_auth: hasMixedAuth,\n isolation_note: isolationNote,\n active_channel_id: activeChannelId,\n detected_channels: detectedChannelIds,\n ...(Object.keys(envConflicts).length > 0 ? { env_conflicts: envConflicts } : {}),\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getSnapshotsDir } from \"../paths.js\";\nimport type { SnapshotClient } from \"../remote/snapshot-client.js\";\nimport type { AuthChannelDefinition, AuthMode, ChannelsSnapshot } from \"../types.js\";\n\nexport interface CompiledAuthChannel {\n definition: AuthChannelDefinition;\n channelId: string;\n legacyId?: string;\n aliases: string[];\n endpointRegexes: RegExp[];\n logAuthMethodValues: Set<string>;\n settingsAuthTypePatterns: string[];\n envPresenceKeys: string[];\n envTrueOnlyKeys: Set<string>;\n envConflictKeys: string[];\n localConfigFiles: string[];\n agySettingsKeys: string[];\n errorSignatureRegexes: RegExp[];\n}\n\nfunction compileRegexList(patterns: string[] | undefined): RegExp[] {\n if (!Array.isArray(patterns)) {\n return [];\n }\n const compiled: RegExp[] = [];\n for (const p of patterns) {\n if (typeof p !== \"string\" || p.trim().length === 0) {\n continue;\n }\n try {\n compiled.push(new RegExp(p, \"i\"));\n } catch {\n // Skip invalid regex from remote snapshot safely\n }\n }\n return compiled;\n}\n\nfunction isNonEmptyEnv(val: string | undefined): boolean {\n return typeof val === \"string\" && val.trim().length > 0;\n}\n\nfunction isTruthyEnv(val: string | undefined): boolean {\n if (typeof val !== \"string\") {\n return false;\n }\n const lower = val.trim().toLowerCase();\n return lower === \"1\" || lower === \"true\" || lower === \"yes\";\n}\n\nexport class ChannelRegistry {\n private readonly channels: CompiledAuthChannel[];\n private readonly byIdOrAlias = new Map<string, CompiledAuthChannel>();\n\n constructor(snapshot: ChannelsSnapshot) {\n const rawChannels = Array.isArray(snapshot.channels)\n ? snapshot.channels\n : Array.isArray(snapshot.auth_channels)\n ? snapshot.auth_channels\n : [];\n this.channels = rawChannels.map((def) => {\n const aliases = Array.isArray(def.aliases) ? def.aliases : [];\n const compiled: CompiledAuthChannel = {\n definition: def,\n channelId: def.channel_id,\n legacyId: def.legacy_id,\n aliases,\n endpointRegexes: compileRegexList(def.detection?.endpoint_regexes),\n logAuthMethodValues: new Set(\n (def.detection?.log_auth_method_values ?? []).map((v) => v.trim().toLowerCase()),\n ),\n settingsAuthTypePatterns: (def.detection?.settings_auth_type_patterns ?? []).map((v) =>\n v.trim().toLowerCase(),\n ),\n envPresenceKeys: def.detection?.env_presence_keys ?? [],\n envTrueOnlyKeys: new Set(def.detection?.env_true_only_keys ?? []),\n envConflictKeys: def.detection?.env_conflict_keys ?? [],\n localConfigFiles: def.detection?.local_config_files ?? [],\n agySettingsKeys: def.detection?.agy_settings_keys ?? [],\n errorSignatureRegexes: compileRegexList(def.error_signature_regexes),\n };\n\n this.byIdOrAlias.set(def.channel_id.toLowerCase(), compiled);\n if (def.legacy_id) {\n this.byIdOrAlias.set(def.legacy_id.toLowerCase(), compiled);\n }\n for (const alias of aliases) {\n this.byIdOrAlias.set(alias.toLowerCase(), compiled);\n }\n return compiled;\n });\n }\n\n static fromSnapshot(snapshot: ChannelsSnapshot): ChannelRegistry {\n return new ChannelRegistry(snapshot);\n }\n\n getChannels(): CompiledAuthChannel[] {\n return this.channels;\n }\n\n getChannelsByPriorityDesc(): CompiledAuthChannel[] {\n return [...this.channels].sort(\n (a, b) => (b.definition.priority ?? 0) - (a.definition.priority ?? 0),\n );\n }\n\n getChannel(idOrAlias: string | undefined | null): CompiledAuthChannel | undefined {\n if (!idOrAlias || typeof idOrAlias !== \"string\") {\n return undefined;\n }\n return this.byIdOrAlias.get(idOrAlias.trim().toLowerCase());\n }\n\n hasChannel(idOrAlias: string | undefined | null): boolean {\n return this.getChannel(idOrAlias) !== undefined;\n }\n\n resolveChannelId(idOrAlias: string): string {\n const found = this.getChannel(idOrAlias);\n return found ? found.channelId : idOrAlias;\n }\n\n toLegacyAuthMode(idOrAlias: string): AuthMode {\n const found = this.getChannel(idOrAlias);\n if (!found) {\n return idOrAlias;\n }\n return found.legacyId ?? found.channelId;\n }\n\n matchesChannel(modeA: string | undefined | null, modeB: string | undefined | null): boolean {\n if (!modeA || !modeB) {\n return false;\n }\n const normA = this.resolveChannelId(modeA.trim()).toLowerCase();\n const normB = this.resolveChannelId(modeB.trim()).toLowerCase();\n return normA === normB;\n }\n\n matchEndpoint(line: string): CompiledAuthChannel | undefined {\n for (const ch of this.getChannelsByPriorityDesc()) {\n for (const re of ch.endpointRegexes) {\n if (re.test(line)) {\n return ch;\n }\n }\n }\n return undefined;\n }\n\n matchLogAuthMethod(rawMethod: string): CompiledAuthChannel | undefined {\n const lower = rawMethod.trim().toLowerCase();\n if (!lower) {\n return undefined;\n }\n for (const ch of this.getChannelsByPriorityDesc()) {\n if (ch.logAuthMethodValues.has(lower)) {\n return ch;\n }\n }\n for (const ch of this.getChannelsByPriorityDesc()) {\n for (const val of ch.logAuthMethodValues) {\n if (val.length >= 3 && lower.includes(val)) {\n return ch;\n }\n }\n }\n return undefined;\n }\n\n matchSettingsAuthType(rawType: unknown): CompiledAuthChannel | undefined {\n if (typeof rawType !== \"string\") {\n return undefined;\n }\n const lower = rawType.trim().toLowerCase();\n if (!lower) {\n return undefined;\n }\n for (const ch of this.getChannelsByPriorityDesc()) {\n for (const pat of ch.settingsAuthTypePatterns) {\n if (pat && lower.includes(pat)) {\n return ch;\n }\n }\n }\n return undefined;\n }\n\n matchErrorText(errorText: string): CompiledAuthChannel | undefined {\n let best: CompiledAuthChannel | undefined;\n let bestHits = 0;\n let bestPriority = -Infinity;\n\n for (const ch of this.channels) {\n let hits = 0;\n for (const re of ch.errorSignatureRegexes) {\n if (re.test(errorText)) {\n hits += 1;\n }\n }\n if (hits > 0) {\n const prio = ch.definition.priority ?? 0;\n if (hits > bestHits || (hits === bestHits && prio > bestPriority)) {\n best = ch;\n bestHits = hits;\n bestPriority = prio;\n }\n }\n }\n return best;\n }\n\n checkEnvPresence(channel: CompiledAuthChannel, env: NodeJS.ProcessEnv): boolean {\n for (const key of channel.envPresenceKeys) {\n const val = env[key];\n if (channel.envTrueOnlyKeys.has(key)) {\n if (isTruthyEnv(val)) {\n return true;\n }\n } else if (isNonEmptyEnv(val)) {\n return true;\n }\n }\n return false;\n }\n\n getMatchedEnvConflicts(channel: CompiledAuthChannel, env: NodeJS.ProcessEnv): string[] {\n const hits: string[] = [];\n for (const key of channel.envConflictKeys) {\n if (isNonEmptyEnv(env[key])) {\n hits.push(key);\n }\n }\n return hits;\n }\n}\n\nlet cachedDefaultRegistry: ChannelRegistry | null = null;\n\nexport function loadBundledChannelRegistry(snapshotsDir?: string): ChannelRegistry {\n if (!snapshotsDir && cachedDefaultRegistry) {\n return cachedDefaultRegistry;\n }\n const dir = snapshotsDir ?? getSnapshotsDir();\n try {\n const raw = readFileSync(join(dir, \"channels.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as ChannelsSnapshot;\n const reg = new ChannelRegistry(parsed);\n if (!snapshotsDir) {\n cachedDefaultRegistry = reg;\n }\n return reg;\n } catch {\n return new ChannelRegistry({\n schema_version: \"1.0.0\",\n channels: [],\n });\n }\n}\n\nexport async function loadChannelRegistry(client?: SnapshotClient): Promise<ChannelRegistry> {\n if (!client) {\n return loadBundledChannelRegistry();\n }\n try {\n const snap = await client.get(\"channels\");\n return new ChannelRegistry(snap.data);\n } catch {\n return loadBundledChannelRegistry();\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nlet cachedPkgVersion: string | null = null;\n\nexport function getPackageVersion(): string {\n if (cachedPkgVersion) {\n return cachedPkgVersion;\n }\n try {\n const pkgPath = new URL(\"../package.json\", import.meta.url);\n const raw = readFileSync(pkgPath, \"utf8\");\n const parsed = JSON.parse(raw) as { version?: unknown };\n if (typeof parsed.version === \"string\" && parsed.version.trim().length > 0) {\n cachedPkgVersion = parsed.version.trim();\n return cachedPkgVersion;\n }\n } catch {\n // Fallback to static package version if package.json cannot be read\n }\n cachedPkgVersion = \"0.2.2\";\n return cachedPkgVersion;\n}\n\nexport function getConfigDir(): string {\n const override = process.env.AGYCRAFT_CONFIG_DIR;\n if (override && override.trim().length > 0) {\n return resolve(override.trim());\n }\n const xdg = process.env.XDG_CONFIG_HOME;\n if (xdg && xdg.trim().length > 0) {\n return join(resolve(xdg.trim()), \"agycraft\");\n }\n return join(homedir(), \".config\", \"agycraft\");\n}\n\nexport function getUsageLogPath(): string {\n return join(getConfigDir(), \"usage.jsonl\");\n}\n\nexport function getCacheDir(): string {\n return join(getConfigDir(), \"cache\");\n}\n\nexport function getRollupsDir(): string {\n return join(getConfigDir(), \"rollups\");\n}\n\nexport function getSaltFilePath(): string {\n return join(getConfigDir(), \".salt\");\n}\n\nexport function getDefaultGeminiTelemetryPath(): string {\n const override = process.env.AGYCRAFT_GEMINI_OTEL_PATH;\n if (override && override.trim().length > 0) {\n return resolve(override.trim());\n }\n return join(homedir(), \".gemini\", \"telemetry_stats.jsonl\");\n}\n\nconst BRAIN_SCAN_DISABLED_VALUES = new Set([\"none\", \"off\", \"false\"]);\n\nexport function isBrainScanDisabledValue(value: string): boolean {\n return BRAIN_SCAN_DISABLED_VALUES.has(value.trim().toLowerCase());\n}\n\nexport function getAgyBrainDir(): string | null {\n const override = process.env.AGYCRAFT_BRAIN_DIR;\n if (override && override.trim().length > 0) {\n const trimmed = override.trim();\n if (isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n const configOverride = process.env.AGYCRAFT_CONFIG_DIR;\n if (configOverride && configOverride.trim().length > 0) {\n // Sandbox isolation: skip scanning global AGY brain dir unless AGYCRAFT_BRAIN_DIR is explicitly set\n return null;\n }\n return join(homedir(), \".gemini\", \"antigravity-cli\", \"brain\");\n}\n\nexport function getAgyHistoryPath(): string | null {\n const override = process.env.AGYCRAFT_HISTORY_PATH;\n if (override && override.trim().length > 0) {\n const trimmed = override.trim();\n if (isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n const configOverride = process.env.AGYCRAFT_CONFIG_DIR;\n if (configOverride && configOverride.trim().length > 0) {\n // Sandbox isolation: skip scanning global AGY history.jsonl unless AGYCRAFT_HISTORY_PATH is explicitly set\n return null;\n }\n return join(homedir(), \".gemini\", \"antigravity-cli\", \"history.jsonl\");\n}\n\nexport function getAgyCliLogDir(): string | null {\n const override = process.env.AGYCRAFT_CLI_LOG_DIR;\n if (override && override.trim().length > 0) {\n const trimmed = override.trim();\n if (isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n const configOverride = process.env.AGYCRAFT_CONFIG_DIR;\n if (configOverride && configOverride.trim().length > 0) {\n // Sandbox isolation: skip scanning global AGY log dir unless AGYCRAFT_CLI_LOG_DIR is explicitly set\n return null;\n }\n return join(homedir(), \".gemini\", \"antigravity-cli\", \"log\");\n}\n\nexport function getSnapshotsDir(): string {\n const override = process.env.AGYCRAFT_SNAPSHOTS_DIR;\n if (override && override.trim().length > 0) {\n return resolve(override.trim());\n }\n // Works from both src/ (vitest/tsx) and dist/ (built bundle)\n return resolve(new URL(\"../snapshots\", import.meta.url).pathname);\n}\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { normalizeModelId } from \"../analyzers/token-window.js\";\nimport { getAgyCliLogDir, isBrainScanDisabledValue } from \"../paths.js\";\nimport {\n type UsageRecord,\n getOrCreateLocalSalt,\n sanitizeUsagePayload,\n} from \"../privacy.js\";\nimport type { AuthMode, ChannelsSnapshot } from \"../types.js\";\nimport { ChannelRegistry, loadBundledChannelRegistry } from \"./channel-registry.js\";\n\nexport interface CliLogAuthEvent {\n tsMs: number;\n authMode: AuthMode;\n channelId?: string;\n source: \"apply_auth_result\" | \"endpoint_match\" | \"daily_cloudcode\" | \"aiplatform\" | string;\n modelHint?: string;\n}\n\nexport interface CollectCliLogOptions {\n cliLogDir?: string | null;\n sinceMs?: number;\n nowMs?: number;\n salt?: string;\n saltPath?: string;\n fallbackAuthMode?: AuthMode;\n hasMixedAuth?: boolean;\n registry?: ChannelRegistry;\n channelsSnapshot?: ChannelsSnapshot;\n}\n\nexport interface CliLogCollection {\n authEvents: CliLogAuthEvent[];\n backgroundRecords: UsageRecord[];\n filesScanned: number;\n}\n\nfunction resolveCliLogDir(explicit: string | null | undefined): string | null {\n if (explicit === null) {\n return null;\n }\n if (explicit !== undefined) {\n const trimmed = explicit.trim();\n if (trimmed.length === 0 || isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n return getAgyCliLogDir();\n}\n\nexport function extractCliLogTimestampMs(line: string): number | null {\n // 1. ISO-8601 timestamp (e.g. 2026-12-01T12:34:56.789Z or 2026-12-01T12:34:56+08:00)\n const isoMatch = line.match(\n /\\b(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})?)\\b/,\n );\n if (isoMatch?.[1]) {\n const parsed = Date.parse(isoMatch[1]);\n if (!Number.isNaN(parsed)) {\n return parsed;\n }\n }\n\n // 2. Standard Go / CLI log prefix: 2026/12/01 12:34:56 or 2026-12-01 12:34:56(.123)\n const dateTimeMatch = line.match(\n /\\b(\\d{4})[/-](\\d{2})[/-](\\d{2})\\s+(\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)\\b/,\n );\n if (dateTimeMatch) {\n const normalized = `${dateTimeMatch[1]}-${dateTimeMatch[2]}-${dateTimeMatch[3]}T${dateTimeMatch[4]}Z`;\n const parsed = Date.parse(normalized);\n if (!Number.isNaN(parsed)) {\n return parsed;\n }\n }\n\n return null;\n}\n\nfunction mapCliAuthMethod(raw: string, registry: ChannelRegistry): { authMode: AuthMode; channelId: string } | null {\n const matched = registry.matchLogAuthMethod(raw);\n if (!matched) {\n return null;\n }\n return {\n authMode: registry.toLegacyAuthMode(matched.channelId),\n channelId: matched.channelId,\n };\n}\n\nexport function resolveAuthModeFromCliLogs(\n authEvents: CliLogAuthEvent[],\n tsMs: number,\n options: {\n fallbackAuthMode?: AuthMode;\n hasMixedAuth?: boolean;\n } = {},\n): AuthMode {\n const maxStaleMs = 12 * 3600_000;\n let latestBefore: CliLogAuthEvent | null = null;\n for (let i = authEvents.length - 1; i >= 0; i -= 1) {\n const ev = authEvents[i]!;\n if (ev.tsMs <= tsMs) {\n if (tsMs - ev.tsMs <= maxStaleMs) {\n latestBefore = ev;\n }\n break;\n }\n }\n if (latestBefore) {\n return latestBefore.authMode;\n }\n\n if (options.hasMixedAuth) {\n // Under mixed auth without cli-*.log coverage for this interval, avoid misattributing consumer traffic to GCP\n return \"unknown\";\n }\n return options.fallbackAuthMode ?? \"unknown\";\n}\n\ninterface PendingMonitorCall {\n tsMs: number;\n inputChars: number;\n model: string;\n}\n\n/**\n * Strictly read-only, zero-PII collector for AGY cli-*.log files.\n * - Never captures or retains emails, GCP project IDs, prompts, arguments, or file paths.\n * - Extracts runtime auth channel switches (consumer/daily-cloudcode-pa vs gcp/aiplatform)\n * and estimates lightweight llm_monitor.go background calls by character length.\n */\nexport async function collectCliLogSignals(\n options?: CollectCliLogOptions,\n): Promise<CliLogCollection> {\n const cliLogDir = resolveCliLogDir(options?.cliLogDir);\n if (cliLogDir === null) {\n return { authEvents: [], backgroundRecords: [], filesScanned: 0 };\n }\n\n let fileNames: string[] = [];\n try {\n const entries = await readdir(cliLogDir, { withFileTypes: true });\n fileNames = entries\n .filter((e) => e.isFile() && /^cli-.*\\.log$/i.test(e.name))\n .map((e) => e.name)\n .sort();\n } catch {\n return { authEvents: [], backgroundRecords: [], filesScanned: 0 };\n }\n\n const nowMs = options?.nowMs ?? Date.now();\n const sinceMs = options?.sinceMs;\n const salt = options?.salt ?? (await getOrCreateLocalSalt(options?.saltPath));\n const registry =\n options?.registry ??\n (options?.channelsSnapshot\n ? ChannelRegistry.fromSnapshot(options.channelsSnapshot)\n : loadBundledChannelRegistry());\n\n const authEvents: CliLogAuthEvent[] = [];\n const pendingBackground: Array<{\n tsMs: number;\n fileName: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n turnIndex: number;\n }> = [];\n\n let filesScanned = 0;\n\n for (const fileName of fileNames) {\n const filePath = join(cliLogDir, fileName);\n let st;\n try {\n st = await stat(filePath);\n } catch {\n continue;\n }\n\n if (sinceMs !== undefined && st.mtimeMs < sinceMs - 86_400_000) {\n continue;\n }\n\n let rawText: string;\n try {\n rawText = await readFile(filePath, \"utf8\");\n } catch {\n continue;\n }\n filesScanned += 1;\n\n let lastLineTsMs = st.mtimeMs;\n let pendingTsMs: number | null = null;\n let pendingInputChars = 0;\n let pendingModel: string | null = null;\n let bgTurnIndex = 0;\n\n for (const line of rawText.split(\"\\n\")) {\n if (!line.trim()) {\n continue;\n }\n\n const lineTs = extractCliLogTimestampMs(line);\n if (lineTs !== null) {\n lastLineTsMs = lineTs;\n }\n const effectiveTs = lineTs ?? lastLineTsMs;\n\n // 1. Auth channel signals (strictly zero PII — never capture email= or projects/<id>)\n if (line.includes(\"applyAuthResult\")) {\n const authMatch = line.match(/\\bauthMethod=([a-zA-Z0-9_-]+)/i);\n if (authMatch?.[1]) {\n const mapped = mapCliAuthMethod(authMatch[1], registry);\n if (mapped) {\n authEvents.push({\n tsMs: effectiveTs,\n authMode: mapped.authMode,\n channelId: mapped.channelId,\n source: \"apply_auth_result\",\n });\n }\n }\n }\n\n const matchedEndpointChannel = registry.matchEndpoint(line);\n if (matchedEndpointChannel) {\n const modelMatch = line.match(\n /\\/models\\/([a-zA-Z0-9._:@-]+)/,\n );\n const modelHint = modelMatch?.[1]\n ? normalizeModelId(modelMatch[1])\n : undefined;\n authEvents.push({\n tsMs: effectiveTs,\n authMode: registry.toLegacyAuthMode(matchedEndpointChannel.channelId),\n channelId: matchedEndpointChannel.channelId,\n source: \"endpoint_match\",\n ...(modelHint ? { modelHint } : {}),\n });\n }\n\n // 2. llm_monitor.go background lightweight calls\n const trajMatch = line.match(/Trajectory formatted,\\s*length:\\s*(\\d+)/i);\n if (trajMatch?.[1]) {\n pendingTsMs = effectiveTs;\n pendingInputChars = Number(trajMatch[1]);\n pendingModel = pendingModel ?? \"MODEL_TIER_FLASH_LITE\";\n }\n\n const callingMatch = line.match(/Calling LLM\\s*\\(\\s*model:\\s*([^)\\s]+)/i);\n if (callingMatch?.[1]) {\n pendingTsMs = pendingTsMs ?? effectiveTs;\n pendingModel = callingMatch[1];\n }\n\n const respMatch = line.match(/LLM response received,\\s*length:\\s*(\\d+)/i);\n if (respMatch?.[1]) {\n const outputChars = Number(respMatch[1]);\n const inputChars = pendingInputChars;\n const rawModel = pendingModel ?? \"MODEL_TIER_FLASH_LITE\";\n const eventTs = pendingTsMs ?? effectiveTs;\n pendingTsMs = null;\n pendingInputChars = 0;\n pendingModel = null;\n\n if (eventTs <= nowMs + 60_000 && (sinceMs === undefined || eventTs >= sinceMs)) {\n const inputTokens =\n inputChars > 0 ? Math.max(1, Math.round(inputChars / 4)) : 0;\n const outputTokens =\n outputChars > 0 ? Math.max(1, Math.round(outputChars / 4)) : 0;\n if (inputTokens > 0 || outputTokens > 0) {\n bgTurnIndex += 1;\n pendingBackground.push({\n tsMs: eventTs,\n fileName,\n model: normalizeModelId(rawModel),\n inputTokens,\n outputTokens,\n turnIndex: bgTurnIndex,\n });\n }\n }\n }\n }\n }\n\n authEvents.sort((a, b) => a.tsMs - b.tsMs);\n\n const backgroundRecords: UsageRecord[] = pendingBackground.map((bg) => {\n const resolvedAuth = resolveAuthModeFromCliLogs(authEvents, bg.tsMs, {\n fallbackAuthMode: options?.fallbackAuthMode,\n hasMixedAuth: options?.hasMixedAuth,\n });\n return sanitizeUsagePayload(\n {\n ts: new Date(bg.tsMs).toISOString(),\n provider: \"antigravity\",\n product: \"agy\",\n session_id: `cli-log-monitor:${bg.fileName}`,\n model: bg.model,\n input_tokens: bg.inputTokens,\n cache_read_tokens: 0,\n output_tokens: bg.outputTokens,\n thinking_tokens: 0,\n tool_calls: 0,\n turn_index: bg.turnIndex,\n project_hash: null,\n auth_mode: resolvedAuth,\n data_quality: \"estimated_from_cli_log\",\n },\n salt,\n );\n });\n\n return {\n authEvents,\n backgroundRecords,\n filesScanned,\n };\n}\n","import type { UsageRecord } from \"../collectors/agy-hook.js\";\nimport type {\n AuthMode,\n FallbackPricingConfig,\n ModelEntry,\n NormalizationRules,\n} from \"../types.js\";\n\nexport type UsageWindow = \"5h\" | \"24h\" | \"7d\" | \"30d\" | \"all\";\n\nexport interface ModelUsageBreakdown {\n model: string;\n requests: number;\n uncached_input_tokens: number;\n cache_read_tokens: number;\n input_tokens: number;\n output_tokens: number;\n total_tokens: number;\n cache_hit_rate_pct: number;\n estimated_input_usd: number;\n estimated_cache_savings_usd: number;\n estimated_output_and_thinking_usd: number;\n estimated_total_usd: number;\n shared_bucket_cost_tier: string;\n}\n\nexport interface TokenWindowAnalysis {\n window: UsageWindow;\n product_filter: string;\n scope: \"global\" | \"project\";\n project_hash?: string;\n auth_mode_filter: AuthMode | \"all\";\n unattributed_sessions_excluded?: number;\n unattributed_sessions_note?: string;\n data_mode:\n | \"exact_token_logs\"\n | \"transcript_token_logs\"\n | \"hook_events_without_tokens\"\n | \"transcript_timestamps_only\";\n usage_note?: string;\n record_count: number;\n session_count: number;\n total_uncached_input_tokens: number;\n total_cache_read_tokens: number;\n total_input_tokens: number;\n total_output_tokens: number;\n total_tokens: number;\n cache_hit_rate_pct: number;\n error_count: number;\n rate_limit_429_count: number;\n peak_context_used_pct: number | null;\n oldest_event_ms: number | null;\n below_kv_cache_threshold_requests: number;\n shared_bucket_risk: \"low\" | \"moderate\" | \"high\" | \"critical\";\n thinking_cost_estimate: {\n estimated_input_usd: number;\n estimated_cache_savings_usd: number;\n estimated_output_and_thinking_usd: number;\n estimated_total_usd: number;\n output_cost_share_pct: number;\n note: string;\n };\n by_model: ModelUsageBreakdown[];\n}\n\nexport const WINDOW_MS: Record<Exclude<UsageWindow, \"all\">, number> = {\n \"5h\": 5 * 60 * 60 * 1000,\n \"24h\": 24 * 60 * 60 * 1000,\n \"7d\": 7 * 24 * 60 * 60 * 1000,\n \"30d\": 30 * 24 * 60 * 60 * 1000,\n};\n\nconst DEFAULT_PRICING = {\n input_per_1m_usd: 1.25,\n output_per_1m_usd: 10.0,\n};\n\nconst GENERIC_CODENAMES = new Set([\n \"flash\",\n \"flash-lite\",\n \"live\",\n \"pro\",\n \"lite\",\n \"mini\",\n \"nano\",\n \"ultra\",\n \"2.5 pro\",\n \"2.5 flash\",\n \"2.0 flash\",\n \"2.0 flash-lite\",\n \"1.5 pro\",\n \"1.5 flash\",\n]);\n\nexport interface NormalizedModelInfo {\n canonicalId: string;\n thinkingTier?: string;\n isPlaceholder: boolean;\n}\n\nconst MAX_RULE_PATTERN_LENGTH = 256;\n\nconst DEFAULT_FALLBACK_PRICING: FallbackPricingConfig = {\n default: {\n input_per_1m_usd: DEFAULT_PRICING.input_per_1m_usd,\n cached_ratio: 0.25,\n output_per_1m_usd: DEFAULT_PRICING.output_per_1m_usd,\n tier: \"medium\",\n },\n rules: [\n { match_any: [\"opus\"], input_per_1m_usd: 15.0, cached_ratio: 0.1, output_per_1m_usd: 75.0, tier: \"high\" },\n { match_any: [\"haiku\"], input_per_1m_usd: 0.8, cached_ratio: 0.1, output_per_1m_usd: 4.0, tier: \"low\" },\n { match_any: [\"claude\", \"sonnet\"], input_per_1m_usd: 3.0, cached_ratio: 0.1, output_per_1m_usd: 15.0, tier: \"medium\" },\n { match_any: [\"flash-lite\", \"lite\"], input_per_1m_usd: 0.1, cached_ratio: 0.25, output_per_1m_usd: 0.4, tier: \"low\" },\n { match_any: [\"flash\", \"hydrogen\"], input_per_1m_usd: 0.3, cached_ratio: 0.25, output_per_1m_usd: 2.5, tier: \"low\" },\n { match_any: [\"neon\", \"carbon\"], input_per_1m_usd: 2.0, cached_ratio: 0.25, output_per_1m_usd: 12.0, tier: \"high\" },\n { match_any: [\"pro\"], input_per_1m_usd: 1.25, cached_ratio: 0.25, output_per_1m_usd: 10.0, tier: \"high\" },\n ],\n};\n\nconst DEFAULT_NORMALIZATION_RULES: NormalizationRules = {\n rules_version: 1,\n placeholder_prefixes: [\"MODEL_PLACEHOLDER_\"],\n enum_mappings: {\n MODEL_TIER_FLASH_LITE: \"gemini-3.5-flash-lite\",\n SIR_FLASH_LITE: \"gemini-3.5-flash-lite\",\n MODEL_TIER_FLASH: \"gemini-3.8-flash\",\n },\n prefix_strip_patterns: [\n \"^(?:projects/[^/]+/locations/[^/]+/(?:publishers/[^/]+/)?models/|publishers/[^/]+/models/|models/)\",\n ],\n suffix_strip_patterns: [\n { pattern: \"-tiered-([a-z0-9-]+)$\", capture_thinking_tier_group: 1 },\n { pattern: \"-(low|medium|high|xhigh)$\", capture_thinking_tier_group: 1 },\n { pattern: \"(?:@|-)\\\\d{8}$\" },\n { pattern: \"-preview(?:-\\\\d{2}-\\\\d{2})?$\" },\n { pattern: \"-sonar$\" },\n ],\n version_format_rules: [\n { pattern: \"^(gemini-(?:omni-)?)(\\\\d+)-(\\\\d+)(?=-|$)\", replace: \"$1$2.$3\" },\n { pattern: \"^(claude-(?:[a-z]+-)?)(\\\\d+)\\\\.(\\\\d+)(?=-|$)\", replace: \"$1$2-$3\" },\n ],\n fallback_pricing: DEFAULT_FALLBACK_PRICING,\n};\n\ninterface CompiledSuffixRule {\n regex: RegExp;\n captureTierGroup?: number;\n}\n\ninterface CompiledVersionRule {\n regex: RegExp;\n replace: string;\n}\n\nexport interface CompiledNormalizationRules {\n placeholderPrefixes: string[];\n enumMappings: Map<string, string>;\n prefixStripPatterns: RegExp[];\n suffixStripPatterns: CompiledSuffixRule[];\n versionFormatRules: CompiledVersionRule[];\n fallbackPricing: FallbackPricingConfig;\n}\n\nconst compiledRulesCache = new WeakMap<NormalizationRules, CompiledNormalizationRules>();\nlet defaultCompiledRules: CompiledNormalizationRules | null = null;\n\nfunction safeCompileRegExp(pattern: string, flags = \"i\"): RegExp | null {\n if (\n typeof pattern !== \"string\" ||\n pattern.length === 0 ||\n pattern.length > MAX_RULE_PATTERN_LENGTH\n ) {\n return null;\n }\n try {\n return new RegExp(pattern, flags);\n } catch {\n return null;\n }\n}\n\nexport function compileNormalizationRules(\n rules?: NormalizationRules,\n): CompiledNormalizationRules {\n if (!rules) {\n if (!defaultCompiledRules) {\n defaultCompiledRules = compileNormalizationRules(DEFAULT_NORMALIZATION_RULES);\n }\n return defaultCompiledRules;\n }\n\n const cached = compiledRulesCache.get(rules);\n if (cached) {\n return cached;\n }\n\n const placeholderPrefixes = (\n rules.placeholder_prefixes?.length\n ? rules.placeholder_prefixes\n : DEFAULT_NORMALIZATION_RULES.placeholder_prefixes!\n ).map((p) => p.toUpperCase());\n\n const enumMappings = new Map<string, string>();\n const rawEnums = rules.enum_mappings ?? DEFAULT_NORMALIZATION_RULES.enum_mappings!;\n for (const [k, v] of Object.entries(rawEnums)) {\n if (typeof k === \"string\" && typeof v === \"string\" && k.trim() && v.trim()) {\n enumMappings.set(k.trim().toUpperCase(), v.trim());\n }\n }\n\n const rawPrefixes =\n rules.prefix_strip_patterns ?? DEFAULT_NORMALIZATION_RULES.prefix_strip_patterns!;\n const prefixStripPatterns: RegExp[] = [];\n for (const p of rawPrefixes) {\n const compiled = safeCompileRegExp(p, \"i\");\n if (compiled) {\n prefixStripPatterns.push(compiled);\n }\n }\n\n const rawSuffixes =\n rules.suffix_strip_patterns ?? DEFAULT_NORMALIZATION_RULES.suffix_strip_patterns!;\n const suffixStripPatterns: CompiledSuffixRule[] = [];\n for (const s of rawSuffixes) {\n const compiled = safeCompileRegExp(s.pattern, \"i\");\n if (compiled) {\n suffixStripPatterns.push({\n regex: compiled,\n ...(typeof s.capture_thinking_tier_group === \"number\"\n ? { captureTierGroup: s.capture_thinking_tier_group }\n : {}),\n });\n }\n }\n\n const rawVersionRules =\n rules.version_format_rules ?? DEFAULT_NORMALIZATION_RULES.version_format_rules!;\n const versionFormatRules: CompiledVersionRule[] = [];\n for (const vr of rawVersionRules) {\n const compiled = safeCompileRegExp(vr.pattern, \"\");\n if (compiled && typeof vr.replace === \"string\") {\n versionFormatRules.push({ regex: compiled, replace: vr.replace });\n }\n }\n\n const fallbackPricing: FallbackPricingConfig =\n rules.fallback_pricing &&\n rules.fallback_pricing.default &&\n Array.isArray(rules.fallback_pricing.rules)\n ? rules.fallback_pricing\n : DEFAULT_FALLBACK_PRICING;\n\n const result: CompiledNormalizationRules = {\n placeholderPrefixes,\n enumMappings,\n prefixStripPatterns,\n suffixStripPatterns,\n versionFormatRules,\n fallbackPricing,\n };\n compiledRulesCache.set(rules, result);\n return result;\n}\n\nfunction stripVariantAndDateSuffixes(\n modelId: string,\n compiled: CompiledNormalizationRules,\n): {\n stripped: string;\n thinkingTier?: string;\n} {\n let normalized = modelId.trim().toLowerCase();\n let thinkingTier: string | undefined;\n let prev = \"\";\n\n while (normalized !== prev) {\n prev = normalized;\n for (const rule of compiled.suffixStripPatterns) {\n const m = normalized.match(rule.regex);\n if (m) {\n if (\n !thinkingTier &&\n typeof rule.captureTierGroup === \"number\" &&\n m[rule.captureTierGroup]\n ) {\n thinkingTier = m[rule.captureTierGroup]!.toLowerCase();\n }\n normalized = normalized.replace(rule.regex, \"\");\n break;\n }\n }\n }\n\n return { stripped: normalized, thinkingTier };\n}\n\nfunction normalizeModelCore(\n raw: string,\n rules?: NormalizationRules,\n): NormalizedModelInfo {\n const trimmed = raw.trim();\n if (!trimmed || trimmed.toLowerCase() === \"unknown\") {\n return { canonicalId: \"unknown\", isPlaceholder: false };\n }\n\n const compiled = compileNormalizationRules(rules);\n const upper = trimmed.toUpperCase();\n if (compiled.placeholderPrefixes.some((prefix) => upper.startsWith(prefix))) {\n return { canonicalId: trimmed, isPlaceholder: true };\n }\n const enumMapped = compiled.enumMappings.get(upper);\n if (enumMapped) {\n return { canonicalId: enumMapped, isPlaceholder: false };\n }\n\n // Step 2: Strip resource path prefixes and runtime/version suffixes\n let withoutPath = trimmed;\n for (const prefixRegex of compiled.prefixStripPatterns) {\n withoutPath = withoutPath.replace(prefixRegex, \"\");\n }\n const { stripped, thinkingTier } = stripVariantAndDateSuffixes(withoutPath, compiled);\n\n // Step 3: Apply version format rules\n let formatted = stripped;\n for (const vRule of compiled.versionFormatRules) {\n formatted = formatted.replace(vRule.regex, vRule.replace);\n }\n\n return {\n canonicalId: formatted || \"unknown\",\n ...(thinkingTier ? { thinkingTier } : {}),\n isPlaceholder: false,\n };\n}\n\nexport function normalizeModelInfo(\n raw: string,\n catalog: ModelEntry[] = [],\n rules?: NormalizationRules,\n): NormalizedModelInfo {\n const core = normalizeModelCore(raw, rules);\n if (core.isPlaceholder || core.canonicalId === \"unknown\" || catalog.length === 0) {\n return core;\n }\n const matched = findModelEntry(core.canonicalId, catalog, rules);\n if (matched) {\n return {\n canonicalId: matched.id,\n ...(core.thinkingTier ? { thinkingTier: core.thinkingTier } : {}),\n isPlaceholder: false,\n };\n }\n return core;\n}\n\nexport function normalizeModelId(\n raw: string,\n catalog: ModelEntry[] = [],\n rules?: NormalizationRules,\n): string {\n return normalizeModelInfo(raw, catalog, rules).canonicalId;\n}\n\nexport function isZeroTokenUnknownLifecycleEvent(r: {\n model?: string;\n input_tokens: number;\n cache_read_tokens?: number;\n output_tokens: number;\n}): boolean {\n const m = (r.model ?? \"\").trim().toLowerCase();\n return (\n (m === \"\" || m === \"unknown\") &&\n r.input_tokens === 0 &&\n (r.cache_read_tokens ?? 0) === 0 &&\n r.output_tokens === 0\n );\n}\n\nfunction extractGeminiMajorMinor(modelId: string): string | null {\n const match = modelId.toLowerCase().match(/gemini-(\\d+(?:[.-]\\d+)?)/);\n return match ? match[1]!.replace(\"-\", \".\") : null;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction matchExactEntry(candidateLower: string, catalog: ModelEntry[]): ModelEntry | undefined {\n const exactId = catalog.find(\n (m) =>\n m.id.toLowerCase() === candidateLower ||\n m.api_model_id.toLowerCase() === candidateLower ||\n Boolean(m.aliases?.some((a) => a.toLowerCase() === candidateLower)),\n );\n if (exactId) return exactId;\n\n return catalog.find(\n (m) =>\n m.display_name.toLowerCase() === candidateLower ||\n (m.codename && m.codename.toLowerCase() === candidateLower),\n );\n}\n\nexport function findModelEntry(\n modelId: string,\n catalog: ModelEntry[],\n rules?: NormalizationRules,\n): ModelEntry | undefined {\n const lower = modelId.trim().toLowerCase();\n if (!lower) return undefined;\n\n // 1. Exact match on id / api_model_id / aliases / display_name / codename\n const exact = matchExactEntry(lower, catalog);\n if (exact) return exact;\n\n // 2. Normalized exact match (enum/path/suffix/dot-version)\n const core = normalizeModelCore(modelId, rules);\n if (core.isPlaceholder || core.canonicalId === \"unknown\") {\n return undefined;\n }\n const normalizedLower = core.canonicalId.toLowerCase();\n if (normalizedLower !== lower) {\n const normalizedExact = matchExactEntry(normalizedLower, catalog);\n if (normalizedExact) return normalizedExact;\n }\n\n // 3. Prefix match on id / api_model_id / aliases (prefer longest match, avoid flash-lite mismatch)\n const isLiteVariant =\n normalizedLower.includes(\"-lite\") || normalizedLower.endsWith(\"lite\");\n const prefixCandidates = catalog\n .map((m) => {\n const mId = m.id.toLowerCase();\n const mApiId = m.api_model_id.toLowerCase();\n const aliases = (m.aliases ?? []).map((a) => a.toLowerCase());\n if (\n isLiteVariant &&\n !mId.includes(\"lite\") &&\n !mApiId.includes(\"lite\") &&\n !aliases.some((a) => a.includes(\"lite\"))\n ) {\n return null;\n }\n const matchedLengths = [mId, mApiId, ...aliases]\n .filter((cand) => cand.length > 0 && normalizedLower.startsWith(`${cand}-`))\n .map((cand) => cand.length);\n if (matchedLengths.length === 0) return null;\n return { entry: m, maxMatchLen: Math.max(...matchedLengths) };\n })\n .filter((x): x is { entry: ModelEntry; maxMatchLen: number } => x !== null)\n .sort((a, b) => b.maxMatchLen - a.maxMatchLen || b.entry.id.length - a.entry.id.length);\n if (prefixCandidates.length > 0) return prefixCandidates[0]!.entry;\n\n // 4. Restricted codename match: only non-generic codenames without version conflict\n const inputVersion = extractGeminiMajorMinor(normalizedLower);\n return catalog.find((m) => {\n if (!m.codename) return false;\n const codeLower = m.codename.toLowerCase();\n if (GENERIC_CODENAMES.has(codeLower)) return false;\n\n const entryVersion = extractGeminiMajorMinor(m.api_model_id || m.id);\n if (inputVersion && entryVersion && inputVersion !== entryVersion) {\n return false;\n }\n\n const boundaryRegex = new RegExp(\n `(?:^|[-_\\\\s.])${escapeRegExp(codeLower)}(?:$|[-_\\\\s.])`,\n );\n return boundaryRegex.test(normalizedLower);\n });\n}\n\nexport function findModelPricing(\n modelId: string,\n catalog: ModelEntry[],\n rules?: NormalizationRules,\n): { input: number; cachedInput: number; output: number; tier: string } {\n const core = normalizeModelCore(modelId, rules);\n if (core.isPlaceholder) {\n return { input: 0, cachedInput: 0, output: 0, tier: \"unknown\" };\n }\n\n const partial = findModelEntry(core.canonicalId, catalog, rules);\n\n if (partial?.pricing) {\n const input = partial.pricing.input_per_1m_usd;\n const cachedInput =\n typeof partial.pricing.cached_input_per_1m_usd === \"number\"\n ? partial.pricing.cached_input_per_1m_usd\n : input * 0.25;\n return {\n input,\n cachedInput,\n output: partial.pricing.output_per_1m_usd,\n tier: partial.quota_profile?.shared_bucket_cost_tier ?? \"medium\",\n };\n }\n\n const compiled = compileNormalizationRules(rules);\n const lower = modelId.toLowerCase();\n const canonicalLower = core.canonicalId.toLowerCase();\n\n for (const rule of compiled.fallbackPricing.rules) {\n if (\n rule.match_any.some((kw) => {\n const k = kw.toLowerCase();\n return lower.includes(k) || canonicalLower.includes(k);\n })\n ) {\n const input = rule.input_per_1m_usd;\n const cachedInput =\n typeof rule.cached_input_per_1m_usd === \"number\"\n ? rule.cached_input_per_1m_usd\n : input * (rule.cached_ratio ?? 0.25);\n return {\n input,\n cachedInput,\n output: rule.output_per_1m_usd,\n tier: rule.tier,\n };\n }\n }\n\n const def = compiled.fallbackPricing.default;\n const defInput = def.input_per_1m_usd;\n const defCached =\n typeof def.cached_input_per_1m_usd === \"number\"\n ? def.cached_input_per_1m_usd\n : defInput * (def.cached_ratio ?? 0.25);\n return {\n input: defInput,\n cachedInput: defCached,\n output: def.output_per_1m_usd,\n tier: def.tier ?? \"medium\",\n };\n}\n\nexport function estimateTokenCosts(\n params: {\n model: string;\n uncachedInputTokens: number;\n cacheReadTokens: number;\n outputTokens: number;\n },\n catalog: ModelEntry[],\n rules?: NormalizationRules,\n): {\n pricing: { input: number; cachedInput: number; output: number; tier: string };\n inputUsd: number;\n cacheSavingsUsd: number;\n outputUsd: number;\n totalUsd: number;\n} {\n const pricing = findModelPricing(params.model, catalog, rules);\n const inputUsd =\n (params.uncachedInputTokens / 1_000_000) * pricing.input +\n (params.cacheReadTokens / 1_000_000) * pricing.cachedInput;\n const cacheSavingsUsd = Math.max(\n 0,\n (params.cacheReadTokens / 1_000_000) * (pricing.input - pricing.cachedInput),\n );\n const outputUsd = (params.outputTokens / 1_000_000) * pricing.output;\n return {\n pricing,\n inputUsd,\n cacheSavingsUsd,\n outputUsd,\n totalUsd: inputUsd + outputUsd,\n };\n}\n\nexport function analyzeTokenWindow(\n records: UsageRecord[],\n options: {\n window: UsageWindow;\n product?: string;\n models?: ModelEntry[];\n normalizationRules?: NormalizationRules;\n nowMs?: number;\n scope?: \"global\" | \"project\";\n projectHash?: string;\n authMode?: AuthMode | \"all\";\n activeAuthMode?: AuthMode;\n dataModeOverride?: TokenWindowAnalysis[\"data_mode\"];\n unattributedSessionCount?: number;\n },\n): TokenWindowAnalysis {\n const nowMs = options.nowMs ?? Date.now();\n const cutoffMs =\n options.window === \"all\"\n ? Number.NEGATIVE_INFINITY\n : nowMs - WINDOW_MS[options.window];\n const catalog = options.models ?? [];\n const scope = options.scope ?? \"global\";\n const authModeFilter = options.authMode ?? \"all\";\n\n const baseFiltered = records.filter((r) => {\n const ts = Date.parse(r.ts);\n if (Number.isNaN(ts) || ts < cutoffMs) {\n return false;\n }\n if (\n options.product &&\n options.product !== \"all\" &&\n r.product !== options.product\n ) {\n return false;\n }\n if (authModeFilter !== \"all\" && (r.auth_mode ?? \"unknown\") !== authModeFilter) {\n return false;\n }\n return true;\n });\n\n const unattributedSessionsInWindow = new Set<string>();\n for (const r of baseFiltered) {\n if (!r.project_hash) {\n const key =\n typeof r.session_hash === \"string\" && r.session_hash.trim().length > 0\n ? r.session_hash.trim()\n : \"default-session\";\n unattributedSessionsInWindow.add(key);\n }\n }\n\n const filtered =\n scope === \"project\"\n ? baseFiltered.filter(\n (r) => Boolean(options.projectHash) && r.project_hash === options.projectHash,\n )\n : baseFiltered;\n\n let totalUncachedInput = 0;\n let totalCacheRead = 0;\n let totalOutput = 0;\n let errorCount = 0;\n let rateLimit429Count = 0;\n let peakCtxPct: number | null = null;\n let oldestMs: number | null = null;\n let belowKvCacheThresholdRequests = 0;\n\n const sessions = new Set<string>();\n const modelMap = new Map<\n string,\n {\n requests: number;\n uncachedInput: number;\n cacheRead: number;\n output: number;\n }\n >();\n\n for (const r of filtered) {\n const uncached = r.input_tokens;\n const cacheRead = r.cache_read_tokens ?? 0;\n const reqTotalInput = uncached + cacheRead;\n\n totalUncachedInput += uncached;\n totalCacheRead += cacheRead;\n totalOutput += r.output_tokens;\n const sessionKey =\n typeof r.session_hash === \"string\" && r.session_hash.trim().length > 0\n ? r.session_hash.trim()\n : \"default-session\";\n sessions.add(sessionKey);\n\n const rules = options.normalizationRules;\n const matchedEntry = findModelEntry(r.model, catalog, rules);\n const kvMinTokens = matchedEntry?.specs?.implicit_cache_min_tokens ?? 4096;\n if (\n kvMinTokens > 0 &&\n reqTotalInput > 0 &&\n reqTotalInput < kvMinTokens &&\n cacheRead === 0\n ) {\n belowKvCacheThresholdRequests += 1;\n }\n\n const ts = Date.parse(r.ts);\n if (!Number.isNaN(ts) && (oldestMs === null || ts < oldestMs)) {\n oldestMs = ts;\n }\n\n if (r.error_code) {\n errorCount += 1;\n if (r.error_code.includes(\"429\") || r.error_code.includes(\"RESOURCE_EXHAUSTED\")) {\n rateLimit429Count += 1;\n }\n }\n\n if (r.context_used_pct !== null) {\n peakCtxPct =\n peakCtxPct === null\n ? r.context_used_pct\n : Math.max(peakCtxPct, r.context_used_pct);\n }\n\n if (!isZeroTokenUnknownLifecycleEvent(r)) {\n const canonicalModel = normalizeModelId(r.model, catalog, rules);\n const agg = modelMap.get(canonicalModel) ?? {\n requests: 0,\n uncachedInput: 0,\n cacheRead: 0,\n output: 0,\n };\n agg.requests += 1;\n agg.uncachedInput += uncached;\n agg.cacheRead += cacheRead;\n agg.output += r.output_tokens;\n modelMap.set(canonicalModel, agg);\n }\n }\n\n let totalInputUsd = 0;\n let totalCacheSavingsUsd = 0;\n let totalOutputUsd = 0;\n const byModel: ModelUsageBreakdown[] = [];\n\n for (const [model, agg] of modelMap.entries()) {\n const {\n pricing,\n inputUsd: inUsd,\n cacheSavingsUsd,\n outputUsd: outUsd,\n } = estimateTokenCosts(\n {\n model,\n uncachedInputTokens: agg.uncachedInput,\n cacheReadTokens: agg.cacheRead,\n outputTokens: agg.output,\n },\n catalog,\n options.normalizationRules,\n );\n totalInputUsd += inUsd;\n totalCacheSavingsUsd += cacheSavingsUsd;\n totalOutputUsd += outUsd;\n\n const modelInputTotal = agg.uncachedInput + agg.cacheRead;\n const modelCacheHitRate =\n modelInputTotal > 0\n ? Math.round((agg.cacheRead / modelInputTotal) * 1000) / 10\n : 0;\n\n byModel.push({\n model,\n requests: agg.requests,\n uncached_input_tokens: agg.uncachedInput,\n cache_read_tokens: agg.cacheRead,\n input_tokens: modelInputTotal,\n output_tokens: agg.output,\n total_tokens: modelInputTotal + agg.output,\n cache_hit_rate_pct: modelCacheHitRate,\n estimated_input_usd: round4(inUsd),\n estimated_cache_savings_usd: round4(cacheSavingsUsd),\n estimated_output_and_thinking_usd: round4(outUsd),\n estimated_total_usd: round4(inUsd + outUsd),\n shared_bucket_cost_tier: pricing.tier,\n });\n }\n\n byModel.sort((a, b) => b.total_tokens - a.total_tokens);\n\n const totalInput = totalUncachedInput + totalCacheRead;\n const totalTokens = totalInput + totalOutput;\n const cacheHitRatePct =\n totalInput > 0 ? Math.round((totalCacheRead / totalInput) * 1000) / 10 : 0;\n const dataMode = resolveDataMode(\n filtered.length,\n totalTokens,\n options.dataModeOverride,\n );\n const usageNote =\n dataMode === \"hook_events_without_tokens\"\n ? `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.`\n : undefined;\n const excludedUnattributed = unattributedSessionsInWindow.size;\n const totalUsd = totalInputUsd + totalOutputUsd;\n const outputCostSharePct =\n totalUsd > 0 ? Math.round((totalOutputUsd / totalUsd) * 1000) / 10 : 0;\n\n const risk = assessSharedBucketRisk(\n options.window,\n totalTokens,\n rateLimit429Count,\n byModel,\n );\n\n return {\n window: options.window,\n product_filter: options.product ?? \"all\",\n scope,\n ...(scope === \"project\" && options.projectHash\n ? { project_hash: options.projectHash }\n : {}),\n auth_mode_filter: authModeFilter,\n ...(scope === \"project\"\n ? {\n unattributed_sessions_excluded: excludedUnattributed,\n unattributed_sessions_note:\n excludedUnattributed > 0\n ? `${excludedUnattributed} unattributed/derived session(s) without workspace mapping in history.jsonl were excluded from project scope.`\n : \"All attributed sessions for this project are included; any unattributed subagent sessions are excluded in project scope.\",\n }\n : {}),\n data_mode: dataMode,\n ...(usageNote ? { usage_note: usageNote } : {}),\n record_count: filtered.length,\n session_count: sessions.size,\n total_uncached_input_tokens: totalUncachedInput,\n total_cache_read_tokens: totalCacheRead,\n total_input_tokens: totalInput,\n total_output_tokens: totalOutput,\n total_tokens: totalTokens,\n cache_hit_rate_pct: cacheHitRatePct,\n error_count: errorCount,\n rate_limit_429_count: rateLimit429Count,\n peak_context_used_pct: peakCtxPct,\n oldest_event_ms: oldestMs,\n below_kv_cache_threshold_requests: belowKvCacheThresholdRequests,\n shared_bucket_risk: risk,\n thinking_cost_estimate: {\n estimated_input_usd: round4(totalInputUsd),\n estimated_cache_savings_usd: round4(totalCacheSavingsUsd),\n estimated_output_and_thinking_usd: round4(totalOutputUsd),\n estimated_total_usd: round4(totalUsd),\n output_cost_share_pct: outputCostSharePct,\n note:\n options.activeAuthMode === \"google_oauth\" || authModeFilter === \"google_oauth\"\n ? \"API-equivalent shadow cost (measures shared 5h/7d subscription quota pressure, not direct cash billing). Thinking tokens are weighted at output rates (typically 4x–8x input cost); high output cost share signals a Thinking-budget or model-tier optimization opportunity.\"\n : \"Estimated at API list rates (API-equivalent shadow cost under subscription plans). Thinking tokens are billed at output rates (typically 4x–8x input cost). High output cost share signals a Thinking-budget or model-tier optimization opportunity.\",\n },\n by_model: byModel,\n };\n}\n\nexport function resolveDataMode(\n recordCount: number,\n totalTokens: number,\n override?: TokenWindowAnalysis[\"data_mode\"],\n): TokenWindowAnalysis[\"data_mode\"] {\n if (recordCount === 0) {\n return \"transcript_timestamps_only\";\n }\n if (totalTokens > 0 && override === \"transcript_token_logs\") {\n return \"transcript_token_logs\";\n }\n return totalTokens > 0 ? \"exact_token_logs\" : \"hook_events_without_tokens\";\n}\n\nfunction assessSharedBucketRisk(\n window: UsageWindow,\n totalTokens: number,\n rateLimit429Count: number,\n byModel: ModelUsageBreakdown[],\n): \"low\" | \"moderate\" | \"high\" | \"critical\" {\n if (rateLimit429Count >= 3) {\n return \"critical\";\n }\n const heavyTokens = byModel\n .filter(\n (m) =>\n m.shared_bucket_cost_tier === \"high\" ||\n m.shared_bucket_cost_tier === \"very_high\",\n )\n .reduce((sum, m) => sum + m.total_tokens, 0);\n\n const scale =\n window === \"5h\"\n ? 1\n : window === \"24h\"\n ? 3\n : window === \"7d\"\n ? 10\n : window === \"30d\"\n ? 35\n : 60;\n if (totalTokens > 8_000_000 * scale || heavyTokens > 4_000_000 * scale) {\n return \"critical\";\n }\n if (totalTokens > 3_000_000 * scale || heavyTokens > 1_500_000 * scale || rateLimit429Count > 0) {\n return \"high\";\n }\n if (totalTokens > 1_000_000 * scale) {\n return \"moderate\";\n }\n return \"low\";\n}\n\nfunction round4(n: number): number {\n return Math.round(n * 10000) / 10000;\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { getSaltFilePath } from \"./paths.js\";\nimport type { AuthMode } from \"./types.js\";\n\n/**\n * Strict numeric/metadata whitelist for local usage telemetry.\n * PRIVACY RED LINE: NEVER add prompts, code, file paths, project names, emails, or account IDs.\n */\nexport interface UsageRecord {\n v: 1;\n ts: string;\n provider: \"google\" | \"antigravity\" | \"other\";\n product: \"agy\" | \"gemini-cli\" | \"api\" | \"web\";\n session_hash: string;\n model: string;\n input_tokens: number;\n cache_read_tokens?: number;\n output_tokens: number;\n thinking_tokens?: number;\n context_used_pct: number | null;\n tool_calls: number;\n turn_index: number;\n error_code: string | null;\n project_hash?: string | null;\n auth_mode?: AuthMode;\n data_quality?: \"exact\" | \"estimated_from_cli_log\";\n}\n\nexport const USAGE_RECORD_WHITELIST_KEYS = [\n \"v\",\n \"ts\",\n \"provider\",\n \"product\",\n \"session_hash\",\n \"model\",\n \"input_tokens\",\n \"cache_read_tokens\",\n \"output_tokens\",\n \"thinking_tokens\",\n \"context_used_pct\",\n \"tool_calls\",\n \"turn_index\",\n \"error_code\",\n \"project_hash\",\n \"auth_mode\",\n \"data_quality\",\n] as const;\n\nconst ALLOWED_PROVIDERS = new Set([\"google\", \"antigravity\", \"other\"]);\nconst ALLOWED_PRODUCTS = new Set([\"agy\", \"gemini-cli\", \"api\", \"web\"]);\nconst ALLOWED_AUTH_MODES = new Set<AuthMode>([\n \"google_oauth\",\n \"gcp_adc\",\n \"api_key\",\n \"unknown\",\n]);\nconst SAFE_MODEL_RE = /^[a-zA-Z0-9._:-]{1,64}$/;\nconst SAFE_ERROR_CODE_RE = /^[A-Z0-9_:-]{1,48}$/;\n\nconst cachedSalts = new Map<string, string>();\n\nexport async function getOrCreateLocalSalt(\n saltPath = getSaltFilePath(),\n): Promise<string> {\n const key = resolve(saltPath);\n const cached = cachedSalts.get(key);\n if (cached) {\n return cached;\n }\n try {\n const existing = (await readFile(key, \"utf8\")).trim();\n if (existing.length >= 16) {\n cachedSalts.set(key, existing);\n return existing;\n }\n } catch {\n // Salt file does not exist yet\n }\n const fresh = randomBytes(16).toString(\"hex\");\n await mkdir(dirname(key), { recursive: true });\n await writeFile(key, fresh, { mode: 0o600 });\n cachedSalts.set(key, fresh);\n return fresh;\n}\n\nexport function resetSaltCache(saltPath?: string): void {\n if (saltPath !== undefined) {\n cachedSalts.delete(resolve(saltPath));\n } else {\n cachedSalts.clear();\n }\n}\n\nexport function hashSessionId(rawSessionId: string, salt: string): string {\n return createHash(\"sha256\")\n .update(`${salt}:${rawSessionId}`)\n .digest(\"hex\")\n .slice(0, 12);\n}\n\n/**\n * One-way irreversible hash for workspace/project directory paths.\n * Never persists or returns the raw workspace path.\n */\nexport function hashProjectPath(workspaceDir: string, salt: string): string {\n return createHash(\"sha256\")\n .update(`${salt}:${resolve(workspaceDir)}`)\n .digest(\"hex\")\n .slice(0, 12);\n}\n\nfunction clampNonNegativeInt(val: unknown): number {\n const n = typeof val === \"number\" ? val : Number(val);\n if (!Number.isFinite(n) || n < 0) {\n return 0;\n }\n return Math.floor(n);\n}\n\nfunction clampPct(val: unknown): number | null {\n if (val === null || val === undefined || val === \"\") {\n return null;\n }\n const n = typeof val === \"number\" ? val : Number(val);\n if (!Number.isFinite(n)) {\n return null;\n }\n return Math.round(Math.min(100, Math.max(0, n)) * 10) / 10;\n}\n\nexport function sanitizeModelName(raw: unknown): string {\n if (typeof raw !== \"string\") {\n return \"unknown\";\n }\n const trimmed = raw.trim().replace(/@\\d{8}$/, \"\");\n // Reject anything that looks like a file path, email, or prompt text\n if (\n trimmed.includes(\"/\") ||\n trimmed.includes(\"\\\\\") ||\n trimmed.includes(\"@\") ||\n trimmed.includes(\" \") ||\n !SAFE_MODEL_RE.test(trimmed)\n ) {\n return \"unknown\";\n }\n return trimmed;\n}\n\nexport function sanitizeErrorCode(raw: unknown): string | null {\n if (raw === null || raw === undefined || raw === \"\") {\n return null;\n }\n const str = String(raw).trim().toUpperCase();\n if (SAFE_ERROR_CODE_RE.test(str)) {\n return str;\n }\n // Extract standard HTTP status code if embedded\n const httpMatch = str.match(/\\b(400|401|403|404|408|429|500|502|503|504)\\b/);\n if (httpMatch?.[1]) {\n return httpMatch[1];\n }\n return \"UNKNOWN_ERROR\";\n}\n\nexport function sanitizeAuthMode(raw: unknown): AuthMode {\n if (typeof raw === \"string\") {\n const normalized = raw.trim().toLowerCase() as AuthMode;\n if (ALLOWED_AUTH_MODES.has(normalized)) {\n return normalized;\n }\n }\n return \"unknown\";\n}\n\nfunction sanitizeIsoTimestamp(raw: unknown): string {\n if (typeof raw === \"string\") {\n const parsed = Date.parse(raw);\n if (!Number.isNaN(parsed)) {\n return new Date(parsed).toISOString();\n }\n }\n if (typeof raw === \"number\" && Number.isFinite(raw)) {\n const ms = raw > 1e12 ? raw : raw * 1000;\n return new Date(ms).toISOString();\n }\n return new Date().toISOString();\n}\n\n/**\n * Strictly constructs a whitelisted UsageRecord from an arbitrary AGY hook / statusline payload.\n * Any non-whitelisted field (prompt, response, code, file_path, project, workspace_dir, cwd, email, api_key, etc.)\n * is silently dropped and never serialized.\n * If workspace_dir or cwd is supplied, it is immediately hashed into project_hash and the original path is discarded.\n */\nexport function sanitizeUsagePayload(\n raw: Record<string, unknown>,\n salt: string,\n): UsageRecord {\n const ctx =\n raw.context_window && typeof raw.context_window === \"object\"\n ? (raw.context_window as Record<string, unknown>)\n : {};\n\n const providerRaw =\n typeof raw.provider === \"string\" ? raw.provider.toLowerCase() : \"antigravity\";\n const provider: UsageRecord[\"provider\"] = ALLOWED_PROVIDERS.has(providerRaw)\n ? (providerRaw as UsageRecord[\"provider\"])\n : \"antigravity\";\n\n const productRaw =\n typeof raw.product === \"string\" ? raw.product.toLowerCase() : \"agy\";\n const product: UsageRecord[\"product\"] = ALLOWED_PRODUCTS.has(productRaw)\n ? (productRaw as UsageRecord[\"product\"])\n : \"agy\";\n\n const sessionSource =\n typeof raw.session_hash === \"string\" && /^[a-f0-9]{8,16}$/.test(raw.session_hash)\n ? raw.session_hash\n : hashSessionId(\n typeof raw.session_hash === \"string\" && raw.session_hash.trim().length > 0\n ? raw.session_hash.trim()\n : typeof raw.session_id === \"string\" && raw.session_id.trim().length > 0\n ? raw.session_id.trim()\n : typeof raw.conversation_id === \"string\" && raw.conversation_id.trim().length > 0\n ? raw.conversation_id.trim()\n : \"default-session\",\n salt,\n );\n\n let projectHash: string | null = null;\n if (typeof raw.project_hash === \"string\" && /^[a-f0-9]{8,16}$/.test(raw.project_hash)) {\n projectHash = raw.project_hash;\n } else if (typeof raw.workspace_dir === \"string\" && raw.workspace_dir.trim().length > 0) {\n projectHash = hashProjectPath(raw.workspace_dir.trim(), salt);\n } else if (typeof raw.cwd === \"string\" && raw.cwd.trim().length > 0) {\n projectHash = hashProjectPath(raw.cwd.trim(), salt);\n }\n\n const inputTokens = clampNonNegativeInt(\n raw.input_tokens ?? ctx.input_tokens ?? raw.prompt_tokens ?? 0,\n );\n const cacheReadTokens = clampNonNegativeInt(\n raw.cache_read_tokens ??\n ctx.cache_read_tokens ??\n raw.cached_content_token_count ??\n 0,\n );\n const outputTokens = clampNonNegativeInt(\n raw.output_tokens ?? ctx.output_tokens ?? raw.completion_tokens ?? 0,\n );\n const thinkingTokens = clampNonNegativeInt(\n raw.thinking_tokens ?? ctx.thinking_tokens ?? raw.thoughts_token_count ?? 0,\n );\n const contextUsedPct = clampPct(\n raw.context_used_pct ?? ctx.used_pct ?? ctx.context_used_pct ?? null,\n );\n\n // Build strictly whitelisted object with exact keys\n return {\n v: 1,\n ts: sanitizeIsoTimestamp(raw.ts ?? raw.timestamp),\n provider,\n product,\n session_hash: sessionSource,\n model: sanitizeModelName(raw.model ?? ctx.model),\n input_tokens: inputTokens,\n cache_read_tokens: cacheReadTokens,\n output_tokens: outputTokens,\n thinking_tokens: thinkingTokens,\n context_used_pct: contextUsedPct,\n tool_calls: clampNonNegativeInt(raw.tool_calls ?? 0),\n turn_index: clampNonNegativeInt(raw.turn_index ?? 0),\n error_code: sanitizeErrorCode(raw.error_code ?? raw.status_code ?? null),\n project_hash: projectHash,\n auth_mode: sanitizeAuthMode(raw.auth_mode),\n data_quality:\n raw.data_quality === \"estimated_from_cli_log\"\n ? \"estimated_from_cli_log\"\n : \"exact\",\n };\n}\n","import type { ChannelRecommendedBehaviors } from \"./types.js\";\n\nexport type SupportedLocale = \"en\" | \"zh\";\nexport type LangOption = \"en\" | \"zh\" | \"auto\";\n\nfunction normalizeExplicitLang(raw: string | undefined): SupportedLocale | undefined {\n if (typeof raw !== \"string\") {\n return undefined;\n }\n const normalized = raw.trim().toLowerCase();\n if (!normalized || normalized === \"auto\") {\n return undefined;\n }\n if (normalized === \"zh\" || normalized.startsWith(\"zh-\") || normalized.startsWith(\"zh_\")) {\n return \"zh\";\n }\n if (normalized === \"en\" || normalized.startsWith(\"en-\") || normalized.startsWith(\"en_\")) {\n return \"en\";\n }\n return undefined;\n}\n\n/**\n * Resolve effective output locale.\n * Priority: explicit `lang` param > `AGYCRAFT_LANG` env > system `LC_ALL`/`LC_MESSAGES`/`LANG` > `\"en\"`.\n */\nexport function resolveLocale(\n explicitLang?: string,\n env: NodeJS.ProcessEnv = process.env,\n): SupportedLocale {\n const fromArg = normalizeExplicitLang(explicitLang);\n if (fromArg) {\n return fromArg;\n }\n\n const fromEnv = normalizeExplicitLang(env.AGYCRAFT_LANG);\n if (fromEnv) {\n return fromEnv;\n }\n\n const sysLocale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || \"\").trim().toLowerCase();\n if (sysLocale.includes(\"zh\")) {\n return \"zh\";\n }\n\n return \"en\";\n}\n\nfunction hasNonEmptyValue(val: unknown): boolean {\n if (typeof val === \"string\") {\n return val.trim().length > 0;\n }\n if (Array.isArray(val)) {\n return val.length > 0;\n }\n return val !== undefined && val !== null;\n}\n\n/**\n * Recursively localize snapshot/record objects:\n * - `\"en\"`: keeps primary English fields and strips all `*_zh` keys to reduce token overhead.\n * - `\"zh\"`: promotes non-empty `*_zh` keys onto their primary counterparts (falling back to primary) and strips `*_zh`.\n */\nexport function localizeSnapshotText<T>(value: T, locale: SupportedLocale): T {\n if (value === null || value === undefined || typeof value !== \"object\") {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => localizeSnapshotText(item, locale)) as unknown as T;\n }\n\n const record = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n\n for (const [key, val] of Object.entries(record)) {\n if (key.endsWith(\"_zh\")) {\n continue;\n }\n out[key] = localizeSnapshotText(val, locale);\n }\n\n if (locale === \"zh\") {\n for (const [key, val] of Object.entries(record)) {\n if (!key.endsWith(\"_zh\") || !hasNonEmptyValue(val)) {\n continue;\n }\n if (key === \"reset_rules_notes_zh\" && out.reset_rules && typeof out.reset_rules === \"object\") {\n (out.reset_rules as Record<string, unknown>).notes = val;\n continue;\n }\n const baseKey = key.slice(0, -3);\n if (baseKey === \"fix_steps\" && !(\"fix_steps\" in out) && \"steps\" in out) {\n out.steps = localizeSnapshotText(val, locale);\n } else {\n out[baseKey] = localizeSnapshotText(val, locale);\n }\n }\n }\n\n return out as T;\n}\n\nexport function localizeDiagnosisEntry<T>(entry: T, locale: SupportedLocale): T {\n return localizeSnapshotText(entry, locale);\n}\n\nexport function localizeModelEntry<T>(entry: T, locale: SupportedLocale): T {\n return localizeSnapshotText(entry, locale);\n}\n\nexport type LocalizedBehaviorKey =\n | \"thinking_guidance\"\n | \"kv_cache_guidance\"\n | \"throttling_guidance\"\n | \"background_spend_guidance\"\n | \"model_routing_guidance\";\n\nexport function getLocalizedBehavior(\n behaviors: ChannelRecommendedBehaviors | undefined,\n key: LocalizedBehaviorKey,\n locale: SupportedLocale,\n): string | undefined {\n if (!behaviors) {\n return undefined;\n }\n if (locale === \"zh\") {\n const zhKey = `${key}_zh` as keyof ChannelRecommendedBehaviors;\n const zhVal = behaviors[zhKey];\n if (typeof zhVal === \"string\" && zhVal.trim().length > 0) {\n return zhVal;\n }\n }\n const enVal = behaviors[key];\n return typeof enVal === \"string\" ? enVal : undefined;\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport {\n mkdir,\n open,\n readdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport {\n estimateTokenCosts,\n findModelEntry,\n isZeroTokenUnknownLifecycleEvent,\n normalizeModelId,\n WINDOW_MS,\n type UsageWindow,\n} from \"../analyzers/token-window.js\";\nimport {\n collectCliLogSignals,\n resolveAuthModeFromCliLogs,\n} from \"../collectors/cli-log.js\";\nimport {\n getAgyBrainDir,\n getAgyHistoryPath,\n getDefaultGeminiTelemetryPath,\n getPackageVersion,\n getRollupsDir,\n getSaltFilePath,\n getUsageLogPath,\n} from \"../paths.js\";\nimport {\n getOrCreateLocalSalt,\n hashSessionId,\n sanitizeUsagePayload,\n type UsageRecord,\n} from \"../privacy.js\";\nimport {\n buildConversationProjectIndex,\n extractStructuralTimestampMs,\n extractTranscriptExplicitModel,\n isPlaceholderOrUnknownModel,\n} from \"../collectors/transcript-meta.js\";\nimport type {\n AuthMode,\n ModelEntry,\n ModelsSnapshot,\n NormalizationRules,\n} from \"../types.js\";\n\nexport type TimeSeriesGranularity = \"hourly\" | \"daily\" | \"weekly\" | \"monthly\";\n\nexport interface RollupCounters {\n requests: number;\n uncached_input_tokens: number;\n cache_read_tokens: number;\n input_tokens: number;\n output_tokens: number;\n thinking_tokens: number;\n total_tokens: number;\n error_count: number;\n rate_limit_429_count: number;\n below_kv_cache_threshold_requests: number;\n estimated_total_usd: number;\n estimated_cache_savings_usd: number;\n}\n\nexport interface RollupBucketEntry extends RollupCounters {\n product: UsageRecord[\"product\"];\n project_hash: string | null;\n auth_mode: AuthMode;\n model?: string;\n estimated_requests?: number;\n session_hashes: string[];\n}\n\nexport interface HourlyRollupFile {\n v: number;\n month: string;\n updated_at: string;\n buckets: Record<string, RollupBucketEntry[]>;\n}\n\nexport interface SourceWatermark {\n mtime_ms: number;\n byte_offset: number;\n last_step_index?: number;\n last_ts_count?: number;\n last_model?: string;\n updated_at: string;\n}\n\nexport interface WatermarksFile {\n v: number;\n fingerprint?: string;\n pkg_version?: string;\n models_fingerprint?: string;\n salt_fingerprint?: string;\n sources: Record<string, SourceWatermark>;\n}\n\nexport interface TimeSeriesBucket extends RollupCounters {\n bucket: string;\n session_count: number;\n cache_hit_rate_pct: number;\n}\n\nexport interface TimeSeriesMeta {\n granularity: TimeSeriesGranularity;\n timezone: string;\n total_buckets: number;\n returned_buckets: number;\n max_buckets: number;\n truncated: boolean;\n source: \"rollups\" | \"memory_fallback\";\n}\n\nexport interface QueryRollupsOptions {\n rollupsDir?: string;\n usageLogPath?: string;\n geminiOtelPath?: string;\n brainDir?: string | null;\n historyPath?: string | null;\n saltPath?: string;\n salt?: string;\n models?: ModelEntry[];\n normalizationRules?: NormalizationRules;\n pkgVersion?: string;\n window: UsageWindow;\n granularity: TimeSeriesGranularity;\n product?: \"agy\" | \"gemini-cli\" | \"all\";\n scope?: \"global\" | \"project\";\n projectHash?: string;\n authMode?: AuthMode | \"all\";\n timezone?: string;\n maxBuckets?: number;\n nowMs?: number;\n readonly?: boolean;\n lockTimeoutMs?: number;\n coldBrainDays?: number;\n transcriptAuthMode?: AuthMode;\n cliLogDir?: string | null;\n hasMixedAuth?: boolean;\n}\n\nexport interface RollupQueryResult {\n time_series: TimeSeriesBucket[];\n time_series_meta: TimeSeriesMeta;\n summary_totals: RollupCounters & {\n session_count: number;\n cache_hit_rate_pct: number;\n unattributed_sessions_excluded: number;\n };\n cost_breakdown?: RollupWindowCostSummary;\n}\n\nconst STALE_LOCK_MS = 10_000;\nconst DEFAULT_COLD_BRAIN_DAYS = 30;\n\nfunction computeSaltFingerprint(salt: string): string {\n return createHash(\"sha256\").update(salt).digest(\"hex\").slice(0, 12);\n}\n\nexport function computeModelsFingerprint(\n input:\n | {\n models?: ModelEntry[];\n normalization_rules?: NormalizationRules;\n }\n | ModelsSnapshot,\n): string {\n const models = Array.isArray(input.models) ? input.models : [];\n const payload = {\n normalization_rules: input.normalization_rules ?? null,\n models: models\n .map((m) => ({\n id: m.id,\n api_model_id: m.api_model_id,\n aliases: m.aliases ?? [],\n lifecycle: m.lifecycle,\n pricing: m.pricing,\n }))\n .sort((a, b) => a.id.localeCompare(b.id)),\n };\n return createHash(\"sha256\").update(JSON.stringify(payload)).digest(\"hex\").slice(0, 12);\n}\n\nasync function cleanupRollupsDirKeepLock(rollupsDir: string): Promise<void> {\n try {\n const entries = await readdir(rollupsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name === \".rollup.lock\") {\n continue;\n }\n await rm(join(rollupsDir, entry.name), { recursive: true, force: true });\n }\n } catch {\n // Directory may not exist yet\n }\n}\n\nexport function isReadonlyEnv(explicit?: boolean): boolean {\n if (explicit === true) {\n return true;\n }\n const envVal = process.env.AGYCRAFT_READONLY?.trim().toLowerCase();\n return envVal === \"1\" || envVal === \"true\";\n}\n\nfunction emptyCounters(): RollupCounters {\n return {\n requests: 0,\n uncached_input_tokens: 0,\n cache_read_tokens: 0,\n input_tokens: 0,\n output_tokens: 0,\n thinking_tokens: 0,\n total_tokens: 0,\n error_count: 0,\n rate_limit_429_count: 0,\n below_kv_cache_threshold_requests: 0,\n estimated_total_usd: 0,\n estimated_cache_savings_usd: 0,\n };\n}\n\nfunction round4(n: number): number {\n return Math.round(n * 10000) / 10000;\n}\n\nexport function normalizeTimezone(tz?: string): string {\n if (!tz || tz.trim().length === 0) {\n return \"UTC\";\n }\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: tz.trim() });\n return tz.trim();\n } catch {\n return \"UTC\";\n }\n}\n\nfunction getDatePartsInTz(\n ms: number,\n timeZone: string,\n): { year: number; month: number; day: number; hour: number } {\n if (timeZone === \"UTC\") {\n const d = new Date(ms);\n return {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour: d.getUTCHours(),\n };\n }\n const fmt = new Intl.DateTimeFormat(\"en-CA\", {\n timeZone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n hour12: false,\n });\n const parts = fmt.formatToParts(new Date(ms));\n const map: Record<string, number> = {};\n for (const p of parts) {\n if (p.type !== \"literal\") {\n map[p.type] = Number(p.value);\n }\n }\n return {\n year: map.year ?? 1970,\n month: map.month ?? 1,\n day: map.day ?? 1,\n hour: (map.hour ?? 0) === 24 ? 0 : (map.hour ?? 0),\n };\n}\n\nfunction pad2(n: number): string {\n return String(n).padStart(2, \"0\");\n}\n\nfunction getIsoWeekKey(year: number, month: number, day: number): string {\n const d = new Date(Date.UTC(year, month - 1, day));\n const dayNum = d.getUTCDay() || 7;\n d.setUTCDate(d.getUTCDate() + 4 - dayNum);\n const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));\n const weekNo = Math.ceil(((d.getTime() - yearStart.getTime()) / 86400_000 + 1) / 7);\n return `${d.getUTCFullYear()}-W${pad2(weekNo)}`;\n}\n\nexport function formatBucketKey(\n ms: number,\n granularity: TimeSeriesGranularity,\n timeZone = \"UTC\",\n): string {\n const p = getDatePartsInTz(ms, timeZone);\n if (granularity === \"hourly\") {\n const suffix = timeZone === \"UTC\" ? \"Z\" : \"\";\n return `${p.year}-${pad2(p.month)}-${pad2(p.day)}T${pad2(p.hour)}:00:00${suffix}`;\n }\n if (granularity === \"daily\") {\n return `${p.year}-${pad2(p.month)}-${pad2(p.day)}`;\n }\n if (granularity === \"weekly\") {\n return getIsoWeekKey(p.year, p.month, p.day);\n }\n return `${p.year}-${pad2(p.month)}`;\n}\n\nfunction getUtcHourKey(ms: number): string {\n return formatBucketKey(ms, \"hourly\", \"UTC\");\n}\n\nfunction getUtcMonthKey(ms: number): string {\n return formatBucketKey(ms, \"monthly\", \"UTC\");\n}\n\nasync function atomicWriteJson(targetPath: string, data: unknown): Promise<void> {\n await mkdir(dirname(targetPath), { recursive: true });\n const tmpPath = `${targetPath}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`;\n await writeFile(tmpPath, JSON.stringify(data, null, 2), {\n encoding: \"utf8\",\n mode: 0o600,\n });\n await rename(tmpPath, targetPath);\n}\n\ntype ReadJsonResult<T> =\n | { status: \"ok\"; data: T }\n | { status: \"missing\" }\n | { status: \"corrupt\" };\n\nasync function safeReadJson<T>(filePath: string): Promise<ReadJsonResult<T>> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"ENOENT\") {\n return { status: \"missing\" };\n }\n return { status: \"corrupt\" };\n }\n try {\n const parsed = JSON.parse(raw) as T;\n if (!parsed || typeof parsed !== \"object\") {\n return { status: \"corrupt\" };\n }\n return { status: \"ok\", data: parsed };\n } catch {\n return { status: \"corrupt\" };\n }\n}\n\nasync function acquireRollupLock(\n rollupsDir: string,\n timeoutMs = 150,\n): Promise<string | null> {\n await mkdir(rollupsDir, { recursive: true });\n const lockPath = join(rollupsDir, \".rollup.lock\");\n const deadline = Date.now() + timeoutMs;\n\n while (true) {\n try {\n const fh = await open(lockPath, \"wx\", 0o600);\n await fh.writeFile(JSON.stringify({ pid: process.pid, ts: Date.now() }), \"utf8\");\n await fh.close();\n return lockPath;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code !== \"EEXIST\") {\n return null;\n }\n // Check stale lock (> 10s)\n try {\n const st = await stat(lockPath);\n let lockTs = st.mtimeMs;\n try {\n const raw = await readFile(lockPath, \"utf8\");\n const parsed = JSON.parse(raw) as { ts?: number };\n if (typeof parsed.ts === \"number\") {\n lockTs = parsed.ts;\n }\n } catch {\n // ignore corrupt lock content, rely on mtime\n }\n if (Date.now() - lockTs > STALE_LOCK_MS) {\n await unlink(lockPath).catch(() => {});\n continue;\n }\n } catch {\n // Lock disappeared concurrently\n continue;\n }\n\n if (Date.now() >= deadline) {\n return null;\n }\n await new Promise((r) => setTimeout(r, 25));\n }\n }\n}\n\nasync function releaseLock(lockPath: string | null): Promise<void> {\n if (!lockPath) {\n return;\n }\n await unlink(lockPath).catch(() => {});\n}\n\ninterface IncrementalLinesResult {\n lines: string[];\n newOffset: number;\n mtimeMs: number;\n resetRequired: boolean;\n}\n\nasync function readFileIncrementalLines(\n filePath: string,\n watermark?: SourceWatermark,\n): Promise<IncrementalLinesResult | null> {\n let st;\n try {\n st = await stat(filePath);\n } catch {\n return null;\n }\n\n if (watermark && st.size === watermark.byte_offset && st.mtimeMs === watermark.mtime_ms) {\n return { lines: [], newOffset: watermark.byte_offset, mtimeMs: st.mtimeMs, resetRequired: false };\n }\n\n const startOffset =\n watermark && st.size >= watermark.byte_offset ? watermark.byte_offset : 0;\n const resetRequired = Boolean(watermark && st.size < watermark.byte_offset);\n const bytesToRead = st.size - startOffset;\n\n if (bytesToRead <= 0) {\n return { lines: [], newOffset: st.size, mtimeMs: st.mtimeMs, resetRequired };\n }\n\n const fh = await open(filePath, \"r\");\n try {\n const buf = Buffer.alloc(bytesToRead);\n const { bytesRead } = await fh.read(buf, 0, bytesToRead, startOffset);\n const text = buf.subarray(0, bytesRead).toString(\"utf8\");\n const lastNewline = text.lastIndexOf(\"\\n\");\n\n if (lastNewline === -1) {\n // Single line without trailing newline: consume only if valid JSON\n const trimmed = text.trim();\n if (!trimmed) {\n return { lines: [], newOffset: startOffset + bytesRead, mtimeMs: st.mtimeMs, resetRequired };\n }\n try {\n JSON.parse(trimmed);\n return { lines: [trimmed], newOffset: startOffset + bytesRead, mtimeMs: st.mtimeMs, resetRequired };\n } catch {\n return { lines: [], newOffset: startOffset, mtimeMs: st.mtimeMs, resetRequired };\n }\n }\n\n const trailing = text.slice(lastNewline + 1);\n const trailingTrimmed = trailing.trim();\n if (trailingTrimmed.length > 0) {\n try {\n JSON.parse(trailingTrimmed);\n return {\n lines: text.split(\"\\n\"),\n newOffset: startOffset + bytesRead,\n mtimeMs: st.mtimeMs,\n resetRequired,\n };\n } catch {\n // Incomplete trailing line: keep byte_offset at lastNewline + 1\n const consumedBytes = Buffer.byteLength(text.slice(0, lastNewline + 1), \"utf8\");\n return {\n lines: text.slice(0, lastNewline + 1).split(\"\\n\"),\n newOffset: startOffset + consumedBytes,\n mtimeMs: st.mtimeMs,\n resetRequired,\n };\n }\n }\n\n return {\n lines: text.split(\"\\n\"),\n newOffset: startOffset + bytesRead,\n mtimeMs: st.mtimeMs,\n resetRequired,\n };\n } finally {\n await fh.close();\n }\n}\n\nfunction mergeRecordIntoBucket(\n bucketsMap: Record<string, RollupBucketEntry[]>,\n bucketKey: string,\n record: UsageRecord,\n catalog: ModelEntry[],\n rules?: NormalizationRules,\n): void {\n let entries = bucketsMap[bucketKey];\n if (!entries) {\n entries = [];\n bucketsMap[bucketKey] = entries;\n }\n const authMode = record.auth_mode ?? \"unknown\";\n const projectHash = record.project_hash ?? null;\n const modelKey = normalizeModelId(record.model || \"unknown\", catalog, rules);\n let target = entries.find(\n (e) =>\n e.product === record.product &&\n e.project_hash === projectHash &&\n e.auth_mode === authMode &&\n (e.model ?? \"unknown\") === modelKey,\n );\n if (!target) {\n target = {\n product: record.product,\n project_hash: projectHash,\n auth_mode: authMode,\n model: modelKey,\n session_hashes: [],\n ...emptyCounters(),\n };\n entries.push(target);\n }\n\n const uncached = record.input_tokens;\n const cacheRead = record.cache_read_tokens ?? 0;\n const thinking = record.thinking_tokens ?? 0;\n const reqInput = uncached + cacheRead;\n const reqTotal = reqInput + record.output_tokens;\n\n const {\n inputUsd: inUsd,\n cacheSavingsUsd,\n outputUsd: outUsd,\n } = estimateTokenCosts(\n {\n model: modelKey,\n uncachedInputTokens: uncached,\n cacheReadTokens: cacheRead,\n outputTokens: record.output_tokens,\n },\n catalog,\n rules,\n );\n\n const matchedEntry = findModelEntry(record.model, catalog, rules);\n const kvMinTokens = matchedEntry?.specs?.implicit_cache_min_tokens ?? 4096;\n const isColdBelowKv =\n kvMinTokens > 0 && reqInput > 0 && reqInput < kvMinTokens && cacheRead === 0;\n\n target.requests += 1;\n if (record.data_quality === \"estimated_from_cli_log\") {\n target.estimated_requests = (target.estimated_requests ?? 0) + 1;\n }\n target.uncached_input_tokens += uncached;\n target.cache_read_tokens += cacheRead;\n target.input_tokens += reqInput;\n target.output_tokens += record.output_tokens;\n target.thinking_tokens += thinking;\n target.total_tokens += reqTotal;\n if (record.error_code) {\n target.error_count += 1;\n if (\n record.error_code.includes(\"429\") ||\n record.error_code.includes(\"RESOURCE_EXHAUSTED\")\n ) {\n target.rate_limit_429_count += 1;\n }\n }\n if (isColdBelowKv) {\n target.below_kv_cache_threshold_requests += 1;\n }\n target.estimated_total_usd = round4(target.estimated_total_usd + inUsd + outUsd);\n target.estimated_cache_savings_usd = round4(\n target.estimated_cache_savings_usd + cacheSavingsUsd,\n );\n\n if (record.session_hash && !target.session_hashes.includes(record.session_hash)) {\n target.session_hashes.push(record.session_hash);\n }\n}\n\nfunction parseUsageLogLine(line: string, salt: string): UsageRecord | null {\n const trimmed = line.trim();\n if (!trimmed) {\n return null;\n }\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n return sanitizeUsagePayload(parsed, salt);\n } catch {\n return null;\n }\n}\n\nfunction parseOtelLine(line: string, salt: string): UsageRecord | null {\n const trimmed = line.trim();\n if (!trimmed) {\n return null;\n }\n try {\n const entry = JSON.parse(trimmed) as Record<string, unknown>;\n const rawAttrs = entry[\"attributes\"];\n const attrs =\n rawAttrs && typeof rawAttrs === \"object\" && !Array.isArray(rawAttrs)\n ? (rawAttrs as Record<string, unknown>)\n : {};\n const firstNum = (...cands: unknown[]): number => {\n for (const v of cands) {\n if (v === null || v === undefined || v === \"\") continue;\n const n = typeof v === \"number\" ? v : Number(v);\n if (Number.isFinite(n) && n >= 0) return Math.floor(n);\n }\n return 0;\n };\n const inputTokens = firstNum(\n attrs[\"gen_ai.usage.input_tokens\"],\n attrs[\"input_token_count\"],\n attrs[\"prompt_tokens\"],\n entry[\"input_tokens\"],\n entry[\"prompt_tokens\"],\n );\n const cacheReadTokens = firstNum(\n attrs[\"gen_ai.usage.cache_read_input_tokens\"],\n attrs[\"cache_read_tokens\"],\n attrs[\"cached_content_token_count\"],\n entry[\"cache_read_tokens\"],\n );\n const outputTokens = firstNum(\n attrs[\"gen_ai.usage.output_tokens\"],\n attrs[\"output_token_count\"],\n attrs[\"completion_tokens\"],\n entry[\"output_tokens\"],\n entry[\"completion_tokens\"],\n );\n const thinkingTokens = firstNum(\n attrs[\"gen_ai.usage.thinking_tokens\"],\n attrs[\"thinking_tokens\"],\n attrs[\"thoughts_token_count\"],\n entry[\"thinking_tokens\"],\n );\n const errorCode =\n attrs[\"error.type\"] ??\n attrs[\"http.response.status_code\"] ??\n entry[\"error_code\"] ??\n null;\n if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0 && !errorCode) {\n return null;\n }\n const rawSession = String(\n attrs[\"session.id\"] ?? entry[\"session_id\"] ?? \"gemini-cli-session\",\n );\n return sanitizeUsagePayload(\n {\n ts: entry[\"timestamp\"] ?? entry[\"ts\"] ?? entry[\"startTime\"],\n provider: \"google\",\n product: \"gemini-cli\",\n session_hash: hashSessionId(rawSession, salt),\n model:\n attrs[\"gen_ai.request.model\"] ??\n attrs[\"gen_ai.response.model\"] ??\n attrs[\"model\"] ??\n entry[\"model\"] ??\n \"unknown\",\n input_tokens: inputTokens,\n cache_read_tokens: cacheReadTokens,\n output_tokens: outputTokens,\n thinking_tokens: thinkingTokens,\n context_used_pct: attrs[\"context_used_pct\"] ?? null,\n tool_calls: firstNum(attrs[\"tool_calls\"], entry[\"tool_calls\"]),\n turn_index: firstNum(attrs[\"turn_index\"], entry[\"turn_index\"]),\n error_code: errorCode,\n },\n salt,\n );\n } catch {\n return null;\n }\n}\n\nexport async function queryRollups(\n options: QueryRollupsOptions,\n): Promise<RollupQueryResult> {\n const nowMs = options.nowMs ?? Date.now();\n const readonly = isReadonlyEnv(options.readonly);\n const rollupsDir = options.rollupsDir ?? getRollupsDir();\n const hourlyDir = join(rollupsDir, \"hourly\");\n const watermarksPath = join(rollupsDir, \"watermarks.json\");\n const catalog = options.models ?? [];\n const rules = options.normalizationRules;\n const tz = normalizeTimezone(options.timezone);\n const maxBuckets = Math.max(1, Math.min(90, options.maxBuckets ?? 31));\n\n // Obtain salt without writing to disk in readonly mode\n let salt = options.salt;\n if (!salt) {\n if (readonly) {\n try {\n salt = await getOrCreateLocalSalt(options.saltPath);\n } catch {\n salt = \"readonly-ephemeral-salt\";\n }\n } else {\n salt = await getOrCreateLocalSalt(options.saltPath);\n }\n }\n\n let lockPath: string | null = null;\n let canWrite = !readonly;\n if (canWrite) {\n lockPath = await acquireRollupLock(rollupsDir, options.lockTimeoutMs ?? 150);\n if (!lockPath) {\n // Lock contention timeout -> degrade gracefully to memory-only return\n canWrite = false;\n }\n }\n\n try {\n const pkgVersion = options.pkgVersion ?? getPackageVersion();\n const modelsFingerprint = computeModelsFingerprint({\n models: catalog,\n normalization_rules: rules,\n });\n const saltFingerprint = computeSaltFingerprint(salt);\n const currentFingerprint = `${pkgVersion}:${modelsFingerprint}:${saltFingerprint}`;\n const wmRes = await safeReadJson<WatermarksFile>(watermarksPath);\n\n let corruptDetected = wmRes.status === \"corrupt\";\n\n let existingHourlyFiles: string[] = [];\n try {\n const files = await readdir(hourlyDir);\n existingHourlyFiles = files.filter((f) => /^\\d{4}-\\d{2}\\.json$/.test(f)).sort();\n } catch {\n existingHourlyFiles = [];\n }\n\n let hasLegacyPeriodFiles = false;\n try {\n const rootFiles = await readdir(rollupsDir);\n hasLegacyPeriodFiles = rootFiles.some(\n (f) => f === \"daily.json\" || f === \"weekly.json\" || f === \"monthly.json\",\n );\n } catch {\n hasLegacyPeriodFiles = false;\n }\n\n let legacySchemaDetected = false;\n if (!corruptDetected) {\n for (const f of existingHourlyFiles) {\n const hRes = await safeReadJson<HourlyRollupFile>(join(hourlyDir, f));\n if (hRes.status === \"corrupt\") {\n corruptDetected = true;\n break;\n }\n if (hRes.status === \"ok\" && hRes.data.v !== 2) {\n legacySchemaDetected = true;\n }\n }\n }\n\n const hasExistingDiskRollups =\n wmRes.status === \"ok\" || existingHourlyFiles.length > 0 || hasLegacyPeriodFiles;\n\n const fingerprintMismatch =\n hasExistingDiskRollups &&\n (wmRes.status !== \"ok\" ||\n wmRes.data.v !== 2 ||\n wmRes.data.fingerprint !== currentFingerprint);\n\n const rebuildRequired =\n corruptDetected || fingerprintMismatch || legacySchemaDetected;\n\n interface PassResult {\n fallbackToCleanMemory: boolean;\n watermarks: WatermarksFile;\n hourlyCache: Map<string, HourlyRollupFile>;\n dirtyHourlyMonths: Set<string>;\n anyNewData: boolean;\n }\n\n const usageLogPath = options.usageLogPath ?? getUsageLogPath();\n const otelPath = options.geminiOtelPath ?? getDefaultGeminiTelemetryPath();\n const brainDir =\n options.brainDir === undefined ? getAgyBrainDir() : options.brainDir;\n const historyPath =\n options.historyPath === undefined ? getAgyHistoryPath() : options.historyPath;\n\n const runIngestionPass = async (useDiskRollups: boolean): Promise<PassResult> => {\n const watermarks: WatermarksFile =\n useDiskRollups && wmRes.status === \"ok\" && wmRes.data.sources\n ? {\n v: 2,\n fingerprint: currentFingerprint,\n pkg_version: pkgVersion,\n models_fingerprint: modelsFingerprint,\n salt_fingerprint: saltFingerprint,\n sources: { ...wmRes.data.sources },\n }\n : {\n v: 2,\n fingerprint: currentFingerprint,\n pkg_version: pkgVersion,\n models_fingerprint: modelsFingerprint,\n salt_fingerprint: saltFingerprint,\n sources: {},\n };\n\n const hourlyCache = new Map<string, HourlyRollupFile>();\n const dirtyHourlyMonths = new Set<string>();\n const diskSessionHashes = new Set<string>();\n\n const loadHourlyMonth = async (monthKey: string): Promise<HourlyRollupFile> => {\n const cached = hourlyCache.get(monthKey);\n if (cached) {\n return cached;\n }\n if (useDiskRollups) {\n const filePath = join(hourlyDir, `${monthKey}.json`);\n const res = await safeReadJson<HourlyRollupFile>(filePath);\n if (res.status === \"ok\" && res.data.buckets) {\n for (const entries of Object.values(res.data.buckets)) {\n for (const entry of entries) {\n for (const sh of entry.session_hashes) {\n diskSessionHashes.add(sh);\n }\n }\n }\n hourlyCache.set(monthKey, res.data);\n return res.data;\n }\n }\n const empty: HourlyRollupFile = {\n v: 2,\n month: monthKey,\n updated_at: new Date(nowMs).toISOString(),\n buckets: {},\n };\n hourlyCache.set(monthKey, empty);\n return empty;\n };\n\n if (useDiskRollups) {\n for (const file of existingHourlyFiles) {\n const monthKey = file.replace(/\\.json$/, \"\");\n await loadHourlyMonth(monthKey);\n }\n }\n\n let anyNewData = !useDiskRollups && rebuildRequired;\n\n const ingestRecords = async (newRecords: UsageRecord[]): Promise<void> => {\n for (const r of newRecords) {\n const tsMs = Date.parse(r.ts);\n if (Number.isNaN(tsMs)) {\n continue;\n }\n const monthKey = getUtcMonthKey(tsMs);\n const hourKey = getUtcHourKey(tsMs);\n\n const hourlyFile = await loadHourlyMonth(monthKey);\n mergeRecordIntoBucket(hourlyFile.buckets, hourKey, r, catalog, rules);\n hourlyFile.updated_at = new Date(nowMs).toISOString();\n dirtyHourlyMonths.add(monthKey);\n anyNewData = true;\n }\n };\n\n // 1. Incremental usage.jsonl\n const prevUsageWm = useDiskRollups ? watermarks.sources[\"usage_log\"] : undefined;\n const usageInc = await readFileIncrementalLines(usageLogPath, prevUsageWm);\n if (usageInc && usageInc.lines.length > 0) {\n const parsedRecords: UsageRecord[] = [];\n for (const line of usageInc.lines) {\n const rec = parseUsageLogLine(line, salt);\n if (rec) parsedRecords.push(rec);\n }\n if (\n !canWrite &&\n useDiskRollups &&\n hasExistingDiskRollups &&\n parsedRecords.length > 0 &&\n (!prevUsageWm || usageInc.resetRequired)\n ) {\n return {\n fallbackToCleanMemory: true,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n }\n await ingestRecords(parsedRecords);\n watermarks.sources[\"usage_log\"] = {\n mtime_ms: usageInc.mtimeMs,\n byte_offset: usageInc.newOffset,\n updated_at: new Date(nowMs).toISOString(),\n };\n anyNewData = true;\n }\n\n // 2. Incremental gemini-otel\n const prevOtelWm = useDiskRollups ? watermarks.sources[\"gemini_otel\"] : undefined;\n const otelInc = await readFileIncrementalLines(otelPath, prevOtelWm);\n if (otelInc && otelInc.lines.length > 0) {\n const parsedRecords: UsageRecord[] = [];\n for (const line of otelInc.lines) {\n const rec = parseOtelLine(line, salt);\n if (rec) parsedRecords.push(rec);\n }\n if (\n !canWrite &&\n useDiskRollups &&\n hasExistingDiskRollups &&\n parsedRecords.length > 0 &&\n (!prevOtelWm || otelInc.resetRequired)\n ) {\n return {\n fallbackToCleanMemory: true,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n }\n await ingestRecords(parsedRecords);\n watermarks.sources[\"gemini_otel\"] = {\n mtime_ms: otelInc.mtimeMs,\n byte_offset: otelInc.newOffset,\n updated_at: new Date(nowMs).toISOString(),\n };\n anyNewData = true;\n }\n\n // 2b. Collect cli-*.log auth channel signals & background lightweight calls\n const prevBgWm = useDiskRollups ? watermarks.sources[\"cli_log_bg\"] : undefined;\n const prevMaxTs = prevBgWm?.last_step_index ?? 0;\n const cliSinceMs = prevMaxTs > 0 ? Math.max(0, prevMaxTs - 60_000) : undefined;\n const effectiveCliLogDir =\n options.cliLogDir !== undefined\n ? options.cliLogDir\n : options.brainDir !== undefined && !process.env.AGYCRAFT_CLI_LOG_DIR\n ? null\n : undefined;\n const cliLogs =\n effectiveCliLogDir === null\n ? { authEvents: [], backgroundRecords: [], filesScanned: 0 }\n : await collectCliLogSignals({\n cliLogDir: effectiveCliLogDir,\n sinceMs: cliSinceMs,\n nowMs,\n salt,\n fallbackAuthMode: options.transcriptAuthMode,\n hasMixedAuth: options.hasMixedAuth,\n });\n\n if (cliLogs.backgroundRecords.length > 0) {\n const hasTsCount = prevBgWm?.last_ts_count !== undefined;\n const prevAtMaxCount = prevBgWm?.last_ts_count ?? 0;\n let seenAtPrevMax = 0;\n const freshBg = cliLogs.backgroundRecords.filter((r) => {\n const ts = Date.parse(r.ts);\n if (Number.isNaN(ts)) return false;\n if (ts > prevMaxTs) return true;\n if (hasTsCount && ts === prevMaxTs) {\n seenAtPrevMax += 1;\n return seenAtPrevMax > prevAtMaxCount;\n }\n return false;\n });\n if (freshBg.length > 0) {\n if (!canWrite && useDiskRollups && hasExistingDiskRollups && !prevBgWm) {\n return {\n fallbackToCleanMemory: true,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n }\n await ingestRecords(freshBg);\n const maxBgTs = freshBg.reduce((mx, r) => Math.max(mx, Date.parse(r.ts) || 0), prevMaxTs);\n const countAtMaxTs = cliLogs.backgroundRecords.reduce(\n (cnt, r) => (Date.parse(r.ts) === maxBgTs ? cnt + 1 : cnt),\n 0,\n );\n watermarks.sources[\"cli_log_bg\"] = {\n mtime_ms: maxBgTs,\n byte_offset: freshBg.length,\n last_step_index: maxBgTs,\n last_ts_count: countAtMaxTs,\n updated_at: new Date(nowMs).toISOString(),\n };\n anyNewData = true;\n }\n }\n\n // 3. Incremental AGY brain transcripts (skip cold > 30d dirs)\n if (brainDir) {\n const coldThresholdMs =\n nowMs - (options.coldBrainDays ?? DEFAULT_COLD_BRAIN_DAYS) * 86400_000;\n const projectIndex = await buildConversationProjectIndex(historyPath, salt);\n let sessionDirs: string[] = [];\n try {\n const entries = await readdir(brainDir, { withFileTypes: true });\n sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch {\n sessionDirs = [];\n }\n\n for (const sessionId of sessionDirs) {\n const transcriptPath = join(\n brainDir,\n sessionId,\n \".system_generated\",\n \"logs\",\n \"transcript.jsonl\",\n );\n let st;\n try {\n st = await stat(transcriptPath);\n } catch {\n continue;\n }\n if (st.mtimeMs < coldThresholdMs) {\n // Skip cold brain directories (> 30 days since last update)\n continue;\n }\n const sessionHash = hashSessionId(sessionId, salt);\n const wmKey = `transcript:${sessionHash}`;\n const prevWm = useDiskRollups ? watermarks.sources[wmKey] : undefined;\n const inc = await readFileIncrementalLines(transcriptPath, prevWm);\n if (!inc || inc.lines.length === 0) {\n continue;\n }\n\n if (\n !canWrite &&\n useDiskRollups &&\n (!prevWm || inc.resetRequired) &&\n diskSessionHashes.has(sessionHash)\n ) {\n return {\n fallbackToCleanMemory: true,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n }\n\n const projectHash = projectIndex.get(sessionId) ?? null;\n const prevLastStep = inc.resetRequired ? -1 : (prevWm?.last_step_index ?? -1);\n let maxStepIndex = prevLastStep;\n let lastSeenModel: string | null = inc.resetRequired ? null : (prevWm?.last_model ?? null);\n const parsedEvents: Record<string, unknown>[] = [];\n const modelFreq = new Map<string, number>();\n\n for (const line of inc.lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const obj = JSON.parse(trimmed) as Record<string, unknown>;\n parsedEvents.push(obj);\n const uObj =\n obj.usage && typeof obj.usage === \"object\" && !Array.isArray(obj.usage)\n ? (obj.usage as Record<string, unknown>)\n : {};\n const typeUpper = typeof obj.type === \"string\" ? obj.type.toUpperCase() : \"\";\n const em = extractTranscriptExplicitModel(obj, uObj);\n if (\n typeUpper !== \"CHECKPOINT\" &&\n em !== null &&\n !isPlaceholderOrUnknownModel(em)\n ) {\n modelFreq.set(em, (modelFreq.get(em) ?? 0) + 1);\n }\n } catch {\n continue;\n }\n }\n\n let dominantModel: string | null = null;\n let dominantCount = 0;\n for (const [m, count] of modelFreq.entries()) {\n if (count > dominantCount) {\n dominantCount = count;\n dominantModel = m;\n }\n }\n\n if (\n lastSeenModel === null &&\n dominantModel === null &&\n prevWm &&\n !inc.resetRequired &&\n prevWm.byte_offset > 0\n ) {\n try {\n const headText = await readFile(transcriptPath, \"utf8\");\n const headFreq = new Map<string, number>();\n for (const rawLine of headText.split(\"\\n\")) {\n const t = rawLine.trim();\n if (!t) continue;\n try {\n const hObj = JSON.parse(t) as Record<string, unknown>;\n const hUsage =\n hObj.usage && typeof hObj.usage === \"object\" && !Array.isArray(hObj.usage)\n ? (hObj.usage as Record<string, unknown>)\n : {};\n const hType = typeof hObj.type === \"string\" ? hObj.type.toUpperCase() : \"\";\n const hm = extractTranscriptExplicitModel(hObj, hUsage);\n if (hType !== \"CHECKPOINT\" && hm !== null && !isPlaceholderOrUnknownModel(hm)) {\n headFreq.set(hm, (headFreq.get(hm) ?? 0) + 1);\n }\n } catch {\n continue;\n }\n }\n let headTopCount = 0;\n for (const [hm, hCount] of headFreq.entries()) {\n if (hCount > headTopCount) {\n headTopCount = hCount;\n dominantModel = hm;\n }\n }\n } catch {\n // Ignore fallback read failure\n }\n }\n\n const parsedRecords: UsageRecord[] = [];\n\n for (const parsed of parsedEvents) {\n const usageObj =\n parsed.usage && typeof parsed.usage === \"object\" && !Array.isArray(parsed.usage)\n ? (parsed.usage as Record<string, unknown>)\n : {};\n const typeStr = typeof parsed.type === \"string\" ? parsed.type.toUpperCase() : \"\";\n const explicitModel = extractTranscriptExplicitModel(parsed, usageObj);\n if (\n typeStr !== \"CHECKPOINT\" &&\n explicitModel !== null &&\n !isPlaceholderOrUnknownModel(explicitModel)\n ) {\n lastSeenModel = explicitModel;\n }\n\n const stepIdx = typeof parsed.step_index === \"number\" ? parsed.step_index : undefined;\n if (\n stepIdx !== undefined &&\n prevLastStep >= 0 &&\n stepIdx <= prevLastStep\n ) {\n continue;\n }\n const tsMs = extractStructuralTimestampMs(parsed);\n if (tsMs === null || tsMs > nowMs + 60_000) continue;\n const num = (...vals: unknown[]): number => {\n for (const v of vals) {\n if (v === null || v === undefined || v === \"\") continue;\n const n = typeof v === \"number\" ? v : Number(v);\n if (Number.isFinite(n) && n >= 0) return Math.floor(n);\n }\n return 0;\n };\n const rawInput = num(parsed.input_tokens, usageObj.input_tokens, usageObj.prompt_tokens);\n const rawCacheRead = num(\n parsed.cache_read_tokens,\n usageObj.cache_read_tokens,\n usageObj.cached_content_token_count,\n );\n const rawOutput = num(\n parsed.output_tokens,\n usageObj.output_tokens,\n usageObj.completion_tokens,\n );\n if (typeStr !== \"PLANNER_RESPONSE\" && rawInput + rawCacheRead === 0 && rawOutput === 0) {\n continue;\n }\n if (rawInput + rawCacheRead === 0 && rawOutput === 0) {\n continue;\n }\n if (stepIdx !== undefined && stepIdx > maxStepIndex) {\n maxStepIndex = stepIdx;\n }\n\n const attributedModel =\n typeStr === \"CHECKPOINT\" || !explicitModel\n ? (lastSeenModel ?? dominantModel ?? \"unknown\")\n : explicitModel;\n\n const resolvedAuthMode =\n cliLogs.authEvents.length > 0 || options.hasMixedAuth\n ? resolveAuthModeFromCliLogs(cliLogs.authEvents, tsMs, {\n fallbackAuthMode: options.transcriptAuthMode ?? \"unknown\",\n hasMixedAuth: options.hasMixedAuth,\n })\n : (options.transcriptAuthMode ?? \"unknown\");\n\n parsedRecords.push(\n sanitizeUsagePayload(\n {\n ts: new Date(tsMs).toISOString(),\n provider: \"antigravity\",\n product: \"agy\",\n session_id: sessionId,\n model: attributedModel,\n input_tokens: rawInput,\n cache_read_tokens: rawCacheRead,\n output_tokens: rawOutput,\n thinking_tokens: 0,\n tool_calls: 0,\n turn_index: stepIdx ?? 0,\n project_hash: projectHash,\n auth_mode: resolvedAuthMode,\n },\n salt,\n ),\n );\n }\n\n await ingestRecords(parsedRecords);\n watermarks.sources[wmKey] = {\n mtime_ms: inc.mtimeMs,\n byte_offset: inc.newOffset,\n ...(maxStepIndex >= 0 ? { last_step_index: maxStepIndex } : {}),\n ...(lastSeenModel ? { last_model: lastSeenModel } : {}),\n updated_at: new Date(nowMs).toISOString(),\n };\n anyNewData = true;\n }\n }\n\n return {\n fallbackToCleanMemory: false,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n };\n\n let passResult = await runIngestionPass(!rebuildRequired);\n if (passResult.fallbackToCleanMemory) {\n passResult = await runIngestionPass(false);\n }\n\n const {\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n } = passResult;\n\n // Persist dirty rollups and watermarks atomically if writable\n if (canWrite && anyNewData) {\n if (rebuildRequired) {\n await cleanupRollupsDirKeepLock(rollupsDir);\n }\n for (const monthKey of dirtyHourlyMonths) {\n const hf = hourlyCache.get(monthKey);\n if (hf) {\n await atomicWriteJson(join(hourlyDir, `${monthKey}.json`), hf);\n }\n }\n await atomicWriteJson(watermarksPath, watermarks);\n }\n\n const cutoffMs =\n options.window === \"all\"\n ? Number.NEGATIVE_INFINITY\n : nowMs - WINDOW_MS[options.window];\n\n // Aggregate from hourly UTC buckets into target granularity + timezone\n const aggregated = new Map<\n string,\n { counters: RollupCounters; sessions: Set<string> }\n >();\n const totalSessions = new Set<string>();\n const unattributedSessions = new Set<string>();\n const totals = emptyCounters();\n\n const productFilter = options.product ?? \"all\";\n const scope = options.scope ?? \"global\";\n const authFilter = options.authMode ?? \"all\";\n\n for (const hf of hourlyCache.values()) {\n for (const [hourUtcKey, entries] of Object.entries(hf.buckets)) {\n const hourMs = Date.parse(hourUtcKey);\n if (Number.isNaN(hourMs) || hourMs + 3600_000 <= cutoffMs || hourMs > nowMs + 3600_000) {\n continue;\n }\n const targetBucketKey = formatBucketKey(hourMs, options.granularity, tz);\n for (const entry of entries) {\n if (productFilter !== \"all\" && entry.product !== productFilter) {\n continue;\n }\n if (authFilter !== \"all\" && entry.auth_mode !== authFilter) {\n continue;\n }\n if (!entry.project_hash) {\n for (const sh of entry.session_hashes) {\n unattributedSessions.add(sh);\n }\n }\n if (scope === \"project\") {\n if (!options.projectHash || entry.project_hash !== options.projectHash) {\n continue;\n }\n }\n\n let bucketAgg = aggregated.get(targetBucketKey);\n if (!bucketAgg) {\n bucketAgg = { counters: emptyCounters(), sessions: new Set<string>() };\n aggregated.set(targetBucketKey, bucketAgg);\n }\n\n // Recompute USD estimates from current model catalog so pricing updates never drift from token-window\n const repriced = entry.model\n ? estimateTokenCosts(\n {\n model: normalizeModelId(entry.model, catalog, rules),\n uncachedInputTokens: entry.uncached_input_tokens,\n cacheReadTokens: entry.cache_read_tokens,\n outputTokens: entry.output_tokens,\n },\n catalog,\n rules,\n )\n : null;\n const entryTotalUsd = repriced ? repriced.totalUsd : entry.estimated_total_usd;\n const entryCacheSavingsUsd = repriced\n ? repriced.cacheSavingsUsd\n : entry.estimated_cache_savings_usd;\n\n const c = bucketAgg.counters;\n c.requests += entry.requests;\n c.uncached_input_tokens += entry.uncached_input_tokens;\n c.cache_read_tokens += entry.cache_read_tokens;\n c.input_tokens += entry.input_tokens;\n c.output_tokens += entry.output_tokens;\n c.thinking_tokens += entry.thinking_tokens;\n c.total_tokens += entry.total_tokens;\n c.error_count += entry.error_count;\n c.rate_limit_429_count += entry.rate_limit_429_count;\n c.below_kv_cache_threshold_requests += entry.below_kv_cache_threshold_requests;\n c.estimated_total_usd += entryTotalUsd;\n c.estimated_cache_savings_usd += entryCacheSavingsUsd;\n\n totals.requests += entry.requests;\n totals.uncached_input_tokens += entry.uncached_input_tokens;\n totals.cache_read_tokens += entry.cache_read_tokens;\n totals.input_tokens += entry.input_tokens;\n totals.output_tokens += entry.output_tokens;\n totals.thinking_tokens += entry.thinking_tokens;\n totals.total_tokens += entry.total_tokens;\n totals.error_count += entry.error_count;\n totals.rate_limit_429_count += entry.rate_limit_429_count;\n totals.below_kv_cache_threshold_requests +=\n entry.below_kv_cache_threshold_requests;\n totals.estimated_total_usd += entryTotalUsd;\n totals.estimated_cache_savings_usd += entryCacheSavingsUsd;\n\n for (const sh of entry.session_hashes) {\n bucketAgg.sessions.add(sh);\n totalSessions.add(sh);\n }\n }\n }\n }\n\n totals.estimated_total_usd = round4(totals.estimated_total_usd);\n totals.estimated_cache_savings_usd = round4(totals.estimated_cache_savings_usd);\n\n const allBuckets: TimeSeriesBucket[] = [...aggregated.entries()]\n .filter(([, v]) => v.counters.requests > 0)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([bucket, v]) => ({\n bucket,\n ...v.counters,\n estimated_total_usd: round4(v.counters.estimated_total_usd),\n estimated_cache_savings_usd: round4(v.counters.estimated_cache_savings_usd),\n session_count: v.sessions.size,\n cache_hit_rate_pct:\n v.counters.input_tokens > 0\n ? Math.round((v.counters.cache_read_tokens / v.counters.input_tokens) * 1000) / 10\n : 0,\n }));\n\n const truncated = allBuckets.length > maxBuckets;\n const returned = truncated ? allBuckets.slice(-maxBuckets) : allBuckets;\n\n const costBreakdown =\n options.window === \"5h\" || options.window === \"24h\" || options.window === \"7d\"\n ? aggregateHourlyFilesToCostWindow(\n [...hourlyCache.values()],\n options.window,\n catalog,\n nowMs,\n rules,\n )\n : undefined;\n\n return {\n time_series: returned,\n time_series_meta: {\n granularity: options.granularity,\n timezone: tz,\n total_buckets: allBuckets.length,\n returned_buckets: returned.length,\n max_buckets: maxBuckets,\n truncated,\n source: canWrite ? \"rollups\" : \"memory_fallback\",\n },\n summary_totals: {\n ...totals,\n session_count: totalSessions.size,\n cache_hit_rate_pct:\n totals.input_tokens > 0\n ? Math.round((totals.cache_read_tokens / totals.input_tokens) * 1000) / 10\n : 0,\n unattributed_sessions_excluded: unattributedSessions.size,\n },\n ...(costBreakdown ? { cost_breakdown: costBreakdown } : {}),\n };\n } finally {\n await releaseLock(lockPath);\n }\n}\n\nexport type CostSummaryWindow = \"5h\" | \"24h\" | \"7d\";\n\nexport interface ModelAuthCostRow {\n model: string;\n auth_mode: AuthMode;\n lifecycle: string;\n deprecated_date: string | null;\n replacement_model_id: string | null;\n requests: number;\n estimated_requests: number;\n uncached_input_tokens: number;\n cache_read_tokens: number;\n input_tokens: number;\n output_tokens: number;\n total_tokens: number;\n cache_hit_rate_pct: number;\n estimated_total_usd: number;\n estimated_cache_savings_usd: number;\n rate_limit_429_count: number;\n}\n\nexport interface AuthChannelCostGroup {\n auth_mode: AuthMode;\n label: string;\n requests: number;\n total_tokens: number;\n estimated_total_usd: number;\n estimated_cache_savings_usd: number;\n rate_limit_429_count: number;\n}\n\nexport interface DeprecatedModelInUse {\n model: string;\n lifecycle: string;\n deprecated_date: string | null;\n replacement_model_id: string | null;\n requests: number;\n}\n\nexport interface RollupWindowCostSummary {\n window: CostSummaryWindow;\n by_model_auth: ModelAuthCostRow[];\n by_auth_channel: AuthChannelCostGroup[];\n deprecated_models_in_use: DeprecatedModelInUse[];\n rate_limit_429_count: number;\n total_requests: number;\n total_tokens: number;\n}\n\nexport interface ReadRollupCostSummaryResult {\n has_cache: boolean;\n windows: Record<CostSummaryWindow, RollupWindowCostSummary>;\n}\n\nfunction getAuthChannelLabel(authMode: AuthMode): string {\n switch (authMode) {\n case \"google_oauth\":\n return \"Shadow Cost (Shared Quota Pressure)\";\n case \"gcp_adc\":\n case \"api_key\":\n return \"Estimated GCP / API Spend\";\n default:\n return \"Unattributed Est.\";\n }\n}\n\nexport function aggregateHourlyFilesToCostWindow(\n hourlyFiles: HourlyRollupFile[],\n window: CostSummaryWindow,\n catalog: ModelEntry[],\n nowMs: number,\n rules?: NormalizationRules,\n): RollupWindowCostSummary {\n const cutoffMs = nowMs - WINDOW_MS[window];\n const modelAuthMap = new Map<string, ModelAuthCostRow>();\n const authGroupMap = new Map<AuthMode, AuthChannelCostGroup>();\n const deprecatedMap = new Map<string, DeprecatedModelInUse>();\n\n let totalRequests = 0;\n let totalTokens = 0;\n let total429 = 0;\n\n for (const hf of hourlyFiles) {\n for (const [hourUtcKey, entries] of Object.entries(hf.buckets)) {\n const hourMs = Date.parse(hourUtcKey);\n if (\n Number.isNaN(hourMs) ||\n hourMs + 3600_000 <= cutoffMs ||\n hourMs > nowMs + 3600_000\n ) {\n continue;\n }\n\n for (const entry of entries) {\n const canonicalModel = normalizeModelId(entry.model ?? \"unknown\", catalog, rules);\n const matchedEntry = findModelEntry(canonicalModel, catalog, rules);\n const lifecycle = matchedEntry?.lifecycle ?? \"active\";\n const deprecatedDate = matchedEntry?.deprecated_date ?? null;\n const replacementModelId = matchedEntry?.replacement_model_id ?? null;\n\n const isZeroUnknown = isZeroTokenUnknownLifecycleEvent({\n model: canonicalModel,\n input_tokens: entry.input_tokens,\n cache_read_tokens: entry.cache_read_tokens,\n output_tokens: entry.output_tokens,\n });\n\n const repriced = isZeroUnknown\n ? { totalUsd: 0, cacheSavingsUsd: 0 }\n : estimateTokenCosts(\n {\n model: canonicalModel,\n uncachedInputTokens: entry.uncached_input_tokens,\n cacheReadTokens: entry.cache_read_tokens,\n outputTokens: entry.output_tokens,\n },\n catalog,\n rules,\n );\n\n const authMode: AuthMode = entry.auth_mode ?? \"unknown\";\n if (!isZeroUnknown) {\n const key = `${canonicalModel}\\u0000${authMode}`;\n let row = modelAuthMap.get(key);\n if (!row) {\n row = {\n model: canonicalModel,\n auth_mode: authMode,\n lifecycle,\n deprecated_date: deprecatedDate,\n replacement_model_id: replacementModelId,\n requests: 0,\n estimated_requests: 0,\n uncached_input_tokens: 0,\n cache_read_tokens: 0,\n input_tokens: 0,\n output_tokens: 0,\n total_tokens: 0,\n cache_hit_rate_pct: 0,\n estimated_total_usd: 0,\n estimated_cache_savings_usd: 0,\n rate_limit_429_count: 0,\n };\n modelAuthMap.set(key, row);\n }\n\n row.requests += entry.requests;\n row.estimated_requests += entry.estimated_requests ?? 0;\n row.uncached_input_tokens += entry.uncached_input_tokens;\n row.cache_read_tokens += entry.cache_read_tokens;\n row.input_tokens += entry.input_tokens;\n row.output_tokens += entry.output_tokens;\n row.total_tokens += entry.total_tokens;\n row.estimated_total_usd += repriced.totalUsd;\n row.estimated_cache_savings_usd += repriced.cacheSavingsUsd;\n row.rate_limit_429_count += entry.rate_limit_429_count;\n }\n\n let group = authGroupMap.get(authMode);\n if (!group) {\n group = {\n auth_mode: authMode,\n label: getAuthChannelLabel(authMode),\n requests: 0,\n total_tokens: 0,\n estimated_total_usd: 0,\n estimated_cache_savings_usd: 0,\n rate_limit_429_count: 0,\n };\n authGroupMap.set(authMode, group);\n }\n group.requests += entry.requests;\n group.total_tokens += entry.total_tokens;\n group.estimated_total_usd += repriced.totalUsd;\n group.estimated_cache_savings_usd += repriced.cacheSavingsUsd;\n group.rate_limit_429_count += entry.rate_limit_429_count;\n\n if (!isZeroUnknown && (lifecycle === \"deprecated\" || lifecycle === \"removed\")) {\n const dep = deprecatedMap.get(canonicalModel) ?? {\n model: canonicalModel,\n lifecycle,\n deprecated_date: deprecatedDate,\n replacement_model_id: replacementModelId,\n requests: 0,\n };\n dep.requests += entry.requests;\n deprecatedMap.set(canonicalModel, dep);\n }\n\n totalRequests += entry.requests;\n totalTokens += entry.total_tokens;\n total429 += entry.rate_limit_429_count;\n }\n }\n }\n\n const byModelAuth = [...modelAuthMap.values()]\n .map((r) => ({\n ...r,\n estimated_total_usd: round4(r.estimated_total_usd),\n estimated_cache_savings_usd: round4(r.estimated_cache_savings_usd),\n cache_hit_rate_pct:\n r.input_tokens > 0\n ? Math.round((r.cache_read_tokens / r.input_tokens) * 1000) / 10\n : 0,\n }))\n .sort((a, b) => b.estimated_total_usd - a.estimated_total_usd || b.total_tokens - a.total_tokens);\n\n const authOrder: Record<string, number> = {\n google_oauth: 0,\n gcp_vertex_adc: 1,\n gcp_adc: 1,\n gemini_api_key: 2,\n api_key: 2,\n vertex_express_key: 3,\n unknown: 99,\n };\n const byAuthChannel = [...authGroupMap.values()]\n .map((g) => ({\n ...g,\n estimated_total_usd: round4(g.estimated_total_usd),\n estimated_cache_savings_usd: round4(g.estimated_cache_savings_usd),\n }))\n .sort((a, b) => (authOrder[a.auth_mode] ?? 50) - (authOrder[b.auth_mode] ?? 50));\n\n return {\n window,\n by_model_auth: byModelAuth,\n by_auth_channel: byAuthChannel,\n deprecated_models_in_use: [...deprecatedMap.values()].sort(\n (a, b) => b.requests - a.requests,\n ),\n rate_limit_429_count: total429,\n total_requests: totalRequests,\n total_tokens: totalTokens,\n };\n}\n\nasync function readSaltReadonly(\n rollupsDir: string,\n explicitSalt?: string,\n explicitSaltPath?: string,\n): Promise<string | null> {\n if (explicitSalt && explicitSalt.trim().length > 0) {\n return explicitSalt.trim();\n }\n const candidates = [\n ...(explicitSaltPath ? [explicitSaltPath] : []),\n join(dirname(rollupsDir), \".salt\"),\n ...(rollupsDir === getRollupsDir() ? [getSaltFilePath()] : []),\n ];\n for (const candidate of candidates) {\n try {\n const content = (await readFile(candidate, \"utf8\")).trim();\n if (content.length > 0) {\n return content;\n }\n } catch {\n // Ignore missing candidate\n }\n }\n return null;\n}\n\n/**\n * Ultra-fast, zero-write, lock-free reader for doctor cost_summary.\n * Only reads current-month (and boundary previous-month) hourly/YYYY-MM.json files.\n * Never scans brainDir, never acquires locks, and never writes to disk.\n * Ignores stale/mismatched fingerprint caches cleanly without migration.\n */\nexport async function readRollupCostSummary(options?: {\n rollupsDir?: string;\n models?: ModelEntry[];\n normalizationRules?: NormalizationRules;\n pkgVersion?: string;\n saltPath?: string;\n salt?: string;\n nowMs?: number;\n}): Promise<ReadRollupCostSummaryResult> {\n const nowMs = options?.nowMs ?? Date.now();\n const rollupsDir = options?.rollupsDir ?? getRollupsDir();\n const hourlyDir = join(rollupsDir, \"hourly\");\n const watermarksPath = join(rollupsDir, \"watermarks.json\");\n const catalog = options?.models ?? [];\n const rules = options?.normalizationRules;\n const pkgVersion = options?.pkgVersion ?? getPackageVersion();\n const modelsFingerprint = computeModelsFingerprint({\n models: catalog,\n normalization_rules: rules,\n });\n\n const wmRes = await safeReadJson<WatermarksFile>(watermarksPath);\n let fingerprintValid = false;\n if (wmRes.status === \"ok\" && wmRes.data.v === 2 && typeof wmRes.data.fingerprint === \"string\") {\n const salt = await readSaltReadonly(rollupsDir, options?.salt, options?.saltPath);\n if (salt !== null) {\n const expectedFp = `${pkgVersion}:${modelsFingerprint}:${computeSaltFingerprint(salt)}`;\n fingerprintValid = wmRes.data.fingerprint === expectedFp;\n } else {\n fingerprintValid = wmRes.data.fingerprint.startsWith(`${pkgVersion}:${modelsFingerprint}:`);\n }\n }\n\n const hourlyFiles: HourlyRollupFile[] = [];\n if (fingerprintValid) {\n const monthKeys = [...new Set([getUtcMonthKey(nowMs), getUtcMonthKey(nowMs - WINDOW_MS[\"7d\"])])];\n for (const mk of monthKeys) {\n const res = await safeReadJson<HourlyRollupFile>(join(hourlyDir, `${mk}.json`));\n if (res.status === \"ok\" && res.data.v === 2 && res.data.buckets) {\n hourlyFiles.push(res.data);\n }\n }\n }\n\n const hasCache = fingerprintValid && hourlyFiles.length > 0;\n return {\n has_cache: hasCache,\n windows: {\n \"5h\": aggregateHourlyFilesToCostWindow(hourlyFiles, \"5h\", catalog, nowMs, rules),\n \"24h\": aggregateHourlyFilesToCostWindow(hourlyFiles, \"24h\", catalog, nowMs, rules),\n \"7d\": aggregateHourlyFilesToCostWindow(hourlyFiles, \"7d\", catalog, nowMs, rules),\n },\n };\n}\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport {\n getAgyBrainDir,\n getAgyHistoryPath,\n isBrainScanDisabledValue,\n} from \"../paths.js\";\nimport {\n type UsageRecord,\n getOrCreateLocalSalt,\n hashProjectPath,\n sanitizeUsagePayload,\n} from \"../privacy.js\";\nimport {\n type CliLogAuthEvent,\n resolveAuthModeFromCliLogs,\n} from \"./cli-log.js\";\nimport type { AuthMode } from \"../types.js\";\n\n/**\n * Pure structural metadata extracted from an AGY transcript.jsonl.\n * PRIVACY RED LINE: NEVER reads, stores, or returns prompt text, assistant text,\n * tool arguments, file paths, or code snippets. Only counts structural events.\n */\nexport interface TranscriptStructuralMeta {\n total_steps: number;\n user_turns: number;\n assistant_turns: number;\n tool_call_count: number;\n tool_error_count: number;\n max_consecutive_tool_failures: number;\n consecutive_failure_tool_type: string | null;\n has_compact_event: boolean;\n steps_since_last_compact: number;\n loop_detected: boolean;\n}\n\nconst SAFE_TOOL_NAME_RE = /^[a-zA-Z0-9._-]{1,48}$/;\n\nfunction sanitizeToolCategory(raw: unknown): string {\n if (typeof raw !== \"string\") {\n return \"unknown_tool\";\n }\n const trimmed = raw.trim();\n if (SAFE_TOOL_NAME_RE.test(trimmed)) {\n return trimmed;\n }\n return \"unknown_tool\";\n}\n\n/**\n * Parses a transcript.jsonl file strictly for structural counters.\n * Never accesses or retains message content/text/arguments/paths.\n */\nexport async function analyzeTranscriptStructure(\n transcriptPath: string,\n loopThreshold = 4,\n): Promise<TranscriptStructuralMeta> {\n let rawText: string;\n try {\n rawText = await readFile(transcriptPath, \"utf8\");\n } catch {\n return emptyTranscriptMeta();\n }\n return parseTranscriptLines(rawText.split(\"\\n\"), loopThreshold);\n}\n\nexport function parseTranscriptLines(\n lines: string[],\n loopThreshold = 4,\n): TranscriptStructuralMeta {\n let totalSteps = 0;\n let userTurns = 0;\n let assistantTurns = 0;\n let toolCallCount = 0;\n let toolErrorCount = 0;\n let hasCompactEvent = false;\n let stepsSinceLastCompact = 0;\n\n let currentStreak = 0;\n let currentStreakTool: string | null = null;\n let maxConsecutiveFailures = 0;\n let maxFailureTool: string | null = null;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n totalSteps += 1;\n stepsSinceLastCompact += 1;\n\n const role = typeof parsed.role === \"string\" ? parsed.role.toLowerCase() : \"\";\n const eventType =\n typeof parsed.type === \"string\" ? parsed.type.toLowerCase() : \"\";\n const source =\n typeof parsed.source === \"string\" ? parsed.source.toUpperCase() : \"\";\n\n if (eventType === \"compact\" || eventType === \"compaction\") {\n hasCompactEvent = true;\n stepsSinceLastCompact = 0;\n continue;\n }\n\n if (\n role === \"user\" ||\n eventType === \"user_message\" ||\n eventType === \"user_input\" ||\n source === \"USER_EXPLICIT\"\n ) {\n userTurns += 1;\n // Human intervention resets autonomous failure streak\n currentStreak = 0;\n currentStreakTool = null;\n } else if (\n role === \"assistant\" ||\n role === \"model\" ||\n eventType === \"assistant_message\" ||\n eventType === \"planner_response\"\n ) {\n assistantTurns += 1;\n }\n\n if (Array.isArray(parsed.tool_calls)) {\n toolCallCount += parsed.tool_calls.length;\n for (const tc of parsed.tool_calls) {\n if (!tc || typeof tc !== \"object\") {\n continue;\n }\n const tcObj = tc as Record<string, unknown>;\n const toolName = sanitizeToolCategory(tcObj.tool_name ?? tcObj.name);\n const failed =\n tcObj.is_error === true ||\n tcObj.status === \"error\" ||\n tcObj.status === \"failed\" ||\n (typeof tcObj.exit_code === \"number\" && tcObj.exit_code !== 0);\n if (failed) {\n toolErrorCount += 1;\n if (currentStreakTool === toolName) {\n currentStreak += 1;\n } else {\n currentStreak = 1;\n currentStreakTool = toolName;\n }\n if (currentStreak > maxConsecutiveFailures) {\n maxConsecutiveFailures = currentStreak;\n maxFailureTool = toolName;\n }\n } else {\n currentStreak = 0;\n currentStreakTool = null;\n }\n }\n } else if (typeof parsed.tool_calls === \"number\" && Number.isFinite(parsed.tool_calls)) {\n toolCallCount += Math.max(0, Math.floor(parsed.tool_calls));\n }\n\n const isToolEvent =\n role === \"tool\" ||\n eventType === \"tool_call\" ||\n eventType === \"tool_result\" ||\n Boolean(parsed.tool_name);\n\n if (isToolEvent) {\n toolCallCount += 1;\n const toolName = sanitizeToolCategory(parsed.tool_name ?? parsed.name);\n const failed =\n parsed.is_error === true ||\n parsed.status === \"error\" ||\n parsed.status === \"failed\" ||\n (typeof parsed.exit_code === \"number\" && parsed.exit_code !== 0);\n\n if (failed) {\n toolErrorCount += 1;\n if (currentStreakTool === toolName) {\n currentStreak += 1;\n } else {\n currentStreak = 1;\n currentStreakTool = toolName;\n }\n if (currentStreak > maxConsecutiveFailures) {\n maxConsecutiveFailures = currentStreak;\n maxFailureTool = toolName;\n }\n } else {\n currentStreak = 0;\n currentStreakTool = null;\n }\n }\n }\n\n return {\n total_steps: totalSteps,\n user_turns: userTurns,\n assistant_turns: assistantTurns,\n tool_call_count: toolCallCount,\n tool_error_count: toolErrorCount,\n max_consecutive_tool_failures: maxConsecutiveFailures,\n consecutive_failure_tool_type: maxFailureTool,\n has_compact_event: hasCompactEvent,\n steps_since_last_compact: stepsSinceLastCompact,\n loop_detected: maxConsecutiveFailures >= loopThreshold,\n };\n}\n\nexport function emptyTranscriptMeta(): TranscriptStructuralMeta {\n return {\n total_steps: 0,\n user_turns: 0,\n assistant_turns: 0,\n tool_call_count: 0,\n tool_error_count: 0,\n max_consecutive_tool_failures: 0,\n consecutive_failure_tool_type: null,\n has_compact_event: false,\n steps_since_last_compact: 0,\n loop_detected: false,\n };\n}\n\nexport interface TranscriptWindowSummary {\n session_count: number;\n turn_count: number;\n tool_call_count: number;\n earliest_turn_at: string | null;\n}\n\nexport interface TranscriptActivityFallback {\n source: \"transcript_timestamps\";\n note: string;\n timezone: string;\n window_5h: TranscriptWindowSummary & {\n estimated_5h_reset_at: string | null;\n estimated_5h_reset_local: string | null;\n };\n window_7d: TranscriptWindowSummary;\n earliest_turn_5h_ms: number | null;\n earliest_turn_7d_ms: number | null;\n}\n\nexport function extractStructuralTimestampMs(\n parsed: Record<string, unknown>,\n): number | null {\n const raw = parsed.created_at ?? parsed.timestamp ?? parsed.ts;\n if (typeof raw === \"string\") {\n const ms = Date.parse(raw);\n return Number.isNaN(ms) ? null : ms;\n }\n if (typeof raw === \"number\" && Number.isFinite(raw)) {\n return raw > 1e12 ? raw : raw * 1000;\n }\n return null;\n}\n\nfunction formatLocalIsoish(ms: number, timezone?: string): string {\n const tz = timezone || Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n try {\n return new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(new Date(ms));\n } catch {\n return new Date(ms).toISOString();\n }\n}\n\n/**\n * Scans ~/.gemini/antigravity-cli/brain/<session>/.system_generated/logs/transcript.jsonl\n * strictly for structural timestamps, step/turn counts, and tool-call indicators.\n * PRIVACY RED LINE: NEVER reads, stores, or returns prompt text, model responses,\n * code diffs, file paths, or session UUIDs.\n */\nexport async function scanTranscriptActivity(options?: {\n brainDir?: string;\n nowMs?: number;\n timezone?: string;\n}): Promise<TranscriptActivityFallback> {\n const explicitBrainDir = options?.brainDir;\n let brainDir: string | null;\n if (explicitBrainDir !== undefined) {\n const trimmed = explicitBrainDir.trim();\n brainDir =\n trimmed.length === 0 || isBrainScanDisabledValue(trimmed)\n ? null\n : resolve(trimmed);\n } else {\n brainDir = getAgyBrainDir();\n }\n\n const nowMs = options?.nowMs ?? Date.now();\n const tz = options?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n\n const cutoff5h = nowMs - 5 * 3600 * 1000;\n const cutoff7d = nowMs - 7 * 86400 * 1000;\n\n let sessions5h = 0;\n let turns5h = 0;\n let tools5h = 0;\n let earliest5h: number | null = null;\n\n let sessions7d = 0;\n let turns7d = 0;\n let tools7d = 0;\n let earliest7d: number | null = null;\n\n let sessionDirs: string[] = [];\n if (brainDir !== null) {\n try {\n const entries = await readdir(brainDir, { withFileTypes: true });\n sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch {\n sessionDirs = [];\n }\n }\n\n for (const dirName of sessionDirs) {\n const transcriptPath = join(brainDir!, dirName, \".system_generated\", \"logs\", \"transcript.jsonl\");\n let rawText: string;\n try {\n rawText = await readFile(transcriptPath, \"utf8\");\n } catch {\n continue;\n }\n\n let seenIn5h = false;\n let seenIn7d = false;\n\n for (const line of rawText.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n const tsMs = extractStructuralTimestampMs(parsed);\n if (tsMs === null || tsMs < cutoff7d || tsMs > nowMs + 60_000) {\n continue;\n }\n\n const typeStr = typeof parsed.type === \"string\" ? parsed.type.toUpperCase() : \"\";\n const sourceStr = typeof parsed.source === \"string\" ? parsed.source.toUpperCase() : \"\";\n const roleStr = typeof parsed.role === \"string\" ? parsed.role.toLowerCase() : \"\";\n\n const isTurn =\n typeStr === \"USER_INPUT\" ||\n typeStr === \"PLANNER_RESPONSE\" ||\n typeStr === \"USER_MESSAGE\" ||\n typeStr === \"ASSISTANT_MESSAGE\" ||\n sourceStr === \"USER_EXPLICIT\" ||\n sourceStr === \"MODEL\" ||\n roleStr === \"user\" ||\n roleStr === \"assistant\" ||\n roleStr === \"model\" ||\n typeof parsed.step_index === \"number\";\n\n const isTool =\n typeStr === \"TOOL_CALL\" ||\n typeStr === \"TOOL_RESULT\" ||\n roleStr === \"tool\" ||\n Boolean(parsed.tool_name);\n\n if (tsMs >= cutoff7d) {\n seenIn7d = true;\n if (isTurn) turns7d += 1;\n if (isTool) tools7d += 1;\n if (earliest7d === null || tsMs < earliest7d) {\n earliest7d = tsMs;\n }\n }\n\n if (tsMs >= cutoff5h) {\n seenIn5h = true;\n if (isTurn) turns5h += 1;\n if (isTool) tools5h += 1;\n if (earliest5h === null || tsMs < earliest5h) {\n earliest5h = tsMs;\n }\n }\n }\n\n if (seenIn5h) sessions5h += 1;\n if (seenIn7d) sessions7d += 1;\n }\n\n const reset5hMs = earliest5h !== null ? earliest5h + 5 * 3600 * 1000 : null;\n\n return {\n source: \"transcript_timestamps\",\n note: \"Estimated from local AGY session timestamps; run agycraft-mcp setup for exact token counts.\",\n timezone: tz,\n window_5h: {\n session_count: sessions5h,\n turn_count: turns5h,\n tool_call_count: tools5h,\n earliest_turn_at: earliest5h !== null ? new Date(earliest5h).toISOString() : null,\n estimated_5h_reset_at: reset5hMs !== null ? new Date(reset5hMs).toISOString() : null,\n estimated_5h_reset_local: reset5hMs !== null ? formatLocalIsoish(reset5hMs, tz) : null,\n },\n window_7d: {\n session_count: sessions7d,\n turn_count: turns7d,\n tool_call_count: tools7d,\n earliest_turn_at: earliest7d !== null ? new Date(earliest7d).toISOString() : null,\n },\n earliest_turn_5h_ms: earliest5h,\n earliest_turn_7d_ms: earliest7d,\n };\n}\n\n/**\n * Builds a Map<conversationId, project_hash> from AGY history.jsonl.\n * PRIVACY RED LINE:\n * - NEVER reads, stores, or returns `display` or any prompt/user text.\n * - Immediately hashes `workspace` with local `.salt` and discards the raw path.\n */\nexport async function buildConversationProjectIndex(\n historyPath: string | null,\n salt: string,\n): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n if (!historyPath) {\n return index;\n }\n\n let rawText: string;\n try {\n rawText = await readFile(historyPath, \"utf8\");\n } catch {\n return index;\n }\n\n for (const line of rawText.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n const convId =\n typeof parsed.conversationId === \"string\" ? parsed.conversationId.trim() : \"\";\n const workspace =\n typeof parsed.workspace === \"string\" ? parsed.workspace.trim() : \"\";\n if (convId.length > 0 && workspace.length > 0) {\n index.set(convId, hashProjectPath(workspace, salt));\n }\n } catch {\n // Skip malformed JSONL lines safely\n }\n }\n\n return index;\n}\n\nexport interface CollectTranscriptUsageOptions {\n brainDir?: string | null;\n historyPath?: string | null;\n salt?: string;\n saltPath?: string;\n sinceMs?: number;\n nowMs?: number;\n authMode?: AuthMode;\n cliLogEvents?: CliLogAuthEvent[];\n hasMixedAuth?: boolean;\n}\n\nexport interface TranscriptUsageCollection {\n records: UsageRecord[];\n attributed_session_count: number;\n unattributed_session_count: number;\n}\n\nfunction firstNonNegInt(...candidates: unknown[]): number {\n for (const val of candidates) {\n if (val === null || val === undefined || val === \"\") {\n continue;\n }\n const n = typeof val === \"number\" ? val : Number(val);\n if (Number.isFinite(n) && n >= 0) {\n return Math.floor(n);\n }\n }\n return 0;\n}\n\nfunction resolveOptionalPath(\n explicit: string | null | undefined,\n fallbackFn: () => string | null,\n): string | null {\n if (explicit === null) {\n return null;\n }\n if (explicit !== undefined) {\n const trimmed = explicit.trim();\n if (trimmed.length === 0 || isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n return fallbackFn();\n}\n\n/**\n * Extracts real token & model usage records from AGY brain transcript.jsonl files\n * (e.g. PLANNER_RESPONSE events) and attributes each session to its hashed workspace via history.jsonl.\n * Unattributed derived/subagent sessions receive `project_hash: null` and are counted in `unattributed_session_count`.\n */\nexport function isPlaceholderOrUnknownModel(raw: unknown): boolean {\n if (typeof raw !== \"string\") return true;\n const trimmed = raw.trim();\n if (!trimmed) return true;\n const upper = trimmed.toUpperCase();\n return upper === \"UNKNOWN\" || upper.startsWith(\"MODEL_PLACEHOLDER_\");\n}\n\nexport function extractTranscriptExplicitModel(\n parsed: Record<string, unknown>,\n usageObj: Record<string, unknown>,\n): string | null {\n const raw = parsed.model ?? usageObj.model;\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n if (!trimmed || trimmed.toLowerCase() === \"unknown\") return null;\n return trimmed;\n}\n\nexport async function collectTranscriptUsageRecords(\n options?: CollectTranscriptUsageOptions,\n): Promise<TranscriptUsageCollection> {\n const brainDir = resolveOptionalPath(options?.brainDir, getAgyBrainDir);\n const historyPath = resolveOptionalPath(options?.historyPath, getAgyHistoryPath);\n const salt = options?.salt ?? (await getOrCreateLocalSalt(options?.saltPath));\n const nowMs = options?.nowMs ?? Date.now();\n const sinceMs = options?.sinceMs;\n\n const projectIndex = await buildConversationProjectIndex(historyPath, salt);\n\n const records: UsageRecord[] = [];\n let attributedSessionCount = 0;\n let unattributedSessionCount = 0;\n\n if (brainDir === null) {\n return {\n records,\n attributed_session_count: 0,\n unattributed_session_count: 0,\n };\n }\n\n let sessionDirs: string[] = [];\n try {\n const entries = await readdir(brainDir, { withFileTypes: true });\n sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch {\n return {\n records,\n attributed_session_count: 0,\n unattributed_session_count: 0,\n };\n }\n\n for (const sessionId of sessionDirs) {\n const transcriptPath = join(\n brainDir,\n sessionId,\n \".system_generated\",\n \"logs\",\n \"transcript.jsonl\",\n );\n let rawText: string;\n try {\n rawText = await readFile(transcriptPath, \"utf8\");\n } catch {\n continue;\n }\n\n const projectHash = projectIndex.get(sessionId) ?? null;\n let sessionHadRecord = false;\n\n const parsedEvents: Record<string, unknown>[] = [];\n const modelFreq = new Map<string, number>();\n\n for (const line of rawText.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n parsedEvents.push(parsed);\n\n const uObj =\n parsed.usage && typeof parsed.usage === \"object\" && !Array.isArray(parsed.usage)\n ? (parsed.usage as Record<string, unknown>)\n : {};\n const typeUpper = typeof parsed.type === \"string\" ? parsed.type.toUpperCase() : \"\";\n const explicitModel = extractTranscriptExplicitModel(parsed, uObj);\n if (\n typeUpper !== \"CHECKPOINT\" &&\n explicitModel !== null &&\n !isPlaceholderOrUnknownModel(explicitModel)\n ) {\n modelFreq.set(explicitModel, (modelFreq.get(explicitModel) ?? 0) + 1);\n }\n }\n\n let dominantModel: string | null = null;\n let dominantCount = 0;\n for (const [m, count] of modelFreq.entries()) {\n if (count > dominantCount) {\n dominantCount = count;\n dominantModel = m;\n }\n }\n\n let lastSeenModel: string | null = null;\n\n for (const parsed of parsedEvents) {\n const usageObj =\n parsed.usage && typeof parsed.usage === \"object\" && !Array.isArray(parsed.usage)\n ? (parsed.usage as Record<string, unknown>)\n : {};\n const typeStr = typeof parsed.type === \"string\" ? parsed.type.toUpperCase() : \"\";\n const explicitModel = extractTranscriptExplicitModel(parsed, usageObj);\n\n if (\n typeStr !== \"CHECKPOINT\" &&\n explicitModel !== null &&\n !isPlaceholderOrUnknownModel(explicitModel)\n ) {\n lastSeenModel = explicitModel;\n }\n\n const tsMs = extractStructuralTimestampMs(parsed);\n if (tsMs === null || tsMs > nowMs + 60_000) {\n continue;\n }\n if (sinceMs !== undefined && tsMs < sinceMs) {\n continue;\n }\n\n const rawInput = firstNonNegInt(\n parsed.input_tokens,\n usageObj.input_tokens,\n usageObj.prompt_tokens,\n );\n const rawCacheRead = firstNonNegInt(\n parsed.cache_read_tokens,\n usageObj.cache_read_tokens,\n usageObj.cached_content_token_count,\n );\n const rawOutput = firstNonNegInt(\n parsed.output_tokens,\n usageObj.output_tokens,\n usageObj.completion_tokens,\n );\n\n const totalInput = rawInput + rawCacheRead;\n if (\n typeStr !== \"PLANNER_RESPONSE\" &&\n totalInput === 0 &&\n rawOutput === 0\n ) {\n continue;\n }\n if (totalInput === 0 && rawOutput === 0) {\n continue;\n }\n\n const attributedModel =\n typeStr === \"CHECKPOINT\" || !explicitModel\n ? (lastSeenModel ?? dominantModel ?? \"unknown\")\n : explicitModel;\n\n const resolvedAuthMode =\n (options?.cliLogEvents && options.cliLogEvents.length > 0) ||\n options?.hasMixedAuth\n ? resolveAuthModeFromCliLogs(options?.cliLogEvents ?? [], tsMs, {\n fallbackAuthMode: options?.authMode ?? \"unknown\",\n hasMixedAuth: options?.hasMixedAuth,\n })\n : (options?.authMode ?? \"unknown\");\n\n const record = sanitizeUsagePayload(\n {\n ts: new Date(tsMs).toISOString(),\n provider: \"antigravity\",\n product: \"agy\",\n session_id: sessionId,\n model: attributedModel,\n input_tokens: rawInput,\n cache_read_tokens: rawCacheRead,\n output_tokens: rawOutput,\n thinking_tokens: 0,\n tool_calls: 0,\n turn_index: typeof parsed.step_index === \"number\" ? parsed.step_index : 0,\n project_hash: projectHash,\n auth_mode: resolvedAuthMode,\n },\n salt,\n );\n\n records.push(record);\n sessionHadRecord = true;\n }\n\n if (sessionHadRecord) {\n if (projectHash !== null) {\n attributedSessionCount += 1;\n } else {\n unattributedSessionCount += 1;\n }\n }\n }\n\n return {\n records,\n attributed_session_count: attributedSessionCount,\n unattributed_session_count: unattributedSessionCount,\n };\n}\n","import type { StatusSnapshot } from \"../types.js\";\n\nconst DEFAULT_DATA_URL = \"https://modelcraft.dev/data/v1\";\n\nexport interface PreflightOptions {\n statusUrl?: string;\n env?: NodeJS.ProcessEnv;\n fetchFn?: typeof fetch;\n timeoutMs?: number;\n}\n\nexport interface PreflightResult {\n ok: boolean;\n exit_code: 0 | 1;\n url: string;\n checked_at: string;\n overall_status: string;\n active_incidents_count: number;\n degraded_surfaces: Array<{ id: string; name: string; status: string }>;\n flagged_sources: Array<{\n id: string;\n http_status: number | string | null;\n error: string | null;\n }>;\n reasons: string[];\n error?: string;\n}\n\nexport function resolvePreflightStatusUrl(options?: {\n statusUrl?: string;\n env?: NodeJS.ProcessEnv;\n}): string {\n if (options?.statusUrl && options.statusUrl.trim().length > 0) {\n return options.statusUrl.trim();\n }\n const env = options?.env ?? process.env;\n const statusUrl = env.MODELCRAFT_STATUS_URL?.trim();\n if (statusUrl) {\n return statusUrl;\n }\n const dataUrl = env.MODELCRAFT_DATA_URL?.trim();\n const base = (dataUrl || DEFAULT_DATA_URL).replace(/\\/+$/, \"\");\n return `${base}/status.json`;\n}\n\nfunction isRateOrCapacityError(status: unknown, errorText: unknown): boolean {\n if (status === 429 || status === 503 || status === \"429\" || status === \"503\") {\n return true;\n }\n if (typeof errorText === \"string\" && /\\b(429|503)\\b/.test(errorText)) {\n return true;\n }\n return false;\n}\n\n/**\n * Live cloud preflight guard against ModelCraft status.json.\n * Performs a single parameterless GET with zero user identifiers or credentials.\n * Returns exit_code 0 only when upstream is operational with no active incidents,\n * no degraded surfaces, and no 429/503 source errors.\n */\nexport async function runPreflight(\n options?: PreflightOptions,\n): Promise<PreflightResult> {\n const url = resolvePreflightStatusUrl(options);\n const fetchFn = options?.fetchFn ?? globalThis.fetch;\n const timeoutMs = options?.timeoutMs ?? 5000;\n const checkedAt = new Date().toISOString();\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n let data: StatusSnapshot;\n try {\n const resp = await fetchFn(url, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n });\n\n if (!resp.ok) {\n const reason = `HTTP ${resp.status} ${resp.statusText || \"\"}`.trim();\n return {\n ok: false,\n exit_code: 1,\n url,\n checked_at: checkedAt,\n overall_status: \"unknown\",\n active_incidents_count: 0,\n degraded_surfaces: [],\n flagged_sources: [],\n reasons: [`Failed to fetch status.json (${reason})`],\n error: reason,\n };\n }\n\n data = (await resp.json()) as StatusSnapshot;\n } catch (err) {\n const msg =\n err instanceof Error\n ? err.name === \"AbortError\"\n ? `Request timed out after ${timeoutMs}ms`\n : err.message\n : String(err);\n return {\n ok: false,\n exit_code: 1,\n url,\n checked_at: checkedAt,\n overall_status: \"unknown\",\n active_incidents_count: 0,\n degraded_surfaces: [],\n flagged_sources: [],\n reasons: [`Failed to fetch status.json: ${msg}`],\n error: msg,\n };\n } finally {\n clearTimeout(timer);\n }\n\n const reasons: string[] = [];\n const overallStatus =\n typeof data?.overall_status === \"string\" ? data.overall_status : \"unknown\";\n if (overallStatus !== \"operational\") {\n reasons.push(\n `overall_status is \"${overallStatus}\" (expected \"operational\")`,\n );\n }\n\n const incidents = Array.isArray(data?.active_incidents)\n ? data.active_incidents\n : [];\n if (incidents.length > 0) {\n const titles = incidents\n .map((inc) => inc?.title || inc?.id || \"unnamed incident\")\n .slice(0, 3)\n .join(\"; \");\n reasons.push(\n `${incidents.length} active incident(s) reported: ${titles}`,\n );\n }\n\n const surfaces = Array.isArray(data?.surfaces) ? data.surfaces : [];\n const degradedSurfaces = surfaces\n .filter((s) => s && s.status !== \"operational\")\n .map((s) => ({\n id: String(s.id ?? \"unknown\"),\n name: String(s.name ?? s.id ?? \"unknown\"),\n status: String(s.status ?? \"unknown\"),\n }));\n for (const s of degradedSurfaces) {\n reasons.push(`surface \"${s.id}\" is \"${s.status}\"`);\n }\n\n const sources = Array.isArray(data?.sources_checked)\n ? data.sources_checked\n : [];\n const flaggedSources: Array<{\n id: string;\n http_status: number | string | null;\n error: string | null;\n }> = [];\n\n for (const src of sources) {\n if (typeof src === \"string\") {\n if (/\\b(429|503)\\b/.test(src)) {\n flaggedSources.push({ id: src, http_status: null, error: src });\n reasons.push(`source \"${src}\" reported 429/503`);\n }\n continue;\n }\n if (src && typeof src === \"object\") {\n const rec = src as Record<string, unknown>;\n const id = String(rec[\"id\"] ?? rec[\"url\"] ?? \"unknown\");\n const httpStatus =\n typeof rec[\"http_status\"] === \"number\" ||\n typeof rec[\"http_status\"] === \"string\"\n ? rec[\"http_status\"]\n : null;\n const errStr = typeof rec[\"error\"] === \"string\" ? rec[\"error\"] : null;\n if (isRateOrCapacityError(httpStatus, errStr)) {\n flaggedSources.push({ id, http_status: httpStatus, error: errStr });\n reasons.push(\n `source \"${id}\" reported ${httpStatus !== null ? `HTTP ${httpStatus}` : errStr ?? \"429/503\"}`,\n );\n }\n }\n }\n\n const ok = reasons.length === 0;\n return {\n ok,\n exit_code: ok ? 0 : 1,\n url,\n checked_at: checkedAt,\n overall_status: overallStatus,\n active_incidents_count: incidents.length,\n degraded_surfaces: degradedSurfaces,\n flagged_sources: flaggedSources,\n reasons,\n };\n}\n\nexport function formatPreflightReport(result: PreflightResult): string {\n const lines: string[] = [\n `agycraft-mcp preflight (${result.url})`,\n \"================================================================\",\n `Status: ${result.ok ? \"[PASS]\" : \"[FAIL]\"} overall_status=${result.overall_status} active_incidents=${result.active_incidents_count}`,\n ];\n\n if (result.reasons.length > 0) {\n lines.push(\"Blocking checks:\");\n for (const reason of result.reasons) {\n lines.push(` - ${reason}`);\n }\n } else {\n lines.push(\"All surfaces operational; no active incidents or 429/503 source errors.\");\n }\n\n return lines.join(\"\\n\");\n}\n","import { getUsageLogPath } from \"../paths.js\";\n\n/**\n * Generates non-destructive, opt-in setup instructions & snippets for\n * Antigravity (AGY) and Gemini CLI. Never modifies user files automatically.\n */\nexport function buildSetupInstructions(): string {\n const usagePath = getUsageLogPath();\n return [\n \"agycraft-mcp setup (non-destructive, opt-in instructions)\",\n \"================================================================\",\n \"No files have been modified automatically. Copy and paste only what you want.\",\n \"\",\n \"1. Register agycraft MCP Server:\",\n \"\",\n \" Option A — Antigravity CLI (`agy`) one-liner:\",\n \" agy mcp add agycraft npx -y agycraft-mcp\",\n \"\",\n \" (Local dev testing against a local ModelCraft server):\",\n \" agy mcp add --env MODELCRAFT_DATA_URL=http://127.0.0.1:4321/data/v1 agycraft agycraft-mcp\",\n \"\",\n \" Option B — Antigravity IDE (~/.gemini/antigravity/mcp_config.json)\",\n \" or Gemini CLI (~/.gemini/settings.json):\",\n \"\",\n JSON.stringify(\n {\n mcpServers: {\n agycraft: {\n command: \"npx\",\n args: [\"-y\", \"agycraft-mcp\"],\n },\n },\n },\n null,\n 2,\n ),\n \"\",\n \"2. (Optional) Enable Privacy-Safe Gemini CLI OpenTelemetry outfile (exact token & model metrics)\",\n \" Add to ~/.gemini/settings.json (logPrompts MUST remain false):\",\n \"\",\n JSON.stringify(\n {\n telemetry: {\n enabled: true,\n target: \"local\",\n otlpEndpoint: \"\",\n logPrompts: false,\n outfile: \"~/.gemini/telemetry_stats.jsonl\",\n },\n },\n null,\n 2,\n ),\n \"\",\n \"3. (Optional) Antigravity CLI Hook Recorder (numeric metadata ONLY)\",\n \" Add to ~/.gemini/config/hooks.json (leaves statusLine untouched):\",\n \"\",\n JSON.stringify(\n {\n hooks: {\n PostInvocation: [\n {\n matcher: \".*\",\n hooks: [\n {\n type: \"command\",\n command: \"npx -y agycraft-mcp record\",\n timeout: 3000,\n },\n ],\n },\n ],\n },\n },\n null,\n 2,\n ),\n \"\",\n ` Whitelisted numeric records are stored locally at: ${usagePath}`,\n \" (Strict whitelist: ts, provider, product, session_hash, model, input_tokens,\",\n \" output_tokens, context_used_pct, tool_calls, turn_index, error_code.\",\n \" Prompts, code, paths, and emails are NEVER written or uploaded.)\",\n \" Note: AGY PostInvocation hooks may only capture invocation timestamps/counts\",\n \" if token/model fields aren't emitted, whereas Gemini CLI OTel (step 2)\",\n \" provides exact token/model metrics.\",\n \"\",\n \"4. (Optional) Project-Scoped Sandbox Isolation (zero global ~/.config/agycraft writes):\",\n \" Set AGYCRAFT_CONFIG_DIR to isolate usage.jsonl, .salt, and cache/ inside your repo/sandbox:\",\n \" export AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft\",\n \"\",\n \" CLI one-liners:\",\n \" Gemini CLI (supports --scope project):\",\n \" gemini mcp add --scope project --env AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft agycraft npx -y agycraft-mcp\",\n \" Antigravity CLI:\",\n \" agy mcp add --env AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft agycraft npx -y agycraft-mcp\",\n \"\",\n \" Example sandboxed settings.json / mcp_config.json:\",\n JSON.stringify(\n {\n mcpServers: {\n agycraft: {\n command: \"npx\",\n args: [\"-y\", \"agycraft-mcp\"],\n env: {\n AGYCRAFT_CONFIG_DIR: \"./sandbox_repo/.agycraft\",\n },\n },\n },\n toolPermission: \"proceed-in-sandbox\",\n },\n null,\n 2,\n ),\n \" Note: \\\"toolPermission\\\": \\\"proceed-in-sandbox\\\" is an Antigravity top-level settings.json\",\n \" permission field (sibling to \\\"mcpServers\\\"). `agy mcp add` / `gemini mcp add` do not\",\n \" write this field automatically; add it manually at the top level if needed.\",\n \"\",\n \"5. Verify & Clear Local Data Anytime:\",\n \" npx agycraft-mcp doctor\",\n \" npx agycraft-mcp preflight\",\n \" npx agycraft-mcp clear-local-data\",\n ].join(\"\\n\");\n}\n","import { rm } from \"node:fs/promises\";\nimport {\n getCacheDir,\n getRollupsDir,\n getSaltFilePath,\n getUsageLogPath,\n} from \"../paths.js\";\nimport { resetSaltCache } from \"../collectors/agy-hook.js\";\n\nexport interface ClearLocalDataResult {\n removed: string[];\n}\n\n/**\n * Safely deletes local usage.jsonl, cache directory, rollups directory, and local salt file.\n */\nexport async function clearLocalData(options?: {\n usageLogPath?: string;\n cacheDir?: string;\n rollupsDir?: string;\n saltPath?: string;\n}): Promise<ClearLocalDataResult> {\n const usageLogPath = options?.usageLogPath ?? getUsageLogPath();\n const cacheDir = options?.cacheDir ?? getCacheDir();\n const rollupsDir = options?.rollupsDir ?? getRollupsDir();\n const saltPath = options?.saltPath ?? getSaltFilePath();\n\n const removed: string[] = [];\n\n for (const target of [usageLogPath, saltPath]) {\n try {\n await rm(target, { force: true });\n removed.push(target);\n } catch {\n // ignore if already absent\n }\n }\n\n for (const dir of [cacheDir, rollupsDir]) {\n try {\n await rm(dir, { recursive: true, force: true });\n removed.push(dir);\n } catch {\n // ignore if already absent\n }\n }\n\n resetSaltCache();\n return { removed };\n}\n","import { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { getUsageLogPath } from \"../paths.js\";\nimport {\n type UsageRecord,\n USAGE_RECORD_WHITELIST_KEYS,\n getOrCreateLocalSalt,\n hashProjectPath,\n hashSessionId,\n resetSaltCache,\n sanitizeAuthMode,\n sanitizeErrorCode,\n sanitizeModelName,\n sanitizeUsagePayload,\n} from \"../privacy.js\";\n\nexport {\n type UsageRecord,\n USAGE_RECORD_WHITELIST_KEYS,\n getOrCreateLocalSalt,\n hashProjectPath,\n hashSessionId,\n resetSaltCache,\n sanitizeAuthMode,\n sanitizeErrorCode,\n sanitizeModelName,\n sanitizeUsagePayload,\n};\n\nexport async function appendUsageRecord(\n rawPayload: Record<string, unknown>,\n options?: { logPath?: string; saltPath?: string },\n): Promise<UsageRecord> {\n const logPath = options?.logPath ?? getUsageLogPath();\n const salt = await getOrCreateLocalSalt(options?.saltPath);\n const record = sanitizeUsagePayload(rawPayload, salt);\n await mkdir(dirname(logPath), { recursive: true });\n await appendFile(logPath, `${JSON.stringify(record)}\\n`, {\n encoding: \"utf8\",\n mode: 0o600,\n });\n return record;\n}\n\nexport async function readUsageRecords(options?: {\n logPath?: string;\n sinceMs?: number;\n product?: \"agy\" | \"gemini-cli\" | \"api\" | \"web\" | \"all\";\n salt?: string;\n saltPath?: string;\n}): Promise<UsageRecord[]> {\n const logPath = options?.logPath ?? getUsageLogPath();\n let content: string;\n try {\n content = await readFile(logPath, \"utf8\");\n } catch {\n return [];\n }\n\n const salt = options?.salt ?? (await getOrCreateLocalSalt(options?.saltPath));\n const records: UsageRecord[] = [];\n const lines = content.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n // Re-validate strictly on read as well\n const safe = sanitizeUsagePayload(parsed, salt);\n if (options?.sinceMs !== undefined && Date.parse(safe.ts) < options.sinceMs) {\n continue;\n }\n if (\n options?.product &&\n options.product !== \"all\" &&\n safe.product !== options.product\n ) {\n continue;\n }\n records.push(safe);\n } catch {\n // Skip malformed JSONL lines safely\n }\n }\n\n return records;\n}\n","import { access } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport {\n getOrCreateLocalSalt,\n hashProjectPath,\n readUsageRecords,\n type UsageRecord,\n} from \"./collectors/agy-hook.js\";\nimport { detectAuthContext } from \"./collectors/auth-detector.js\";\nimport { ChannelRegistry } from \"./collectors/channel-registry.js\";\nimport { collectCliLogSignals } from \"./collectors/cli-log.js\";\nimport { readGeminiOtelRecords } from \"./collectors/gemini-otel.js\";\nimport {\n analyzeTranscriptStructure,\n collectTranscriptUsageRecords,\n scanTranscriptActivity,\n type TranscriptActivityFallback,\n} from \"./collectors/transcript-meta.js\";\nimport { analyzeTokenWindow, resolveDataMode } from \"./analyzers/token-window.js\";\nimport { analyzeAntipatterns } from \"./analyzers/antipatterns.js\";\nimport { diagnoseError } from \"./analyzers/error-diagnoser.js\";\nimport { computeResetCountdown } from \"./analyzers/countdown.js\";\nimport { SnapshotClient } from \"./remote/snapshot-client.js\";\nimport { isReadonlyEnv, queryRollups } from \"./storage/rollups.js\";\nimport {\n localizeModelEntry,\n localizeSnapshotText,\n resolveLocale,\n} from \"./i18n.js\";\nimport type { AuthContext, AuthMode } from \"./types.js\";\n\nexport interface ServerDependencies {\n snapshotClient?: SnapshotClient;\n usageLogPath?: string;\n geminiOtelPath?: string;\n brainDir?: string;\n historyPath?: string | null;\n cliLogDir?: string | null;\n saltPath?: string;\n rollupsDir?: string;\n readonly?: boolean;\n authContext?: AuthContext;\n defaultLang?: string;\n}\n\nasync function resolveSaltForServer(deps: ServerDependencies): Promise<string> {\n if (isReadonlyEnv(deps.readonly)) {\n try {\n return await getOrCreateLocalSalt(deps.saltPath);\n } catch {\n return \"readonly-ephemeral-salt\";\n }\n }\n return getOrCreateLocalSalt(deps.saltPath);\n}\n\nasync function resolveScopeProjectHash(\n scope: \"global\" | \"project\",\n workspaceDir: string | undefined,\n deps: ServerDependencies,\n): Promise<string | undefined> {\n if (scope !== \"project\") {\n return undefined;\n }\n const targetDir =\n workspaceDir && workspaceDir.trim().length > 0\n ? workspaceDir.trim()\n : process.cwd();\n const salt = await resolveSaltForServer(deps);\n return hashProjectPath(targetDir, salt);\n}\n\nfunction filterRecordsByScopeAndAuth(\n records: UsageRecord[],\n scope: \"global\" | \"project\",\n projectHash: string | undefined,\n authMode: AuthMode | \"all\",\n registry?: ChannelRegistry,\n): UsageRecord[] {\n return records.filter((r) => {\n if (authMode !== \"all\") {\n const recMode = r.auth_mode ?? \"unknown\";\n const matched = registry\n ? registry.matchesChannel(recMode, authMode)\n : recMode === authMode;\n if (!matched) {\n return false;\n }\n }\n if (scope === \"project\") {\n return Boolean(projectHash) && r.project_hash === projectHash;\n }\n return true;\n });\n}\n\nasync function loadCombinedLocalRecords(\n deps: ServerDependencies,\n sinceMs?: number,\n): Promise<UsageRecord[]> {\n const salt = await resolveSaltForServer(deps);\n const [agyRecords, otelRecords] = await Promise.all([\n readUsageRecords({ logPath: deps.usageLogPath, sinceMs, salt }),\n readGeminiOtelRecords({ otelPath: deps.geminiOtelPath, sinceMs, salt }),\n ]);\n return [...agyRecords, ...otelRecords];\n}\n\nasync function loadMergedUsageRecords(\n deps: ServerDependencies,\n options: {\n product: \"agy\" | \"gemini-cli\" | \"all\";\n activeAuthMode: AuthMode;\n hasMixedAuth?: boolean;\n sinceMs?: number;\n nowMs?: number;\n },\n): Promise<{ records: UsageRecord[]; dataModeOverride?: \"transcript_token_logs\" }> {\n const salt = await resolveSaltForServer(deps);\n const [agyHookRecords, otelRecords] = await Promise.all([\n readUsageRecords({ logPath: deps.usageLogPath, sinceMs: options.sinceMs, salt }),\n readGeminiOtelRecords({ otelPath: deps.geminiOtelPath, sinceMs: options.sinceMs, salt }),\n ]);\n\n const agyOnlyHooks = agyHookRecords.filter((r) => r.product === \"agy\");\n const nonAgyHooks = agyHookRecords.filter((r) => r.product !== \"agy\");\n const agyHasTokens = agyOnlyHooks.some(\n (r) => r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens > 0,\n );\n\n if (options.product === \"gemini-cli\") {\n return { records: [...otelRecords, ...nonAgyHooks] };\n }\n\n const effectiveCliLogDir =\n deps.cliLogDir !== undefined\n ? deps.cliLogDir\n : deps.brainDir !== undefined && !process.env.AGYCRAFT_CLI_LOG_DIR\n ? null\n : undefined;\n\n let transcriptRecords: UsageRecord[] = [];\n let cliBackgroundRecords: UsageRecord[] = [];\n if (!agyHasTokens) {\n const cliLogs = await collectCliLogSignals({\n cliLogDir: effectiveCliLogDir,\n sinceMs: options.sinceMs,\n nowMs: options.nowMs,\n salt,\n fallbackAuthMode: options.activeAuthMode,\n hasMixedAuth: options.hasMixedAuth,\n });\n const collected = await collectTranscriptUsageRecords({\n brainDir: deps.brainDir,\n historyPath: deps.historyPath,\n salt,\n sinceMs: options.sinceMs,\n nowMs: options.nowMs,\n authMode: options.activeAuthMode,\n cliLogEvents: cliLogs.authEvents,\n hasMixedAuth: options.hasMixedAuth,\n });\n transcriptRecords = collected.records;\n cliBackgroundRecords = cliLogs.backgroundRecords;\n }\n\n const combinedAgy = [...transcriptRecords, ...cliBackgroundRecords];\n const agySide = agyHasTokens\n ? agyOnlyHooks\n : combinedAgy.length > 0\n ? combinedAgy\n : agyOnlyHooks;\n\n const usedTranscriptOnly =\n !agyHasTokens &&\n combinedAgy.length > 0 &&\n (options.product === \"agy\" || otelRecords.length === 0);\n\n if (options.product === \"agy\") {\n return {\n records: agySide,\n ...(usedTranscriptOnly ? { dataModeOverride: \"transcript_token_logs\" } : {}),\n };\n }\n\n return {\n records: [...agySide, ...nonAgyHooks, ...otelRecords],\n ...(usedTranscriptOnly ? { dataModeOverride: \"transcript_token_logs\" } : {}),\n };\n}\n\nfunction buildActivitySummary(\n fallback: TranscriptActivityFallback,\n windowLabel: \"5h\" | \"7d\",\n): string | undefined {\n const stats = windowLabel === \"5h\" ? fallback.window_5h : fallback.window_7d;\n if (stats.session_count === 0 && stats.turn_count === 0) {\n return undefined;\n }\n const resetPart = fallback.window_5h.estimated_5h_reset_local\n ? `; estimated 5h rolling reset at ${fallback.window_5h.estimated_5h_reset_local}`\n : \"\";\n 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).`;\n}\n\nexport function createAgycraftServer(deps: ServerDependencies = {}): McpServer {\n const client = deps.snapshotClient ?? new SnapshotClient();\n\n const server = new McpServer({\n name: \"agycraft-mcp\",\n version: \"0.2.2\",\n });\n\n // 1. analyze_token_usage\n server.tool(\n \"analyze_token_usage\",\n \"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.\",\n {\n window: z.enum([\"5h\", \"24h\", \"7d\", \"30d\", \"all\"]).default(\"5h\"),\n granularity: z\n .enum([\"summary\", \"hourly\", \"daily\", \"weekly\", \"monthly\"])\n .default(\"summary\"),\n timezone: z\n .string()\n .optional()\n .describe(\"IANA timezone for time-series bucketing (default: UTC).\"),\n max_buckets: z\n .number()\n .int()\n .min(1)\n .max(90)\n .default(31)\n .describe(\"Maximum number of time-series buckets to return (1..90, default: 31).\"),\n product: z.enum([\"agy\", \"gemini-cli\", \"all\"]).default(\"all\"),\n scope: z.enum([\"global\", \"project\"]).default(\"global\"),\n workspace_dir: z\n .string()\n .optional()\n .describe(\n \"Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned).\",\n ),\n auth_mode: z\n .string()\n .default(\"all\")\n .describe(\"Optional auth channel filter ('all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', 'unknown', or any registered channel_id).\"),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ window, granularity, timezone, max_buckets, product, scope, workspace_dir, auth_mode, lang }) => {\n const locale = resolveLocale(lang, process.env);\n const effectiveLocale = lang === \"auto\" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : locale;\n const [modelsSnap, channelsSnap, projectHash] = await Promise.all([\n client.get(\"models\"),\n client.get(\"channels\"),\n resolveScopeProjectHash(scope, workspace_dir, deps),\n ]);\n const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);\n const authContext = deps.authContext\n ? deps.authContext\n : await detectAuthContext({ cliLogDir: deps.cliLogDir, registry });\n\n if (granularity !== \"summary\") {\n const salt = await resolveSaltForServer(deps);\n const rollupRes = await queryRollups({\n rollupsDir: deps.rollupsDir,\n usageLogPath: deps.usageLogPath,\n geminiOtelPath: deps.geminiOtelPath,\n brainDir: deps.brainDir,\n historyPath: deps.historyPath,\n saltPath: deps.saltPath,\n salt,\n models: modelsSnap.data.models,\n normalizationRules: modelsSnap.data.normalization_rules,\n window,\n granularity,\n product,\n scope,\n projectHash,\n authMode: auth_mode,\n timezone,\n maxBuckets: max_buckets,\n readonly: deps.readonly,\n transcriptAuthMode: authContext.active_auth_mode,\n cliLogDir: deps.cliLogDir,\n hasMixedAuth: authContext.has_mixed_auth,\n });\n\n const tot = rollupRes.summary_totals;\n const isSpecificAuthEmpty = auth_mode !== \"all\" && tot.requests === 0;\n const dataMode = resolveDataMode(tot.requests, tot.total_tokens);\n const usageNote = isSpecificAuthEmpty\n ? `No usage records matched auth_mode=\"${auth_mode}\" in the ${window} window (active local auth mode is \"${authContext.active_auth_mode}\").`\n : dataMode === \"hook_events_without_tokens\"\n ? `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.`\n : undefined;\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n window,\n granularity,\n product_filter: product,\n scope,\n ...(scope === \"project\" && projectHash\n ? {\n project_hash: projectHash,\n unattributed_sessions_excluded: tot.unattributed_sessions_excluded,\n }\n : {}),\n auth_mode_filter: auth_mode,\n data_mode: dataMode,\n ...(usageNote ? { usage_note: usageNote } : {}),\n record_count: tot.requests,\n session_count: isSpecificAuthEmpty ? 0 : tot.session_count,\n total_uncached_input_tokens: tot.uncached_input_tokens,\n total_cache_read_tokens: tot.cache_read_tokens,\n total_input_tokens: tot.input_tokens,\n total_output_tokens: tot.output_tokens,\n total_tokens: tot.total_tokens,\n cache_hit_rate_pct: tot.cache_hit_rate_pct,\n error_count: tot.error_count,\n rate_limit_429_count: tot.rate_limit_429_count,\n below_kv_cache_threshold_requests: tot.below_kv_cache_threshold_requests,\n estimated_total_usd: tot.estimated_total_usd,\n estimated_cache_savings_usd: tot.estimated_cache_savings_usd,\n time_series: rollupRes.time_series,\n time_series_meta: rollupRes.time_series_meta,\n models_snapshot_source: modelsSnap.source,\n locale: effectiveLocale,\n privacy_note:\n effectiveLocale === \"zh\"\n ? \"100% 本地数值聚合;零用户数据上传。\"\n : \"100% local numeric aggregation; zero user data uploaded.\",\n },\n null,\n 2,\n ),\n },\n ],\n };\n }\n\n const merged = await loadMergedUsageRecords(deps, {\n product,\n activeAuthMode: authContext.active_auth_mode,\n hasMixedAuth: authContext.has_mixed_auth,\n });\n\n const analysis = analyzeTokenWindow(merged.records, {\n window,\n product,\n models: modelsSnap.data.models,\n normalizationRules: modelsSnap.data.normalization_rules,\n scope,\n projectHash,\n authMode: auth_mode,\n activeAuthMode: authContext.active_auth_mode,\n dataModeOverride: merged.dataModeOverride,\n });\n\n const isSpecificAuthEmpty = auth_mode !== \"all\" && analysis.record_count === 0;\n const transcriptFallback =\n !isSpecificAuthEmpty && analysis.record_count === 0 && scope === \"global\"\n ? await scanTranscriptActivity({ brainDir: deps.brainDir })\n : undefined;\n\n const summaryWindow = window === \"5h\" ? \"5h\" : \"7d\";\n const activitySummary = transcriptFallback\n ? buildActivitySummary(transcriptFallback, summaryWindow)\n : undefined;\n const effectiveSessionCount = isSpecificAuthEmpty\n ? 0\n : analysis.record_count > 0\n ? analysis.session_count\n : summaryWindow === \"5h\"\n ? (transcriptFallback?.window_5h.session_count ?? 0)\n : (transcriptFallback?.window_7d.session_count ?? 0);\n\n const finalAnalysis = isSpecificAuthEmpty\n ? {\n ...analysis,\n usage_note: `No usage records matched auth_mode=\"${auth_mode}\" in the ${window} window (active local auth mode is \"${authContext.active_auth_mode}\").`,\n }\n : analysis;\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n ...(activitySummary ? { activity_summary: activitySummary } : {}),\n ...finalAnalysis,\n session_count: effectiveSessionCount,\n ...(transcriptFallback\n ? { transcript_activity_fallback: transcriptFallback }\n : {}),\n models_snapshot_source: modelsSnap.source,\n locale: effectiveLocale,\n privacy_note:\n effectiveLocale === \"zh\"\n ? \"100% 本地数值聚合;零用户数据上传。\"\n : \"100% local numeric aggregation; zero user data uploaded.\",\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // 2. get_saving_recommendations\n server.tool(\n \"get_saving_recommendations\",\n \"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.\",\n {\n window: z.enum([\"24h\", \"7d\"]).default(\"24h\"),\n scope: z.enum([\"global\", \"project\"]).default(\"global\"),\n transcript_path: z\n .string()\n .optional()\n .describe(\"Optional local transcript.jsonl path for structural step/loop counting only (never reads prompt/content).\"),\n loopThreshold: z\n .number()\n .int()\n .positive()\n .default(4)\n .describe(\"Consecutive tool-failure streak threshold for infinite-loop detection (default: 4).\"),\n workspace_dir: z\n .string()\n .optional()\n .describe(\"Optional workspace directory path for .geminiignore check and project-scoped filtering.\"),\n timezone: z\n .string()\n .optional()\n .describe(\"IANA timezone for peak_hours bucketing (default: UTC).\"),\n auth_mode: z\n .string()\n .default(\"auto\")\n .describe(\"Optional auth channel filter ('auto', 'all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id).\"),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ window, scope, transcript_path, loopThreshold, workspace_dir, timezone, auth_mode, lang }) => {\n const effectiveLocale =\n lang === \"auto\" && deps.defaultLang\n ? resolveLocale(deps.defaultLang, process.env)\n : resolveLocale(lang, process.env);\n const [modelsSnap, channelsSnap, projectHash, transcriptMeta, hasGeminiIgnore] =\n await Promise.all([\n client.get(\"models\"),\n client.get(\"channels\"),\n resolveScopeProjectHash(scope, workspace_dir, deps),\n transcript_path\n ? analyzeTranscriptStructure(transcript_path, loopThreshold)\n : Promise.resolve(null),\n workspace_dir\n ? access(join(workspace_dir, \".geminiignore\"))\n .then(() => true)\n .catch(() => false)\n : Promise.resolve(undefined),\n ]);\n const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);\n const authContext = deps.authContext\n ? deps.authContext\n : await detectAuthContext({ cliLogDir: deps.cliLogDir, registry });\n\n const merged = await loadMergedUsageRecords(deps, {\n product: \"all\",\n activeAuthMode: authContext.active_auth_mode,\n hasMixedAuth: authContext.has_mixed_auth,\n });\n\n const salt = await resolveSaltForServer(deps);\n const rollupHourly = await queryRollups({\n rollupsDir: deps.rollupsDir,\n usageLogPath: deps.usageLogPath,\n geminiOtelPath: deps.geminiOtelPath,\n brainDir: deps.brainDir,\n historyPath: deps.historyPath,\n cliLogDir: deps.cliLogDir,\n hasMixedAuth: authContext.has_mixed_auth,\n saltPath: deps.saltPath,\n salt,\n models: modelsSnap.data.models,\n normalizationRules: modelsSnap.data.normalization_rules,\n window,\n granularity: \"hourly\",\n product: \"all\",\n scope,\n projectHash,\n timezone,\n maxBuckets: 90,\n readonly: deps.readonly,\n transcriptAuthMode: authContext.active_auth_mode,\n }).catch(() => null);\n\n const report = analyzeAntipatterns(merged.records, {\n window,\n scope,\n projectHash,\n transcriptMeta,\n hasGeminiIgnore,\n hourlyBuckets: rollupHourly?.time_series,\n models: modelsSnap.data.models,\n timezone,\n authContext: {\n active_auth_mode: authContext.active_auth_mode,\n has_mixed_auth: authContext.has_mixed_auth,\n },\n authMode: auth_mode,\n channels: registry,\n locale: effectiveLocale,\n });\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n ...report,\n locale: effectiveLocale,\n transcript_structure: transcriptMeta,\n more_tips_url: \"https://modelcraft.dev/quotas\",\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // 3. diagnose_error\n server.tool(\n \"diagnose_error\",\n \"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.\",\n {\n error_text: z.string().min(1).describe(\"Raw error message or JSON snippet.\"),\n product: z.enum([\"agy\", \"cli\", \"api\", \"web\"]).optional(),\n doctor_summary: z.string().optional(),\n auth_mode: z\n .string()\n .default(\"auto\")\n .describe(\"Optional auth channel hint ('auto', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id).\"),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ error_text, product, auth_mode, lang }) => {\n const effectiveLocale =\n lang === \"auto\" && deps.defaultLang\n ? resolveLocale(deps.defaultLang, process.env)\n : resolveLocale(lang, process.env);\n const [records, statusSnap, diagnosisSnap, channelsSnap] = await Promise.all([\n loadCombinedLocalRecords(deps),\n client.get(\"status\"),\n client.get(\"diagnosis\"),\n client.get(\"channels\"),\n ]);\n const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);\n const [authContext, cliSignals] = await Promise.all([\n deps.authContext\n ? Promise.resolve(deps.authContext)\n : detectAuthContext({ registry }),\n deps.cliLogDir !== null\n ? collectCliLogSignals({ cliLogDir: deps.cliLogDir, registry }).catch(() => null)\n : Promise.resolve(null),\n ]);\n const latestCliEvent =\n cliSignals && cliSignals.authEvents.length > 0\n ? cliSignals.authEvents[cliSignals.authEvents.length - 1]\n : undefined;\n const cliChannel =\n latestCliEvent && Date.now() - latestCliEvent.tsMs <= 12 * 3600_000\n ? (latestCliEvent.channelId ?? latestCliEvent.authMode)\n : undefined;\n\n const result = diagnoseError({\n errorText: error_text,\n product,\n localRecords: records,\n statusSnapshot: statusSnap.data,\n diagnosisEntries: diagnosisSnap.data.entries,\n authMode: auth_mode,\n authContext,\n cliChannel,\n channels: registry,\n locale: effectiveLocale,\n });\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n ...result,\n locale: effectiveLocale,\n data_sources: {\n status: statusSnap.source,\n diagnosis: diagnosisSnap.source,\n },\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // 4. lookup_model_guide\n server.tool(\n \"lookup_model_guide\",\n \"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.\",\n {\n task: z.string().optional().describe(\"Task description (e.g. 'architecture', 'multi-file refactor', 'quick qa', 'batch').\"),\n model_id: z.string().optional().describe(\"Specific model id, api_model_id, or codename (e.g. 'neon', 'hydrogen', 'argon', 'gemini-3.8-flash').\"),\n provider: z.enum([\"google\", \"antigravity\", \"anthropic\", \"all\"]).default(\"all\"),\n include_history: z.boolean().default(false),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ task, model_id, provider, include_history, lang }) => {\n const effectiveLocale =\n lang === \"auto\" && deps.defaultLang\n ? resolveLocale(deps.defaultLang, process.env)\n : resolveLocale(lang, process.env);\n const [modelsSnap, chronicleSnap] = await Promise.all([\n client.get(\"models\"),\n include_history ? client.get(\"chronicle\") : Promise.resolve(null),\n ]);\n\n let models = modelsSnap.data.models;\n if (provider === \"antigravity\") {\n models = models.filter(\n (m) =>\n m.provider === \"antigravity\" ||\n Boolean(m.availability?.products?.includes(\"agy\")),\n );\n } else if (provider !== \"all\") {\n models = models.filter((m) => m.provider === provider);\n }\n\n let matched = models;\n if (model_id) {\n const needle = model_id.toLowerCase();\n matched = models.filter(\n (m) =>\n m.id.toLowerCase().includes(needle) ||\n m.api_model_id.toLowerCase().includes(needle) ||\n m.display_name.toLowerCase().includes(needle) ||\n Boolean(m.aliases?.some((a) => a.toLowerCase().includes(needle))) ||\n (m.codename && m.codename.toLowerCase().includes(needle)),\n );\n } else if (task) {\n const needle = task.toLowerCase();\n const scored = models\n .filter((m) => m.lifecycle !== \"deprecated\" && m.lifecycle !== \"removed\")\n .map((m) => {\n let score = 0;\n if (m.best_for.some((b) => b.toLowerCase().includes(needle) || needle.includes(b.toLowerCase()))) {\n score += 3;\n }\n if (m.summary.toLowerCase().includes(needle)) {\n score += 2;\n }\n if (needle.includes(\"plan\") || needle.includes(\"architect\") || needle.includes(\"debug\")) {\n if (m.specs.reasoning_tier === \"flagship\" || m.id.includes(\"neon\")) score += 4;\n }\n if (needle.includes(\"fast\") || needle.includes(\"cheap\") || needle.includes(\"edit\") || needle.includes(\"test\") || needle.includes(\"refactor\")) {\n if (m.quota_profile.shared_bucket_cost_tier === \"low\" || m.id.includes(\"hydrogen\") || m.id.includes(\"flash\")) score += 4;\n }\n if (needle.includes(\"batch\") || needle.includes(\"bulk\") || needle.includes(\"high-volume\")) {\n if (m.id.includes(\"flash-lite\") || m.id.includes(\"flash\")) score += 4;\n }\n return { model: m, score };\n })\n .sort((a, b) => b.score - a.score);\n matched = scored.slice(0, 3).map((s) => s.model);\n } else if (!include_history) {\n matched = models.filter(\n (m) => m.lifecycle !== \"deprecated\" && m.lifecycle !== \"removed\",\n );\n }\n\n const history =\n include_history && chronicleSnap\n ? chronicleSnap.data.entries.filter((e) => {\n if (!model_id) return true;\n const needle = model_id.toLowerCase();\n return (\n e.entity_ids.some((id) => id.toLowerCase().includes(needle)) ||\n e.title.toLowerCase().includes(needle)\n );\n })\n : undefined;\n\n const deprecationWarnings = matched\n .filter((m) => m.lifecycle === \"deprecated\" || m.lifecycle === \"removed\")\n .map((m) => ({\n model: m.id,\n lifecycle: m.lifecycle,\n deprecated_date: m.deprecated_date,\n replacement_model_id: m.replacement_model_id,\n }));\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n models: matched.map((m) => localizeModelEntry(m, effectiveLocale)),\n orchestrator_recipes: localizeSnapshotText(\n modelsSnap.data.orchestrator_recipes,\n effectiveLocale,\n ),\n deprecation_warnings: deprecationWarnings,\n chronicle_history: history?.map((h) => localizeSnapshotText(h, effectiveLocale)),\n locale: effectiveLocale,\n guide_url: \"https://modelcraft.dev/models\",\n official_source_urls: [\n ...new Set(matched.flatMap((m) => m.official_source_urls ?? [])),\n ],\n snapshot_source: modelsSnap.source,\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // 5. get_ecosystem_status\n server.tool(\n \"get_ecosystem_status\",\n \"Get live Gemini & Antigravity upstream status, latest CLI/SDK versions, recent official updates, quota rules, and local PT midnight + 5h/7d rolling reset countdowns.\",\n {\n plan: z.enum([\"free\", \"pro\", \"ultra\"]).optional(),\n product: z.enum([\"agy\", \"cli\", \"api\", \"web\"]).optional(),\n timezone: z.string().optional().describe(\"IANA timezone (e.g. 'Asia/Shanghai', 'America/Los_Angeles').\"),\n scope: z.enum([\"global\", \"project\"]).default(\"global\"),\n workspace_dir: z\n .string()\n .optional()\n .describe(\n \"Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned).\",\n ),\n auth_mode: z\n .string()\n .default(\"all\")\n .describe(\"Optional auth channel filter ('all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', 'unknown', or any registered channel_id).\"),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ plan, product, timezone, scope, workspace_dir, auth_mode, lang }) => {\n const effectiveLocale =\n lang === \"auto\" && deps.defaultLang\n ? resolveLocale(deps.defaultLang, process.env)\n : resolveLocale(lang, process.env);\n const nowMs = Date.now();\n const since7d = nowMs - 7 * 86400 * 1000;\n const [statusSnap, quotasSnap, updatesSnap, channelsSnap, projectHash] =\n await Promise.all([\n client.get(\"status\"),\n client.get(\"quotas\"),\n client.get(\"updates\"),\n client.get(\"channels\"),\n resolveScopeProjectHash(scope, workspace_dir, deps),\n ]);\n const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);\n const authContext = deps.authContext\n ? deps.authContext\n : await detectAuthContext({ cliLogDir: deps.cliLogDir, registry });\n\n const merged = await loadMergedUsageRecords(deps, {\n product: \"all\",\n activeAuthMode: authContext.active_auth_mode,\n hasMixedAuth: authContext.has_mixed_auth,\n sinceMs: since7d,\n nowMs,\n });\n\n const effectiveBase = filterRecordsByScopeAndAuth(\n merged.records,\n \"global\",\n undefined,\n auth_mode,\n registry,\n );\n const effectiveRecords = filterRecordsByScopeAndAuth(\n merged.records,\n scope,\n projectHash,\n auth_mode,\n registry,\n );\n const effectiveTotalTokens7d = effectiveRecords.reduce(\n (sum, r) => sum + r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens,\n 0,\n );\n const usingTranscriptTokenLogs = merged.dataModeOverride === \"transcript_token_logs\";\n const unattributedExcluded = new Set(\n effectiveBase\n .filter((r) => !r.project_hash)\n .map((r) => r.session_hash || \"default-session\"),\n ).size;\n\n const fiveHoursAgo = nowMs - 5 * 3600 * 1000;\n const in5h = effectiveRecords\n .map((r) => Date.parse(r.ts))\n .filter((t) => !Number.isNaN(t) && t >= fiveHoursAgo);\n const in7d = effectiveRecords\n .map((r) => Date.parse(r.ts))\n .filter((t) => !Number.isNaN(t));\n\n const isSpecificAuthEmpty = auth_mode !== \"all\" && effectiveRecords.length === 0;\n const transcriptFallback =\n !isSpecificAuthEmpty && effectiveRecords.length === 0 && scope === \"global\"\n ? await scanTranscriptActivity({\n brainDir: deps.brainDir,\n nowMs,\n timezone,\n })\n : undefined;\n\n const countdown = computeResetCountdown({\n now: new Date(nowMs),\n timezone,\n oldestEventIn5hMs:\n in5h.length > 0\n ? Math.min(...in5h)\n : transcriptFallback?.earliest_turn_5h_ms ?? null,\n oldestEventIn7dMs:\n in7d.length > 0\n ? Math.min(...in7d)\n : transcriptFallback?.earliest_turn_7d_ms ?? null,\n });\n\n const filteredPlans = plan\n ? quotasSnap.data.plans.filter(\n (p) =>\n p.id.toLowerCase().includes(plan) ||\n p.name.toLowerCase().includes(plan),\n )\n : quotasSnap.data.plans;\n\n const filteredUpdates = product\n ? updatesSnap.data.items.filter(\n (u) => u.product === product || u.product === \"all\",\n )\n : updatesSnap.data.items;\n\n const statusActivitySummary = transcriptFallback\n ? buildActivitySummary(transcriptFallback, \"5h\")\n : undefined;\n\n const statusDataMode = resolveDataMode(\n effectiveRecords.length,\n effectiveTotalTokens7d,\n usingTranscriptTokenLogs ? \"transcript_token_logs\" : undefined,\n );\n const statusUsageNote = isSpecificAuthEmpty\n ? `No usage records matched auth_mode=\"${auth_mode}\" in the 7d window (active local auth mode is \"${authContext.active_auth_mode}\").`\n : statusDataMode === \"hook_events_without_tokens\"\n ? `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.`\n : undefined;\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n ...(statusActivitySummary\n ? { activity_summary: statusActivitySummary }\n : {}),\n scope,\n ...(scope === \"project\" && projectHash\n ? {\n project_hash: projectHash,\n unattributed_sessions_excluded: unattributedExcluded,\n }\n : {}),\n auth_mode_filter: auth_mode,\n auth_context: authContext,\n data_mode: statusDataMode,\n ...(statusUsageNote ? { usage_note: statusUsageNote } : {}),\n session_count: isSpecificAuthEmpty\n ? 0\n : effectiveRecords.length > 0\n ? new Set(effectiveRecords.map((r) => r.session_hash)).size\n : (transcriptFallback?.window_5h.session_count ?? 0),\n overall_status: statusSnap.data.overall_status,\n surfaces: localizeSnapshotText(statusSnap.data.surfaces, effectiveLocale),\n active_incidents: localizeSnapshotText(\n statusSnap.data.active_incidents,\n effectiveLocale,\n ),\n latest_versions: statusSnap.data.latest_versions,\n countdown,\n ...(transcriptFallback\n ? { transcript_activity_fallback: transcriptFallback }\n : {}),\n quota_rules: localizeSnapshotText(\n {\n reset_rules: quotasSnap.data.reset_rules,\n ...(typeof quotasSnap.data.reset_rules_notes_zh === \"string\"\n ? { reset_rules_notes_zh: quotasSnap.data.reset_rules_notes_zh }\n : {}),\n },\n effectiveLocale,\n ).reset_rules,\n plans: filteredPlans.map((p) => localizeSnapshotText(p, effectiveLocale)),\n recent_updates: filteredUpdates\n .slice(0, 8)\n .map((u) => localizeSnapshotText(u, effectiveLocale)),\n locale: effectiveLocale,\n dashboard_url: \"https://modelcraft.dev\",\n official_source_urls: quotasSnap.data.official_source_urls ?? [],\n snapshot_sources: {\n status: statusSnap.source,\n quotas: quotasSnap.source,\n updates: updatesSnap.source,\n },\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n return server;\n}\n\nexport async function startStdioServer(deps: ServerDependencies = {}): Promise<void> {\n const server = createAgycraftServer(deps);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { getDefaultGeminiTelemetryPath } from \"../paths.js\";\nimport {\n type UsageRecord,\n getOrCreateLocalSalt,\n hashSessionId,\n sanitizeUsagePayload,\n} from \"./agy-hook.js\";\n\n/**\n * Readonly parser for Gemini CLI OpenTelemetry outfile (~/.gemini/telemetry_stats.jsonl).\n * PRIVACY RED LINE: Only extracts numeric token counts, model name, timestamp, error code,\n * and hashed session ID. Explicitly ignores any prompt/completion body even if present.\n */\nexport async function readGeminiOtelRecords(options?: {\n otelPath?: string;\n sinceMs?: number;\n salt?: string;\n saltPath?: string;\n}): Promise<UsageRecord[]> {\n const otelPath = options?.otelPath ?? getDefaultGeminiTelemetryPath();\n const salt = options?.salt ?? (await getOrCreateLocalSalt(options?.saltPath));\n\n let content: string;\n try {\n content = await readFile(otelPath, \"utf8\");\n } catch {\n return [];\n }\n\n const records: UsageRecord[] = [];\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n try {\n const entry = JSON.parse(trimmed) as Record<string, unknown>;\n const attrs = extractOtelAttributes(entry);\n\n const inputTokens = firstNumber(\n attrs[\"gen_ai.usage.input_tokens\"],\n attrs[\"input_token_count\"],\n attrs[\"prompt_tokens\"],\n entry[\"input_tokens\"],\n entry[\"prompt_tokens\"],\n );\n const outputTokens = firstNumber(\n attrs[\"gen_ai.usage.output_tokens\"],\n attrs[\"output_token_count\"],\n attrs[\"completion_tokens\"],\n entry[\"output_tokens\"],\n entry[\"completion_tokens\"],\n );\n\n const cacheReadTokens = firstNumber(\n attrs[\"gen_ai.usage.cache_read_input_tokens\"],\n attrs[\"cache_read_tokens\"],\n attrs[\"cached_content_token_count\"],\n entry[\"cache_read_tokens\"],\n );\n const thinkingTokens = firstNumber(\n attrs[\"gen_ai.usage.thinking_tokens\"],\n attrs[\"thinking_tokens\"],\n attrs[\"thoughts_token_count\"],\n entry[\"thinking_tokens\"],\n );\n\n // Skip non-LLM spans that have no token usage and no error code\n const errorCode =\n attrs[\"error.type\"] ??\n attrs[\"http.response.status_code\"] ??\n entry[\"error_code\"] ??\n null;\n if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0 && !errorCode) {\n continue;\n }\n\n const rawSession = String(\n attrs[\"session.id\"] ?? entry[\"session_id\"] ?? \"gemini-cli-session\",\n );\n\n const record = sanitizeUsagePayload(\n {\n ts: entry[\"timestamp\"] ?? entry[\"ts\"] ?? entry[\"startTime\"],\n provider: \"google\",\n product: \"gemini-cli\",\n session_hash: hashSessionId(rawSession, salt),\n model:\n attrs[\"gen_ai.request.model\"] ??\n attrs[\"gen_ai.response.model\"] ??\n attrs[\"model\"] ??\n entry[\"model\"] ??\n \"unknown\",\n input_tokens: inputTokens,\n cache_read_tokens: cacheReadTokens,\n output_tokens: outputTokens,\n thinking_tokens: thinkingTokens,\n context_used_pct: attrs[\"context_used_pct\"] ?? null,\n tool_calls: firstNumber(attrs[\"tool_calls\"], entry[\"tool_calls\"]),\n turn_index: firstNumber(attrs[\"turn_index\"], entry[\"turn_index\"]),\n error_code: errorCode,\n },\n salt,\n );\n\n if (options?.sinceMs !== undefined && Date.parse(record.ts) < options.sinceMs) {\n continue;\n }\n records.push(record);\n } catch {\n // Skip malformed lines safely\n }\n }\n\n return records;\n}\n\nfunction extractOtelAttributes(\n entry: Record<string, unknown>,\n): Record<string, unknown> {\n const attrs = entry[\"attributes\"];\n if (attrs && typeof attrs === \"object\" && !Array.isArray(attrs)) {\n return attrs as Record<string, unknown>;\n }\n return {};\n}\n\nfunction firstNumber(...candidates: unknown[]): number {\n for (const val of candidates) {\n if (val === null || val === undefined || val === \"\") {\n continue;\n }\n const n = typeof val === \"number\" ? val : Number(val);\n if (Number.isFinite(n) && n >= 0) {\n return Math.floor(n);\n }\n }\n return 0;\n}\n","import type { UsageRecord } from \"../collectors/agy-hook.js\";\nimport {\n ChannelRegistry,\n loadBundledChannelRegistry,\n type CompiledAuthChannel,\n} from \"../collectors/channel-registry.js\";\nimport type { TranscriptStructuralMeta } from \"../collectors/transcript-meta.js\";\nimport { formatBucketKey, normalizeTimezone } from \"../storage/rollups.js\";\nimport type {\n AuthContext,\n AuthMode,\n ChannelsSnapshot,\n ModelEntry,\n} from \"../types.js\";\nimport { estimateTokenCosts } from \"./token-window.js\";\n\nimport { getLocalizedBehavior, type SupportedLocale } from \"../i18n.js\";\n\nexport interface SavingRecommendation {\n id: string;\n severity: \"high\" | \"medium\" | \"low\";\n category:\n | \"long_session_snowball\"\n | \"heavy_model_mismatch\"\n | \"thinking_downgrade\"\n | \"infinite_loop_warning\"\n | \"missing_geminiignore\"\n | \"low_kv_cache_efficiency\"\n | \"peak_window_misalignment\"\n | \"burst_rpm_tpm_throttling\"\n | \"background_spend_warning\";\n title: string;\n evidence: string;\n action: string;\n estimated_savings_pct: string;\n}\n\nexport interface BehaviorSummaryTopModel {\n model: string;\n requests: number;\n token_share_pct: number;\n total_tokens: number;\n}\n\nexport interface BehaviorSummaryPeakHour {\n bucket: string;\n requests: number;\n total_tokens: number;\n cache_hit_rate_pct: number;\n}\n\nexport interface BehaviorSummary {\n avg_input_tokens_per_request: number;\n cache_hit_rate_pct: number;\n estimated_cache_savings_usd: number;\n light_model_request_share_pct: number;\n heavy_model_request_share_pct: number;\n top_models: BehaviorSummaryTopModel[];\n peak_hours: BehaviorSummaryPeakHour[];\n project_share_of_global_pct: number | null;\n auth_context: {\n active_auth_mode: AuthMode;\n has_mixed_auth: boolean;\n };\n}\n\nexport interface SavingRecommendationsReport {\n window: \"24h\" | \"7d\";\n scope?: \"global\" | \"project\";\n project_hash?: string;\n auth_mode_filter?: string;\n analyzed_records: number;\n recommendations: SavingRecommendation[];\n healthy: boolean;\n note?: string;\n behavior_summary: BehaviorSummary;\n executive_summary: string;\n channel_reports?: Record<string, SavingRecommendationsReport>;\n}\n\nexport interface HourlyDistributionBucket {\n bucket: string;\n total_tokens: number;\n rate_limit_429_count: number;\n requests?: number;\n cache_hit_rate_pct?: number;\n}\n\nconst HEAVY_MODEL_RE = /(neon|carbon|pro|ultra|opus)/i;\n\nexport function analyzeAntipatterns(\n records: UsageRecord[],\n options?: {\n window?: \"24h\" | \"7d\";\n scope?: \"global\" | \"project\";\n projectHash?: string;\n transcriptMeta?: TranscriptStructuralMeta | null;\n hasGeminiIgnore?: boolean;\n hourlyBuckets?: HourlyDistributionBucket[];\n models?: ModelEntry[];\n timezone?: string;\n authContext?: Pick<AuthContext, \"active_auth_mode\" | \"has_mixed_auth\">;\n authMode?: AuthMode | \"auto\" | \"all\";\n channels?: ChannelsSnapshot | ChannelRegistry;\n nowMs?: number;\n locale?: SupportedLocale;\n },\n): SavingRecommendationsReport {\n const window = options?.window ?? \"24h\";\n const scope = options?.scope ?? \"global\";\n const nowMs = options?.nowMs ?? Date.now();\n const locale = options?.locale ?? \"en\";\n const registry =\n options?.channels instanceof ChannelRegistry\n ? options.channels\n : options?.channels\n ? ChannelRegistry.fromSnapshot(options.channels)\n : loadBundledChannelRegistry();\n\n const requestedAuthMode = options?.authMode;\n const isSpecificAuthFilter = Boolean(\n requestedAuthMode &&\n requestedAuthMode !== \"auto\" &&\n requestedAuthMode !== \"all\" &&\n requestedAuthMode !== \"unknown\",\n );\n const resolvedFilterChannel = isSpecificAuthFilter && requestedAuthMode\n ? registry.resolveChannelId(requestedAuthMode)\n : undefined;\n\n const activeChannelForPolicy: CompiledAuthChannel | undefined = resolvedFilterChannel\n ? registry.getChannel(resolvedFilterChannel)\n : options?.authContext?.active_auth_mode &&\n options.authContext.active_auth_mode !== \"unknown\"\n ? registry.getChannel(options.authContext.active_auth_mode)\n : undefined;\n\n const cutoffMs = nowMs - (window === \"24h\" ? 86400_000 : 7 * 86400_000);\n const windowRecords = records.filter((r) => {\n const ts = Date.parse(r.ts);\n if (Number.isNaN(ts) || ts < cutoffMs) {\n return false;\n }\n if (resolvedFilterChannel) {\n return registry.matchesChannel(r.auth_mode, resolvedFilterChannel);\n }\n return true;\n });\n const filtered =\n scope === \"project\"\n ? windowRecords.filter(\n (r) => Boolean(options?.projectHash) && r.project_hash === options?.projectHash,\n )\n : windowRecords;\n\n const recs: SavingRecommendation[] = [];\n\n let totalUncachedInput = 0;\n let totalCacheRead = 0;\n for (const r of filtered) {\n totalUncachedInput += r.input_tokens;\n totalCacheRead += r.cache_read_tokens ?? 0;\n }\n const totalInputWithCache = totalUncachedInput + totalCacheRead;\n const cacheHitRatePct =\n totalInputWithCache > 0 ? (totalCacheRead / totalInputWithCache) * 100 : 0;\n\n // 1. Long-session snowball detection\n const longSessions = new Map<\n string,\n { maxTurn: number; maxCtxPct: number | null; totalInput: number; turns: number }\n >();\n for (const r of filtered) {\n const cur = longSessions.get(r.session_hash) ?? {\n maxTurn: 0,\n maxCtxPct: null,\n totalInput: 0,\n turns: 0,\n };\n cur.maxTurn = Math.max(cur.maxTurn, r.turn_index);\n if (typeof r.context_used_pct === \"number\") {\n cur.maxCtxPct =\n cur.maxCtxPct === null\n ? r.context_used_pct\n : Math.max(cur.maxCtxPct, r.context_used_pct);\n }\n cur.totalInput += r.input_tokens + (r.cache_read_tokens ?? 0);\n cur.turns += 1;\n longSessions.set(r.session_hash, cur);\n }\n\n const snowballSessions = [...longSessions.values()].filter(\n (s) =>\n s.maxTurn >= 20 ||\n (s.maxCtxPct !== null && s.maxCtxPct >= 70) ||\n (s.turns >= 25 && (s.maxTurn > 0 || (s.maxCtxPct !== null && s.maxCtxPct > 0))),\n );\n const transcriptUncompacted =\n options?.transcriptMeta &&\n options.transcriptMeta.steps_since_last_compact >= 30;\n\n if (snowballSessions.length > 0 || transcriptUncompacted) {\n const ctxValues = snowballSessions\n .map((s) => s.maxCtxPct)\n .filter((v): v is number => v !== null);\n const peakCtx = ctxValues.length > 0 ? Math.max(...ctxValues) : null;\n const peakTurn = Math.max(0, ...snowballSessions.map((s) => s.maxTurn));\n const snowballTotalInput = snowballSessions.reduce((s, v) => s + v.totalInput, 0);\n const snowballTotalTurns = snowballSessions.reduce((s, v) => s + v.turns, 0);\n const snowballAvgInput =\n snowballTotalTurns > 0 ? Math.round(snowballTotalInput / snowballTotalTurns) : 0;\n const avgInputLabel =\n snowballAvgInput >= 1000\n ? `~${Math.round(snowballAvgInput / 1000)}K`\n : `${snowballAvgInput}`;\n const highCacheHit = totalInputWithCache > 0 && cacheHitRatePct >= 85;\n const roundedHit = Math.round(cacheHitRatePct * 10) / 10;\n\n recs.push({\n id: \"long_session_snowball\",\n severity: \"high\",\n category: \"long_session_snowball\",\n title: \"Long-session context snowball detected\",\n evidence:\n snowballSessions.length > 0\n ? peakCtx !== null\n ? `${snowballSessions.length} session(s) reached turn ${peakTurn} / ${peakCtx}% context utilization without compacting.`\n : `${snowballSessions.length} session(s) reached turn ${peakTurn} (context % unavailable, avg ${avgInputLabel} input tokens/req) without compacting.`\n : `Transcript has ${options?.transcriptMeta?.steps_since_last_compact} steps since last /compact.`,\n action: highCacheHit\n ? `With ${roundedHit}% KV cache hit rate, avoid mechanical \\`/compact\\` every 12–15 turns (which breaks prefix caching); run \\`/compact\\` or start a fresh thread at phase milestones or when per-request input approaches 150K–200K tokens.`\n : \"Run `/compact` (or `/compress`) every 12–15 turns or start a fresh thread per subtask. Uncompacted histories re-bill growing prefixes every turn.\",\n estimated_savings_pct: highCacheHit ? \"15–30%\" : \"35–60%\",\n });\n }\n\n // 2. Heavy model mismatch (using Neon/Pro/Carbon for tiny low-complexity turns)\n const heavyTurns = filtered.filter((r) => HEAVY_MODEL_RE.test(r.model));\n const lightweightOnHeavy = heavyTurns.filter(\n (r) => r.output_tokens > 0 && r.output_tokens < 350 && r.tool_calls <= 1,\n );\n if (heavyTurns.length >= 4 && lightweightOnHeavy.length / heavyTurns.length >= 0.45) {\n const pct = Math.round((lightweightOnHeavy.length / heavyTurns.length) * 100);\n recs.push({\n id: \"heavy_model_mismatch\",\n severity: \"high\",\n category: \"heavy_model_mismatch\",\n title: \"Heavy flagship model used for lightweight turns\",\n evidence: `${lightweightOnHeavy.length}/${heavyTurns.length} (${pct}%) heavy-model turns produced <350 output tokens with <=1 tool call.`,\n action:\n \"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.\",\n estimated_savings_pct: \"50–75%\",\n });\n }\n\n // 3. Thinking downgrade opportunity (high output ratio on heavy models)\n const totalHeavyInput = heavyTurns.reduce((s, r) => s + r.input_tokens, 0);\n const totalHeavyOutput = heavyTurns.reduce((s, r) => s + r.output_tokens, 0);\n if (\n heavyTurns.length >= 3 &&\n totalHeavyOutput > 15_000 &&\n (totalHeavyInput === 0 || totalHeavyOutput / Math.max(1, totalHeavyInput) >= 0.15)\n ) {\n const policy = activeChannelForPolicy?.definition.quota_reset_policy;\n const behaviors = activeChannelForPolicy?.definition.recommended_behaviors;\n const multiplierNote = policy?.thinking_bucket_multiplier\n ? `billed at ${policy.thinking_bucket_multiplier} input rate in ${policy.window_type} buckets`\n : policy\n ? `billed under ${activeChannelForPolicy?.definition.billing_model} (${policy.window_type})`\n : \"billed at 4x–8x input rate in shared 5h/7d buckets\";\n recs.push({\n id: \"thinking_downgrade\",\n severity: \"medium\",\n category: \"thinking_downgrade\",\n title: \"High Thinking/output token burn on flagship models\",\n evidence: `${totalHeavyOutput.toLocaleString()} output/thinking tokens on heavy models (${multiplierNote}).`,\n action:\n getLocalizedBehavior(behaviors, \"thinking_guidance\", locale) ??\n \"Lower Thinking level (e.g. Medium/Low) for boilerplate coding & log parsing, reserving High Thinking strictly for multi-file debugging or architecture.\",\n estimated_savings_pct: \"25–45%\",\n });\n }\n\n // 4. Agent infinite loop warning (from pure structural transcript metadata)\n if (options?.transcriptMeta?.loop_detected) {\n const tool = options.transcriptMeta.consecutive_failure_tool_type ?? \"tool\";\n const streak = options.transcriptMeta.max_consecutive_tool_failures;\n recs.push({\n id: \"infinite_loop_warning\",\n severity: \"high\",\n category: \"infinite_loop_warning\",\n title: `Autonomous failure loop detected (${streak} consecutive \"${tool}\" errors)`,\n evidence: `Transcript recorded ${streak} consecutive failures on \"${tool}\" (${options.transcriptMeta.tool_error_count} total tool errors).`,\n action:\n \"Stop the agent immediately, inspect the failing command manually, fix the root cause or environment, and resume with a concise summary.\",\n estimated_savings_pct: \"40–80% on runaway turns\",\n });\n }\n\n // 5. Missing .geminiignore context hygiene check (when workspace_dir is inspected)\n if (options?.hasGeminiIgnore === false) {\n recs.push({\n id: \"missing_geminiignore\",\n severity: \"medium\",\n category: \"missing_geminiignore\",\n title: \"Missing .geminiignore in workspace\",\n evidence: \"No .geminiignore file was found in the provided workspace_dir.\",\n action:\n \"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.\",\n estimated_savings_pct: \"15–35%\",\n });\n }\n\n // 6. Low KV cache efficiency (high uncached input ratio on multi-turn/long contexts)\n const hasLongTurns =\n snowballSessions.length > 0 ||\n [...longSessions.values()].some((s) => s.turns >= 5);\n\n if (\n filtered.length >= 4 &&\n totalInputWithCache >= 16_384 &&\n cacheHitRatePct < 30 &&\n (totalCacheRead > 0 || hasLongTurns)\n ) {\n const policy = activeChannelForPolicy?.definition.quota_reset_policy;\n const behaviors = activeChannelForPolicy?.definition.recommended_behaviors;\n const discountNote =\n policy?.supports_kv_cache_discount && policy.kv_cache_discount_rate\n ? ` (${policy.kv_cache_discount_rate} KV cache discount applies)`\n : \"\";\n recs.push({\n id: \"low_kv_cache_efficiency\",\n severity: \"medium\",\n category: \"low_kv_cache_efficiency\",\n title: `Low KV cache hit efficiency${discountNote}`,\n evidence: `KV cache hit rate is ${Math.round(cacheHitRatePct * 10) / 10}% (${totalCacheRead.toLocaleString()} cached / ${totalInputWithCache.toLocaleString()} total input tokens).`,\n action:\n getLocalizedBehavior(behaviors, \"kv_cache_guidance\", locale) ??\n \"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.\",\n estimated_savings_pct: \"20–50% on input cost\",\n });\n }\n\n // 7. Peak window misalignment (burst concentration in 2-3 hours accompanied by 429s)\n const tz = normalizeTimezone(options?.timezone);\n const hourlyMap = new Map<\n string,\n {\n tokens: number;\n count429: number;\n requests: number;\n uncachedInput: number;\n cacheRead: number;\n cacheHitRatePct?: number;\n }\n >();\n if (options?.hourlyBuckets && options.hourlyBuckets.length > 0) {\n for (const b of options.hourlyBuckets) {\n hourlyMap.set(b.bucket, {\n tokens: b.total_tokens,\n count429: b.rate_limit_429_count,\n requests: b.requests ?? 0,\n uncachedInput: 0,\n cacheRead: 0,\n cacheHitRatePct: b.cache_hit_rate_pct,\n });\n }\n } else {\n for (const r of filtered) {\n const tsMs = Date.parse(r.ts);\n if (Number.isNaN(tsMs)) continue;\n const hourKey = formatBucketKey(tsMs, \"hourly\", tz);\n const cur = hourlyMap.get(hourKey) ?? {\n tokens: 0,\n count429: 0,\n requests: 0,\n uncachedInput: 0,\n cacheRead: 0,\n };\n const cacheRead = r.cache_read_tokens ?? 0;\n cur.requests += 1;\n cur.uncachedInput += r.input_tokens;\n cur.cacheRead += cacheRead;\n cur.tokens += r.input_tokens + cacheRead + r.output_tokens;\n if (\n r.error_code &&\n (r.error_code.includes(\"429\") || r.error_code.includes(\"RESOURCE_EXHAUSTED\"))\n ) {\n cur.count429 += 1;\n }\n hourlyMap.set(hourKey, cur);\n }\n }\n\n const hourlyValues = [...hourlyMap.values()];\n const totalHourlyTokens = hourlyValues.reduce((s, v) => s + v.tokens, 0);\n const total429 = hourlyValues.reduce((s, v) => s + v.count429, 0);\n if (hourlyValues.length >= 3 && totalHourlyTokens > 0 && total429 > 0) {\n const sortedTokens = hourlyValues.map((v) => v.tokens).sort((a, b) => b - a);\n const top3Tokens = sortedTokens.slice(0, 3).reduce((s, t) => s + t, 0);\n const top3SharePct = Math.round((top3Tokens / totalHourlyTokens) * 1000) / 10;\n if (top3SharePct >= 70) {\n const policy = activeChannelForPolicy?.definition.quota_reset_policy;\n const behaviors = activeChannelForPolicy?.definition.recommended_behaviors;\n const isRollingBucket = !policy || policy.window_type === \"rolling_5h_7d\";\n if (isRollingBucket) {\n recs.push({\n id: \"peak_window_misalignment\",\n severity: \"medium\",\n category: \"peak_window_misalignment\",\n title: \"Peak window concentration causing 429 rate limits\",\n evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s).`,\n action:\n getLocalizedBehavior(behaviors, \"throttling_guidance\", locale) ??\n \"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.\",\n estimated_savings_pct: \"15–30% fewer 429 retries\",\n });\n } else {\n recs.push({\n id: \"burst_rpm_tpm_throttling\",\n severity: \"medium\",\n category: \"burst_rpm_tpm_throttling\",\n title: `Burst RPM/TPM concentration causing 429 throttling (${activeChannelForPolicy.definition.display_name})`,\n evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s) under ${policy.window_type}.`,\n action:\n getLocalizedBehavior(behaviors, \"throttling_guidance\", locale) ??\n \"Spread concurrent requests across regions or upgrade RPM/TPM quota.\",\n estimated_savings_pct: \"15–30% fewer 429 retries\",\n });\n }\n }\n }\n\n // 8. Background call spend warning (policy-driven: only when background_call_billed === true)\n if (activeChannelForPolicy?.definition.quota_reset_policy.background_call_billed) {\n const bgRecords = filtered.filter((r) => r.data_quality === \"estimated_from_cli_log\");\n const bgTokens = bgRecords.reduce((s, r) => s + r.input_tokens + r.output_tokens, 0);\n if (bgRecords.length >= 3 || bgTokens >= 10_000) {\n recs.push({\n id: \"background_spend_warning\",\n severity: \"medium\",\n category: \"background_spend_warning\",\n title: `Background monitor / checkpoint calls billed on ${activeChannelForPolicy.definition.display_name}`,\n evidence: `Detected ${bgRecords.length} estimated background CLI monitor call(s) (${bgTokens.toLocaleString()} tokens) on a pay-as-you-go/metered channel.`,\n action:\n getLocalizedBehavior(\n activeChannelForPolicy.definition.recommended_behaviors,\n \"background_spend_guidance\",\n locale,\n ) ??\n \"Background lightweight calls incur real metered usage on this channel; avoid idle polling loops.\",\n estimated_savings_pct: \"10–25% background spend\",\n });\n }\n }\n\n const hasTelemetry = filtered.some(\n (r) =>\n r.input_tokens > 0 ||\n (r.cache_read_tokens ?? 0) > 0 ||\n r.output_tokens > 0 ||\n r.turn_index > 0 ||\n (r.context_used_pct !== null && r.context_used_pct > 0),\n );\n const note =\n filtered.length > 0 && !hasTelemetry && !options?.transcriptMeta\n ? \"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.\"\n : undefined;\n\n // Behavior summary (100% numeric/enum/bucketed metadata)\n const catalog = options?.models ?? [];\n const totalOutput = filtered.reduce((s, r) => s + r.output_tokens, 0);\n const totalTokens = totalInputWithCache + totalOutput;\n const totalRequests = filtered.length;\n const avgInputTokensPerRequest =\n totalRequests > 0 ? Math.round(totalInputWithCache / totalRequests) : 0;\n const roundedCacheHitRatePct =\n totalInputWithCache > 0 ? Math.round(cacheHitRatePct * 10) / 10 : 0;\n\n const modelAgg = new Map<\n string,\n { requests: number; uncachedInput: number; cacheRead: number; output: number }\n >();\n for (const r of filtered) {\n const cur = modelAgg.get(r.model) ?? {\n requests: 0,\n uncachedInput: 0,\n cacheRead: 0,\n output: 0,\n };\n cur.requests += 1;\n cur.uncachedInput += r.input_tokens;\n cur.cacheRead += r.cache_read_tokens ?? 0;\n cur.output += r.output_tokens;\n modelAgg.set(r.model, cur);\n }\n\n let estimatedCacheSavingsUsd = 0;\n let lightModelRequests = 0;\n let heavyModelRequests = 0;\n const modelEntries: Array<{\n model: string;\n requests: number;\n total_tokens: number;\n }> = [];\n\n for (const [model, agg] of modelAgg.entries()) {\n const { pricing, cacheSavingsUsd } = estimateTokenCosts(\n {\n model,\n uncachedInputTokens: agg.uncachedInput,\n cacheReadTokens: agg.cacheRead,\n outputTokens: agg.output,\n },\n catalog,\n );\n estimatedCacheSavingsUsd += cacheSavingsUsd;\n if (pricing.tier === \"low\" || pricing.tier === \"minimal\") {\n lightModelRequests += agg.requests;\n } else if (\n pricing.tier === \"high\" ||\n pricing.tier === \"very-high\" ||\n pricing.tier === \"very_high\"\n ) {\n heavyModelRequests += agg.requests;\n }\n const modelTotalTokens = agg.uncachedInput + agg.cacheRead + agg.output;\n modelEntries.push({\n model,\n requests: agg.requests,\n total_tokens: modelTotalTokens,\n });\n }\n\n modelEntries.sort(\n (a, b) => b.total_tokens - a.total_tokens || b.requests - a.requests,\n );\n const topModels: BehaviorSummaryTopModel[] = modelEntries\n .slice(0, 3)\n .map((m) => ({\n model: m.model,\n requests: m.requests,\n token_share_pct:\n totalTokens > 0\n ? Math.round((m.total_tokens / totalTokens) * 1000) / 10\n : totalRequests > 0\n ? Math.round((m.requests / totalRequests) * 1000) / 10\n : 0,\n total_tokens: m.total_tokens,\n }));\n\n const lightModelRequestSharePct =\n totalRequests > 0\n ? Math.round((lightModelRequests / totalRequests) * 1000) / 10\n : 0;\n const heavyModelRequestSharePct =\n totalRequests > 0\n ? Math.round((heavyModelRequests / totalRequests) * 1000) / 10\n : 0;\n\n const hasBucketRequests = Boolean(\n options?.hourlyBuckets?.some((b) => typeof b.requests === \"number\"),\n );\n const peakHoursSource =\n options?.hourlyBuckets && options.hourlyBuckets.length > 0 && hasBucketRequests\n ? options.hourlyBuckets.map((b) => ({\n bucket: b.bucket,\n requests: b.requests ?? 0,\n total_tokens: b.total_tokens,\n cache_hit_rate_pct: b.cache_hit_rate_pct ?? 0,\n }))\n : [...hourlyMap.entries()].map(([bucket, v]) => {\n const inputTotal = v.uncachedInput + v.cacheRead;\n const hitPct =\n typeof v.cacheHitRatePct === \"number\"\n ? v.cacheHitRatePct\n : inputTotal > 0\n ? Math.round((v.cacheRead / inputTotal) * 1000) / 10\n : 0;\n return {\n bucket,\n requests: v.requests,\n total_tokens: v.tokens,\n cache_hit_rate_pct: hitPct,\n };\n });\n\n const peakHours: BehaviorSummaryPeakHour[] = peakHoursSource\n .filter((b) => b.requests > 0 || b.total_tokens > 0)\n .sort((a, b) => b.total_tokens - a.total_tokens || b.requests - a.requests)\n .slice(0, 3);\n\n const globalTotalTokens = windowRecords.reduce(\n (s, r) => s + r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens,\n 0,\n );\n const projectShareOfGlobalPct =\n scope === \"project\"\n ? globalTotalTokens > 0\n ? Math.round((totalTokens / globalTotalTokens) * 1000) / 10\n : 0\n : null;\n\n const roundedSavingsUsd = Math.round(estimatedCacheSavingsUsd * 10000) / 10000;\n const effectiveAuthMode: AuthMode = resolvedFilterChannel\n ? registry.toLegacyAuthMode(resolvedFilterChannel)\n : (options?.authContext?.active_auth_mode ?? \"unknown\");\n const authSummary = {\n active_auth_mode: effectiveAuthMode,\n has_mixed_auth: options?.authContext?.has_mixed_auth ?? false,\n };\n\n const behaviorSummary: BehaviorSummary = {\n avg_input_tokens_per_request: avgInputTokensPerRequest,\n cache_hit_rate_pct: roundedCacheHitRatePct,\n estimated_cache_savings_usd: roundedSavingsUsd,\n light_model_request_share_pct: lightModelRequestSharePct,\n heavy_model_request_share_pct: heavyModelRequestSharePct,\n top_models: topModels,\n peak_hours: peakHours,\n project_share_of_global_pct: projectShareOfGlobalPct,\n auth_context: authSummary,\n };\n\n const isShadowBucket =\n activeChannelForPolicy?.definition.quota_reset_policy.window_type === \"rolling_5h_7d\" ||\n authSummary.active_auth_mode === \"google_oauth\";\n\n const executiveSummary = buildExecutiveSummary({\n window,\n scope,\n requests: totalRequests,\n totalTokens,\n avgInputTokensPerRequest,\n cacheHitRatePct: roundedCacheHitRatePct,\n estimatedCacheSavingsUsd: roundedSavingsUsd,\n projectShareOfGlobalPct,\n isShadowBucket,\n recommendations: recs,\n hasMissingTelemetryNote: Boolean(note),\n });\n\n // Multi-channel split reports when authMode is \"all\" or \"auto\" with >=2 distinct channels\n let channelReports: Record<string, SavingRecommendationsReport> | undefined;\n if (!isSpecificAuthFilter && (!requestedAuthMode || requestedAuthMode === \"auto\" || requestedAuthMode === \"all\")) {\n const distinctChannelIds = new Set<string>();\n for (const r of filtered) {\n if (r.auth_mode && r.auth_mode !== \"unknown\") {\n distinctChannelIds.add(registry.resolveChannelId(r.auth_mode));\n }\n }\n if (distinctChannelIds.size >= 2 || (requestedAuthMode === \"all\" && distinctChannelIds.size >= 1)) {\n channelReports = {};\n for (const chId of distinctChannelIds) {\n channelReports[chId] = analyzeAntipatterns(records, {\n ...options,\n authMode: chId,\n channels: registry,\n hourlyBuckets: undefined,\n });\n }\n }\n }\n\n return {\n window,\n ...(options?.scope ? { scope } : {}),\n ...(scope === \"project\" && options?.projectHash\n ? { project_hash: options.projectHash }\n : {}),\n ...(requestedAuthMode ? { auth_mode_filter: requestedAuthMode } : {}),\n analyzed_records: filtered.length,\n recommendations: recs,\n healthy: recs.length === 0,\n ...(note ? { note } : {}),\n behavior_summary: behaviorSummary,\n executive_summary: executiveSummary,\n ...(channelReports ? { channel_reports: channelReports } : {}),\n };\n}\n\nfunction buildExecutiveSummary(params: {\n window: \"24h\" | \"7d\";\n scope: \"global\" | \"project\";\n requests: number;\n totalTokens: number;\n avgInputTokensPerRequest: number;\n cacheHitRatePct: number;\n estimatedCacheSavingsUsd: number;\n projectShareOfGlobalPct: number | null;\n isShadowBucket: boolean;\n recommendations: SavingRecommendation[];\n hasMissingTelemetryNote: boolean;\n}): string {\n const {\n window,\n scope,\n requests,\n totalTokens,\n avgInputTokensPerRequest,\n cacheHitRatePct,\n estimatedCacheSavingsUsd,\n projectShareOfGlobalPct,\n isShadowBucket,\n recommendations,\n hasMissingTelemetryNote,\n } = params;\n\n if (requests === 0) {\n return `No usage records found in the ${window} ${scope} window; run active sessions or enable Gemini CLI OTel to capture token telemetry.`;\n }\n\n const shareText =\n scope === \"project\" && projectShareOfGlobalPct !== null\n ? ` (${projectShareOfGlobalPct}% of global volume)`\n : \"\";\n const costLabel = isShadowBucket\n ? `$${estimatedCacheSavingsUsd.toFixed(2)} API-equivalent shadow cost saved`\n : `$${estimatedCacheSavingsUsd.toFixed(2)} saved`;\n 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}).`;\n\n if (recommendations.length === 0) {\n if (hasMissingTelemetryNote) {\n return `${usagePart} Token telemetry is incomplete; enable Gemini CLI OTel or pass transcript_path for deeper antipattern diagnostics.`;\n }\n return `${usagePart} Status: healthy with no quota-burning antipatterns detected; maintain stable prefixes and current model tier routing.`;\n }\n\n const rank: Record<SavingRecommendation[\"severity\"], number> = {\n high: 0,\n medium: 1,\n low: 2,\n };\n const sorted = [...recommendations].sort(\n (a, b) => rank[a.severity] - rank[b.severity],\n );\n const top = sorted[0]!;\n return `${usagePart} Primary bottleneck: ${top.title} (${recommendations.length} issue(s) flagged). Top action: ${top.action}`;\n}\n","import type {\n ChannelRegistry,\n CompiledAuthChannel,\n} from \"../collectors/channel-registry.js\";\nimport {\n getLocalizedBehavior,\n localizeDiagnosisEntry,\n type SupportedLocale,\n} from \"../i18n.js\";\nimport type {\n AuthContext,\n AuthMode,\n ChannelPrescriptionOverride,\n DiagnosisCommand,\n DiagnosisEntry,\n} from \"../types.js\";\n\nexport interface AuthChannelAnalysis {\n resolved_channel: string;\n resolution_source:\n | \"error_signature\"\n | \"explicit_auth_mode\"\n | \"cli_log\"\n | \"auth_context\"\n | \"mixed_ambiguous\"\n | \"unknown\";\n cross_talk_detected: boolean;\n expected_channel?: string;\n isolation_commands?: string[];\n note: string;\n}\n\nexport interface ChannelResolutionOutput {\n resolvedChannel: string;\n analysis: AuthChannelAnalysis;\n}\n\nfunction normalizeCandidateChannel(\n raw: string | undefined | null,\n registry: ChannelRegistry,\n): string | undefined {\n if (!raw || typeof raw !== \"string\") {\n return undefined;\n }\n const trimmed = raw.trim();\n if (!trimmed || trimmed === \"auto\" || trimmed === \"unknown\") {\n return undefined;\n }\n return registry.resolveChannelId(trimmed);\n}\n\nexport function resolveErrorAuthChannel(params: {\n errorText: string;\n authMode?: AuthMode | \"auto\";\n authContext?: AuthContext;\n cliChannel?: string;\n registry: ChannelRegistry;\n}): ChannelResolutionOutput {\n const { errorText, authMode, authContext, cliChannel, registry } = params;\n\n const explicitChannel = normalizeCandidateChannel(authMode, registry);\n const logChannel = normalizeCandidateChannel(cliChannel, registry);\n const staticChannel = normalizeCandidateChannel(\n authContext?.active_channel_id ?? authContext?.active_auth_mode,\n registry,\n );\n const expectedChannel = explicitChannel ?? logChannel ?? staticChannel;\n\n // Level 1: Error text strong signature match\n const signatureMatch = registry.matchErrorText(errorText);\n if (signatureMatch) {\n const resolved = signatureMatch.channelId;\n const crossTalk = Boolean(\n expectedChannel && !registry.matchesChannel(expectedChannel, resolved),\n );\n const isolationCommands =\n signatureMatch.definition.recommended_behaviors.isolation_commands;\n return {\n resolvedChannel: resolved,\n analysis: {\n resolved_channel: resolved,\n resolution_source: \"error_signature\",\n cross_talk_detected: crossTalk,\n ...(expectedChannel ? { expected_channel: expectedChannel } : {}),\n ...(crossTalk || authContext?.has_mixed_auth\n ? { isolation_commands: isolationCommands }\n : {}),\n note: crossTalk\n ? `Cross-talk detected: expected/active channel \"${expectedChannel}\", but error signature matched \"${resolved}\" (${signatureMatch.definition.display_name}). Isolate env vars before retrying.`\n : `Error signature matched auth channel \"${resolved}\" (${signatureMatch.definition.display_name}).`,\n },\n };\n }\n\n // Level 2: Explicit auth_mode != \"auto\"\n if (explicitChannel) {\n const ch = registry.getChannel(explicitChannel);\n const mixedWithStatic = Boolean(\n authContext?.has_mixed_auth ||\n (staticChannel && !registry.matchesChannel(explicitChannel, staticChannel)),\n );\n return {\n resolvedChannel: explicitChannel,\n analysis: {\n resolved_channel: explicitChannel,\n resolution_source: \"explicit_auth_mode\",\n cross_talk_detected: false,\n ...(mixedWithStatic && ch\n ? { isolation_commands: ch.definition.recommended_behaviors.isolation_commands }\n : {}),\n note: ch\n ? `Using explicit auth_mode \"${explicitChannel}\" (${ch.definition.display_name}).`\n : `Using explicit auth_mode \"${explicitChannel}\".`,\n },\n };\n }\n\n // Level 3: Recent active cli-*.log channel\n if (logChannel) {\n const ch = registry.getChannel(logChannel);\n return {\n resolvedChannel: logChannel,\n analysis: {\n resolved_channel: logChannel,\n resolution_source: \"cli_log\",\n cross_talk_detected: false,\n ...(authContext?.has_mixed_auth && ch\n ? { isolation_commands: ch.definition.recommended_behaviors.isolation_commands }\n : {}),\n note: ch\n ? `Resolved active channel \"${logChannel}\" (${ch.definition.display_name}) from recent cli-*.log.`\n : `Resolved active channel \"${logChannel}\" from recent cli-*.log.`,\n },\n };\n }\n\n // Level 4: Static authContext\n if (authContext?.has_mixed_auth) {\n const fallback = staticChannel ?? \"mixed_ambiguous\";\n const ch = staticChannel ? registry.getChannel(staticChannel) : undefined;\n const detectedList = authContext.detected_channels ?? authContext.detected_modes;\n return {\n resolvedChannel: fallback,\n analysis: {\n resolved_channel: fallback,\n resolution_source: \"mixed_ambiguous\",\n cross_talk_detected: false,\n ...(ch\n ? { isolation_commands: ch.definition.recommended_behaviors.isolation_commands }\n : {}),\n note: `Mixed auth contexts detected (${detectedList.join(\", \")}) with no channel-specific error signature or cli-*.log event. Verify active auth channel to avoid cross-channel misattribution.`,\n },\n };\n }\n\n if (staticChannel) {\n const ch = registry.getChannel(staticChannel);\n return {\n resolvedChannel: staticChannel,\n analysis: {\n resolved_channel: staticChannel,\n resolution_source: \"auth_context\",\n cross_talk_detected: false,\n note: ch\n ? `Resolved single local auth channel \"${staticChannel}\" (${ch.definition.display_name}).`\n : `Resolved local auth channel \"${staticChannel}\".`,\n },\n };\n }\n\n return {\n resolvedChannel: \"unknown\",\n analysis: {\n resolved_channel: \"unknown\",\n resolution_source: \"unknown\",\n cross_talk_detected: false,\n note: \"No specific auth channel resolved; using channel-agnostic diagnostics.\",\n },\n };\n}\n\nexport function findChannelVariant(\n entry: DiagnosisEntry,\n resolvedChannel: string,\n registry: ChannelRegistry,\n): ChannelPrescriptionOverride | undefined {\n if (!entry.channel_variants || resolvedChannel === \"unknown\") {\n return undefined;\n }\n if (entry.channel_variants[resolvedChannel]) {\n return entry.channel_variants[resolvedChannel];\n }\n const compiled = registry.getChannel(resolvedChannel);\n if (compiled) {\n if (compiled.legacyId && entry.channel_variants[compiled.legacyId]) {\n return entry.channel_variants[compiled.legacyId];\n }\n for (const alias of compiled.aliases) {\n if (entry.channel_variants[alias]) {\n return entry.channel_variants[alias];\n }\n }\n }\n return undefined;\n}\n\nexport function isEntryApplicableToChannel(\n entry: DiagnosisEntry,\n resolvedChannel: string,\n registry: ChannelRegistry,\n): boolean {\n if (\n !entry.applicable_auth_modes ||\n entry.applicable_auth_modes.length === 0 ||\n resolvedChannel === \"unknown\" ||\n resolvedChannel === \"mixed_ambiguous\"\n ) {\n return true;\n }\n return entry.applicable_auth_modes.some((m) =>\n registry.matchesChannel(m, resolvedChannel),\n );\n}\n\nconst GENERIC_CHANNEL_SENSITIVE_RULE_IDS = new Set([\n \"429-desync\",\n \"google-429-desync\",\n \"weekly-cap\",\n \"403-auth-mismatch\",\n \"google-403-auth-mismatch\",\n]);\n\nfunction buildIsolationCommands(channel: CompiledAuthChannel): DiagnosisCommand[] {\n const cmds: DiagnosisCommand[] = channel.definition.recommended_behaviors.isolation_commands.map(\n (cmd, idx) => ({\n label:\n idx === 0\n ? `Isolate ${channel.definition.display_name} env`\n : `Configure ${channel.definition.display_name} env`,\n os: \"unix\",\n command: cmd,\n }),\n );\n cmds.push({\n label: `Verify ${channel.definition.display_name}`,\n os: \"all\",\n command: channel.definition.recommended_behaviors.verify_command,\n });\n return cmds;\n}\n\nexport function applyChannelPrescription(params: {\n chosen: DiagnosisEntry;\n resolvedChannel: string;\n registry: ChannelRegistry;\n locale?: SupportedLocale;\n}): DiagnosisEntry {\n const { chosen, resolvedChannel, registry, locale = \"en\" } = params;\n const variant = findChannelVariant(chosen, resolvedChannel, registry);\n if (variant) {\n const localizedVariant = localizeDiagnosisEntry(variant, locale);\n const localizedChosen = localizeDiagnosisEntry(chosen, locale);\n return {\n ...localizedChosen,\n title: localizedVariant.title ?? localizedChosen.title,\n root_cause: localizedVariant.root_cause ?? localizedChosen.root_cause,\n steps: localizedVariant.steps ?? localizedChosen.steps,\n commands: localizedVariant.commands ?? localizedChosen.commands,\n verify_command: localizedVariant.verify_command ?? localizedChosen.verify_command,\n dont_dos: localizedVariant.dont_dos ?? localizedChosen.dont_dos,\n deep_link: localizedVariant.deep_link ?? localizedChosen.deep_link,\n };\n }\n\n const channel =\n resolvedChannel !== \"unknown\" && resolvedChannel !== \"mixed_ambiguous\"\n ? registry.getChannel(resolvedChannel)\n : undefined;\n if (!channel) {\n return chosen;\n }\n\n // Only adapt generic cross-channel rules (leave specific GCP rules like gcp-vertex-api-disabled intact)\n const isGenericChannelSensitive =\n GENERIC_CHANNEL_SENSITIVE_RULE_IDS.has(chosen.id) ||\n GENERIC_CHANNEL_SENSITIVE_RULE_IDS.has(chosen.slug);\n\n if (!isGenericChannelSensitive) {\n return chosen;\n }\n\n const localizedChosen = localizeDiagnosisEntry(chosen, locale);\n const behaviors = channel.definition.recommended_behaviors;\n const policy = channel.definition.quota_reset_policy;\n const isoCommands = buildIsolationCommands(channel);\n const displayName =\n locale === \"zh\" && channel.definition.display_name_zh\n ? channel.definition.display_name_zh\n : channel.definition.display_name;\n const throttlingGuidance =\n getLocalizedBehavior(behaviors, \"throttling_guidance\", locale) ?? behaviors.throttling_guidance;\n const kvCacheGuidance =\n getLocalizedBehavior(behaviors, \"kv_cache_guidance\", locale) ?? behaviors.kv_cache_guidance;\n const backgroundSpendGuidance = getLocalizedBehavior(\n behaviors,\n \"background_spend_guidance\",\n locale,\n );\n\n if (localizedChosen.domain === \"quota\") {\n if (policy.window_type === \"rolling_5h_7d\") {\n // Consumer OAuth track: strip any cloud-billing / gcloud / AI Studio cross-contamination\n const cleanSteps = localizedChosen.steps.filter(\n (s) => !/gcloud|aiplatform|cloud\\s*billing|aistudio\\.google\\.com/i.test(s),\n );\n return {\n ...localizedChosen,\n root_cause:\n locale === \"zh\"\n ? `${displayName} 的 ${policy.window_type} 共享配额桶已耗尽或权益失步。${throttlingGuidance}`\n : `Shared ${policy.window_type} quota bucket exhausted or entitlement desync on ${displayName}. ${throttlingGuidance}`,\n steps:\n cleanSteps.length > 0\n ? cleanSteps\n : [throttlingGuidance, kvCacheGuidance],\n commands: isoCommands,\n verify_command: behaviors.verify_command,\n };\n }\n\n // Non-rolling-5h channels (Vertex ADC, Gemini API Key, Vertex Express, custom OIDC/WIF, etc.)\n const steps = [\n throttlingGuidance,\n kvCacheGuidance,\n ...(backgroundSpendGuidance ? [backgroundSpendGuidance] : []),\n ];\n return {\n ...localizedChosen,\n title:\n locale === \"zh\"\n ? `429 限流 / 配额耗尽(${displayName})`\n : `429 Rate Limit / Quota Exhausted (${displayName})`,\n root_cause: `${displayName} (${channel.definition.billing_model}, ${policy.window_type}): ${throttlingGuidance}`,\n steps,\n commands: isoCommands,\n verify_command: behaviors.verify_command,\n dont_dos: [\n locale === \"zh\"\n ? \"不要对该认证通道执行个人 OAuth 共享配额桶的 Reset Onboarding 重置操作。\"\n : \"Do NOT apply consumer OAuth shared-bucket onboarding resets to this auth channel.\",\n ...localizedChosen.dont_dos.filter(\n (d) => !/reset\\s*onboarding|5h\\/7d/i.test(d),\n ),\n ],\n };\n }\n\n if (localizedChosen.domain === \"auth\") {\n return {\n ...localizedChosen,\n title:\n locale === \"zh\"\n ? `401/403 认证与权益不匹配(${displayName})`\n : `401/403 Auth & Entitlement Mismatch (${displayName})`,\n root_cause:\n locale === \"zh\"\n ? `${displayName} 存在认证或权益不匹配,请确认已清理其他通道的冲突环境变量。`\n : `Authentication or entitlement mismatch on ${displayName}. Ensure conflicting credentials from other channels are unset.`,\n steps: [\n locale === \"zh\"\n ? `为 ${displayName} 隔离冲突环境变量。`\n : `Isolate environment variables for ${displayName}.`,\n throttlingGuidance,\n locale === \"zh\"\n ? `运行校验命令确认连通性:${behaviors.verify_command}`\n : `Verify connectivity with: ${behaviors.verify_command}`,\n ],\n commands: isoCommands,\n verify_command: behaviors.verify_command,\n };\n }\n\n return localizedChosen;\n}\n","import type { UsageRecord } from \"../collectors/agy-hook.js\";\nimport {\n ChannelRegistry,\n loadBundledChannelRegistry,\n} from \"../collectors/channel-registry.js\";\nimport {\n getLocalizedBehavior,\n localizeDiagnosisEntry,\n type SupportedLocale,\n} from \"../i18n.js\";\nimport type {\n AuthContext,\n AuthMode,\n ChannelsSnapshot,\n DiagnosisCommand,\n DiagnosisEntry,\n StatusSnapshot,\n} from \"../types.js\";\nimport {\n applyChannelPrescription,\n findChannelVariant,\n isEntryApplicableToChannel,\n resolveErrorAuthChannel,\n type AuthChannelAnalysis,\n} from \"./channel-diagnosis.js\";\n\nexport interface DiagnosisResult {\n matched: boolean;\n domain: string;\n diagnosis_id: string;\n title: string;\n confidence: \"high\" | \"medium\" | \"low\";\n attribution: string;\n root_cause: string;\n steps: string[];\n commands: DiagnosisCommand[];\n verify_command: string;\n dont_dos: string[];\n deep_link: string;\n official_source_url: string | null;\n upstream_status: string;\n extracted_signals: {\n http_status: string | null;\n retry_delay: string | null;\n quota_metric: string | null;\n };\n auth_channel_analysis?: AuthChannelAnalysis;\n}\n\ninterface PatternRule {\n id: string;\n domain: string;\n regex: RegExp;\n fallback: DiagnosisEntry;\n}\n\nconst EXTERNAL_GCP_DATA_PLANE_403_RE =\n /\\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;\n\nconst MODEL_AUTH_CONFLICT_RE =\n /cloudaicompanion|generativelanguage|aiplatform|gemini|antigravity|ACCESS_TOKEN_TYPE_UNSUPPORTED|API_KEY_INVALID|GEMINI_API_KEY|GOOGLE_CLOUD_PROJECT/i;\n\nfunction isExternalGcpDataPlane403(text: string): boolean {\n return (\n EXTERNAL_GCP_DATA_PLANE_403_RE.test(text) &&\n !MODEL_AUTH_CONFLICT_RE.test(text)\n );\n}\n\nconst SPECIFIC_GCP_RULE_IDS = new Set([\n \"gcp-vertex-api-disabled\",\n \"gcp-adc-expired\",\n \"gcp-vertex-iam-or-location\",\n \"gcp-vpc-sc-blocked\",\n]);\n\nconst BUILTIN_RULES: PatternRule[] = [\n {\n id: \"weekly-cap\",\n domain: \"quota\",\n regex:\n /weekly\\s*(?:cap|limit)|WEEKLY_LIMIT_EXCEEDED|5-?hour|rolling\\s*(?:5h|7d)|reached\\s+your\\s+usage\\s+limit/i,\n fallback: {\n id: \"weekly-cap\",\n slug: \"weekly-cap\",\n provider: \"antigravity\",\n route_provider: \"agy\",\n domain: \"quota\",\n title: \"Shared 5h / 7d Weekly Quota Cap Reached\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"web\"],\n error_codes: [\"429\", \"WEEKLY_LIMIT_EXCEEDED\", \"RATE_LIMIT_EXCEEDED\"],\n error_patterns: [\"weekly limit\", \"5-hour\", \"Try again later\", \"reached your usage limit\"],\n root_cause:\n \"You have exhausted the shared 5-hour or 7-day rolling quota bucket across Antigravity / Gemini CLI.\",\n steps: [\n \"Check `get_ecosystem_status` for local 5h/7d rolling window estimates and the official AGY/CLI quota UI for authoritative remaining %.\",\n \"Switch to a lighter model (Gemini 4 Hydrogen or Gemini 3.8 Flash) or run `/compact` to reduce per-turn token burn.\",\n ],\n commands: [\n { label: \"Switch Gemini CLI to Flash\", os: \"all\", command: \"gemini --model gemini-3.8-flash\" },\n ],\n verify_command: \"gemini --version && npx agycraft-mcp doctor\",\n dont_dos: [\n \"Do NOT hammer retry in a tight loop while capped.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/quota/weekly-cap\",\n },\n },\n {\n id: \"429-desync\",\n domain: \"quota\",\n regex: /\\b429\\b|RESOURCE_EXHAUSTED|quotaMetric|limit:\\s*0|rate\\s*limit/i,\n fallback: {\n id: \"429-desync\",\n slug: \"429-desync\",\n provider: \"antigravity\",\n route_provider: \"agy\",\n domain: \"quota\",\n title: \"429 RESOURCE_EXHAUSTED / Quota Desync or Shared Bucket Cap\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"429\", \"RESOURCE_EXHAUSTED\"],\n error_patterns: [\"429\", \"RESOURCE_EXHAUSTED\", \"limit: 0\"],\n root_cause:\n \"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).\",\n steps: [\n \"Compare local 5h token consumption against the error to separate real cap vs entitlement/billing desync.\",\n \"If desynced: run Reset Onboarding in Antigravity or verify Google Cloud Billing / AI Pro subscription binding.\",\n \"If real cap: switch to Gemini 4 Hydrogen or Gemini 3.8 Flash, run `/compact`, and wait for the rolling 5h window relief.\",\n ],\n commands: [\n { label: \"Run local preflight doctor\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n { label: \"Switch Gemini CLI to lighter Flash model\", os: \"all\", command: \"gemini --model gemini-3.8-flash\" },\n ],\n verify_command: \"gemini --version && npx agycraft-mcp doctor\",\n dont_dos: [\n \"Do NOT hammer retry in a tight loop — repeated 429 bursts can trigger automated abuse cooldowns.\",\n \"Do NOT rotate multiple personal API keys to bypass free-tier limits.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/quota/429-desync\",\n },\n },\n {\n id: \"gcp-vertex-api-disabled\",\n domain: \"auth\",\n regex:\n /\\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,\n fallback: {\n id: \"gcp-vertex-api-disabled\",\n slug: \"gcp-vertex-api-disabled\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"auth\",\n title: \"GCP Vertex AI / Companion API Disabled (SERVICE_DISABLED)\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"403\", \"PERMISSION_DENIED\", \"SERVICE_DISABLED\"],\n error_patterns: [\n \"SERVICE_DISABLED\",\n \"aiplatform.googleapis.com\",\n \"cloudaicompanion.googleapis.com\",\n \"Vertex AI API has not been used\",\n ],\n root_cause:\n \"The target GCP project does not have the Vertex AI API (`aiplatform.googleapis.com`) or Gemini Code Assist API (`cloudaicompanion.googleapis.com`) enabled.\",\n steps: [\n \"Enable `aiplatform.googleapis.com` on your active `GOOGLE_CLOUD_PROJECT`.\",\n \"If using Gemini CLI / Code Assist enterprise seats, also enable `cloudaicompanion.googleapis.com` as needed.\",\n \"Wait 1-2 minutes for GCP service enablement propagation, then retry.\",\n ],\n commands: [\n {\n label: \"Enable Vertex AI API\",\n os: \"all\",\n command:\n \"gcloud services enable aiplatform.googleapis.com --project=${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id}\",\n },\n {\n label: \"Enable Gemini Code Assist API (if needed)\",\n os: \"all\",\n command:\n \"gcloud services enable cloudaicompanion.googleapis.com --project=${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id}\",\n },\n ],\n verify_command:\n \"gcloud services list --enabled --filter=\\\"config.name:(aiplatform.googleapis.com OR cloudaicompanion.googleapis.com)\\\"\",\n dont_dos: [\n \"Do NOT switch to an unrelated personal API key to work around a disabled project API.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/auth/gcp-vertex-api-disabled\",\n },\n },\n {\n id: \"gcp-adc-expired\",\n domain: \"auth\",\n regex:\n /\\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,\n fallback: {\n id: \"gcp-adc-expired\",\n slug: \"gcp-adc-expired\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"auth\",\n title: \"GCP Application Default Credentials (ADC) Expired / Reauth Required\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"401\", \"403\", \"UNAUTHENTICATED\", \"invalid_grant\"],\n error_patterns: [\n \"invalid_grant\",\n \"reauth related error\",\n \"Refreshing credentials failed\",\n \"Getting metadata from plugin failed\",\n \"application-default login\",\n ],\n root_cause:\n \"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.\",\n steps: [\n \"Re-authenticate Application Default Credentials via `gcloud auth application-default login`.\",\n \"Check whether `GOOGLE_APPLICATION_CREDENTIALS` is set to a stale or deleted file path (without printing secret contents).\",\n ],\n commands: [\n {\n label: \"Refresh Application Default Credentials\",\n os: \"all\",\n command: \"gcloud auth application-default login\",\n },\n {\n label: \"Check GOOGLE_APPLICATION_CREDENTIALS path existence\",\n os: \"unix\",\n command: \"test -n \\\"$GOOGLE_APPLICATION_CREDENTIALS\\\" && ls -l \\\"$GOOGLE_APPLICATION_CREDENTIALS\\\" || echo \\\"unset\\\"\",\n },\n ],\n verify_command: \"gcloud auth application-default print-access-token >/dev/null && echo OK\",\n dont_dos: [\n \"Do NOT read, print, or paste raw service account JSON keys or OAuth refresh tokens.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/auth/gcp-adc-expired\",\n },\n },\n {\n id: \"gcp-vertex-iam-or-location\",\n domain: \"auth\",\n regex:\n /roles\\/aiplatform\\.user|aiplatform\\.endpoints\\.predict|not\\s+found\\s+in\\s+location|Publisher\\s+Model.*(?:not\\s+found|permission)/i,\n fallback: {\n id: \"gcp-vertex-iam-or-location\",\n slug: \"gcp-vertex-iam-or-location\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"auth\",\n title: \"Vertex AI IAM Role (roles/aiplatform.user) or Location Mismatch\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"403\", \"404\", \"PERMISSION_DENIED\", \"NOT_FOUND\"],\n error_patterns: [\n \"roles/aiplatform.user\",\n \"aiplatform.endpoints.predict\",\n \"not found in location\",\n \"Publisher Model\",\n ],\n root_cause:\n \"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.\",\n steps: [\n \"Verify `GOOGLE_CLOUD_LOCATION` matches a supported region for the target model (e.g. `us-central1` or `global`).\",\n \"Confirm your user or service account has `roles/aiplatform.user` (including `aiplatform.endpoints.predict`) on the target project.\",\n ],\n commands: [\n {\n label: \"Set supported Vertex AI location\",\n os: \"unix\",\n command: \"export GOOGLE_CLOUD_LOCATION=us-central1\",\n },\n {\n label: \"Inspect project IAM policy for active account\",\n os: \"all\",\n command:\n \"gcloud projects get-iam-policy ${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id} --flatten=\\\"bindings[].members\\\" --format=\\\"table(bindings.role,bindings.members)\\\"\",\n },\n ],\n verify_command: \"echo \\\"GOOGLE_CLOUD_LOCATION=${GOOGLE_CLOUD_LOCATION:-unset}\\\"\",\n dont_dos: [\n \"Do NOT grant `roles/owner` when `roles/aiplatform.user` is sufficient.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/auth/gcp-vertex-iam-or-location\",\n },\n },\n {\n id: \"gcp-vpc-sc-blocked\",\n domain: \"network\",\n regex:\n /VPC\\s+Service\\s+Controls|prohibited\\s+by\\s+organization(?:'s)?\\s+policy|vpcServiceControlsUniqueIdentifier|Request\\s+is\\s+prohibited\\s+by\\s+organization/i,\n fallback: {\n id: \"gcp-vpc-sc-blocked\",\n slug: \"gcp-vpc-sc-blocked\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"network\",\n title: \"Blocked by GCP VPC Service Controls / Organization Policy\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"403\", \"PERMISSION_DENIED\", \"VPC_SERVICE_CONTROLS\"],\n error_patterns: [\n \"VPC Service Controls\",\n \"prohibited by organization's policy\",\n \"vpcServiceControlsUniqueIdentifier\",\n \"Request is prohibited by organization\",\n ],\n root_cause:\n \"The request was blocked at the enterprise GCP VPC Service Controls perimeter or organization policy boundary.\",\n steps: [\n \"Record the `vpcServiceControlsUniqueIdentifier` (if present) from the error payload.\",\n \"Contact your GCP security/network administrator to review VPC-SC ingress/egress rules, or run from an authorized corporate network/perimeter.\",\n ],\n commands: [\n {\n label: \"Verify active gcloud account and project\",\n os: \"all\",\n command: \"gcloud config list --format=\\\"table(core.account,core.project)\\\"\",\n },\n ],\n verify_command: \"gcloud config get-value project\",\n dont_dos: [\n \"Do NOT attempt to bypass corporate VPC Service Controls with unapproved proxies or personal projects.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/network/gcp-vpc-sc-blocked\",\n },\n },\n {\n id: \"403-auth-mismatch\",\n domain: \"auth\",\n regex:\n /\\b401\\b|\\b403\\b|UNAUTHENTICATED|Permission\\s*Denied|cloudaicompanion.*denied|ACCESS_TOKEN_TYPE_UNSUPPORTED|API_KEY_INVALID/i,\n fallback: {\n id: \"403-auth-mismatch\",\n slug: \"403-auth-mismatch\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"auth\",\n title: \"401/403 Auth & Entitlement Mismatch\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"401\", \"403\", \"UNAUTHENTICATED\", \"PERMISSION_DENIED\"],\n error_patterns: [\"401\", \"403\", \"UNAUTHENTICATED\", \"ACCESS_TOKEN_TYPE_UNSUPPORTED\"],\n root_cause:\n \"Mixed authentication state (e.g., GEMINI_API_KEY colliding with GOOGLE_CLOUD_PROJECT OAuth) or stale local OAuth consent/ADC cache.\",\n steps: [\n \"Unset conflicting env vars so only ONE auth mode (API Key OR Google Cloud OAuth) is active.\",\n \"Revoke stale third-party authorization at https://myaccount.google.com/connections if OAuth is stuck.\",\n \"Clear local auth cache and re-authenticate cleanly.\",\n ],\n commands: [\n { label: \"Unset conflicting API key vars\", os: \"unix\", command: \"unset GEMINI_API_KEY GOOGLE_API_KEY\" },\n { label: \"Set GCP project for OAuth/Vertex\", os: \"unix\", command: \"export GOOGLE_CLOUD_PROJECT=your-gcp-project-id\" },\n { label: \"Refresh Application Default Credentials\", os: \"all\", command: \"gcloud auth application-default login\" },\n ],\n verify_command: \"gcloud auth application-default print-access-token >/dev/null && echo OK\",\n dont_dos: [\n \"Do NOT paste OAuth tokens or API keys into public issue trackers or MCP logs.\",\n \"Do NOT mix Vertex AI GOOGLE_CLOUD_PROJECT with AI Studio GEMINI_API_KEY in the same shell.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/auth/403-auth-mismatch\",\n },\n },\n {\n id: \"503-504-stall\",\n domain: \"capacity\",\n regex:\n /\\b503\\b|\\b504\\b|No\\s*capacity|DEADLINE_EXCEEDED|UNAVAILABLE|antigravity-unleash\\.goog|overloaded/i,\n fallback: {\n id: \"503-504-stall\",\n slug: \"503-504-stall\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"capacity\",\n title: \"503 No Capacity / 504 DEADLINE_EXCEEDED / Stall\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"503\", \"504\", \"UNAVAILABLE\", \"DEADLINE_EXCEEDED\"],\n error_patterns: [\"503\", \"504\", \"DEADLINE_EXCEEDED\", \"No capacity\"],\n root_cause:\n \"Upstream model capacity saturation (503) or oversized uncompacted prompt context exceeding backend deadline (504).\",\n steps: [\n \"Check ModelCraft live upstream status to confirm whether a global 503 wave is active.\",\n \"If upstream is healthy and you hit 504: add a `.geminiignore` file, run `/compact`, and split the task.\",\n \"Temporarily switch from flagship Neon to Hydrogen or Flash until capacity recovers.\",\n ],\n commands: [\n { label: \"Check context hygiene & .geminiignore\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n ],\n verify_command: \"curl -sI https://modelcraft.dev/data/v1/status.json | head -n 1\",\n dont_dos: [\n \"Do NOT keep retrying massive 500k+ token prompts on 504 without compacting context first.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/capacity/503-504-stall\",\n },\n },\n {\n id: \"mcp-disconnected\",\n domain: \"mcp\",\n regex:\n /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,\n fallback: {\n id: \"mcp-disconnected\",\n slug: \"mcp-disconnected\",\n provider: \"antigravity\",\n route_provider: \"agy\",\n domain: \"mcp\",\n title: \"MCP Disconnected / Transport Mismatch / Env Stripped\",\n severity: \"high\",\n products: [\"agy\", \"cli\"],\n error_codes: [\"EADDRINUSE\", \"MCP_DISCONNECTED\"],\n error_patterns: [\"MCP Disconnected\", \"EADDRINUSE\", \"httpUrl\"],\n root_cause:\n \"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.\",\n steps: [\n \"Trust the workspace directory with `gemini trust`.\",\n \"Run `npx agycraft-mcp doctor` to check JSON syntax, `url` vs `httpUrl`, and env key stripping.\",\n \"Pass required credentials explicitly inside the server's `env` block in mcp_config.json / settings.json.\",\n ],\n commands: [\n { label: \"Trust workspace\", os: \"all\", command: \"gemini trust\" },\n { label: \"Run offline config doctor\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n { label: \"List active MCP servers\", os: \"all\", command: \"gemini mcp list\" },\n ],\n verify_command: \"gemini mcp list\",\n dont_dos: [\n \"Do NOT log debug text to stdout in stdio MCP servers — stdout is reserved for JSON-RPC frames.\",\n \"Do NOT set both `url` and `httpUrl` on the same MCP server entry.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/mcp/mcp-disconnected\",\n },\n },\n {\n id: \"ssl-proxy\",\n domain: \"network\",\n regex:\n /UNABLE_TO_GET_ISSUER_CERT_LOCALLY|UNABLE_TO_VERIFY_LEAF_SIGNATURE|SELF_SIGNED_CERT_IN_CHAIN|CERT_HAS_EXPIRED|ECONNRESET|ETIMEDOUT|ECONNREFUSED/i,\n fallback: {\n id: \"ssl-proxy\",\n slug: \"ssl-proxy\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"network\",\n title: \"Corporate Proxy / SSL Certificate Verification Failure\",\n severity: \"medium\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\", \"SELF_SIGNED_CERT_IN_CHAIN\"],\n error_patterns: [\"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\", \"SELF_SIGNED_CERT_IN_CHAIN\"],\n root_cause:\n \"Node.js does not automatically trust corporate TLS-inspecting proxy root certificates unless NODE_EXTRA_CA_CERTS is configured.\",\n steps: [\n \"Export your corporate root CA bundle in PEM format.\",\n \"Set `NODE_EXTRA_CA_CERTS` in your shell profile and verify the file is readable.\",\n \"Verify `HTTP_PROXY` / `HTTPS_PROXY` URLs are reachable.\",\n ],\n commands: [\n { label: \"Configure Node extra CA bundle\", os: \"unix\", command: \"export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem\" },\n { label: \"Verify SSL & proxy setup\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n ],\n verify_command: \"node -e \\\"fetch('https://modelcraft.dev/data/v1/status.json').then(r => console.log(r.status))\\\"\",\n dont_dos: [\n \"Do NOT permanently set `NODE_TLS_REJECT_UNAUTHORIZED=0` — it disables all TLS verification.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/network/ssl-proxy\",\n },\n },\n {\n id: \"function-calling-state\",\n domain: \"protocol\",\n regex:\n /thought_signature|function[\\s_]+call|function[\\s_]+response|FunctionCall|MALFORMED_FUNCTION_CALL|INVALID_ARGUMENT.*turn|tool_call_id/i,\n fallback: {\n id: \"function-calling-state\",\n slug: \"function-calling-state\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"protocol\",\n title: \"Function Calling Turn Alignment / Missing thought_signature\",\n severity: \"medium\",\n products: [\"api\", \"cli\", \"agy\"],\n error_codes: [\"INVALID_ARGUMENT\"],\n error_patterns: [\"thought_signature\", \"function_call\", \"function_response\"],\n root_cause:\n \"Tool call/response turn sequence is misaligned, or Thinking-model `thought_signature` was stripped when replaying assistant tool calls.\",\n steps: [\n \"Preserve the exact `thought_signature` field on model `functionCall` parts when sending back `functionResponse` turns.\",\n \"Ensure every `functionCall` turn is immediately followed by matching `functionResponse` parts in the next user/tool turn.\",\n \"Upgrade `@google/genai` or `@google/gemini-cli` to the latest release.\",\n ],\n commands: [\n { label: \"Check latest Gemini CLI version\", os: \"all\", command: \"npm view @google/gemini-cli version\" },\n ],\n verify_command: \"Replay a single 2-turn tool call with unmodified model parts including thought_signature.\",\n dont_dos: [\n \"Do NOT manually reconstruct or strip unknown fields from model `parts` during multi-turn tool calling.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/protocol/function-calling-state\",\n },\n },\n {\n id: \"structured-output-schema\",\n domain: \"protocol\",\n regex:\n /(?: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,\n fallback: {\n id: \"structured-output-schema\",\n slug: \"structured-output-schema\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"protocol\",\n title: \"Structured Output JSON Schema Too Deep or Unsupported Keyword\",\n severity: \"medium\",\n products: [\"api\", \"cli\"],\n error_codes: [\"INVALID_ARGUMENT\"],\n error_patterns: [\"response_schema\", \"nesting depth\", \"too many states\"],\n root_cause:\n \"Gemini constrained decoding rejects deeply nested schemas, recursive `$ref` cycles, or excessive union branches ('too many states').\",\n steps: [\n \"Flatten nested objects to <= 4 levels and remove recursive `$ref` definitions.\",\n \"Replace large `oneOf`/`anyOf` unions with a flat discriminator string enum + optional fields.\",\n \"Keep property descriptions concise so grammar compilation stays within state limits.\",\n ],\n commands: [\n { label: \"Run doctor preflight\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n ],\n verify_command: \"Re-run the API call with flattened JSON schema (depth <= 4, no recursive $ref).\",\n dont_dos: [\n \"Do NOT pass unconstrained TypeScript ASTs or OpenAPI specs directly as `response_schema`.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/protocol/structured-output-schema\",\n },\n },\n];\n\nfunction extractSignals(errorText: string): {\n http_status: string | null;\n retry_delay: string | null;\n quota_metric: string | null;\n} {\n const httpMatch = errorText.match(/\\b(400|401|403|404|408|429|500|502|503|504)\\b/);\n const retryMatch = errorText.match(/retryDelay[\"']?\\s*[:=]\\s*[\"']?([0-9.]+s?)/i);\n const metricMatch = errorText.match(/quotaMetric[\"']?\\s*[:=]\\s*[\"']?([a-zA-Z0-9._/-]+)/i);\n\n return {\n http_status: httpMatch?.[1] ?? null,\n retry_delay: retryMatch?.[1] ?? null,\n quota_metric: metricMatch?.[1] ?? null,\n };\n}\n\nexport function diagnoseError(options: {\n errorText: string;\n product?: string;\n localRecords?: UsageRecord[];\n statusSnapshot?: StatusSnapshot | null;\n diagnosisEntries?: DiagnosisEntry[];\n authMode?: AuthMode | \"auto\";\n authContext?: AuthContext;\n cliChannel?: string;\n channels?: ChannelsSnapshot | ChannelRegistry;\n nowMs?: number;\n locale?: SupportedLocale;\n}): DiagnosisResult {\n const locale = options.locale ?? \"en\";\n const text = options.errorText;\n const lowerText = text.toLowerCase();\n const signals = extractSignals(text);\n const nowMs = options.nowMs ?? Date.now();\n const registry =\n options.channels instanceof ChannelRegistry\n ? options.channels\n : options.channels\n ? ChannelRegistry.fromSnapshot(options.channels)\n : loadBundledChannelRegistry();\n\n const { resolvedChannel, analysis: authChannelAnalysis } = resolveErrorAuthChannel({\n errorText: text,\n authMode: options.authMode,\n authContext: options.authContext,\n cliChannel: options.cliChannel,\n registry,\n });\n\n const upstreamStatus = options.statusSnapshot?.overall_status ?? \"unknown\";\n const hasActiveIncident =\n upstreamStatus === \"degraded\" ||\n upstreamStatus === \"outage\" ||\n (options.statusSnapshot?.active_incidents?.some(\n (i) => i.status !== \"resolved\",\n ) ??\n false);\n\n const skip403AuthMismatch = isExternalGcpDataPlane403(text);\n\n // Match against built-in regex rules first for precision, then enrich from remote diagnosis entries\n let matchedRule: PatternRule | null = null;\n for (const rule of BUILTIN_RULES) {\n if (skip403AuthMismatch && rule.id === \"403-auth-mismatch\") {\n continue;\n }\n if (rule.regex.test(text)) {\n matchedRule = rule;\n break;\n }\n }\n\n const GENERIC_ERROR_CODES = new Set([\n \"400\",\n \"401\",\n \"403\",\n \"404\",\n \"500\",\n \"502\",\n \"503\",\n \"504\",\n \"invalid_argument\",\n ]);\n\n const skipGeneric403 =\n skip403AuthMismatch ||\n (matchedRule !== null && SPECIFIC_GCP_RULE_IDS.has(matchedRule.id));\n\n let remoteMatch: DiagnosisEntry | null = null;\n let bestScore = 0;\n for (const entry of options.diagnosisEntries ?? []) {\n if (\n skipGeneric403 &&\n (entry.id === \"google-403-auth-mismatch\" || entry.slug === \"403-auth-mismatch\")\n ) {\n continue;\n }\n if (!isEntryApplicableToChannel(entry, resolvedChannel, registry)) {\n continue;\n }\n let score = 0;\n let hasSpecificSignal = false;\n const codeSet = new Set((entry.error_codes ?? []).map((c) => c.toLowerCase()));\n for (const p of entry.error_patterns ?? []) {\n const lp = p.toLowerCase();\n if (lowerText.includes(lp)) {\n if (codeSet.has(lp) || GENERIC_ERROR_CODES.has(lp)) {\n score += 2;\n } else {\n score += 10;\n hasSpecificSignal = true;\n }\n }\n }\n for (const c of entry.error_codes ?? []) {\n const lc = c.toLowerCase();\n if (lowerText.includes(lc)) {\n score += 2;\n if (!GENERIC_ERROR_CODES.has(lc)) {\n hasSpecificSignal = true;\n }\n }\n }\n if (matchedRule && (entry.id === matchedRule.id || entry.slug === matchedRule.id)) {\n score += 25;\n hasSpecificSignal = true;\n }\n if (\n resolvedChannel !== \"unknown\" &&\n resolvedChannel !== \"mixed_ambiguous\" &&\n entry.applicable_auth_modes?.some((m) => registry.matchesChannel(m, resolvedChannel))\n ) {\n score += 20;\n }\n if (findChannelVariant(entry, resolvedChannel, registry)) {\n score += 15;\n }\n if (hasSpecificSignal && score > bestScore) {\n bestScore = score;\n remoteMatch = entry;\n }\n }\n\n const rawChosen = remoteMatch ?? matchedRule?.fallback ?? null;\n const chosen = rawChosen\n ? applyChannelPrescription({\n chosen: rawChosen,\n resolvedChannel,\n registry,\n locale,\n })\n : null;\n\n if (!chosen) {\n return {\n matched: false,\n domain: \"unknown\",\n diagnosis_id: \"unclassified\",\n title: \"Unclassified Error\",\n confidence: \"low\",\n attribution: hasActiveIncident\n ? `Upstream status is currently \"${upstreamStatus}\" — this may be related to an active provider incident.`\n : \"No known fault signature matched. Run `npx agycraft-mcp doctor` to check local environment hygiene.\",\n root_cause:\n \"Error text did not match the 5 primary fault domains (quota, auth, capacity, mcp, network) or protocol signatures.\",\n steps: [\n \"Run `npx agycraft-mcp doctor` to inspect local config syntax, auth env booleans, and proxy settings.\",\n \"Check https://modelcraft.dev/fix for the latest community-verified troubleshooting guides.\",\n ],\n commands: [\n { label: \"Run local preflight doctor\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n ],\n verify_command: \"npx agycraft-mcp doctor\",\n dont_dos: [\n \"Do NOT paste raw API keys, OAuth tokens, or private code when asking for help.\",\n ],\n deep_link: \"https://modelcraft.dev/fix\",\n official_source_url: \"https://aistudio.google.com/docs/troubleshooting\",\n upstream_status: upstreamStatus,\n extracted_signals: signals,\n auth_channel_analysis: authChannelAnalysis,\n };\n }\n\n // Cross-correlate local 5h usage (strictly isolated by resolvedChannel) & upstream status for attribution\n const resolvedChannelDef =\n resolvedChannel !== \"unknown\" && resolvedChannel !== \"mixed_ambiguous\"\n ? registry.getChannel(resolvedChannel)\n : undefined;\n const windowType = resolvedChannelDef?.definition.quota_reset_policy.window_type;\n const isRollingBucketChannel = !windowType || windowType === \"rolling_5h_7d\";\n\n let attribution = `Matched fault domain: ${chosen.domain}.`;\n if (chosen.domain === \"quota\") {\n const fiveHoursAgo = nowMs - 5 * 3600 * 1000;\n const recentRecords = (options.localRecords ?? []).filter((r) => {\n if (Date.parse(r.ts) < fiveHoursAgo) {\n return false;\n }\n if (resolvedChannel !== \"unknown\" && resolvedChannel !== \"mixed_ambiguous\" && r.auth_mode) {\n return registry.matchesChannel(r.auth_mode, resolvedChannel);\n }\n return true;\n });\n const recentTokens = recentRecords.reduce(\n (sum, r) => sum + r.input_tokens + r.output_tokens,\n 0,\n );\n\n if (!isRollingBucketChannel && resolvedChannelDef) {\n const displayName =\n locale === \"zh\" && resolvedChannelDef.definition.display_name_zh\n ? resolvedChannelDef.definition.display_name_zh\n : resolvedChannelDef.definition.display_name;\n const throttlingGuidance =\n getLocalizedBehavior(\n resolvedChannelDef.definition.recommended_behaviors,\n \"throttling_guidance\",\n locale,\n ) ?? resolvedChannelDef.definition.recommended_behaviors.throttling_guidance;\n attribution = hasActiveIncident\n ? `POSSIBLE UPSTREAM INCIDENT (${upstreamStatus}) on ${displayName}: ${throttlingGuidance}`\n : `${displayName} (${resolvedChannelDef.definition.billing_model}, ${recentRecords.length} recent channel turns / ${recentTokens.toLocaleString()} tokens): ${throttlingGuidance}`;\n } else if (lowerText.includes(\"limit: 0\") || (recentRecords.length > 0 && recentTokens < 50_000)) {\n attribution =\n \"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.\";\n } else if (recentTokens >= 500_000) {\n 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.`;\n } else if (hasActiveIncident) {\n attribution = `POSSIBLE UPSTREAM INCIDENT: Upstream status is \"${upstreamStatus}\" — 429s may be caused by upstream throttling.`;\n } else {\n attribution =\n \"QUOTA / RATE LIMIT HIT: Enable local numeric usage logging (`npx agycraft-mcp setup`) to distinguish real 5h/7d exhaustion from entitlement desync.\";\n }\n } else if (chosen.domain === \"capacity\") {\n attribution = hasActiveIncident\n ? `UPSTREAM OUTAGE/DEGRADATION CONFIRMED (${upstreamStatus}): Not a local machine issue. Wait for recovery or temporarily switch to Flash/Hydrogen.`\n : \"LOCAL CONTEXT OR TRANSIENT CAPACITY SPIKE: Upstream status appears operational; check for oversized context (>200k tokens) and add `.geminiignore`.\";\n }\n\n return localizeDiagnosisEntry(\n {\n matched: true,\n domain: chosen.domain,\n diagnosis_id: chosen.id,\n title: chosen.title,\n confidence: \"high\",\n attribution,\n root_cause: chosen.root_cause,\n steps: chosen.steps,\n commands: chosen.commands,\n verify_command: chosen.verify_command,\n dont_dos: chosen.dont_dos,\n deep_link: chosen.deep_link.startsWith(\"/\")\n ? `https://modelcraft.dev${chosen.deep_link}`\n : chosen.deep_link,\n official_source_url: chosen.official_source_url ?? null,\n upstream_status: upstreamStatus,\n extracted_signals: signals,\n auth_channel_analysis: authChannelAnalysis,\n },\n locale,\n );\n}\n","/**\n * Pure local reset countdown calculator for Gemini API / AI Studio PT midnight\n * and AGY 5-hour / 7-day rolling shared quota windows.\n */\nexport interface ResetCountdown {\n timezone: string;\n now_iso: string;\n pt_midnight: {\n next_reset_iso: string;\n next_reset_local: string;\n remaining_seconds: number;\n remaining_human: string;\n };\n rolling_5h: {\n window_hours: 5;\n is_local_estimate: true;\n estimate_note: string;\n oldest_active_event_iso: string | null;\n estimated_relief_iso: string | null;\n estimated_relief_local: string | null;\n remaining_seconds: number | null;\n remaining_human: string;\n };\n rolling_7d: {\n window_days: 7;\n is_local_estimate: true;\n estimate_note: string;\n oldest_active_event_iso: string | null;\n estimated_relief_iso: string | null;\n estimated_relief_local: string | null;\n remaining_seconds: number | null;\n remaining_human: string;\n };\n}\n\nconst ROLLING_ESTIMATE_NOTE =\n \"Approximated solely from the earliest local event timestamp in this window; does not reflect server-side multi-device usage or official remaining quota percentages.\";\n\nexport function formatDuration(seconds: number): string {\n const clamped = Math.max(0, Math.floor(seconds));\n const days = Math.floor(clamped / 86400);\n const hours = Math.floor((clamped % 86400) / 3600);\n const mins = Math.floor((clamped % 3600) / 60);\n if (days > 0) {\n return `${days}d ${hours}h ${mins}m`;\n }\n if (hours > 0) {\n return `${hours}h ${mins}m`;\n }\n return `${mins}m`;\n}\n\nfunction validateTimezone(tz?: string): string {\n if (!tz) {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n }\n try {\n Intl.DateTimeFormat(\"en-US\", { timeZone: tz });\n return tz;\n } catch {\n return \"UTC\";\n }\n}\n\nfunction getPtDateParts(now: Date): {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n} {\n const fmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: \"America/Los_Angeles\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n const parts = fmt.formatToParts(now);\n const get = (type: string): number =>\n Number(parts.find((p) => p.type === type)?.value ?? \"0\");\n return {\n year: get(\"year\"),\n month: get(\"month\"),\n day: get(\"day\"),\n hour: get(\"hour\") === 24 ? 0 : get(\"hour\"),\n minute: get(\"minute\"),\n second: get(\"second\"),\n };\n}\n\n/**\n * Computes the exact next midnight in America/Los_Angeles (handles PST/PDT transitions).\n */\nexport function computeNextPtMidnight(now: Date): Date {\n const pt = getPtDateParts(now);\n const remainingTodaySec =\n (23 - pt.hour) * 3600 + (59 - pt.minute) * 60 + (60 - pt.second);\n // Step forward to approximate next PT midnight, then refine to exact 00:00:00 PT\n let candidate = new Date(now.getTime() + remainingTodaySec * 1000);\n // Adjust by up to +/-1h if DST switched overnight\n for (let i = 0; i < 3; i++) {\n const check = getPtDateParts(candidate);\n if (check.hour === 0 && check.minute === 0 && check.second === 0) {\n break;\n }\n if (check.hour >= 22) {\n candidate = new Date(\n candidate.getTime() + ((24 - check.hour) * 3600 - check.minute * 60 - check.second) * 1000,\n );\n } else if (check.hour <= 2) {\n candidate = new Date(\n candidate.getTime() - (check.hour * 3600 + check.minute * 60 + check.second) * 1000,\n );\n }\n }\n return candidate;\n}\n\nexport function computeResetCountdown(options?: {\n now?: Date;\n timezone?: string;\n oldestEventIn5hMs?: number | null;\n oldestEventIn7dMs?: number | null;\n}): ResetCountdown {\n const now = options?.now ?? new Date();\n const tz = validateTimezone(options?.timezone);\n\n const nextPt = computeNextPtMidnight(now);\n const ptRemainingSec = Math.max(\n 0,\n Math.floor((nextPt.getTime() - now.getTime()) / 1000),\n );\n const nextPtLocal = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(nextPt);\n\n const fiveHoursMs = 5 * 3600 * 1000;\n const sevenDaysMs = 7 * 86400 * 1000;\n\n let relief5hIso: string | null = null;\n let relief5hLocal: string | null = null;\n let relief5hSec: number | null = null;\n if (options?.oldestEventIn5hMs) {\n const reliefMs = options.oldestEventIn5hMs + fiveHoursMs;\n relief5hIso = new Date(reliefMs).toISOString();\n relief5hLocal = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(new Date(reliefMs));\n relief5hSec = Math.max(0, Math.floor((reliefMs - now.getTime()) / 1000));\n }\n\n let relief7dIso: string | null = null;\n let relief7dLocal: string | null = null;\n let relief7dSec: number | null = null;\n if (options?.oldestEventIn7dMs) {\n const reliefMs = options.oldestEventIn7dMs + sevenDaysMs;\n relief7dIso = new Date(reliefMs).toISOString();\n relief7dLocal = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(new Date(reliefMs));\n relief7dSec = Math.max(0, Math.floor((reliefMs - now.getTime()) / 1000));\n }\n\n return {\n timezone: tz,\n now_iso: now.toISOString(),\n pt_midnight: {\n next_reset_iso: nextPt.toISOString(),\n next_reset_local: nextPtLocal,\n remaining_seconds: ptRemainingSec,\n remaining_human: formatDuration(ptRemainingSec),\n },\n rolling_5h: {\n window_hours: 5,\n is_local_estimate: true,\n estimate_note: ROLLING_ESTIMATE_NOTE,\n oldest_active_event_iso: options?.oldestEventIn5hMs\n ? new Date(options.oldestEventIn5hMs).toISOString()\n : null,\n estimated_relief_iso: relief5hIso,\n estimated_relief_local: relief5hLocal,\n remaining_seconds: relief5hSec,\n remaining_human:\n relief5hSec !== null\n ? formatDuration(relief5hSec)\n : \"No active usage recorded in last 5h\",\n },\n rolling_7d: {\n window_days: 7,\n is_local_estimate: true,\n estimate_note: ROLLING_ESTIMATE_NOTE,\n oldest_active_event_iso: options?.oldestEventIn7dMs\n ? new Date(options.oldestEventIn7dMs).toISOString()\n : null,\n estimated_relief_iso: relief7dIso,\n estimated_relief_local: relief7dLocal,\n remaining_seconds: relief7dSec,\n remaining_human:\n relief7dSec !== null\n ? formatDuration(relief7dSec)\n : \"No active usage recorded in last 7d\",\n },\n };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { getCacheDir, getPackageVersion, getSnapshotsDir } from \"../paths.js\";\nimport type {\n ModelsSnapshot,\n NormalizationRules,\n SnapshotMap,\n SnapshotName,\n} from \"../types.js\";\n\nconst DEFAULT_DATA_URL = \"https://modelcraft.dev/data/v1\";\n\nconst TTL_MS: Record<SnapshotName, number> = {\n status: 5 * 60 * 1000,\n updates: 15 * 60 * 1000,\n models: 6 * 60 * 60 * 1000,\n chronicle: 6 * 60 * 60 * 1000,\n diagnosis: 6 * 60 * 60 * 1000,\n quotas: 6 * 60 * 60 * 1000,\n channels: 6 * 60 * 60 * 1000,\n};\n\ninterface CacheMeta {\n etag: string | null;\n fetched_at_ms: number;\n pkg_version?: string;\n}\n\nexport interface SnapshotFetchResult<T> {\n data: T;\n source: \"remote\" | \"cache\" | \"bundled_fallback\";\n}\n\nexport interface SnapshotClientOptions {\n baseUrl?: string;\n cacheDir?: string;\n snapshotsDir?: string;\n fetchFn?: typeof fetch;\n offlineOnly?: boolean;\n timeoutMs?: number;\n pkgVersion?: string;\n}\n\nfunction getProviderId(p: string | { id: string }): string {\n return typeof p === \"string\" ? p : p.id;\n}\n\nfunction mergeNormalizationRules(\n remote?: NormalizationRules,\n fallback?: NormalizationRules,\n): NormalizationRules | undefined {\n if (!remote) return fallback;\n if (!fallback) return remote;\n return {\n rules_version: remote.rules_version ?? fallback.rules_version,\n placeholder_prefixes: remote.placeholder_prefixes ?? fallback.placeholder_prefixes,\n enum_mappings: remote.enum_mappings ?? fallback.enum_mappings,\n prefix_strip_patterns: remote.prefix_strip_patterns ?? fallback.prefix_strip_patterns,\n suffix_strip_patterns: remote.suffix_strip_patterns ?? fallback.suffix_strip_patterns,\n version_format_rules: remote.version_format_rules ?? fallback.version_format_rules,\n fallback_pricing: remote.fallback_pricing ?? fallback.fallback_pricing,\n };\n}\n\n/**\n * Anti-regression merge for remote models.json:\n * Keeps all remote entries as authoritative, while backfilling any missing\n * providers or historical/anthropic models from bundledFallback.\n */\nexport function mergeModelsSnapshotWithFallback(\n remote: ModelsSnapshot,\n fallback: ModelsSnapshot,\n): ModelsSnapshot {\n const remoteProviders = Array.isArray(remote.providers) ? remote.providers : [];\n const fallbackProviders = Array.isArray(fallback.providers) ? fallback.providers : [];\n const seenProviderIds = new Set(remoteProviders.map((p) => getProviderId(p).toLowerCase()));\n const mergedProviders = [\n ...remoteProviders,\n ...fallbackProviders.filter((p) => !seenProviderIds.has(getProviderId(p).toLowerCase())),\n ];\n\n const remoteModels = Array.isArray(remote.models) ? remote.models : [];\n const fallbackModels = Array.isArray(fallback.models) ? fallback.models : [];\n const seenIds = new Set(remoteModels.map((m) => m.id.toLowerCase()));\n const seenApiIds = new Set(remoteModels.map((m) => m.api_model_id.toLowerCase()));\n const mergedModels = [\n ...remoteModels,\n ...fallbackModels.filter(\n (m) =>\n !seenIds.has(m.id.toLowerCase()) &&\n !seenApiIds.has(m.api_model_id.toLowerCase()),\n ),\n ];\n\n const mergedRules = mergeNormalizationRules(\n remote.normalization_rules,\n fallback.normalization_rules,\n );\n\n const mergedRecipes =\n Array.isArray(remote.orchestrator_recipes) && remote.orchestrator_recipes.length > 0\n ? remote.orchestrator_recipes\n : (fallback.orchestrator_recipes ?? []);\n\n return {\n ...remote,\n providers: mergedProviders,\n models: mergedModels,\n ...(mergedRules ? { normalization_rules: mergedRules } : {}),\n orchestrator_recipes: mergedRecipes,\n };\n}\n\nfunction isCachedNewerThanBundled(cachedData: unknown, bundledData: unknown): boolean {\n const cachedTs =\n cachedData &&\n typeof cachedData === \"object\" &&\n \"generated_at\" in cachedData &&\n typeof (cachedData as { generated_at?: unknown }).generated_at === \"string\"\n ? Date.parse((cachedData as { generated_at: string }).generated_at)\n : Number.NaN;\n const bundledTs =\n bundledData &&\n typeof bundledData === \"object\" &&\n \"generated_at\" in bundledData &&\n typeof (bundledData as { generated_at?: unknown }).generated_at === \"string\"\n ? Date.parse((bundledData as { generated_at: string }).generated_at)\n : Number.NaN;\n\n if (Number.isNaN(cachedTs) || Number.isNaN(bundledTs)) {\n return false;\n }\n return cachedTs > bundledTs;\n}\n\n/**\n * One-way read-only snapshot client.\n * PRIVACY RED LINE:\n * - Only performs GET requests to public static JSON at MODELCRAFT_DATA_URL (default https://modelcraft.dev/data/v1).\n * - NEVER sends user identifiers, telemetry, query params, cookies, or authorization headers.\n * - NEVER contacts Google/AGY internal endpoints.\n */\nexport class SnapshotClient {\n private readonly baseUrl: string;\n private readonly cacheDir: string;\n private readonly snapshotsDir: string;\n private readonly fetchFn: typeof fetch;\n private readonly offlineOnly: boolean;\n private readonly timeoutMs: number;\n private readonly pkgVersion: string;\n\n constructor(options?: SnapshotClientOptions) {\n const envUrl = process.env.MODELCRAFT_DATA_URL?.trim();\n this.baseUrl = (options?.baseUrl || envUrl || DEFAULT_DATA_URL).replace(\n /\\/+$/,\n \"\",\n );\n this.cacheDir = options?.cacheDir ?? getCacheDir();\n this.snapshotsDir = options?.snapshotsDir ?? getSnapshotsDir();\n this.fetchFn = options?.fetchFn ?? globalThis.fetch;\n this.offlineOnly =\n options?.offlineOnly ?? process.env.AGYCRAFT_OFFLINE === \"1\";\n this.timeoutMs = options?.timeoutMs ?? 4000;\n this.pkgVersion = options?.pkgVersion ?? getPackageVersion();\n }\n\n async get<K extends SnapshotName>(\n name: K,\n ): Promise<SnapshotFetchResult<SnapshotMap[K]>> {\n const cacheFile = join(this.cacheDir, `${name}.json`);\n const metaFile = join(this.cacheDir, `${name}.meta.json`);\n const ttl = TTL_MS[name];\n\n const cached = await this.readCache<SnapshotMap[K]>(cacheFile, metaFile);\n const versionMatches = cached?.meta.pkg_version === this.pkgVersion;\n const now = Date.now();\n\n if (cached && versionMatches && now - cached.meta.fetched_at_ms < ttl) {\n return { data: cached.data, source: \"cache\" };\n }\n\n if (!this.offlineOnly) {\n const remoteResult = await this.fetchRemote<SnapshotMap[K]>(\n name,\n versionMatches ? (cached?.meta.etag ?? null) : null,\n cacheFile,\n metaFile,\n versionMatches ? (cached?.data ?? null) : null,\n );\n if (remoteResult) {\n return remoteResult;\n }\n }\n\n const fallback = await this.readBundledFallback<SnapshotMap[K]>(name);\n if (cached && versionMatches && isCachedNewerThanBundled(cached.data, fallback)) {\n return { data: cached.data, source: \"cache\" };\n }\n\n return { data: fallback, source: \"bundled_fallback\" };\n }\n\n private async readCache<T>(\n cacheFile: string,\n metaFile: string,\n ): Promise<{ data: T; meta: CacheMeta } | null> {\n try {\n const [rawJson, rawMeta] = await Promise.all([\n readFile(cacheFile, \"utf8\"),\n readFile(metaFile, \"utf8\"),\n ]);\n const data = JSON.parse(rawJson) as T;\n const meta = JSON.parse(rawMeta) as CacheMeta;\n return { data, meta };\n } catch {\n return null;\n }\n }\n\n private async writeCache<T>(\n cacheFile: string,\n metaFile: string,\n data: T,\n etag: string | null,\n ): Promise<void> {\n try {\n await mkdir(this.cacheDir, { recursive: true });\n const meta: CacheMeta = {\n etag,\n fetched_at_ms: Date.now(),\n pkg_version: this.pkgVersion,\n };\n await Promise.all([\n writeFile(cacheFile, JSON.stringify(data), \"utf8\"),\n writeFile(metaFile, JSON.stringify(meta), \"utf8\"),\n ]);\n } catch {\n // Cache write failure is non-fatal\n }\n }\n\n private async fetchRemote<T>(\n name: SnapshotName,\n etag: string | null,\n cacheFile: string,\n metaFile: string,\n cachedData: T | null,\n ): Promise<SnapshotFetchResult<T> | null> {\n const url = `${this.baseUrl}/${name}.json`;\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n };\n if (etag) {\n headers[\"If-None-Match\"] = etag;\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const resp = await this.fetchFn(url, {\n method: \"GET\",\n headers,\n signal: controller.signal,\n });\n\n if (resp.status === 304 && cachedData !== null) {\n await this.writeCache(cacheFile, metaFile, cachedData, etag);\n return { data: cachedData, source: \"cache\" };\n }\n\n if (!resp.ok) {\n return null;\n }\n\n let data = (await resp.json()) as T;\n if (name === \"models\") {\n const modelsData = data as unknown as ModelsSnapshot;\n if (!modelsData || !Array.isArray(modelsData.models) || modelsData.models.length === 0) {\n return null;\n }\n try {\n const fallback = await this.readBundledFallback<ModelsSnapshot>(\"models\");\n data = mergeModelsSnapshotWithFallback(modelsData, fallback) as unknown as T;\n } catch {\n // Proceed with remote models snapshot if bundled fallback is unavailable\n }\n }\n\n const newEtag = resp.headers.get(\"etag\");\n await this.writeCache(cacheFile, metaFile, data, newEtag);\n return { data, source: \"remote\" };\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async readBundledFallback<T>(name: SnapshotName): Promise<T> {\n const filePath = join(this.snapshotsDir, `${name}.json`);\n const raw = await readFile(filePath, \"utf8\");\n return JSON.parse(raw) as T;\n }\n}\n","import {\n formatDoctorCostReport,\n formatDoctorReport,\n runDoctor,\n runDoctorCost,\n} from \"./cli/doctor.js\";\nimport type { CostSummaryWindow } from \"./storage/rollups.js\";\nimport { runPreflight, formatPreflightReport } from \"./cli/preflight.js\";\nimport { buildSetupInstructions } from \"./cli/setup.js\";\nimport { clearLocalData } from \"./cli/clear-local-data.js\";\nimport { appendUsageRecord } from \"./collectors/agy-hook.js\";\nimport { startStdioServer } from \"./server.js\";\n\nasync function readStdinText(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction printPreflightHelp(): void {\n console.log(\n [\n \"agycraft-mcp preflight — Live ModelCraft cloud status guard\",\n \"\",\n \"Usage:\",\n \" agycraft-mcp preflight [--json]\",\n \"\",\n \"Environment:\",\n \" MODELCRAFT_STATUS_URL Full URL override for status.json\",\n \" MODELCRAFT_DATA_URL Base URL override (default: https://modelcraft.dev/data/v1)\",\n \"\",\n \"Exit codes:\",\n \" 0 overall_status is operational, no active_incidents, all surfaces operational, no 429/503 sources\",\n \" 1 degraded, active incident, 429/503 source error, or network/timeout failure\",\n ].join(\"\\n\"),\n );\n}\n\nfunction printHelp(): void {\n console.log(\n [\n \"agycraft-mcp — Privacy-first local MCP server & CLI doctor for Antigravity (AGY) & Gemini CLI\",\n \"\",\n \"Usage:\",\n \" agycraft-mcp [--lang en|zh|auto] Start Stdio MCP Server (default)\",\n \" agycraft-mcp doctor [--cost] [--window 5h|24h|7d] [--lang en|zh|auto] [--json]\",\n \" Run offline preflight & hygiene check or readonly cost breakdown\",\n \" agycraft-mcp preflight [--json] Check live ModelCraft status.json (exits 1 if degraded/429/503)\",\n \" agycraft-mcp setup Print non-destructive, opt-in AGY / Gemini CLI setup snippets\",\n \" agycraft-mcp record Read hook JSON from stdin and append strictly whitelisted numeric metrics\",\n \" agycraft-mcp clear-local-data Safely delete ~/.config/agycraft/usage.jsonl and cache\",\n \" agycraft-mcp --help Show this help message\",\n \"\",\n \"Independent community project (ModelCraft). Not affiliated with or endorsed by Google.\",\n ].join(\"\\n\"),\n );\n}\n\nfunction extractLangArg(argv: string[]): { lang?: string; rest: string[] } {\n const rest: string[] = [];\n let lang: string | undefined;\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i];\n if (arg === undefined) {\n continue;\n }\n if (arg === \"--lang\") {\n const next = argv[i + 1];\n if (next !== \"en\" && next !== \"zh\" && next !== \"auto\") {\n throw new Error(`Invalid --lang value \"${next ?? \"\"}\". Expected: en, zh, or auto.`);\n }\n lang = next;\n i += 1;\n continue;\n }\n if (arg.startsWith(\"--lang=\")) {\n const val = arg.slice(\"--lang=\".length);\n if (val !== \"en\" && val !== \"zh\" && val !== \"auto\") {\n throw new Error(`Invalid --lang value \"${val}\". Expected: en, zh, or auto.`);\n }\n lang = val;\n continue;\n }\n rest.push(arg);\n }\n return { lang, rest };\n}\n\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<void> {\n let langArg: string | undefined;\n let restArgv: string[];\n try {\n const parsed = extractLangArg(argv);\n langArg = parsed.lang;\n restArgv = parsed.rest;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n return;\n }\n const cmd = restArgv[0];\n\n if (!cmd) {\n await startStdioServer({ defaultLang: langArg });\n return;\n }\n\n switch (cmd) {\n case \"doctor\": {\n const asJson = restArgv.includes(\"--json\");\n const withCost = restArgv.includes(\"--cost\");\n if (withCost) {\n let windowArg: CostSummaryWindow = \"24h\";\n const winIdx = restArgv.indexOf(\"--window\");\n if (winIdx !== -1) {\n const val = restArgv[winIdx + 1];\n if (val !== \"5h\" && val !== \"24h\" && val !== \"7d\") {\n console.error(`Invalid --window value \"${val ?? \"\"}\". Expected: 5h, 24h, or 7d.`);\n process.exitCode = 1;\n return;\n }\n windowArg = val;\n }\n const costReport = await runDoctorCost({ window: windowArg });\n if (asJson) {\n console.log(JSON.stringify(costReport, null, 2));\n } else {\n console.log(formatDoctorCostReport(costReport));\n }\n return;\n }\n\n let authModeArg: string | undefined;\n const authIdx = restArgv.indexOf(\"--auth-mode\");\n if (authIdx !== -1 && restArgv[authIdx + 1]) {\n authModeArg = restArgv[authIdx + 1];\n }\n const report = await runDoctor({\n ...(authModeArg ? { authMode: authModeArg } : {}),\n ...(langArg ? { lang: langArg } : {}),\n });\n if (asJson) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(formatDoctorReport(report));\n }\n return;\n }\n\n case \"preflight\": {\n if (restArgv.includes(\"--help\") || restArgv.includes(\"-h\")) {\n printPreflightHelp();\n return;\n }\n const asJson = restArgv.includes(\"--json\");\n const result = await runPreflight();\n if (asJson) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(formatPreflightReport(result));\n }\n process.exitCode = result.exit_code;\n return;\n }\n\n case \"setup\": {\n console.log(buildSetupInstructions());\n return;\n }\n\n case \"clear-local-data\": {\n const result = await clearLocalData();\n console.log(\n `Cleared local agycraft data (${result.removed.length} path(s) processed).`,\n );\n return;\n }\n\n case \"record\": {\n const raw = (await readStdinText()).trim();\n if (!raw) {\n return;\n }\n try {\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n await appendUsageRecord(parsed);\n } catch {\n // Ignore malformed stdin payloads silently so hooks never break AGY turns\n }\n return;\n }\n\n case \"-h\":\n case \"--help\":\n case \"help\": {\n printHelp();\n return;\n }\n\n default: {\n console.error(`Unknown subcommand: ${cmd}`);\n printHelp();\n process.exitCode = 1;\n }\n }\n}\n\n// Run when invoked directly as CLI binary\nconst isDirectRun =\n process.argv[1] &&\n (process.argv[1].endsWith(\"index.js\") ||\n process.argv[1].endsWith(\"index.ts\") ||\n process.argv[1].endsWith(\"agycraft-mcp\"));\n\nif (isDirectRun) {\n main().catch((err) => {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n });\n}\n"],"mappings":";;;AAAA,SAAS,QAAQ,YAAAA,WAAU,QAAAC,aAAY;AACvC,SAAS,aAAa,mBAAmB;AACzC,SAAS,WAAAC,gBAAe;AACxB,SAAS,QAAAC,aAAY;AACrB,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;;;ACL1B,SAAS,kBAAkB;AAC3B,SAAS,YAAAC,iBAAgB;AACzB,SAAS,WAAAC,gBAAe;AACxB,SAAS,QAAAC,aAAY;;;ACHrB,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,QAAAC,aAAY;;;ACDrB,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAE9B,IAAI,mBAAkC;AAE/B,SAAS,oBAA4B;AAC1C,MAAI,kBAAkB;AACpB,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,UAAU,IAAI,IAAI,mBAAmB,YAAY,GAAG;AAC1D,UAAM,MAAM,aAAa,SAAS,MAAM;AACxC,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,QAAI,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,KAAK,EAAE,SAAS,GAAG;AAC1E,yBAAmB,OAAO,QAAQ,KAAK;AACvC,aAAO;AAAA,IACT;AAAA,EACF,QAAQ;AAAA,EAER;AACA,qBAAmB;AACnB,SAAO;AACT;AAEO,SAAS,eAAuB;AACrC,QAAM,WAAW,QAAQ,IAAI;AAC7B,MAAI,YAAY,SAAS,KAAK,EAAE,SAAS,GAAG;AAC1C,WAAO,QAAQ,SAAS,KAAK,CAAC;AAAA,EAChC;AACA,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,OAAO,IAAI,KAAK,EAAE,SAAS,GAAG;AAChC,WAAO,KAAK,Q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AChC,QAAQ;AAAA,MAER;AACA;AAAA,IACF;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,QAAQ;AACX,gBAAU;AACV;AAAA,IACF;AAAA,IAEA,SAAS;AACP,cAAQ,MAAM,uBAAuB,GAAG,EAAE;AAC1C,gBAAU;AACV,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF;AAGA,IAAM,cACJ,QAAQ,KAAK,CAAC,MACb,QAAQ,KAAK,CAAC,EAAE,SAAS,UAAU,KAClC,QAAQ,KAAK,CAAC,EAAE,SAAS,UAAU,KACnC,QAAQ,KAAK,CAAC,EAAE,SAAS,cAAc;AAE3C,IAAI,aAAa;AACf,OAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,YAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAC9D,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;","names":["readFile","stat","homedir","join","readFile","homedir","join","readFileSync","join","readFileSync","join","readFile","join","resolve","resolve","resolve","resolve","join","readFile","readFile","join","homedir","createHash","randomBytes","mkdir","readdir","readFile","stat","writeFile","dirname","join","readdir","readFile","join","resolve","readFile","resolve","readdir","join","createHash","readdir","join","round4","mkdir","dirname","randomBytes","writeFile","readFile","stat","watermarks","hourlyCache","dirtyHourlyMonths","anyNewData","readFile","join","homedir","stat","rm","mkdir","readFile","dirname","mkdir","dirname","readFile","rm","access","join","readFile","readFile","localizedChosen","mkdir","readFile","writeFile","join","DEFAULT_DATA_URL","join","readFile","mkdir","writeFile","isSpecificAuthEmpty","access","join"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/doctor.ts","../src/collectors/auth-detector.ts","../src/collectors/channel-registry.ts","../src/paths.ts","../src/collectors/cli-log.ts","../src/analyzers/token-window.ts","../src/privacy.ts","../src/i18n.ts","../src/collectors/transcript-meta.ts","../src/analyzers/session-lifecycle.ts","../src/cli/hook-check.ts","../src/storage/rollups.ts","../src/cli/preflight.ts","../src/cli/hook-manage.ts","../src/cli/ignore-manage.ts","../src/cli/telemetry-manage.ts","../src/cli/setup.ts","../src/cli/clear-local-data.ts","../src/collectors/agy-hook.ts","../src/server.ts","../src/collectors/gemini-otel.ts","../src/analyzers/antipatterns.ts","../src/analyzers/channel-diagnosis.ts","../src/analyzers/error-diagnoser.ts","../src/analyzers/countdown.ts","../src/remote/snapshot-client.ts","../src/index.ts"],"sourcesContent":["import { access, readFile, stat } from \"node:fs/promises\";\nimport { constants as fsConstants } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { detectAuthContext } from \"../collectors/auth-detector.js\";\nimport {\n ChannelRegistry,\n loadBundledChannelRegistry,\n} from \"../collectors/channel-registry.js\";\nimport { getLocalizedBehavior, resolveLocale } from \"../i18n.js\";\nimport { getSnapshotsDir } from \"../paths.js\";\nimport { analyzeTranscriptStructure } from \"../collectors/transcript-meta.js\";\nimport { evaluateSessionLifecycle } from \"../analyzers/session-lifecycle.js\";\nimport {\n extractTranscriptTailLifecycleMetrics,\n findLatestTranscriptPath,\n} from \"./hook-check.js\";\nimport {\n queryRollups,\n readRollupCostSummary,\n type AuthChannelCostGroup,\n type CostSummaryWindow,\n type DeprecatedModelInUse,\n type ModelAuthCostRow,\n type RollupWindowCostSummary,\n} from \"../storage/rollups.js\";\nimport type {\n AuthMode,\n ChannelsSnapshot,\n ModelEntry,\n ModelsSnapshot,\n} from \"../types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type CheckSeverity = \"ok\" | \"warn\" | \"error\" | \"info\";\n\nexport interface DoctorCheckItem {\n id: string;\n category:\n | \"runtime\"\n | \"mcp_config\"\n | \"auth_env\"\n | \"network_ssl\"\n | \"context_hygiene\"\n | \"cost_usage\"\n | \"safety_guardrail\";\n severity: CheckSeverity;\n title: string;\n detail: string;\n fix_hint?: string;\n}\n\nexport interface DoctorReport {\n generated_at: string;\n node_version: string;\n checks: DoctorCheckItem[];\n summary: {\n ok: number;\n warn: number;\n error: number;\n info: number;\n };\n git_safety_guardrail_snippet: string;\n geminiignore_template: string;\n}\n\nexport interface DoctorOptions {\n cwd?: string;\n homeDir?: string;\n env?: NodeJS.ProcessEnv;\n mcpConfigPaths?: string[];\n settingsJsonPaths?: string[];\n skipBinaryChecks?: boolean;\n rollupsDir?: string;\n snapshotsDir?: string;\n brainDir?: string | null;\n authMode?: AuthMode;\n channels?: ChannelsSnapshot | ChannelRegistry;\n nowMs?: number;\n lang?: string;\n}\n\nexport interface DoctorCostOptions {\n window?: CostSummaryWindow;\n cwd?: string;\n homeDir?: string;\n env?: NodeJS.ProcessEnv;\n rollupsDir?: string;\n usageLogPath?: string;\n geminiOtelPath?: string;\n brainDir?: string | null;\n historyPath?: string | null;\n cliLogDir?: string | null;\n saltPath?: string;\n snapshotsDir?: string;\n nowMs?: number;\n}\n\nexport interface DoctorCostReport {\n generated_at: string;\n window: CostSummaryWindow;\n data_source: \"rollups\" | \"memory_fallback\";\n auth_groups: AuthChannelCostGroup[];\n by_model_auth: ModelAuthCostRow[];\n deprecated_models_in_use: DeprecatedModelInUse[];\n rate_limit_429_count: number;\n total_requests: number;\n total_tokens: number;\n notes: string[];\n}\n\nconst SENSITIVE_KEY_RE = /(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH)/i;\n\nexport const GIT_SAFETY_GUARDRAIL_SNIPPET = `# Git Safety Guardrail (add to AGENTS.md or GEMINI.md)\n- NEVER run destructive git commands (\\`git push --force\\`, \\`git reset --hard\\`, \\`git clean -fd\\`, \\`git checkout -- .\\`) without explicit user confirmation.\n- NEVER delete files outside the current workspace or run \\`rm -rf\\` on broad paths.\n- Always run \\`git status\\` and \\`git diff --stat\\` before committing or staging changes.`;\n\nexport const GEMINIIGNORE_TEMPLATE = `# Recommended .geminiignore to prevent context bloat & 504 timeouts\n# JS/TS & Web\nnode_modules/\ndist/\nbuild/\n.next/\n.astro/\ncoverage/\n*.lock\npackage-lock.json\npnpm-lock.yaml\nyarn.lock\n*.min.js\n*.map\n\n# Python & Data Engineering\n.venv/\nvenv/\n__pycache__/\n.pytest_cache/\n.mypy_cache/\n.ruff_cache/\ndata/\nlogs/\ntmp/\n*.parquet\n*.sqlite\n*.db\n*.log\n\n# VCS\n.git/\n`;\n\nasync function loadOfflineModelsSnapshot(\n snapshotsDir?: string,\n): Promise<{ models: ModelEntry[]; normalization_rules?: ModelsSnapshot[\"normalization_rules\"] }> {\n const dir = snapshotsDir ?? getSnapshotsDir();\n try {\n const raw = await readFile(join(dir, \"models.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as ModelsSnapshot;\n return {\n models: Array.isArray(parsed.models) ? parsed.models : [],\n normalization_rules: parsed.normalization_rules,\n };\n } catch {\n return { models: [] };\n }\n}\n\nfunction formatChannelSummaryText(winSummary: RollupWindowCostSummary): string {\n if (winSummary.by_auth_channel.length === 0) {\n return \"no usage recorded\";\n }\n return winSummary.by_auth_channel\n .map((g) => {\n const usd = `$${g.estimated_total_usd.toFixed(2)}`;\n if (g.auth_mode === \"google_oauth\") {\n return `Shadow Cost (Shared Quota Pressure): ~${usd} equiv`;\n }\n if (g.auth_mode === \"gcp_adc\" || g.auth_mode === \"api_key\") {\n return `Estimated GCP / API Spend: ~${usd} est.`;\n }\n return `Unattributed Est.: ~${usd}`;\n })\n .join(\" | \");\n}\n\nasync function fileExists(filePath: string): Promise<boolean> {\n try {\n await access(filePath, fsConstants.R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function detectBinaryVersion(\n cmd: string,\n args: string[] = [\"--version\"],\n): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync(cmd, args, { timeout: 2500 });\n const firstLine = stdout.trim().split(\"\\n\")[0]?.trim() ?? \"\";\n return firstLine.slice(0, 64) || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Inspects JSON config structure ONLY. Never reads or echoes secret/token/key values.\n */\nasync function inspectJsonConfig(\n filePath: string,\n kind: \"mcp_config\" | \"settings\",\n): Promise<DoctorCheckItem[]> {\n const checks: DoctorCheckItem[] = [];\n if (!(await fileExists(filePath))) {\n return checks;\n }\n\n let parsed: unknown;\n try {\n const raw = await readFile(filePath, \"utf8\");\n parsed = JSON.parse(raw);\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Invalid JSON syntax\";\n checks.push({\n id: `${kind}_syntax_error`,\n category: \"mcp_config\",\n severity: \"error\",\n title: `Invalid JSON syntax in ${kind === \"mcp_config\" ? \"mcp_config.json\" : \"settings.json\"}`,\n detail: `Parse error: ${msg.slice(0, 120)}`,\n fix_hint: \"Validate trailing commas, quotes, and braces with `jq . <file>`.\",\n });\n return checks;\n }\n\n checks.push({\n id: `${kind}_syntax_ok`,\n category: \"mcp_config\",\n severity: \"ok\",\n title: `${kind === \"mcp_config\" ? \"mcp_config.json\" : \"settings.json\"} JSON syntax valid`,\n detail: \"Parsed cleanly.\",\n });\n\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return checks;\n }\n\n const root = parsed as Record<string, unknown>;\n const serversObj = root[\"mcpServers\"];\n if (serversObj && typeof serversObj === \"object\" && !Array.isArray(serversObj)) {\n const serverEntries = Object.entries(serversObj as Record<string, unknown>);\n const serverCount = serverEntries.length;\n\n if (serverCount > 8) {\n checks.push({\n id: \"mcp_server_bloat\",\n category: \"context_hygiene\",\n severity: \"warn\",\n title: `High mounted MCP server count (${serverCount})`,\n detail: `${serverCount} MCP servers inject many tool schemas into every turn, accelerating 5h/7d quota burn.`,\n fix_hint: \"Disable unused MCP servers or split specialized workflows into on-demand SKILL.md files.\",\n });\n } else {\n checks.push({\n id: \"mcp_server_count_ok\",\n category: \"context_hygiene\",\n severity: \"ok\",\n title: `Mounted MCP server count healthy (${serverCount})`,\n detail: `${serverCount} configured MCP server(s).`,\n });\n }\n\n for (const [serverName, cfg] of serverEntries) {\n if (!cfg || typeof cfg !== \"object\" || Array.isArray(cfg)) {\n continue;\n }\n const serverCfg = cfg as Record<string, unknown>;\n const safeName = serverName.replace(/[^a-zA-Z0-9._-]/g, \"_\").slice(0, 32);\n\n // Check url vs httpUrl mismatch\n const hasUrl = typeof serverCfg[\"url\"] === \"string\";\n const hasHttpUrl = typeof serverCfg[\"httpUrl\"] === \"string\";\n if (hasUrl && hasHttpUrl) {\n checks.push({\n id: `mcp_transport_conflict_${safeName}`,\n category: \"mcp_config\",\n severity: \"error\",\n title: `MCP server \"${safeName}\" sets both \"url\" and \"httpUrl\"`,\n detail: \"Use 'url' for SSE transport OR 'httpUrl' for Streamable HTTP, never both.\",\n fix_hint: `Remove one of 'url' or 'httpUrl' in mcpServers.${safeName} and verify with \\`gemini mcp list\\`.`,\n });\n } else if (hasUrl) {\n const urlStr = String(serverCfg[\"url\"]);\n if (urlStr.includes(\"/mcp\") && !urlStr.includes(\"/sse\")) {\n checks.push({\n id: `mcp_url_mismatch_${safeName}`,\n category: \"mcp_config\",\n severity: \"warn\",\n title: `Possible url vs httpUrl mismatch on \"${safeName}\"`,\n detail: \"Endpoint looks like Streamable HTTP (/mcp) but uses legacy SSE key 'url'.\",\n fix_hint: `Rename key \"url\" -> \"httpUrl\" in mcpServers.${safeName} if the server uses Streamable HTTP.`,\n });\n }\n } else if (hasHttpUrl) {\n const httpUrlStr = String(serverCfg[\"httpUrl\"]);\n if (httpUrlStr.includes(\"/sse\")) {\n checks.push({\n id: `mcp_httpurl_mismatch_${safeName}`,\n category: \"mcp_config\",\n severity: \"warn\",\n title: `Possible httpUrl vs url mismatch on \"${safeName}\"`,\n detail: \"Endpoint looks like SSE (/sse) but uses Streamable HTTP key 'httpUrl'.\",\n fix_hint: `Rename key \"httpUrl\" -> \"url\" in mcpServers.${safeName} if the server uses SSE.`,\n });\n }\n }\n\n // Check env keys for *TOKEN*/*KEY*/*SECRET* stripping risk (NAMES ONLY, NEVER VALUES)\n const envBlock = serverCfg[\"env\"];\n if (envBlock && typeof envBlock === \"object\" && !Array.isArray(envBlock)) {\n const sensitiveKeyCount = Object.keys(envBlock as Record<string, unknown>).filter(\n (k) => SENSITIVE_KEY_RE.test(k),\n ).length;\n if (sensitiveKeyCount > 0) {\n checks.push({\n id: `mcp_env_explicit_${safeName}`,\n category: \"mcp_config\",\n severity: \"info\",\n title: `MCP server \"${safeName}\" defines ${sensitiveKeyCount} explicit credential env key(s)`,\n detail: \"Explicit env keys are present (values not inspected or logged).\",\n });\n }\n }\n }\n }\n\n return checks;\n}\n\n/**\n * Runs offline preflight & hygiene checks.\n * PRIVACY RED LINE: Only inspects boolean existence, structural syntax, and byte counts.\n * NEVER reads, retains, or prints secret/token/key values or credential files.\n */\nexport async function runDoctor(options?: DoctorOptions): Promise<DoctorReport> {\n const cwd = options?.cwd ?? process.cwd();\n const home = options?.homeDir ?? homedir();\n const env = options?.env ?? process.env;\n const locale = resolveLocale(options?.lang, env);\n const registry =\n options?.channels instanceof ChannelRegistry\n ? options.channels\n : options?.channels\n ? ChannelRegistry.fromSnapshot(options.channels)\n : loadBundledChannelRegistry(options?.snapshotsDir);\n const authContext = await detectAuthContext({\n homeDir: home,\n env,\n registry,\n nowMs: options?.nowMs,\n });\n const targetChannelId =\n options?.authMode && options.authMode !== \"unknown\"\n ? registry.resolveChannelId(options.authMode)\n : (authContext.active_channel_id ?? registry.resolveChannelId(authContext.active_auth_mode));\n const activeChannel =\n targetChannelId && targetChannelId !== \"unknown\"\n ? registry.getChannel(targetChannelId)\n : undefined;\n const checks: DoctorCheckItem[] = [];\n\n // 1. Node.js version check (Node 20+ supported, Node 22+ LTS recommended)\n const nodeVersion = process.version;\n const major = Number(nodeVersion.replace(/^v/, \"\").split(\".\")[0] ?? \"0\");\n checks.push({\n id: \"node_version\",\n category: \"runtime\",\n severity: major >= 20 ? \"ok\" : \"warn\",\n title: `Node.js ${nodeVersion}`,\n detail:\n major >= 22\n ? \"Node 22+ runtime detected.\"\n : major >= 20\n ? \"Node 20+ runtime supported (Node 22+ LTS recommended for latest Gemini CLI).\"\n : \"Node.js >= 20.0.0 is required for agycraft-mcp (Node 22+ LTS recommended).\",\n fix_hint: major >= 20 ? undefined : \"Upgrade Node.js to v20 LTS or v22 LTS.\",\n });\n\n // 2. AGY & Gemini CLI binary presence\n if (!options?.skipBinaryChecks) {\n const [geminiVer, agyVer] = await Promise.all([\n detectBinaryVersion(\"gemini\", [\"--version\"]),\n detectBinaryVersion(\"agy\", [\"--version\"]),\n ]);\n checks.push({\n id: \"gemini_cli_version\",\n category: \"runtime\",\n severity: geminiVer ? \"ok\" : \"info\",\n title: geminiVer ? `Gemini CLI detected (${geminiVer})` : \"Gemini CLI not found on PATH\",\n detail: geminiVer\n ? \"Gemini CLI binary is reachable.\"\n : \"Optional (Enterprise / paid API key workflows only; personal tier sunset Jun 2026 — use Antigravity CLI `agy` for personal workflows): install with `npm i -g @google/gemini-cli`.\",\n });\n checks.push({\n id: \"agy_cli_version\",\n category: \"runtime\",\n severity: agyVer ? \"ok\" : \"info\",\n title: agyVer ? `Antigravity CLI detected (${agyVer})` : \"Antigravity CLI (`agy`) not found on PATH\",\n detail: agyVer\n ? \"Antigravity CLI binary is reachable.\"\n : \"If using Antigravity IDE only, CLI binary on PATH is optional.\",\n });\n }\n\n // 3. mcp_config.json & settings.json syntax / transport checks\n const mcpPaths = options?.mcpConfigPaths ?? [\n join(home, \".gemini\", \"antigravity\", \"mcp_config.json\"),\n join(cwd, \"mcp_config.json\"),\n ];\n const settingsPaths = options?.settingsJsonPaths ?? [\n join(home, \".gemini\", \"settings.json\"),\n join(cwd, \".gemini\", \"settings.json\"),\n ];\n\n let foundAnyConfig = false;\n for (const p of mcpPaths) {\n const res = await inspectJsonConfig(p, \"mcp_config\");\n if (res.length > 0) {\n foundAnyConfig = true;\n checks.push(...res);\n }\n }\n for (const p of settingsPaths) {\n const res = await inspectJsonConfig(p, \"settings\");\n if (res.length > 0) {\n foundAnyConfig = true;\n checks.push(...res);\n }\n }\n if (!foundAnyConfig) {\n checks.push({\n id: \"no_mcp_config_found\",\n category: \"mcp_config\",\n severity: \"info\",\n title: \"No local mcp_config.json or settings.json found in default locations\",\n detail: \"Run `npx agycraft-mcp setup` to view copyable MCP & OTel setup snippets.\",\n });\n }\n\n // 4. Environment variable hygiene (BOOLEAN EXISTENCE ONLY — NEVER READ/PRINT VALUES)\n const hasGeminiApiKey = Boolean(env[\"GEMINI_API_KEY\"] || env[\"GOOGLE_API_KEY\"]);\n const hasGcpProject = Boolean(env[\"GOOGLE_CLOUD_PROJECT\"]);\n if (hasGeminiApiKey && hasGcpProject) {\n checks.push({\n id: \"auth_env_dual_set\",\n category: \"auth_env\",\n severity: \"warn\",\n title: \"Both API Key env and GOOGLE_CLOUD_PROJECT are set\",\n detail:\n \"Mixing API Key auth with Vertex/OAuth project env can trigger 403 Permission Denied or ACCESS_TOKEN_TYPE_UNSUPPORTED.\",\n fix_hint:\n \"Unset the unused auth method in your shell profile (`unset GEMINI_API_KEY` or `unset GOOGLE_CLOUD_PROJECT`).\",\n });\n } else {\n checks.push({\n id: \"auth_env_boolean_ok\",\n category: \"auth_env\",\n severity: \"ok\",\n title: \"Auth environment variables checked (boolean presence only)\",\n detail: `GEMINI_API_KEY/GOOGLE_API_KEY set: ${hasGeminiApiKey}, GOOGLE_CLOUD_PROJECT set: ${hasGcpProject}.`,\n });\n }\n\n // 4b. Multi-channel auth isolation check (driven by ChannelRegistry)\n const detectedChannelIds = authContext.detected_channels ?? authContext.detected_modes;\n if (authContext.has_mixed_auth) {\n const channelHints = detectedChannelIds\n .map((id) => {\n const ch = registry.getChannel(id);\n const conflicts = authContext.env_conflicts?.[id] ?? [];\n const iso = ch?.definition.recommended_behaviors.isolation_commands.join(\" && \");\n return ch\n ? `${id}${conflicts.length > 0 ? ` (conflicts: ${conflicts.join(\", \")})` : \"\"}${iso ? ` -> ${iso}` : \"\"}`\n : id;\n })\n .join(\" | \");\n const verifyHint = activeChannel?.definition.recommended_behaviors.verify_command;\n checks.push({\n id: \"auth_mixed_isolation\",\n category: \"auth_env\",\n severity: \"warn\",\n title: `Mixed auth channels detected (${detectedChannelIds.join(\", \")})`,\n detail: authContext.isolation_note,\n fix_hint: `Isolate active channel: ${channelHints}${verifyHint ? ` | Verify: ${verifyHint}` : \"\"}`,\n });\n } else if (activeChannel) {\n checks.push({\n id: \"auth_mixed_isolation\",\n category: \"auth_env\",\n severity: \"ok\",\n title: `Auth channel isolated (${activeChannel.channelId})`,\n detail: `${activeChannel.definition.display_name} (${activeChannel.definition.billing_model}, window: ${activeChannel.definition.quota_reset_policy.window_type}).`,\n fix_hint: activeChannel.definition.recommended_behaviors.verify_command,\n });\n } else {\n checks.push({\n id: \"auth_mixed_isolation\",\n category: \"auth_env\",\n severity: \"info\",\n title: \"No active local auth channel detected\",\n detail: authContext.isolation_note,\n });\n }\n\n // Check for *TOKEN*/*KEY*/*SECRET* env stripping warning in CLI subprocesses\n const sensitiveEnvCount = Object.keys(env).filter((k) =>\n SENSITIVE_KEY_RE.test(k),\n ).length;\n if (sensitiveEnvCount > 0) {\n checks.push({\n id: \"env_stripping_warning\",\n category: \"auth_env\",\n severity: \"info\",\n title: `Detected ${sensitiveEnvCount} shell env var(s) matching *TOKEN*/*KEY*/*SECRET*`,\n detail:\n \"Gemini CLI & AGY sanitize/strip *TOKEN*/*KEY*/*SECRET* env vars from child MCP servers by default (values not inspected).\",\n fix_hint:\n \"If an MCP server requires a specific variable, pass it explicitly in that server's `env` block in mcp_config.json / settings.json.\",\n });\n }\n\n // 5. Proxy & NODE_EXTRA_CA_CERTS presence (BOOLEAN & READABILITY ONLY)\n const hasProxy = Boolean(\n env[\"HTTP_PROXY\"] ||\n env[\"HTTPS_PROXY\"] ||\n env[\"http_proxy\"] ||\n env[\"https_proxy\"],\n );\n const caCertPath = env[\"NODE_EXTRA_CA_CERTS\"];\n const hasCaCert = Boolean(caCertPath);\n\n if (hasProxy && !hasCaCert) {\n checks.push({\n id: \"proxy_without_ca_certs\",\n category: \"network_ssl\",\n severity: \"warn\",\n title: \"HTTP(S)_PROXY is set without NODE_EXTRA_CA_CERTS\",\n detail:\n \"Corporate SSL-inspecting proxies often cause `UNABLE_TO_GET_ISSUER_CERT_LOCALLY` in Node.js.\",\n fix_hint:\n \"If behind a corporate TLS proxy, export `NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem`.\",\n });\n } else if (hasCaCert && caCertPath) {\n const readable = await fileExists(caCertPath);\n checks.push({\n id: \"node_extra_ca_certs_check\",\n category: \"network_ssl\",\n severity: readable ? \"ok\" : \"error\",\n title: readable\n ? \"NODE_EXTRA_CA_CERTS is set and readable\"\n : \"NODE_EXTRA_CA_CERTS points to an unreadable or missing file\",\n detail: readable\n ? \"Custom CA bundle is readable by Node.js.\"\n : \"Node.js will ignore or fail TLS verification when NODE_EXTRA_CA_CERTS is unreadable.\",\n fix_hint: readable\n ? undefined\n : \"Verify the CA certificate path and file permissions (`chmod 644`).\",\n });\n } else {\n checks.push({\n id: \"network_ssl_ok\",\n category: \"network_ssl\",\n severity: \"ok\",\n title: \"No proxy/SSL misconfiguration detected\",\n detail: \"Direct HTTPS connection environment.\",\n });\n }\n\n // 6. Context hygiene: .geminiignore check\n const hasGeminiIgnore = await fileExists(join(cwd, \".geminiignore\"));\n checks.push({\n id: \"geminiignore_check\",\n category: \"context_hygiene\",\n severity: hasGeminiIgnore ? \"ok\" : \"warn\",\n title: hasGeminiIgnore\n ? \".geminiignore found in workspace\"\n : \"Missing .geminiignore in current workspace\",\n detail: hasGeminiIgnore\n ? \"Workspace ignore rules help prevent lockfile/build-artifact context bloat.\"\n : \"Without .geminiignore, lockfiles and build outputs can bloat context and trigger 504 timeouts or quota burn.\",\n fix_hint: hasGeminiIgnore\n ? undefined\n : \"Create a `.geminiignore` file using the recommended template below.\",\n });\n\n // 7. Global rules token bloat estimate (byte size -> ~chars/4, never reads/prints contents)\n const ruleCandidates = [\n { label: \"~/.gemini/GEMINI.md\", path: join(home, \".gemini\", \"GEMINI.md\") },\n { label: \"./GEMINI.md\", path: join(cwd, \"GEMINI.md\") },\n { label: \"./AGENTS.md\", path: join(cwd, \"AGENTS.md\") },\n ];\n let totalRuleBytes = 0;\n let foundRuleFiles = 0;\n for (const candidate of ruleCandidates) {\n try {\n const s = await stat(candidate.path);\n if (s.isFile()) {\n totalRuleBytes += s.size;\n foundRuleFiles += 1;\n }\n } catch {\n // ignore missing\n }\n }\n const estimatedRuleTokens = Math.ceil(totalRuleBytes / 4);\n if (estimatedRuleTokens > 3000) {\n const channelHint = activeChannel\n ? ` Active channel (${activeChannel.channelId}): ${getLocalizedBehavior(activeChannel.definition.recommended_behaviors, \"kv_cache_guidance\", locale) ?? activeChannel.definition.recommended_behaviors.kv_cache_guidance}`\n : \"\";\n checks.push({\n id: \"global_rules_bloat\",\n category: \"context_hygiene\",\n severity: \"warn\",\n title: `Global rules token bloat (~${estimatedRuleTokens} tokens across ${foundRuleFiles} file(s))`,\n detail:\n activeChannel?.definition.quota_reset_policy.window_type === \"rolling_5h_7d\"\n ? \"Large always-loaded rule files are re-sent on every single turn and inflate 5h/7d token consumption.\"\n : \"Large always-loaded rule files are re-sent on every single turn and increase per-turn input token spend.\",\n fix_hint: `Keep global rules under ~2,000 tokens and move domain-specific instructions into on-demand SKILL.md files.${channelHint}`,\n });\n } else {\n checks.push({\n id: \"global_rules_ok\",\n category: \"context_hygiene\",\n severity: \"ok\",\n title: `Global rules size healthy (~${estimatedRuleTokens} tokens across ${foundRuleFiles} file(s))`,\n detail: \"Baseline instruction overhead is lean.\",\n });\n }\n\n // 8. Offline, zero-write, lock-free rollup cost_summary & deprecated model alerts\n const modelsSnapshot = await loadOfflineModelsSnapshot(options?.snapshotsDir);\n const costSummary = await readRollupCostSummary({\n rollupsDir: options?.rollupsDir,\n models: modelsSnapshot.models,\n normalizationRules: modelsSnapshot.normalization_rules,\n nowMs: options?.nowMs,\n });\n\n if (!costSummary.has_cache) {\n checks.push({\n id: \"cost_summary\",\n category: \"cost_usage\",\n severity: \"info\",\n title: \"Cost summary: no local rollups cache yet\",\n detail:\n \"No cached rollups/hourly/*.json found (zero-scan fast path). Run 'agycraft-mcp doctor --cost' or call MCP usage tools to warm local stats.\",\n });\n } else {\n const w5h = costSummary.windows[\"5h\"];\n const w24h = costSummary.windows[\"24h\"];\n const has429 = w5h.rate_limit_429_count > 0;\n checks.push({\n id: \"cost_summary\",\n category: \"cost_usage\",\n severity: has429 ? \"warn\" : \"ok\",\n title: has429\n ? `Cost summary (5h: ${w5h.total_requests} reqs, ${w5h.rate_limit_429_count} x 429; 24h: ${w24h.total_requests} reqs)`\n : `Cost summary (5h: ${w5h.total_requests} reqs | 24h: ${w24h.total_requests} reqs)`,\n detail: `5h -> ${formatChannelSummaryText(w5h)} || 24h -> ${formatChannelSummaryText(w24h)}`,\n ...(has429\n ? {\n fix_hint: activeChannel\n ? `429 rate limits detected in last 5h (${activeChannel.channelId}): ${getLocalizedBehavior(activeChannel.definition.recommended_behaviors, \"throttling_guidance\", locale) ?? activeChannel.definition.recommended_behaviors.throttling_guidance}`\n : \"429 rate limits detected in last 5h. Run `npx agycraft-mcp preflight` to inspect live upstream status.json.\",\n }\n : {}),\n });\n\n if (w24h.deprecated_models_in_use.length > 0) {\n const depList = w24h.deprecated_models_in_use\n .map(\n (d) =>\n `${d.model} (${d.lifecycle}${d.deprecated_date ? `, deprecated ${d.deprecated_date}` : \"\"})`,\n )\n .join(\"; \");\n const hints = w24h.deprecated_models_in_use\n .map((d) =>\n d.replacement_model_id\n ? `${d.model} -> ${d.replacement_model_id}`\n : `${d.model} -> migrate to active model`,\n )\n .join(\"; \");\n checks.push({\n id: \"deprecated_model_in_use\",\n category: \"cost_usage\",\n severity: \"warn\",\n title: `Deprecated/removed model(s) detected in last 24h (${w24h.deprecated_models_in_use.length})`,\n detail: `Used recently: ${depList}.`,\n fix_hint: `Migrate to recommended replacements: ${hints}.`,\n });\n }\n }\n\n // 8b. Latest session redundant tool-call & context-watermark check (offline, zero-plaintext)\n const effectiveBrainDir =\n options?.brainDir !== undefined\n ? options.brainDir\n : options?.homeDir\n ? join(options.homeDir, \".gemini\", \"antigravity-cli\", \"brain\")\n : undefined;\n const latestTranscript = await findLatestTranscriptPath(effectiveBrainDir);\n if (!latestTranscript) {\n checks.push({\n id: \"session_redundant_tool_calls\",\n category: \"context_hygiene\",\n severity: \"info\",\n title: \"Session tool-call hygiene: no local AGY transcript found\",\n detail:\n \"No active transcript.jsonl found to audit redundant file re-reads or polling duplicates.\",\n });\n checks.push({\n id: \"session_context_watermark\",\n category: \"cost_usage\",\n severity: \"info\",\n title: \"Session context watermark: no active transcript found\",\n detail:\n \"No active transcript.jsonl found to inspect per-request token watermarks (160K/240K/360K).\",\n });\n } else {\n const [transcriptMeta, tailMetrics] = await Promise.all([\n analyzeTranscriptStructure(latestTranscript),\n extractTranscriptTailLifecycleMetrics(latestTranscript, {\n nowMs: options?.nowMs,\n }),\n ]);\n\n const redundantReads = transcriptMeta.redundant_read_file_count ?? 0;\n const redundantReadPct = transcriptMeta.redundant_read_file_pct ?? 0;\n const pollingDups = transcriptMeta.polling_dup_count ?? 0;\n const pollingDupPct = transcriptMeta.polling_dup_rate_pct ?? 0;\n const hasRedundancyRisk =\n (redundantReadPct >= 20 && redundantReads >= 5) ||\n (pollingDupPct >= 15 && pollingDups >= 5);\n\n checks.push({\n id: \"session_redundant_tool_calls\",\n category: \"context_hygiene\",\n severity: hasRedundancyRisk ? \"warn\" : \"ok\",\n title: hasRedundancyRisk\n ? `Redundant tool calls detected in latest session (${redundantReads} re-reads / ${pollingDups} exact dups)`\n : \"Latest session tool-call redundancy is healthy\",\n detail: `Redundant unedited read_file: ${redundantReads} (${redundantReadPct}%); exact-duplicate polling calls: ${pollingDups} (${pollingDupPct}% across ${transcriptMeta.tool_call_count} tool calls).`,\n ...(hasRedundancyRisk\n ? {\n fix_hint:\n \"Use `quick_outline` + targeted line ranges instead of re-reading unchanged files, and avoid polling `manage_task` / `call_mcp_tool` / `read_board` in loops.\",\n }\n : {}),\n });\n\n if (tailMetrics && tailMetrics.current_input_tokens > 0) {\n const { decision } = evaluateSessionLifecycle(tailMetrics, undefined, {\n nowMs: options?.nowMs,\n locale,\n });\n const highWatermark = decision.action !== \"HOLD_CACHE\";\n const kTokens = Math.round(tailMetrics.current_input_tokens / 1000);\n checks.push({\n id: \"session_context_watermark\",\n category: \"cost_usage\",\n severity: highWatermark ? \"warn\" : \"ok\",\n title: highWatermark\n ? `Latest session context watermark elevated (~${kTokens}K tokens -> ${decision.action})`\n : `Latest session context watermark healthy (~${kTokens}K tokens, ${tailMetrics.recent_cache_hit_pct}% KV hit)`,\n detail: `Current input: ${tailMetrics.current_input_tokens.toLocaleString()} tokens | Recent KV cache hit: ${tailMetrics.recent_cache_hit_pct}% | Lifecycle: ${decision.action} (${decision.reason_code}).`,\n ...(highWatermark && decision.message\n ? { fix_hint: decision.message }\n : {}),\n });\n } else {\n checks.push({\n id: \"session_context_watermark\",\n category: \"cost_usage\",\n severity: \"info\",\n title: \"Session context watermark: no token telemetry in latest transcript\",\n detail:\n \"Latest transcript.jsonl has no per-request input/cache token fields yet.\",\n });\n }\n }\n\n // 9. Safety guardrail check\n checks.push({\n id: \"git_safety_guardrail\",\n category: \"safety_guardrail\",\n severity: \"info\",\n title: \"Git safety guardrail template available\",\n detail:\n \"Add the non-destructive Git safety snippet below to GEMINI.md / AGENTS.md to prevent accidental force-pushes or hard resets.\",\n });\n\n const summary = {\n ok: checks.filter((c) => c.severity === \"ok\").length,\n warn: checks.filter((c) => c.severity === \"warn\").length,\n error: checks.filter((c) => c.severity === \"error\").length,\n info: checks.filter((c) => c.severity === \"info\").length,\n };\n\n return {\n generated_at: new Date().toISOString(),\n node_version: nodeVersion,\n checks,\n summary,\n git_safety_guardrail_snippet: GIT_SAFETY_GUARDRAIL_SNIPPET,\n geminiignore_template: GEMINIIGNORE_TEMPLATE,\n };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n const icon: Record<CheckSeverity, string> = {\n ok: \"[OK]\",\n warn: \"[WARN]\",\n error: \"[ERR]\",\n info: \"[INFO]\",\n };\n const lines: string[] = [\n \"agycraft-mcp doctor (100% local, zero secret values inspected)\",\n \"================================================================\",\n ];\n\n for (const check of report.checks) {\n lines.push(`${icon[check.severity]} ${check.title}`);\n lines.push(` ${check.detail}`);\n if (check.fix_hint) {\n lines.push(` Fix: ${check.fix_hint}`);\n }\n }\n\n lines.push(\"\");\n lines.push(\n `Summary: ${report.summary.ok} ok, ${report.summary.warn} warn, ${report.summary.error} error, ${report.summary.info} info`,\n );\n lines.push(\"\");\n lines.push(\"--- Recommended Git Safety Guardrail Snippet ---\");\n lines.push(report.git_safety_guardrail_snippet);\n\n const missingIgnore = report.checks.some(\n (c) => c.id === \"geminiignore_check\" && c.severity === \"warn\",\n );\n if (missingIgnore) {\n lines.push(\"\");\n lines.push(\"--- Recommended .geminiignore Template ---\");\n lines.push(report.geminiignore_template.trimEnd());\n }\n\n return lines.join(\"\\n\");\n}\n\nexport async function runDoctorCost(\n options?: DoctorCostOptions,\n): Promise<DoctorCostReport> {\n const window: CostSummaryWindow = options?.window ?? \"24h\";\n const nowMs = options?.nowMs ?? Date.now();\n const [modelsSnapshot, authContext] = await Promise.all([\n loadOfflineModelsSnapshot(options?.snapshotsDir),\n detectAuthContext({\n homeDir: options?.homeDir,\n env: options?.env,\n }),\n ]);\n\n const rollupRes = await queryRollups({\n rollupsDir: options?.rollupsDir,\n usageLogPath: options?.usageLogPath,\n geminiOtelPath: options?.geminiOtelPath,\n brainDir: options?.brainDir,\n historyPath: options?.historyPath,\n cliLogDir: options?.cliLogDir,\n saltPath: options?.saltPath,\n models: modelsSnapshot.models,\n normalizationRules: modelsSnapshot.normalization_rules,\n window,\n granularity: \"hourly\",\n product: \"all\",\n scope: \"global\",\n authMode: \"all\",\n readonly: true,\n coldBrainDays: 1,\n transcriptAuthMode: authContext.active_auth_mode,\n hasMixedAuth: authContext.has_mixed_auth,\n nowMs,\n });\n\n const breakdown: RollupWindowCostSummary = rollupRes.cost_breakdown ?? {\n window,\n by_model_auth: [],\n by_auth_channel: [],\n deprecated_models_in_use: [],\n rate_limit_429_count: 0,\n total_requests: 0,\n total_tokens: 0,\n };\n\n const notes: string[] = [\n \"Shadow Cost (google_oauth) measures shared subscription quota pressure only and is strictly separated from Estimated GCP / API Spend.\",\n \"100% local readonly calculation; zero session hashes, project hashes, or local paths exposed.\",\n ];\n if (breakdown.rate_limit_429_count > 0) {\n notes.push(\n `Detected ${breakdown.rate_limit_429_count} rate-limit (429) event(s). Run \\`npx agycraft-mcp preflight\\` to check live upstream status.json.`,\n );\n }\n if (breakdown.deprecated_models_in_use.length > 0) {\n const replacements = breakdown.deprecated_models_in_use\n .map((d) => `${d.model} -> ${d.replacement_model_id ?? \"active model\"}`)\n .join(\"; \");\n notes.push(`Deprecated/removed model(s) in window: ${replacements}.`);\n }\n\n return {\n generated_at: new Date(nowMs).toISOString(),\n window,\n data_source: rollupRes.time_series_meta.source,\n auth_groups: breakdown.by_auth_channel,\n by_model_auth: breakdown.by_model_auth,\n deprecated_models_in_use: breakdown.deprecated_models_in_use,\n rate_limit_429_count: breakdown.rate_limit_429_count,\n total_requests: breakdown.total_requests,\n total_tokens: breakdown.total_tokens,\n notes,\n };\n}\n\nexport function formatDoctorCostReport(report: DoctorCostReport): string {\n const lines: string[] = [\n `agycraft-mcp doctor --cost (window: ${report.window}, source: ${report.data_source}, readonly)`,\n \"================================================================\",\n ];\n\n if (report.auth_groups.length === 0) {\n lines.push(\"No token usage recorded in this window.\");\n } else {\n lines.push(\"Channel Cost Summary (strictly isolated by auth_mode):\");\n for (const g of report.auth_groups) {\n const suffix = g.auth_mode === \"google_oauth\" ? \"equiv\" : \"est.\";\n lines.push(\n ` - ${g.label} [${g.auth_mode}]: ~$${g.estimated_total_usd.toFixed(4)} ${suffix} (${g.requests} reqs, ${g.total_tokens.toLocaleString()} tokens, saved ~$${g.estimated_cache_savings_usd.toFixed(4)})`,\n );\n }\n\n lines.push(\"\");\n lines.push(\"Breakdown by Canonical Model x Auth Mode:\");\n for (const row of report.by_model_auth) {\n const estTag =\n row.estimated_requests > 0\n ? ` [est_from_cli_log:${row.estimated_requests}]`\n : \"\";\n const depTag =\n row.lifecycle === \"deprecated\" || row.lifecycle === \"removed\"\n ? ` [${row.lifecycle.toUpperCase()} -> ${row.replacement_model_id ?? \"migrate\"}]`\n : \"\";\n lines.push(\n ` * ${row.model} (${row.auth_mode})${depTag}${estTag}: ${row.requests} reqs | ${row.total_tokens.toLocaleString()} tok | cache ${row.cache_hit_rate_pct}% | ~$${row.estimated_total_usd.toFixed(4)} (saved ~$${row.estimated_cache_savings_usd.toFixed(4)})`,\n );\n }\n }\n\n lines.push(\"\");\n for (const note of report.notes) {\n lines.push(`Note: ${note}`);\n }\n return lines.join(\"\\n\");\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AuthContext, AuthMode, ChannelsSnapshot } from \"../types.js\";\nimport {\n ChannelRegistry,\n loadBundledChannelRegistry,\n type CompiledAuthChannel,\n} from \"./channel-registry.js\";\nimport { collectCliLogSignals, type CliLogAuthEvent } from \"./cli-log.js\";\n\nexport interface DetectAuthContextOptions {\n homeDir?: string;\n env?: NodeJS.ProcessEnv;\n geminiSettingsPath?: string;\n agySettingsPath?: string;\n oauthCredsPath?: string;\n adcPath?: string;\n cliLogDir?: string | null;\n cliLogEvents?: CliLogAuthEvent[];\n nowMs?: number;\n registry?: ChannelRegistry;\n channelsSnapshot?: ChannelsSnapshot;\n}\n\nasync function readSafeJsonObject(filePath: string): Promise<Record<string, unknown> | null> {\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // Missing or malformed settings file\n }\n return null;\n}\n\nfunction expandHomePath(pattern: string, home: string): string {\n if (pattern.startsWith(\"~/\")) {\n return join(home, pattern.slice(2));\n }\n return pattern;\n}\n\nfunction resolveLocalConfigPath(\n pattern: string,\n home: string,\n oauthOverride?: string,\n adcOverride?: string,\n): string {\n if (oauthOverride && pattern.endsWith(\"oauth_creds.json\")) {\n return oauthOverride;\n }\n if (adcOverride && pattern.endsWith(\"application_default_credentials.json\")) {\n return adcOverride;\n }\n return expandHomePath(pattern, home);\n}\n\nfunction hasNonEmptySettingsKey(\n settings: Record<string, unknown> | null,\n key: string,\n): boolean {\n if (!settings) {\n return false;\n }\n const val = settings[key];\n return Boolean(\n val &&\n (typeof val !== \"object\" ||\n (!Array.isArray(val) && Object.keys(val as Record<string, unknown>).length > 0)),\n );\n}\n\n/**\n * Readonly detector for local Auth Channels (OAuth / Vertex ADC / AI Studio Key / Express / Custom).\n * PRIVACY RED LINE:\n * - Credential files (oauth_creds.json, application_default_credentials.json, etc.) are ONLY checked via existsSync.\n * - NEVER reads, parses, or logs credential file contents or env var values.\n * - 100% data-driven by ChannelRegistry (zero hardcoded auth channel if/else branches).\n */\nexport async function detectAuthContext(\n options?: DetectAuthContextOptions,\n): Promise<AuthContext> {\n const home = options?.homeDir ?? homedir();\n const env = options?.env ?? process.env;\n const nowMs = options?.nowMs ?? Date.now();\n const registry =\n options?.registry ??\n (options?.channelsSnapshot\n ? ChannelRegistry.fromSnapshot(options.channelsSnapshot)\n : loadBundledChannelRegistry());\n\n const geminiSettingsPath =\n options?.geminiSettingsPath ?? join(home, \".gemini\", \"settings.json\");\n const agySettingsPath =\n options?.agySettingsPath ??\n join(home, \".gemini\", \"antigravity-cli\", \"settings.json\");\n const oauthCredsPath =\n options?.oauthCredsPath ?? join(home, \".gemini\", \"oauth_creds.json\");\n const adcPath =\n options?.adcPath ??\n join(home, \".config\", \"gcloud\", \"application_default_credentials.json\");\n const hasDefaultOauthCredsFile = existsSync(oauthCredsPath);\n const hasDefaultAdcFile = existsSync(adcPath);\n\n const [geminiSettings, agySettings] = await Promise.all([\n readSafeJsonObject(geminiSettingsPath),\n readSafeJsonObject(agySettingsPath),\n ]);\n\n let selectedChannel: CompiledAuthChannel | undefined;\n if (geminiSettings) {\n const security = geminiSettings[\"security\"];\n if (security && typeof security === \"object\" && !Array.isArray(security)) {\n const auth = (security as Record<string, unknown>)[\"auth\"];\n if (auth && typeof auth === \"object\" && !Array.isArray(auth)) {\n selectedChannel = registry.matchSettingsAuthType(\n (auth as Record<string, unknown>)[\"selectedType\"],\n );\n }\n }\n }\n\n // Optional Stage 1: runtime cli-*.log events (last 12h) when cliLogDir or cliLogEvents provided\n let runtimeChannel: CompiledAuthChannel | undefined;\n const runtimeEvents =\n options?.cliLogEvents ??\n (options?.cliLogDir\n ? (\n await collectCliLogSignals({\n cliLogDir: options.cliLogDir,\n nowMs,\n registry,\n })\n ).authEvents\n : []);\n if (runtimeEvents.length > 0) {\n const maxStaleMs = 12 * 3600_000;\n for (let i = runtimeEvents.length - 1; i >= 0; i -= 1) {\n const ev = runtimeEvents[i]!;\n if (ev.tsMs <= nowMs && nowMs - ev.tsMs <= maxStaleMs) {\n const ch = registry.getChannel(ev.authMode);\n if (ch) {\n runtimeChannel = ch;\n break;\n }\n }\n }\n }\n\n const channelsInOrder = registry.getChannels();\n const channelsByPriority = registry.getChannelsByPriorityDesc();\n\n const envHitSet = new Set<string>();\n const fileHitSet = new Set<string>();\n const agyConfigHitSet = new Set<string>();\n const detectedChannelIds: string[] = [];\n const envConflicts: Record<string, string[]> = {};\n\n for (const ch of channelsInOrder) {\n const hasEnv = registry.checkEnvPresence(ch, env);\n const hasFile = ch.localConfigFiles.some((p) => {\n const targetPath = resolveLocalConfigPath(p, home, oauthCredsPath, adcPath);\n if (targetPath === oauthCredsPath) {\n return hasDefaultOauthCredsFile;\n }\n if (targetPath === adcPath) {\n return hasDefaultAdcFile;\n }\n return existsSync(targetPath);\n });\n const hasAgyKey = ch.agySettingsKeys.some((k) =>\n hasNonEmptySettingsKey(agySettings, k),\n );\n const hasSelected = selectedChannel?.channelId === ch.channelId;\n const hasRuntime = runtimeChannel?.channelId === ch.channelId;\n\n if (hasEnv) {\n envHitSet.add(ch.channelId);\n }\n if (hasFile) {\n fileHitSet.add(ch.channelId);\n }\n if (hasAgyKey) {\n agyConfigHitSet.add(ch.channelId);\n }\n\n if (hasEnv || hasFile || hasAgyKey || hasSelected || hasRuntime) {\n detectedChannelIds.push(ch.channelId);\n const conflicts = registry.getMatchedEnvConflicts(ch, env);\n if (conflicts.length > 0) {\n envConflicts[ch.channelId] = conflicts;\n }\n }\n }\n\n // Precedence: L1 runtime cli-*.log > L2 env (priority desc) > AGY settings key > Gemini selectedType > L3 local credential files\n let activeChannelId: string = \"unknown\";\n if (runtimeChannel) {\n activeChannelId = runtimeChannel.channelId;\n } else {\n const envWinner = channelsByPriority.find((ch) => envHitSet.has(ch.channelId));\n if (envWinner) {\n activeChannelId = envWinner.channelId;\n } else {\n const agyWinner = channelsByPriority.find((ch) => agyConfigHitSet.has(ch.channelId));\n if (agyWinner) {\n activeChannelId = agyWinner.channelId;\n } else if (selectedChannel) {\n activeChannelId = selectedChannel.channelId;\n } else {\n const fileWinner = channelsInOrder.find((ch) => fileHitSet.has(ch.channelId));\n if (fileWinner) {\n activeChannelId = fileWinner.channelId;\n }\n }\n }\n }\n\n const activeAuthMode: AuthMode =\n activeChannelId === \"unknown\" ? \"unknown\" : registry.toLegacyAuthMode(activeChannelId);\n const detectedModes: AuthMode[] = detectedChannelIds.map((id) =>\n registry.toLegacyAuthMode(id),\n );\n\n const hasMixedAuth = detectedChannelIds.length > 1;\n const isolationNote = hasMixedAuth\n ? `Mixed auth contexts detected (${detectedModes.join(\", \")}). Active mode inferred as ${activeAuthMode}; auth channel quotas and credentials are isolated—verify active auth before attributing 429/401/403 errors.`\n : activeAuthMode !== \"unknown\"\n ? `Single auth context detected (${activeAuthMode}); no cross-auth mixing.`\n : \"No local auth credentials or env flags detected (active_auth_mode: unknown).\";\n\n return {\n active_auth_mode: activeAuthMode,\n detected_modes: detectedModes,\n has_mixed_auth: hasMixedAuth,\n isolation_note: isolationNote,\n active_channel_id: activeChannelId,\n detected_channels: detectedChannelIds,\n ...(Object.keys(envConflicts).length > 0 ? { env_conflicts: envConflicts } : {}),\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getSnapshotsDir } from \"../paths.js\";\nimport type { SnapshotClient } from \"../remote/snapshot-client.js\";\nimport type { AuthChannelDefinition, AuthMode, ChannelsSnapshot } from \"../types.js\";\n\nexport interface CompiledAuthChannel {\n definition: AuthChannelDefinition;\n channelId: string;\n legacyId?: string;\n aliases: string[];\n endpointRegexes: RegExp[];\n logAuthMethodValues: Set<string>;\n settingsAuthTypePatterns: string[];\n envPresenceKeys: string[];\n envTrueOnlyKeys: Set<string>;\n envConflictKeys: string[];\n localConfigFiles: string[];\n agySettingsKeys: string[];\n errorSignatureRegexes: RegExp[];\n}\n\nfunction compileRegexList(patterns: string[] | undefined): RegExp[] {\n if (!Array.isArray(patterns)) {\n return [];\n }\n const compiled: RegExp[] = [];\n for (const p of patterns) {\n if (typeof p !== \"string\" || p.trim().length === 0) {\n continue;\n }\n try {\n compiled.push(new RegExp(p, \"i\"));\n } catch {\n // Skip invalid regex from remote snapshot safely\n }\n }\n return compiled;\n}\n\nfunction isNonEmptyEnv(val: string | undefined): boolean {\n return typeof val === \"string\" && val.trim().length > 0;\n}\n\nfunction isTruthyEnv(val: string | undefined): boolean {\n if (typeof val !== \"string\") {\n return false;\n }\n const lower = val.trim().toLowerCase();\n return lower === \"1\" || lower === \"true\" || lower === \"yes\";\n}\n\nexport class ChannelRegistry {\n private readonly channels: CompiledAuthChannel[];\n private readonly byIdOrAlias = new Map<string, CompiledAuthChannel>();\n\n constructor(snapshot: ChannelsSnapshot) {\n const rawChannels = Array.isArray(snapshot.channels)\n ? snapshot.channels\n : Array.isArray(snapshot.auth_channels)\n ? snapshot.auth_channels\n : [];\n this.channels = rawChannels.map((def) => {\n const aliases = Array.isArray(def.aliases) ? def.aliases : [];\n const compiled: CompiledAuthChannel = {\n definition: def,\n channelId: def.channel_id,\n legacyId: def.legacy_id,\n aliases,\n endpointRegexes: compileRegexList(def.detection?.endpoint_regexes),\n logAuthMethodValues: new Set(\n (def.detection?.log_auth_method_values ?? []).map((v) => v.trim().toLowerCase()),\n ),\n settingsAuthTypePatterns: (def.detection?.settings_auth_type_patterns ?? []).map((v) =>\n v.trim().toLowerCase(),\n ),\n envPresenceKeys: def.detection?.env_presence_keys ?? [],\n envTrueOnlyKeys: new Set(def.detection?.env_true_only_keys ?? []),\n envConflictKeys: def.detection?.env_conflict_keys ?? [],\n localConfigFiles: def.detection?.local_config_files ?? [],\n agySettingsKeys: def.detection?.agy_settings_keys ?? [],\n errorSignatureRegexes: compileRegexList(def.error_signature_regexes),\n };\n\n this.byIdOrAlias.set(def.channel_id.toLowerCase(), compiled);\n if (def.legacy_id) {\n this.byIdOrAlias.set(def.legacy_id.toLowerCase(), compiled);\n }\n for (const alias of aliases) {\n this.byIdOrAlias.set(alias.toLowerCase(), compiled);\n }\n return compiled;\n });\n }\n\n static fromSnapshot(snapshot: ChannelsSnapshot): ChannelRegistry {\n return new ChannelRegistry(snapshot);\n }\n\n getChannels(): CompiledAuthChannel[] {\n return this.channels;\n }\n\n getChannelsByPriorityDesc(): CompiledAuthChannel[] {\n return [...this.channels].sort(\n (a, b) => (b.definition.priority ?? 0) - (a.definition.priority ?? 0),\n );\n }\n\n getChannel(idOrAlias: string | undefined | null): CompiledAuthChannel | undefined {\n if (!idOrAlias || typeof idOrAlias !== \"string\") {\n return undefined;\n }\n return this.byIdOrAlias.get(idOrAlias.trim().toLowerCase());\n }\n\n hasChannel(idOrAlias: string | undefined | null): boolean {\n return this.getChannel(idOrAlias) !== undefined;\n }\n\n resolveChannelId(idOrAlias: string): string {\n const found = this.getChannel(idOrAlias);\n return found ? found.channelId : idOrAlias;\n }\n\n toLegacyAuthMode(idOrAlias: string): AuthMode {\n const found = this.getChannel(idOrAlias);\n if (!found) {\n return idOrAlias;\n }\n return found.legacyId ?? found.channelId;\n }\n\n matchesChannel(modeA: string | undefined | null, modeB: string | undefined | null): boolean {\n if (!modeA || !modeB) {\n return false;\n }\n const normA = this.resolveChannelId(modeA.trim()).toLowerCase();\n const normB = this.resolveChannelId(modeB.trim()).toLowerCase();\n return normA === normB;\n }\n\n matchEndpoint(line: string): CompiledAuthChannel | undefined {\n for (const ch of this.getChannelsByPriorityDesc()) {\n for (const re of ch.endpointRegexes) {\n if (re.test(line)) {\n return ch;\n }\n }\n }\n return undefined;\n }\n\n matchLogAuthMethod(rawMethod: string): CompiledAuthChannel | undefined {\n const lower = rawMethod.trim().toLowerCase();\n if (!lower) {\n return undefined;\n }\n for (const ch of this.getChannelsByPriorityDesc()) {\n if (ch.logAuthMethodValues.has(lower)) {\n return ch;\n }\n }\n for (const ch of this.getChannelsByPriorityDesc()) {\n for (const val of ch.logAuthMethodValues) {\n if (val.length >= 3 && lower.includes(val)) {\n return ch;\n }\n }\n }\n return undefined;\n }\n\n matchSettingsAuthType(rawType: unknown): CompiledAuthChannel | undefined {\n if (typeof rawType !== \"string\") {\n return undefined;\n }\n const lower = rawType.trim().toLowerCase();\n if (!lower) {\n return undefined;\n }\n for (const ch of this.getChannelsByPriorityDesc()) {\n for (const pat of ch.settingsAuthTypePatterns) {\n if (pat && lower.includes(pat)) {\n return ch;\n }\n }\n }\n return undefined;\n }\n\n matchErrorText(errorText: string): CompiledAuthChannel | undefined {\n let best: CompiledAuthChannel | undefined;\n let bestHits = 0;\n let bestPriority = -Infinity;\n\n for (const ch of this.channels) {\n let hits = 0;\n for (const re of ch.errorSignatureRegexes) {\n if (re.test(errorText)) {\n hits += 1;\n }\n }\n if (hits > 0) {\n const prio = ch.definition.priority ?? 0;\n if (hits > bestHits || (hits === bestHits && prio > bestPriority)) {\n best = ch;\n bestHits = hits;\n bestPriority = prio;\n }\n }\n }\n return best;\n }\n\n checkEnvPresence(channel: CompiledAuthChannel, env: NodeJS.ProcessEnv): boolean {\n for (const key of channel.envPresenceKeys) {\n const val = env[key];\n if (channel.envTrueOnlyKeys.has(key)) {\n if (isTruthyEnv(val)) {\n return true;\n }\n } else if (isNonEmptyEnv(val)) {\n return true;\n }\n }\n return false;\n }\n\n getMatchedEnvConflicts(channel: CompiledAuthChannel, env: NodeJS.ProcessEnv): string[] {\n const hits: string[] = [];\n for (const key of channel.envConflictKeys) {\n if (isNonEmptyEnv(env[key])) {\n hits.push(key);\n }\n }\n return hits;\n }\n}\n\nlet cachedDefaultRegistry: ChannelRegistry | null = null;\n\nexport function loadBundledChannelRegistry(snapshotsDir?: string): ChannelRegistry {\n if (!snapshotsDir && cachedDefaultRegistry) {\n return cachedDefaultRegistry;\n }\n const dir = snapshotsDir ?? getSnapshotsDir();\n try {\n const raw = readFileSync(join(dir, \"channels.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as ChannelsSnapshot;\n const reg = new ChannelRegistry(parsed);\n if (!snapshotsDir) {\n cachedDefaultRegistry = reg;\n }\n return reg;\n } catch {\n return new ChannelRegistry({\n schema_version: \"1.0.0\",\n channels: [],\n });\n }\n}\n\nexport async function loadChannelRegistry(client?: SnapshotClient): Promise<ChannelRegistry> {\n if (!client) {\n return loadBundledChannelRegistry();\n }\n try {\n const snap = await client.get(\"channels\");\n return new ChannelRegistry(snap.data);\n } catch {\n return loadBundledChannelRegistry();\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nlet cachedPkgVersion: string | null = null;\n\nexport function getPackageVersion(): string {\n if (cachedPkgVersion) {\n return cachedPkgVersion;\n }\n try {\n const pkgPath = new URL(\"../package.json\", import.meta.url);\n const raw = readFileSync(pkgPath, \"utf8\");\n const parsed = JSON.parse(raw) as { version?: unknown };\n if (typeof parsed.version === \"string\" && parsed.version.trim().length > 0) {\n cachedPkgVersion = parsed.version.trim();\n return cachedPkgVersion;\n }\n } catch {\n // Fallback to static package version if package.json cannot be read\n }\n cachedPkgVersion = \"0.2.3\";\n return cachedPkgVersion;\n}\n\nexport function getConfigDir(): string {\n const override = process.env.AGYCRAFT_CONFIG_DIR;\n if (override && override.trim().length > 0) {\n return resolve(override.trim());\n }\n const xdg = process.env.XDG_CONFIG_HOME;\n if (xdg && xdg.trim().length > 0) {\n return join(resolve(xdg.trim()), \"agycraft\");\n }\n return join(homedir(), \".config\", \"agycraft\");\n}\n\nexport function getUsageLogPath(): string {\n return join(getConfigDir(), \"usage.jsonl\");\n}\n\nexport function getCacheDir(): string {\n return join(getConfigDir(), \"cache\");\n}\n\nexport function getRollupsDir(): string {\n return join(getConfigDir(), \"rollups\");\n}\n\nexport function getSaltFilePath(): string {\n return join(getConfigDir(), \".salt\");\n}\n\nexport function getDefaultGeminiTelemetryPath(): string {\n const override = process.env.AGYCRAFT_GEMINI_OTEL_PATH;\n if (override && override.trim().length > 0) {\n return resolve(override.trim());\n }\n return join(homedir(), \".gemini\", \"telemetry_stats.jsonl\");\n}\n\nconst BRAIN_SCAN_DISABLED_VALUES = new Set([\"none\", \"off\", \"false\"]);\n\nexport function isBrainScanDisabledValue(value: string): boolean {\n return BRAIN_SCAN_DISABLED_VALUES.has(value.trim().toLowerCase());\n}\n\nexport function getAgyBrainDir(): string | null {\n const override = process.env.AGYCRAFT_BRAIN_DIR;\n if (override && override.trim().length > 0) {\n const trimmed = override.trim();\n if (isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n const configOverride = process.env.AGYCRAFT_CONFIG_DIR;\n if (configOverride && configOverride.trim().length > 0) {\n // Sandbox isolation: skip scanning global AGY brain dir unless AGYCRAFT_BRAIN_DIR is explicitly set\n return null;\n }\n return join(homedir(), \".gemini\", \"antigravity-cli\", \"brain\");\n}\n\nexport function getAgyHistoryPath(): string | null {\n const override = process.env.AGYCRAFT_HISTORY_PATH;\n if (override && override.trim().length > 0) {\n const trimmed = override.trim();\n if (isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n const configOverride = process.env.AGYCRAFT_CONFIG_DIR;\n if (configOverride && configOverride.trim().length > 0) {\n // Sandbox isolation: skip scanning global AGY history.jsonl unless AGYCRAFT_HISTORY_PATH is explicitly set\n return null;\n }\n return join(homedir(), \".gemini\", \"antigravity-cli\", \"history.jsonl\");\n}\n\nexport function getAgyCliLogDir(): string | null {\n const override = process.env.AGYCRAFT_CLI_LOG_DIR;\n if (override && override.trim().length > 0) {\n const trimmed = override.trim();\n if (isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n const configOverride = process.env.AGYCRAFT_CONFIG_DIR;\n if (configOverride && configOverride.trim().length > 0) {\n // Sandbox isolation: skip scanning global AGY log dir unless AGYCRAFT_CLI_LOG_DIR is explicitly set\n return null;\n }\n return join(homedir(), \".gemini\", \"antigravity-cli\", \"log\");\n}\n\nexport function getSnapshotsDir(): string {\n const override = process.env.AGYCRAFT_SNAPSHOTS_DIR;\n if (override && override.trim().length > 0) {\n return resolve(override.trim());\n }\n // Works from both src/ (vitest/tsx) and dist/ (built bundle)\n return resolve(new URL(\"../snapshots\", import.meta.url).pathname);\n}\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { normalizeModelId } from \"../analyzers/token-window.js\";\nimport { getAgyCliLogDir, isBrainScanDisabledValue } from \"../paths.js\";\nimport {\n type UsageRecord,\n getOrCreateLocalSalt,\n sanitizeUsagePayload,\n} from \"../privacy.js\";\nimport type { AuthMode, ChannelsSnapshot } from \"../types.js\";\nimport { ChannelRegistry, loadBundledChannelRegistry } from \"./channel-registry.js\";\n\nexport interface CliLogAuthEvent {\n tsMs: number;\n authMode: AuthMode;\n channelId?: string;\n source: \"apply_auth_result\" | \"endpoint_match\" | \"daily_cloudcode\" | \"aiplatform\" | string;\n modelHint?: string;\n}\n\nexport interface CollectCliLogOptions {\n cliLogDir?: string | null;\n sinceMs?: number;\n nowMs?: number;\n salt?: string;\n saltPath?: string;\n fallbackAuthMode?: AuthMode;\n hasMixedAuth?: boolean;\n registry?: ChannelRegistry;\n channelsSnapshot?: ChannelsSnapshot;\n}\n\nexport interface CliLogCollection {\n authEvents: CliLogAuthEvent[];\n backgroundRecords: UsageRecord[];\n filesScanned: number;\n}\n\nfunction resolveCliLogDir(explicit: string | null | undefined): string | null {\n if (explicit === null) {\n return null;\n }\n if (explicit !== undefined) {\n const trimmed = explicit.trim();\n if (trimmed.length === 0 || isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n return getAgyCliLogDir();\n}\n\nexport function extractCliLogTimestampMs(line: string): number | null {\n // 1. ISO-8601 timestamp (e.g. 2026-12-01T12:34:56.789Z or 2026-12-01T12:34:56+08:00)\n const isoMatch = line.match(\n /\\b(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})?)\\b/,\n );\n if (isoMatch?.[1]) {\n const parsed = Date.parse(isoMatch[1]);\n if (!Number.isNaN(parsed)) {\n return parsed;\n }\n }\n\n // 2. Standard Go / CLI log prefix: 2026/12/01 12:34:56 or 2026-12-01 12:34:56(.123)\n const dateTimeMatch = line.match(\n /\\b(\\d{4})[/-](\\d{2})[/-](\\d{2})\\s+(\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)\\b/,\n );\n if (dateTimeMatch) {\n const normalized = `${dateTimeMatch[1]}-${dateTimeMatch[2]}-${dateTimeMatch[3]}T${dateTimeMatch[4]}Z`;\n const parsed = Date.parse(normalized);\n if (!Number.isNaN(parsed)) {\n return parsed;\n }\n }\n\n return null;\n}\n\nfunction mapCliAuthMethod(raw: string, registry: ChannelRegistry): { authMode: AuthMode; channelId: string } | null {\n const matched = registry.matchLogAuthMethod(raw);\n if (!matched) {\n return null;\n }\n return {\n authMode: registry.toLegacyAuthMode(matched.channelId),\n channelId: matched.channelId,\n };\n}\n\nexport function resolveAuthModeFromCliLogs(\n authEvents: CliLogAuthEvent[],\n tsMs: number,\n options: {\n fallbackAuthMode?: AuthMode;\n hasMixedAuth?: boolean;\n } = {},\n): AuthMode {\n const maxStaleMs = 12 * 3600_000;\n let latestBefore: CliLogAuthEvent | null = null;\n for (let i = authEvents.length - 1; i >= 0; i -= 1) {\n const ev = authEvents[i]!;\n if (ev.tsMs <= tsMs) {\n if (tsMs - ev.tsMs <= maxStaleMs) {\n latestBefore = ev;\n }\n break;\n }\n }\n if (latestBefore) {\n return latestBefore.authMode;\n }\n\n if (options.hasMixedAuth) {\n // Under mixed auth without cli-*.log coverage for this interval, avoid misattributing consumer traffic to GCP\n return \"unknown\";\n }\n return options.fallbackAuthMode ?? \"unknown\";\n}\n\ninterface PendingMonitorCall {\n tsMs: number;\n inputChars: number;\n model: string;\n}\n\n/**\n * Strictly read-only, zero-PII collector for AGY cli-*.log files.\n * - Never captures or retains emails, GCP project IDs, prompts, arguments, or file paths.\n * - Extracts runtime auth channel switches (consumer/daily-cloudcode-pa vs gcp/aiplatform)\n * and estimates lightweight llm_monitor.go background calls by character length.\n */\nexport async function collectCliLogSignals(\n options?: CollectCliLogOptions,\n): Promise<CliLogCollection> {\n const cliLogDir = resolveCliLogDir(options?.cliLogDir);\n if (cliLogDir === null) {\n return { authEvents: [], backgroundRecords: [], filesScanned: 0 };\n }\n\n let fileNames: string[] = [];\n try {\n const entries = await readdir(cliLogDir, { withFileTypes: true });\n fileNames = entries\n .filter((e) => e.isFile() && /^cli-.*\\.log$/i.test(e.name))\n .map((e) => e.name)\n .sort();\n } catch {\n return { authEvents: [], backgroundRecords: [], filesScanned: 0 };\n }\n\n const nowMs = options?.nowMs ?? Date.now();\n const sinceMs = options?.sinceMs;\n const salt = options?.salt ?? (await getOrCreateLocalSalt(options?.saltPath));\n const registry =\n options?.registry ??\n (options?.channelsSnapshot\n ? ChannelRegistry.fromSnapshot(options.channelsSnapshot)\n : loadBundledChannelRegistry());\n\n const authEvents: CliLogAuthEvent[] = [];\n const pendingBackground: Array<{\n tsMs: number;\n fileName: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n turnIndex: number;\n }> = [];\n\n let filesScanned = 0;\n\n for (const fileName of fileNames) {\n const filePath = join(cliLogDir, fileName);\n let st;\n try {\n st = await stat(filePath);\n } catch {\n continue;\n }\n\n if (sinceMs !== undefined && st.mtimeMs < sinceMs - 86_400_000) {\n continue;\n }\n\n let rawText: string;\n try {\n rawText = await readFile(filePath, \"utf8\");\n } catch {\n continue;\n }\n filesScanned += 1;\n\n let lastLineTsMs = st.mtimeMs;\n let pendingTsMs: number | null = null;\n let pendingInputChars = 0;\n let pendingModel: string | null = null;\n let bgTurnIndex = 0;\n\n for (const line of rawText.split(\"\\n\")) {\n if (!line.trim()) {\n continue;\n }\n\n const lineTs = extractCliLogTimestampMs(line);\n if (lineTs !== null) {\n lastLineTsMs = lineTs;\n }\n const effectiveTs = lineTs ?? lastLineTsMs;\n\n // 1. Auth channel signals (strictly zero PII — never capture email= or projects/<id>)\n if (line.includes(\"applyAuthResult\")) {\n const authMatch = line.match(/\\bauthMethod=([a-zA-Z0-9_-]+)/i);\n if (authMatch?.[1]) {\n const mapped = mapCliAuthMethod(authMatch[1], registry);\n if (mapped) {\n authEvents.push({\n tsMs: effectiveTs,\n authMode: mapped.authMode,\n channelId: mapped.channelId,\n source: \"apply_auth_result\",\n });\n }\n }\n }\n\n const matchedEndpointChannel = registry.matchEndpoint(line);\n if (matchedEndpointChannel) {\n const modelMatch = line.match(\n /\\/models\\/([a-zA-Z0-9._:@-]+)/,\n );\n const modelHint = modelMatch?.[1]\n ? normalizeModelId(modelMatch[1])\n : undefined;\n authEvents.push({\n tsMs: effectiveTs,\n authMode: registry.toLegacyAuthMode(matchedEndpointChannel.channelId),\n channelId: matchedEndpointChannel.channelId,\n source: \"endpoint_match\",\n ...(modelHint ? { modelHint } : {}),\n });\n }\n\n // 2. llm_monitor.go background lightweight calls\n const trajMatch = line.match(/Trajectory formatted,\\s*length:\\s*(\\d+)/i);\n if (trajMatch?.[1]) {\n pendingTsMs = effectiveTs;\n pendingInputChars = Number(trajMatch[1]);\n pendingModel = pendingModel ?? \"MODEL_TIER_FLASH_LITE\";\n }\n\n const callingMatch = line.match(/Calling LLM\\s*\\(\\s*model:\\s*([^)\\s]+)/i);\n if (callingMatch?.[1]) {\n pendingTsMs = pendingTsMs ?? effectiveTs;\n pendingModel = callingMatch[1];\n }\n\n const respMatch = line.match(/LLM response received,\\s*length:\\s*(\\d+)/i);\n if (respMatch?.[1]) {\n const outputChars = Number(respMatch[1]);\n const inputChars = pendingInputChars;\n const rawModel = pendingModel ?? \"MODEL_TIER_FLASH_LITE\";\n const eventTs = pendingTsMs ?? effectiveTs;\n pendingTsMs = null;\n pendingInputChars = 0;\n pendingModel = null;\n\n if (eventTs <= nowMs + 60_000 && (sinceMs === undefined || eventTs >= sinceMs)) {\n const inputTokens =\n inputChars > 0 ? Math.max(1, Math.round(inputChars / 4)) : 0;\n const outputTokens =\n outputChars > 0 ? Math.max(1, Math.round(outputChars / 4)) : 0;\n if (inputTokens > 0 || outputTokens > 0) {\n bgTurnIndex += 1;\n pendingBackground.push({\n tsMs: eventTs,\n fileName,\n model: normalizeModelId(rawModel),\n inputTokens,\n outputTokens,\n turnIndex: bgTurnIndex,\n });\n }\n }\n }\n }\n }\n\n authEvents.sort((a, b) => a.tsMs - b.tsMs);\n\n const backgroundRecords: UsageRecord[] = pendingBackground.map((bg) => {\n const resolvedAuth = resolveAuthModeFromCliLogs(authEvents, bg.tsMs, {\n fallbackAuthMode: options?.fallbackAuthMode,\n hasMixedAuth: options?.hasMixedAuth,\n });\n return sanitizeUsagePayload(\n {\n ts: new Date(bg.tsMs).toISOString(),\n provider: \"antigravity\",\n product: \"agy\",\n session_id: `cli-log-monitor:${bg.fileName}`,\n model: bg.model,\n input_tokens: bg.inputTokens,\n cache_read_tokens: 0,\n output_tokens: bg.outputTokens,\n thinking_tokens: 0,\n tool_calls: 0,\n turn_index: bg.turnIndex,\n project_hash: null,\n auth_mode: resolvedAuth,\n data_quality: \"estimated_from_cli_log\",\n },\n salt,\n );\n });\n\n return {\n authEvents,\n backgroundRecords,\n filesScanned,\n };\n}\n","import type { UsageRecord } from \"../collectors/agy-hook.js\";\nimport type {\n AuthMode,\n FallbackPricingConfig,\n ModelEntry,\n NormalizationRules,\n} from \"../types.js\";\n\nexport type UsageWindow = \"5h\" | \"24h\" | \"7d\" | \"30d\" | \"all\";\n\nexport interface ModelUsageBreakdown {\n model: string;\n requests: number;\n uncached_input_tokens: number;\n cache_read_tokens: number;\n input_tokens: number;\n output_tokens: number;\n total_tokens: number;\n cache_hit_rate_pct: number;\n estimated_input_usd: number;\n estimated_cache_savings_usd: number;\n estimated_output_and_thinking_usd: number;\n estimated_total_usd: number;\n shared_bucket_cost_tier: string;\n}\n\nexport interface TokenWindowAnalysis {\n window: UsageWindow;\n product_filter: string;\n scope: \"global\" | \"project\";\n project_hash?: string;\n auth_mode_filter: AuthMode | \"all\";\n unattributed_sessions_excluded?: number;\n unattributed_sessions_note?: string;\n data_mode:\n | \"exact_token_logs\"\n | \"transcript_token_logs\"\n | \"hook_events_without_tokens\"\n | \"transcript_timestamps_only\";\n usage_note?: string;\n record_count: number;\n session_count: number;\n total_uncached_input_tokens: number;\n total_cache_read_tokens: number;\n total_input_tokens: number;\n total_output_tokens: number;\n total_tokens: number;\n cache_hit_rate_pct: number;\n error_count: number;\n rate_limit_429_count: number;\n peak_context_used_pct: number | null;\n oldest_event_ms: number | null;\n below_kv_cache_threshold_requests: number;\n shared_bucket_risk: \"low\" | \"moderate\" | \"high\" | \"critical\";\n thinking_cost_estimate: {\n estimated_input_usd: number;\n estimated_cache_savings_usd: number;\n estimated_output_and_thinking_usd: number;\n estimated_total_usd: number;\n output_cost_share_pct: number;\n note: string;\n };\n by_model: ModelUsageBreakdown[];\n}\n\nexport const WINDOW_MS: Record<Exclude<UsageWindow, \"all\">, number> = {\n \"5h\": 5 * 60 * 60 * 1000,\n \"24h\": 24 * 60 * 60 * 1000,\n \"7d\": 7 * 24 * 60 * 60 * 1000,\n \"30d\": 30 * 24 * 60 * 60 * 1000,\n};\n\nconst DEFAULT_PRICING = {\n input_per_1m_usd: 1.25,\n output_per_1m_usd: 10.0,\n};\n\nconst GENERIC_CODENAMES = new Set([\n \"flash\",\n \"flash-lite\",\n \"live\",\n \"pro\",\n \"lite\",\n \"mini\",\n \"nano\",\n \"ultra\",\n \"2.5 pro\",\n \"2.5 flash\",\n \"2.0 flash\",\n \"2.0 flash-lite\",\n \"1.5 pro\",\n \"1.5 flash\",\n]);\n\nexport interface NormalizedModelInfo {\n canonicalId: string;\n thinkingTier?: string;\n isPlaceholder: boolean;\n}\n\nconst MAX_RULE_PATTERN_LENGTH = 256;\n\nconst DEFAULT_FALLBACK_PRICING: FallbackPricingConfig = {\n default: {\n input_per_1m_usd: DEFAULT_PRICING.input_per_1m_usd,\n cached_ratio: 0.25,\n output_per_1m_usd: DEFAULT_PRICING.output_per_1m_usd,\n tier: \"medium\",\n },\n rules: [\n { match_any: [\"opus\"], input_per_1m_usd: 15.0, cached_ratio: 0.1, output_per_1m_usd: 75.0, tier: \"high\" },\n { match_any: [\"haiku\"], input_per_1m_usd: 0.8, cached_ratio: 0.1, output_per_1m_usd: 4.0, tier: \"low\" },\n { match_any: [\"claude\", \"sonnet\"], input_per_1m_usd: 3.0, cached_ratio: 0.1, output_per_1m_usd: 15.0, tier: \"medium\" },\n { match_any: [\"flash-lite\", \"lite\"], input_per_1m_usd: 0.1, cached_ratio: 0.25, output_per_1m_usd: 0.4, tier: \"low\" },\n { match_any: [\"flash\", \"hydrogen\"], input_per_1m_usd: 0.3, cached_ratio: 0.25, output_per_1m_usd: 2.5, tier: \"low\" },\n { match_any: [\"neon\", \"carbon\"], input_per_1m_usd: 2.0, cached_ratio: 0.25, output_per_1m_usd: 12.0, tier: \"high\" },\n { match_any: [\"pro\"], input_per_1m_usd: 1.25, cached_ratio: 0.25, output_per_1m_usd: 10.0, tier: \"high\" },\n ],\n};\n\nconst DEFAULT_NORMALIZATION_RULES: NormalizationRules = {\n rules_version: 1,\n placeholder_prefixes: [\"MODEL_PLACEHOLDER_\"],\n enum_mappings: {\n MODEL_TIER_FLASH_LITE: \"gemini-3.5-flash-lite\",\n SIR_FLASH_LITE: \"gemini-3.5-flash-lite\",\n MODEL_TIER_FLASH: \"gemini-3.8-flash\",\n },\n prefix_strip_patterns: [\n \"^(?:projects/[^/]+/locations/[^/]+/(?:publishers/[^/]+/)?models/|publishers/[^/]+/models/|models/)\",\n ],\n suffix_strip_patterns: [\n { pattern: \"-tiered-([a-z0-9-]+)$\", capture_thinking_tier_group: 1 },\n { pattern: \"-(low|medium|high|xhigh)$\", capture_thinking_tier_group: 1 },\n { pattern: \"(?:@|-)\\\\d{8}$\" },\n { pattern: \"-preview(?:-\\\\d{2}-\\\\d{2})?$\" },\n { pattern: \"-sonar$\" },\n ],\n version_format_rules: [\n { pattern: \"^(gemini-(?:omni-)?)(\\\\d+)-(\\\\d+)(?=-|$)\", replace: \"$1$2.$3\" },\n { pattern: \"^(claude-(?:[a-z]+-)?)(\\\\d+)\\\\.(\\\\d+)(?=-|$)\", replace: \"$1$2-$3\" },\n ],\n fallback_pricing: DEFAULT_FALLBACK_PRICING,\n};\n\ninterface CompiledSuffixRule {\n regex: RegExp;\n captureTierGroup?: number;\n}\n\ninterface CompiledVersionRule {\n regex: RegExp;\n replace: string;\n}\n\nexport interface CompiledNormalizationRules {\n placeholderPrefixes: string[];\n enumMappings: Map<string, string>;\n prefixStripPatterns: RegExp[];\n suffixStripPatterns: CompiledSuffixRule[];\n versionFormatRules: CompiledVersionRule[];\n fallbackPricing: FallbackPricingConfig;\n}\n\nconst compiledRulesCache = new WeakMap<NormalizationRules, CompiledNormalizationRules>();\nlet defaultCompiledRules: CompiledNormalizationRules | null = null;\n\nfunction safeCompileRegExp(pattern: string, flags = \"i\"): RegExp | null {\n if (\n typeof pattern !== \"string\" ||\n pattern.length === 0 ||\n pattern.length > MAX_RULE_PATTERN_LENGTH\n ) {\n return null;\n }\n try {\n return new RegExp(pattern, flags);\n } catch {\n return null;\n }\n}\n\nexport function compileNormalizationRules(\n rules?: NormalizationRules,\n): CompiledNormalizationRules {\n if (!rules) {\n if (!defaultCompiledRules) {\n defaultCompiledRules = compileNormalizationRules(DEFAULT_NORMALIZATION_RULES);\n }\n return defaultCompiledRules;\n }\n\n const cached = compiledRulesCache.get(rules);\n if (cached) {\n return cached;\n }\n\n const placeholderPrefixes = (\n rules.placeholder_prefixes?.length\n ? rules.placeholder_prefixes\n : DEFAULT_NORMALIZATION_RULES.placeholder_prefixes!\n ).map((p) => p.toUpperCase());\n\n const enumMappings = new Map<string, string>();\n const rawEnums = rules.enum_mappings ?? DEFAULT_NORMALIZATION_RULES.enum_mappings!;\n for (const [k, v] of Object.entries(rawEnums)) {\n if (typeof k === \"string\" && typeof v === \"string\" && k.trim() && v.trim()) {\n enumMappings.set(k.trim().toUpperCase(), v.trim());\n }\n }\n\n const rawPrefixes =\n rules.prefix_strip_patterns ?? DEFAULT_NORMALIZATION_RULES.prefix_strip_patterns!;\n const prefixStripPatterns: RegExp[] = [];\n for (const p of rawPrefixes) {\n const compiled = safeCompileRegExp(p, \"i\");\n if (compiled) {\n prefixStripPatterns.push(compiled);\n }\n }\n\n const rawSuffixes =\n rules.suffix_strip_patterns ?? DEFAULT_NORMALIZATION_RULES.suffix_strip_patterns!;\n const suffixStripPatterns: CompiledSuffixRule[] = [];\n for (const s of rawSuffixes) {\n const compiled = safeCompileRegExp(s.pattern, \"i\");\n if (compiled) {\n suffixStripPatterns.push({\n regex: compiled,\n ...(typeof s.capture_thinking_tier_group === \"number\"\n ? { captureTierGroup: s.capture_thinking_tier_group }\n : {}),\n });\n }\n }\n\n const rawVersionRules =\n rules.version_format_rules ?? DEFAULT_NORMALIZATION_RULES.version_format_rules!;\n const versionFormatRules: CompiledVersionRule[] = [];\n for (const vr of rawVersionRules) {\n const compiled = safeCompileRegExp(vr.pattern, \"\");\n if (compiled && typeof vr.replace === \"string\") {\n versionFormatRules.push({ regex: compiled, replace: vr.replace });\n }\n }\n\n const fallbackPricing: FallbackPricingConfig =\n rules.fallback_pricing &&\n rules.fallback_pricing.default &&\n Array.isArray(rules.fallback_pricing.rules)\n ? rules.fallback_pricing\n : DEFAULT_FALLBACK_PRICING;\n\n const result: CompiledNormalizationRules = {\n placeholderPrefixes,\n enumMappings,\n prefixStripPatterns,\n suffixStripPatterns,\n versionFormatRules,\n fallbackPricing,\n };\n compiledRulesCache.set(rules, result);\n return result;\n}\n\nfunction stripVariantAndDateSuffixes(\n modelId: string,\n compiled: CompiledNormalizationRules,\n): {\n stripped: string;\n thinkingTier?: string;\n} {\n let normalized = modelId.trim().toLowerCase();\n let thinkingTier: string | undefined;\n let prev = \"\";\n\n while (normalized !== prev) {\n prev = normalized;\n for (const rule of compiled.suffixStripPatterns) {\n const m = normalized.match(rule.regex);\n if (m) {\n if (\n !thinkingTier &&\n typeof rule.captureTierGroup === \"number\" &&\n m[rule.captureTierGroup]\n ) {\n thinkingTier = m[rule.captureTierGroup]!.toLowerCase();\n }\n normalized = normalized.replace(rule.regex, \"\");\n break;\n }\n }\n }\n\n return { stripped: normalized, thinkingTier };\n}\n\nfunction normalizeModelCore(\n raw: string,\n rules?: NormalizationRules,\n): NormalizedModelInfo {\n const trimmed = raw.trim();\n if (!trimmed || trimmed.toLowerCase() === \"unknown\") {\n return { canonicalId: \"unknown\", isPlaceholder: false };\n }\n\n const compiled = compileNormalizationRules(rules);\n const upper = trimmed.toUpperCase();\n if (compiled.placeholderPrefixes.some((prefix) => upper.startsWith(prefix))) {\n return { canonicalId: trimmed, isPlaceholder: true };\n }\n const enumMapped = compiled.enumMappings.get(upper);\n if (enumMapped) {\n return { canonicalId: enumMapped, isPlaceholder: false };\n }\n\n // Step 2: Strip resource path prefixes and runtime/version suffixes\n let withoutPath = trimmed;\n for (const prefixRegex of compiled.prefixStripPatterns) {\n withoutPath = withoutPath.replace(prefixRegex, \"\");\n }\n const { stripped, thinkingTier } = stripVariantAndDateSuffixes(withoutPath, compiled);\n\n // Step 3: Apply version format rules\n let formatted = stripped;\n for (const vRule of compiled.versionFormatRules) {\n formatted = formatted.replace(vRule.regex, vRule.replace);\n }\n\n return {\n canonicalId: formatted || \"unknown\",\n ...(thinkingTier ? { thinkingTier } : {}),\n isPlaceholder: false,\n };\n}\n\nexport function normalizeModelInfo(\n raw: string,\n catalog: ModelEntry[] = [],\n rules?: NormalizationRules,\n): NormalizedModelInfo {\n const core = normalizeModelCore(raw, rules);\n if (core.isPlaceholder || core.canonicalId === \"unknown\" || catalog.length === 0) {\n return core;\n }\n const matched = findModelEntry(core.canonicalId, catalog, rules);\n if (matched) {\n return {\n canonicalId: matched.id,\n ...(core.thinkingTier ? { thinkingTier: core.thinkingTier } : {}),\n isPlaceholder: false,\n };\n }\n return core;\n}\n\nexport function normalizeModelId(\n raw: string,\n catalog: ModelEntry[] = [],\n rules?: NormalizationRules,\n): string {\n return normalizeModelInfo(raw, catalog, rules).canonicalId;\n}\n\nexport function isZeroTokenUnknownLifecycleEvent(r: {\n model?: string;\n input_tokens: number;\n cache_read_tokens?: number;\n output_tokens: number;\n}): boolean {\n const m = (r.model ?? \"\").trim().toLowerCase();\n return (\n (m === \"\" || m === \"unknown\") &&\n r.input_tokens === 0 &&\n (r.cache_read_tokens ?? 0) === 0 &&\n r.output_tokens === 0\n );\n}\n\nfunction extractGeminiMajorMinor(modelId: string): string | null {\n const match = modelId.toLowerCase().match(/gemini-(\\d+(?:[.-]\\d+)?)/);\n return match ? match[1]!.replace(\"-\", \".\") : null;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction matchExactEntry(candidateLower: string, catalog: ModelEntry[]): ModelEntry | undefined {\n const exactId = catalog.find(\n (m) =>\n m.id.toLowerCase() === candidateLower ||\n m.api_model_id.toLowerCase() === candidateLower ||\n Boolean(m.aliases?.some((a) => a.toLowerCase() === candidateLower)),\n );\n if (exactId) return exactId;\n\n return catalog.find(\n (m) =>\n m.display_name.toLowerCase() === candidateLower ||\n (m.codename && m.codename.toLowerCase() === candidateLower),\n );\n}\n\nexport function findModelEntry(\n modelId: string,\n catalog: ModelEntry[],\n rules?: NormalizationRules,\n): ModelEntry | undefined {\n const lower = modelId.trim().toLowerCase();\n if (!lower) return undefined;\n\n // 1. Exact match on id / api_model_id / aliases / display_name / codename\n const exact = matchExactEntry(lower, catalog);\n if (exact) return exact;\n\n // 2. Normalized exact match (enum/path/suffix/dot-version)\n const core = normalizeModelCore(modelId, rules);\n if (core.isPlaceholder || core.canonicalId === \"unknown\") {\n return undefined;\n }\n const normalizedLower = core.canonicalId.toLowerCase();\n if (normalizedLower !== lower) {\n const normalizedExact = matchExactEntry(normalizedLower, catalog);\n if (normalizedExact) return normalizedExact;\n }\n\n // 3. Prefix match on id / api_model_id / aliases (prefer longest match, avoid flash-lite mismatch)\n const isLiteVariant =\n normalizedLower.includes(\"-lite\") || normalizedLower.endsWith(\"lite\");\n const prefixCandidates = catalog\n .map((m) => {\n const mId = m.id.toLowerCase();\n const mApiId = m.api_model_id.toLowerCase();\n const aliases = (m.aliases ?? []).map((a) => a.toLowerCase());\n if (\n isLiteVariant &&\n !mId.includes(\"lite\") &&\n !mApiId.includes(\"lite\") &&\n !aliases.some((a) => a.includes(\"lite\"))\n ) {\n return null;\n }\n const matchedLengths = [mId, mApiId, ...aliases]\n .filter((cand) => cand.length > 0 && normalizedLower.startsWith(`${cand}-`))\n .map((cand) => cand.length);\n if (matchedLengths.length === 0) return null;\n return { entry: m, maxMatchLen: Math.max(...matchedLengths) };\n })\n .filter((x): x is { entry: ModelEntry; maxMatchLen: number } => x !== null)\n .sort((a, b) => b.maxMatchLen - a.maxMatchLen || b.entry.id.length - a.entry.id.length);\n if (prefixCandidates.length > 0) return prefixCandidates[0]!.entry;\n\n // 4. Restricted codename match: only non-generic codenames without version conflict\n const inputVersion = extractGeminiMajorMinor(normalizedLower);\n return catalog.find((m) => {\n if (!m.codename) return false;\n const codeLower = m.codename.toLowerCase();\n if (GENERIC_CODENAMES.has(codeLower)) return false;\n\n const entryVersion = extractGeminiMajorMinor(m.api_model_id || m.id);\n if (inputVersion && entryVersion && inputVersion !== entryVersion) {\n return false;\n }\n\n const boundaryRegex = new RegExp(\n `(?:^|[-_\\\\s.])${escapeRegExp(codeLower)}(?:$|[-_\\\\s.])`,\n );\n return boundaryRegex.test(normalizedLower);\n });\n}\n\nexport function findModelPricing(\n modelId: string,\n catalog: ModelEntry[],\n rules?: NormalizationRules,\n): { input: number; cachedInput: number; output: number; tier: string } {\n const core = normalizeModelCore(modelId, rules);\n if (core.isPlaceholder) {\n return { input: 0, cachedInput: 0, output: 0, tier: \"unknown\" };\n }\n\n const partial = findModelEntry(core.canonicalId, catalog, rules);\n\n if (partial?.pricing) {\n const input = partial.pricing.input_per_1m_usd;\n const cachedInput =\n typeof partial.pricing.cached_input_per_1m_usd === \"number\"\n ? partial.pricing.cached_input_per_1m_usd\n : input * 0.25;\n return {\n input,\n cachedInput,\n output: partial.pricing.output_per_1m_usd,\n tier: partial.quota_profile?.shared_bucket_cost_tier ?? \"medium\",\n };\n }\n\n const compiled = compileNormalizationRules(rules);\n const lower = modelId.toLowerCase();\n const canonicalLower = core.canonicalId.toLowerCase();\n\n for (const rule of compiled.fallbackPricing.rules) {\n if (\n rule.match_any.some((kw) => {\n const k = kw.toLowerCase();\n return lower.includes(k) || canonicalLower.includes(k);\n })\n ) {\n const input = rule.input_per_1m_usd;\n const cachedInput =\n typeof rule.cached_input_per_1m_usd === \"number\"\n ? rule.cached_input_per_1m_usd\n : input * (rule.cached_ratio ?? 0.25);\n return {\n input,\n cachedInput,\n output: rule.output_per_1m_usd,\n tier: rule.tier,\n };\n }\n }\n\n const def = compiled.fallbackPricing.default;\n const defInput = def.input_per_1m_usd;\n const defCached =\n typeof def.cached_input_per_1m_usd === \"number\"\n ? def.cached_input_per_1m_usd\n : defInput * (def.cached_ratio ?? 0.25);\n return {\n input: defInput,\n cachedInput: defCached,\n output: def.output_per_1m_usd,\n tier: def.tier ?? \"medium\",\n };\n}\n\nexport function estimateTokenCosts(\n params: {\n model: string;\n uncachedInputTokens: number;\n cacheReadTokens: number;\n outputTokens: number;\n },\n catalog: ModelEntry[],\n rules?: NormalizationRules,\n): {\n pricing: { input: number; cachedInput: number; output: number; tier: string };\n inputUsd: number;\n cacheSavingsUsd: number;\n outputUsd: number;\n totalUsd: number;\n} {\n const pricing = findModelPricing(params.model, catalog, rules);\n const inputUsd =\n (params.uncachedInputTokens / 1_000_000) * pricing.input +\n (params.cacheReadTokens / 1_000_000) * pricing.cachedInput;\n const cacheSavingsUsd = Math.max(\n 0,\n (params.cacheReadTokens / 1_000_000) * (pricing.input - pricing.cachedInput),\n );\n const outputUsd = (params.outputTokens / 1_000_000) * pricing.output;\n return {\n pricing,\n inputUsd,\n cacheSavingsUsd,\n outputUsd,\n totalUsd: inputUsd + outputUsd,\n };\n}\n\nexport function analyzeTokenWindow(\n records: UsageRecord[],\n options: {\n window: UsageWindow;\n product?: string;\n models?: ModelEntry[];\n normalizationRules?: NormalizationRules;\n nowMs?: number;\n scope?: \"global\" | \"project\";\n projectHash?: string;\n authMode?: AuthMode | \"all\";\n activeAuthMode?: AuthMode;\n dataModeOverride?: TokenWindowAnalysis[\"data_mode\"];\n unattributedSessionCount?: number;\n },\n): TokenWindowAnalysis {\n const nowMs = options.nowMs ?? Date.now();\n const cutoffMs =\n options.window === \"all\"\n ? Number.NEGATIVE_INFINITY\n : nowMs - WINDOW_MS[options.window];\n const catalog = options.models ?? [];\n const scope = options.scope ?? \"global\";\n const authModeFilter = options.authMode ?? \"all\";\n\n const baseFiltered = records.filter((r) => {\n const ts = Date.parse(r.ts);\n if (Number.isNaN(ts) || ts < cutoffMs) {\n return false;\n }\n if (\n options.product &&\n options.product !== \"all\" &&\n r.product !== options.product\n ) {\n return false;\n }\n if (authModeFilter !== \"all\" && (r.auth_mode ?? \"unknown\") !== authModeFilter) {\n return false;\n }\n return true;\n });\n\n const unattributedSessionsInWindow = new Set<string>();\n for (const r of baseFiltered) {\n if (!r.project_hash) {\n const key =\n typeof r.session_hash === \"string\" && r.session_hash.trim().length > 0\n ? r.session_hash.trim()\n : \"default-session\";\n unattributedSessionsInWindow.add(key);\n }\n }\n\n const filtered =\n scope === \"project\"\n ? baseFiltered.filter(\n (r) => Boolean(options.projectHash) && r.project_hash === options.projectHash,\n )\n : baseFiltered;\n\n let totalUncachedInput = 0;\n let totalCacheRead = 0;\n let totalOutput = 0;\n let errorCount = 0;\n let rateLimit429Count = 0;\n let peakCtxPct: number | null = null;\n let oldestMs: number | null = null;\n let belowKvCacheThresholdRequests = 0;\n\n const sessions = new Set<string>();\n const modelMap = new Map<\n string,\n {\n requests: number;\n uncachedInput: number;\n cacheRead: number;\n output: number;\n }\n >();\n\n for (const r of filtered) {\n const uncached = r.input_tokens;\n const cacheRead = r.cache_read_tokens ?? 0;\n const reqTotalInput = uncached + cacheRead;\n\n totalUncachedInput += uncached;\n totalCacheRead += cacheRead;\n totalOutput += r.output_tokens;\n const sessionKey =\n typeof r.session_hash === \"string\" && r.session_hash.trim().length > 0\n ? r.session_hash.trim()\n : \"default-session\";\n sessions.add(sessionKey);\n\n const rules = options.normalizationRules;\n const matchedEntry = findModelEntry(r.model, catalog, rules);\n const kvMinTokens = matchedEntry?.specs?.implicit_cache_min_tokens ?? 4096;\n if (\n kvMinTokens > 0 &&\n reqTotalInput > 0 &&\n reqTotalInput < kvMinTokens &&\n cacheRead === 0\n ) {\n belowKvCacheThresholdRequests += 1;\n }\n\n const ts = Date.parse(r.ts);\n if (!Number.isNaN(ts) && (oldestMs === null || ts < oldestMs)) {\n oldestMs = ts;\n }\n\n if (r.error_code) {\n errorCount += 1;\n if (r.error_code.includes(\"429\") || r.error_code.includes(\"RESOURCE_EXHAUSTED\")) {\n rateLimit429Count += 1;\n }\n }\n\n if (r.context_used_pct !== null) {\n peakCtxPct =\n peakCtxPct === null\n ? r.context_used_pct\n : Math.max(peakCtxPct, r.context_used_pct);\n }\n\n if (!isZeroTokenUnknownLifecycleEvent(r)) {\n const canonicalModel = normalizeModelId(r.model, catalog, rules);\n const agg = modelMap.get(canonicalModel) ?? {\n requests: 0,\n uncachedInput: 0,\n cacheRead: 0,\n output: 0,\n };\n agg.requests += 1;\n agg.uncachedInput += uncached;\n agg.cacheRead += cacheRead;\n agg.output += r.output_tokens;\n modelMap.set(canonicalModel, agg);\n }\n }\n\n let totalInputUsd = 0;\n let totalCacheSavingsUsd = 0;\n let totalOutputUsd = 0;\n const byModel: ModelUsageBreakdown[] = [];\n\n for (const [model, agg] of modelMap.entries()) {\n const {\n pricing,\n inputUsd: inUsd,\n cacheSavingsUsd,\n outputUsd: outUsd,\n } = estimateTokenCosts(\n {\n model,\n uncachedInputTokens: agg.uncachedInput,\n cacheReadTokens: agg.cacheRead,\n outputTokens: agg.output,\n },\n catalog,\n options.normalizationRules,\n );\n totalInputUsd += inUsd;\n totalCacheSavingsUsd += cacheSavingsUsd;\n totalOutputUsd += outUsd;\n\n const modelInputTotal = agg.uncachedInput + agg.cacheRead;\n const modelCacheHitRate =\n modelInputTotal > 0\n ? Math.round((agg.cacheRead / modelInputTotal) * 1000) / 10\n : 0;\n\n byModel.push({\n model,\n requests: agg.requests,\n uncached_input_tokens: agg.uncachedInput,\n cache_read_tokens: agg.cacheRead,\n input_tokens: modelInputTotal,\n output_tokens: agg.output,\n total_tokens: modelInputTotal + agg.output,\n cache_hit_rate_pct: modelCacheHitRate,\n estimated_input_usd: round4(inUsd),\n estimated_cache_savings_usd: round4(cacheSavingsUsd),\n estimated_output_and_thinking_usd: round4(outUsd),\n estimated_total_usd: round4(inUsd + outUsd),\n shared_bucket_cost_tier: pricing.tier,\n });\n }\n\n byModel.sort((a, b) => b.total_tokens - a.total_tokens);\n\n const totalInput = totalUncachedInput + totalCacheRead;\n const totalTokens = totalInput + totalOutput;\n const cacheHitRatePct =\n totalInput > 0 ? Math.round((totalCacheRead / totalInput) * 1000) / 10 : 0;\n const dataMode = resolveDataMode(\n filtered.length,\n totalTokens,\n options.dataModeOverride,\n );\n const usageNote =\n dataMode === \"hook_events_without_tokens\"\n ? `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.`\n : undefined;\n const excludedUnattributed = unattributedSessionsInWindow.size;\n const totalUsd = totalInputUsd + totalOutputUsd;\n const outputCostSharePct =\n totalUsd > 0 ? Math.round((totalOutputUsd / totalUsd) * 1000) / 10 : 0;\n\n const risk = assessSharedBucketRisk(\n options.window,\n totalTokens,\n rateLimit429Count,\n byModel,\n );\n\n return {\n window: options.window,\n product_filter: options.product ?? \"all\",\n scope,\n ...(scope === \"project\" && options.projectHash\n ? { project_hash: options.projectHash }\n : {}),\n auth_mode_filter: authModeFilter,\n ...(scope === \"project\"\n ? {\n unattributed_sessions_excluded: excludedUnattributed,\n unattributed_sessions_note:\n excludedUnattributed > 0\n ? `${excludedUnattributed} unattributed/derived session(s) without workspace mapping in history.jsonl were excluded from project scope.`\n : \"All attributed sessions for this project are included; any unattributed subagent sessions are excluded in project scope.\",\n }\n : {}),\n data_mode: dataMode,\n ...(usageNote ? { usage_note: usageNote } : {}),\n record_count: filtered.length,\n session_count: sessions.size,\n total_uncached_input_tokens: totalUncachedInput,\n total_cache_read_tokens: totalCacheRead,\n total_input_tokens: totalInput,\n total_output_tokens: totalOutput,\n total_tokens: totalTokens,\n cache_hit_rate_pct: cacheHitRatePct,\n error_count: errorCount,\n rate_limit_429_count: rateLimit429Count,\n peak_context_used_pct: peakCtxPct,\n oldest_event_ms: oldestMs,\n below_kv_cache_threshold_requests: belowKvCacheThresholdRequests,\n shared_bucket_risk: risk,\n thinking_cost_estimate: {\n estimated_input_usd: round4(totalInputUsd),\n estimated_cache_savings_usd: round4(totalCacheSavingsUsd),\n estimated_output_and_thinking_usd: round4(totalOutputUsd),\n estimated_total_usd: round4(totalUsd),\n output_cost_share_pct: outputCostSharePct,\n note:\n options.activeAuthMode === \"google_oauth\" || authModeFilter === \"google_oauth\"\n ? \"API-equivalent shadow cost (measures shared 5h/7d subscription quota pressure, not direct cash billing). Thinking tokens are weighted at output rates (typically 4x–8x input cost); high output cost share signals a Thinking-budget or model-tier optimization opportunity.\"\n : \"Estimated at API list rates (API-equivalent shadow cost under subscription plans). Thinking tokens are billed at output rates (typically 4x–8x input cost). High output cost share signals a Thinking-budget or model-tier optimization opportunity.\",\n },\n by_model: byModel,\n };\n}\n\nexport function resolveDataMode(\n recordCount: number,\n totalTokens: number,\n override?: TokenWindowAnalysis[\"data_mode\"],\n): TokenWindowAnalysis[\"data_mode\"] {\n if (recordCount === 0) {\n return \"transcript_timestamps_only\";\n }\n if (totalTokens > 0 && override === \"transcript_token_logs\") {\n return \"transcript_token_logs\";\n }\n return totalTokens > 0 ? \"exact_token_logs\" : \"hook_events_without_tokens\";\n}\n\nfunction assessSharedBucketRisk(\n window: UsageWindow,\n totalTokens: number,\n rateLimit429Count: number,\n byModel: ModelUsageBreakdown[],\n): \"low\" | \"moderate\" | \"high\" | \"critical\" {\n if (rateLimit429Count >= 3) {\n return \"critical\";\n }\n const heavyTokens = byModel\n .filter(\n (m) =>\n m.shared_bucket_cost_tier === \"high\" ||\n m.shared_bucket_cost_tier === \"very_high\",\n )\n .reduce((sum, m) => sum + m.total_tokens, 0);\n\n const scale =\n window === \"5h\"\n ? 1\n : window === \"24h\"\n ? 3\n : window === \"7d\"\n ? 10\n : window === \"30d\"\n ? 35\n : 60;\n if (totalTokens > 8_000_000 * scale || heavyTokens > 4_000_000 * scale) {\n return \"critical\";\n }\n if (totalTokens > 3_000_000 * scale || heavyTokens > 1_500_000 * scale || rateLimit429Count > 0) {\n return \"high\";\n }\n if (totalTokens > 1_000_000 * scale) {\n return \"moderate\";\n }\n return \"low\";\n}\n\nfunction round4(n: number): number {\n return Math.round(n * 10000) / 10000;\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { getSaltFilePath } from \"./paths.js\";\nimport type { AuthMode } from \"./types.js\";\n\n/**\n * Strict numeric/metadata whitelist for local usage telemetry.\n * PRIVACY RED LINE: NEVER add prompts, code, file paths, project names, emails, or account IDs.\n */\nexport interface UsageRecord {\n v: 1;\n ts: string;\n provider: \"google\" | \"antigravity\" | \"other\";\n product: \"agy\" | \"gemini-cli\" | \"api\" | \"web\";\n session_hash: string;\n model: string;\n input_tokens: number;\n cache_read_tokens?: number;\n output_tokens: number;\n thinking_tokens?: number;\n context_used_pct: number | null;\n tool_calls: number;\n turn_index: number;\n error_code: string | null;\n project_hash?: string | null;\n auth_mode?: AuthMode;\n data_quality?: \"exact\" | \"estimated_from_cli_log\";\n}\n\nexport const USAGE_RECORD_WHITELIST_KEYS = [\n \"v\",\n \"ts\",\n \"provider\",\n \"product\",\n \"session_hash\",\n \"model\",\n \"input_tokens\",\n \"cache_read_tokens\",\n \"output_tokens\",\n \"thinking_tokens\",\n \"context_used_pct\",\n \"tool_calls\",\n \"turn_index\",\n \"error_code\",\n \"project_hash\",\n \"auth_mode\",\n \"data_quality\",\n] as const;\n\nconst ALLOWED_PROVIDERS = new Set([\"google\", \"antigravity\", \"other\"]);\nconst ALLOWED_PRODUCTS = new Set([\"agy\", \"gemini-cli\", \"api\", \"web\"]);\nconst ALLOWED_AUTH_MODES = new Set<AuthMode>([\n \"google_oauth\",\n \"gcp_adc\",\n \"api_key\",\n \"unknown\",\n]);\nconst SAFE_MODEL_RE = /^[a-zA-Z0-9._:-]{1,64}$/;\nconst SAFE_ERROR_CODE_RE = /^[A-Z0-9_:-]{1,48}$/;\n\nconst cachedSalts = new Map<string, string>();\n\nexport async function getOrCreateLocalSalt(\n saltPath = getSaltFilePath(),\n): Promise<string> {\n const key = resolve(saltPath);\n const cached = cachedSalts.get(key);\n if (cached) {\n return cached;\n }\n try {\n const existing = (await readFile(key, \"utf8\")).trim();\n if (existing.length >= 16) {\n cachedSalts.set(key, existing);\n return existing;\n }\n } catch {\n // Salt file does not exist yet\n }\n const fresh = randomBytes(16).toString(\"hex\");\n await mkdir(dirname(key), { recursive: true });\n await writeFile(key, fresh, { mode: 0o600 });\n cachedSalts.set(key, fresh);\n return fresh;\n}\n\nexport function resetSaltCache(saltPath?: string): void {\n if (saltPath !== undefined) {\n cachedSalts.delete(resolve(saltPath));\n } else {\n cachedSalts.clear();\n }\n}\n\nexport function hashSessionId(rawSessionId: string, salt: string): string {\n return createHash(\"sha256\")\n .update(`${salt}:${rawSessionId}`)\n .digest(\"hex\")\n .slice(0, 12);\n}\n\n/**\n * One-way irreversible hash for workspace/project directory paths.\n * Never persists or returns the raw workspace path.\n */\nexport function hashProjectPath(workspaceDir: string, salt: string): string {\n return createHash(\"sha256\")\n .update(`${salt}:${resolve(workspaceDir)}`)\n .digest(\"hex\")\n .slice(0, 12);\n}\n\nfunction clampNonNegativeInt(val: unknown): number {\n const n = typeof val === \"number\" ? val : Number(val);\n if (!Number.isFinite(n) || n < 0) {\n return 0;\n }\n return Math.floor(n);\n}\n\nfunction clampPct(val: unknown): number | null {\n if (val === null || val === undefined || val === \"\") {\n return null;\n }\n const n = typeof val === \"number\" ? val : Number(val);\n if (!Number.isFinite(n)) {\n return null;\n }\n return Math.round(Math.min(100, Math.max(0, n)) * 10) / 10;\n}\n\nexport function sanitizeModelName(raw: unknown): string {\n if (typeof raw !== \"string\") {\n return \"unknown\";\n }\n const trimmed = raw.trim().replace(/@\\d{8}$/, \"\");\n // Reject anything that looks like a file path, email, or prompt text\n if (\n trimmed.includes(\"/\") ||\n trimmed.includes(\"\\\\\") ||\n trimmed.includes(\"@\") ||\n trimmed.includes(\" \") ||\n !SAFE_MODEL_RE.test(trimmed)\n ) {\n return \"unknown\";\n }\n return trimmed;\n}\n\nexport function sanitizeErrorCode(raw: unknown): string | null {\n if (raw === null || raw === undefined || raw === \"\") {\n return null;\n }\n const str = String(raw).trim().toUpperCase();\n if (SAFE_ERROR_CODE_RE.test(str)) {\n return str;\n }\n // Extract standard HTTP status code if embedded\n const httpMatch = str.match(/\\b(400|401|403|404|408|429|500|502|503|504)\\b/);\n if (httpMatch?.[1]) {\n return httpMatch[1];\n }\n return \"UNKNOWN_ERROR\";\n}\n\nexport function sanitizeAuthMode(raw: unknown): AuthMode {\n if (typeof raw === \"string\") {\n const normalized = raw.trim().toLowerCase() as AuthMode;\n if (ALLOWED_AUTH_MODES.has(normalized)) {\n return normalized;\n }\n }\n return \"unknown\";\n}\n\nfunction sanitizeIsoTimestamp(raw: unknown): string {\n if (typeof raw === \"string\") {\n const parsed = Date.parse(raw);\n if (!Number.isNaN(parsed)) {\n return new Date(parsed).toISOString();\n }\n }\n if (typeof raw === \"number\" && Number.isFinite(raw)) {\n const ms = raw > 1e12 ? raw : raw * 1000;\n return new Date(ms).toISOString();\n }\n return new Date().toISOString();\n}\n\n/**\n * Strictly constructs a whitelisted UsageRecord from an arbitrary AGY hook / statusline payload.\n * Any non-whitelisted field (prompt, response, code, file_path, project, workspace_dir, cwd, email, api_key, etc.)\n * is silently dropped and never serialized.\n * If workspace_dir or cwd is supplied, it is immediately hashed into project_hash and the original path is discarded.\n */\nexport function sanitizeUsagePayload(\n raw: Record<string, unknown>,\n salt: string,\n): UsageRecord {\n const ctx =\n raw.context_window && typeof raw.context_window === \"object\"\n ? (raw.context_window as Record<string, unknown>)\n : {};\n\n const providerRaw =\n typeof raw.provider === \"string\" ? raw.provider.toLowerCase() : \"antigravity\";\n const provider: UsageRecord[\"provider\"] = ALLOWED_PROVIDERS.has(providerRaw)\n ? (providerRaw as UsageRecord[\"provider\"])\n : \"antigravity\";\n\n const productRaw =\n typeof raw.product === \"string\" ? raw.product.toLowerCase() : \"agy\";\n const product: UsageRecord[\"product\"] = ALLOWED_PRODUCTS.has(productRaw)\n ? (productRaw as UsageRecord[\"product\"])\n : \"agy\";\n\n const sessionSource =\n typeof raw.session_hash === \"string\" && /^[a-f0-9]{8,16}$/.test(raw.session_hash)\n ? raw.session_hash\n : hashSessionId(\n typeof raw.session_hash === \"string\" && raw.session_hash.trim().length > 0\n ? raw.session_hash.trim()\n : typeof raw.session_id === \"string\" && raw.session_id.trim().length > 0\n ? raw.session_id.trim()\n : typeof raw.conversation_id === \"string\" && raw.conversation_id.trim().length > 0\n ? raw.conversation_id.trim()\n : \"default-session\",\n salt,\n );\n\n let projectHash: string | null = null;\n if (typeof raw.project_hash === \"string\" && /^[a-f0-9]{8,16}$/.test(raw.project_hash)) {\n projectHash = raw.project_hash;\n } else if (typeof raw.workspace_dir === \"string\" && raw.workspace_dir.trim().length > 0) {\n projectHash = hashProjectPath(raw.workspace_dir.trim(), salt);\n } else if (typeof raw.cwd === \"string\" && raw.cwd.trim().length > 0) {\n projectHash = hashProjectPath(raw.cwd.trim(), salt);\n }\n\n const inputTokens = clampNonNegativeInt(\n raw.input_tokens ?? ctx.input_tokens ?? raw.prompt_tokens ?? 0,\n );\n const cacheReadTokens = clampNonNegativeInt(\n raw.cache_read_tokens ??\n ctx.cache_read_tokens ??\n raw.cached_content_token_count ??\n 0,\n );\n const outputTokens = clampNonNegativeInt(\n raw.output_tokens ?? ctx.output_tokens ?? raw.completion_tokens ?? 0,\n );\n const thinkingTokens = clampNonNegativeInt(\n raw.thinking_tokens ?? ctx.thinking_tokens ?? raw.thoughts_token_count ?? 0,\n );\n const contextUsedPct = clampPct(\n raw.context_used_pct ?? ctx.used_pct ?? ctx.context_used_pct ?? null,\n );\n\n // Build strictly whitelisted object with exact keys\n return {\n v: 1,\n ts: sanitizeIsoTimestamp(raw.ts ?? raw.timestamp),\n provider,\n product,\n session_hash: sessionSource,\n model: sanitizeModelName(raw.model ?? ctx.model),\n input_tokens: inputTokens,\n cache_read_tokens: cacheReadTokens,\n output_tokens: outputTokens,\n thinking_tokens: thinkingTokens,\n context_used_pct: contextUsedPct,\n tool_calls: clampNonNegativeInt(raw.tool_calls ?? 0),\n turn_index: clampNonNegativeInt(raw.turn_index ?? 0),\n error_code: sanitizeErrorCode(raw.error_code ?? raw.status_code ?? null),\n project_hash: projectHash,\n auth_mode: sanitizeAuthMode(raw.auth_mode),\n data_quality:\n raw.data_quality === \"estimated_from_cli_log\"\n ? \"estimated_from_cli_log\"\n : \"exact\",\n };\n}\n","import type { ChannelRecommendedBehaviors } from \"./types.js\";\n\nexport type SupportedLocale = \"en\" | \"zh\";\nexport type LangOption = \"en\" | \"zh\" | \"auto\";\n\nfunction normalizeExplicitLang(raw: string | undefined): SupportedLocale | undefined {\n if (typeof raw !== \"string\") {\n return undefined;\n }\n const normalized = raw.trim().toLowerCase();\n if (!normalized || normalized === \"auto\") {\n return undefined;\n }\n if (normalized === \"zh\" || normalized.startsWith(\"zh-\") || normalized.startsWith(\"zh_\")) {\n return \"zh\";\n }\n if (normalized === \"en\" || normalized.startsWith(\"en-\") || normalized.startsWith(\"en_\")) {\n return \"en\";\n }\n return undefined;\n}\n\n/**\n * Resolve effective output locale.\n * Priority: explicit `lang` param > `AGYCRAFT_LANG` env > system `LC_ALL`/`LC_MESSAGES`/`LANG` > `\"en\"`.\n */\nexport function resolveLocale(\n explicitLang?: string,\n env: NodeJS.ProcessEnv = process.env,\n): SupportedLocale {\n const fromArg = normalizeExplicitLang(explicitLang);\n if (fromArg) {\n return fromArg;\n }\n\n const fromEnv = normalizeExplicitLang(env.AGYCRAFT_LANG);\n if (fromEnv) {\n return fromEnv;\n }\n\n const sysLocale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || \"\").trim().toLowerCase();\n if (sysLocale.includes(\"zh\")) {\n return \"zh\";\n }\n\n return \"en\";\n}\n\nfunction hasNonEmptyValue(val: unknown): boolean {\n if (typeof val === \"string\") {\n return val.trim().length > 0;\n }\n if (Array.isArray(val)) {\n return val.length > 0;\n }\n return val !== undefined && val !== null;\n}\n\n/**\n * Recursively localize snapshot/record objects:\n * - `\"en\"`: keeps primary English fields and strips all `*_zh` keys to reduce token overhead.\n * - `\"zh\"`: promotes non-empty `*_zh` keys onto their primary counterparts (falling back to primary) and strips `*_zh`.\n */\nexport function localizeSnapshotText<T>(value: T, locale: SupportedLocale): T {\n if (value === null || value === undefined || typeof value !== \"object\") {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => localizeSnapshotText(item, locale)) as unknown as T;\n }\n\n const record = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n\n for (const [key, val] of Object.entries(record)) {\n if (key.endsWith(\"_zh\")) {\n continue;\n }\n out[key] = localizeSnapshotText(val, locale);\n }\n\n if (locale === \"zh\") {\n for (const [key, val] of Object.entries(record)) {\n if (!key.endsWith(\"_zh\") || !hasNonEmptyValue(val)) {\n continue;\n }\n if (key === \"reset_rules_notes_zh\" && out.reset_rules && typeof out.reset_rules === \"object\") {\n (out.reset_rules as Record<string, unknown>).notes = val;\n continue;\n }\n const baseKey = key.slice(0, -3);\n if (baseKey === \"fix_steps\" && !(\"fix_steps\" in out) && \"steps\" in out) {\n out.steps = localizeSnapshotText(val, locale);\n } else {\n out[baseKey] = localizeSnapshotText(val, locale);\n }\n }\n }\n\n return out as T;\n}\n\nexport function localizeDiagnosisEntry<T>(entry: T, locale: SupportedLocale): T {\n return localizeSnapshotText(entry, locale);\n}\n\nexport function localizeModelEntry<T>(entry: T, locale: SupportedLocale): T {\n return localizeSnapshotText(entry, locale);\n}\n\nexport type LocalizedBehaviorKey =\n | \"thinking_guidance\"\n | \"kv_cache_guidance\"\n | \"throttling_guidance\"\n | \"background_spend_guidance\"\n | \"model_routing_guidance\";\n\nexport function getLocalizedBehavior(\n behaviors: ChannelRecommendedBehaviors | undefined,\n key: LocalizedBehaviorKey,\n locale: SupportedLocale,\n): string | undefined {\n if (!behaviors) {\n return undefined;\n }\n if (locale === \"zh\") {\n const zhKey = `${key}_zh` as keyof ChannelRecommendedBehaviors;\n const zhVal = behaviors[zhKey];\n if (typeof zhVal === \"string\" && zhVal.trim().length > 0) {\n return zhVal;\n }\n }\n const enVal = behaviors[key];\n return typeof enVal === \"string\" ? enVal : undefined;\n}\n","import { createHash } from \"node:crypto\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport {\n getAgyBrainDir,\n getAgyHistoryPath,\n isBrainScanDisabledValue,\n} from \"../paths.js\";\nimport {\n type UsageRecord,\n getOrCreateLocalSalt,\n hashProjectPath,\n sanitizeUsagePayload,\n} from \"../privacy.js\";\nimport {\n type CliLogAuthEvent,\n resolveAuthModeFromCliLogs,\n} from \"./cli-log.js\";\nimport type { AuthMode } from \"../types.js\";\n\n/**\n * Pure structural metadata extracted from an AGY transcript.jsonl.\n * PRIVACY RED LINE: NEVER reads, stores, or returns prompt text, assistant text,\n * tool arguments, file paths, or code snippets. Only counts structural events.\n */\nexport interface TranscriptStructuralMeta {\n total_steps: number;\n user_turns: number;\n assistant_turns: number;\n tool_call_count: number;\n tool_error_count: number;\n max_consecutive_tool_failures: number;\n consecutive_failure_tool_type: string | null;\n has_compact_event: boolean;\n steps_since_last_compact: number;\n loop_detected: boolean;\n redundant_read_file_count?: number;\n redundant_read_file_pct?: number;\n polling_dup_count?: number;\n polling_dup_rate_pct?: number;\n peak_input_tokens?: number;\n latest_input_tokens?: number;\n}\n\nconst SAFE_TOOL_NAME_RE = /^[a-zA-Z0-9._-]{1,48}$/;\nconst READ_FILE_TOOLS = new Set([\"read_file\", \"view_file\"]);\nconst WRITE_EDIT_TOOLS = new Set([\n \"edit_file\",\n \"write_file\",\n \"replace_file_content\",\n \"multi_replace_file_content\",\n \"mcp_agy-fast_fast_apply_edits\",\n]);\n\nfunction hashOpaqueValue(raw: string): string {\n return createHash(\"sha256\").update(raw).digest(\"hex\");\n}\n\nfunction stableSerialize(val: unknown): string {\n if (val === null || val === undefined) {\n return \"null\";\n }\n if (typeof val !== \"object\") {\n return JSON.stringify(val);\n }\n if (Array.isArray(val)) {\n return `[${val.map((item) => stableSerialize(item)).join(\",\")}]`;\n }\n const obj = val as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${stableSerialize(obj[k])}`).join(\",\")}}`;\n}\n\nfunction parseMaybeJsonArgs(raw: unknown): unknown {\n if (typeof raw === \"string\") {\n const trimmed = raw.trim();\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return raw;\n }\n }\n }\n return raw ?? null;\n}\n\nfunction extractFilePathsFromArgs(args: unknown): string[] {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) {\n return [];\n }\n const obj = args as Record<string, unknown>;\n const paths: string[] = [];\n for (const key of [\n \"Path\",\n \"path\",\n \"file_path\",\n \"AbsolutePath\",\n \"target_file\",\n \"TargetFile\",\n \"file\",\n ]) {\n const val = obj[key];\n if (typeof val === \"string\" && val.trim().length > 0) {\n paths.push(val.trim());\n }\n }\n if (Array.isArray(obj.edits)) {\n for (const item of obj.edits) {\n if (item && typeof item === \"object\") {\n const itemObj = item as Record<string, unknown>;\n const p = itemObj.path ?? itemObj.file_path ?? itemObj.Path;\n if (typeof p === \"string\" && p.trim().length > 0) {\n paths.push(p.trim());\n }\n }\n }\n }\n return paths;\n}\n\nfunction sanitizeToolCategory(raw: unknown): string {\n if (typeof raw !== \"string\") {\n return \"unknown_tool\";\n }\n const trimmed = raw.trim();\n if (SAFE_TOOL_NAME_RE.test(trimmed)) {\n return trimmed;\n }\n return \"unknown_tool\";\n}\n\n/**\n * Parses a transcript.jsonl file strictly for structural counters.\n * Never accesses or retains message content/text/arguments/paths.\n */\nexport async function analyzeTranscriptStructure(\n transcriptPath: string,\n loopThreshold = 4,\n): Promise<TranscriptStructuralMeta> {\n let rawText: string;\n try {\n rawText = await readFile(transcriptPath, \"utf8\");\n } catch {\n return emptyTranscriptMeta();\n }\n return parseTranscriptLines(rawText.split(\"\\n\"), loopThreshold);\n}\n\nexport function parseTranscriptLines(\n lines: string[],\n loopThreshold = 4,\n): TranscriptStructuralMeta {\n let totalSteps = 0;\n let userTurns = 0;\n let assistantTurns = 0;\n let toolCallCount = 0;\n let toolErrorCount = 0;\n let hasCompactEvent = false;\n let stepsSinceLastCompact = 0;\n\n let currentStreak = 0;\n let currentStreakTool: string | null = null;\n let maxConsecutiveFailures = 0;\n let maxFailureTool: string | null = null;\n\n const seenReadFileHashes = new Set<string>();\n const seenToolCallHashes = new Set<string>();\n let readFileCount = 0;\n let redundantReadFileCount = 0;\n let pollingDupCount = 0;\n let peakInputTokens = 0;\n let latestInputTokens = 0;\n\n const trackToolRedundancy = (toolName: string, rawArgs: unknown): void => {\n const parsedArgs = parseMaybeJsonArgs(rawArgs);\n const sigHash = hashOpaqueValue(`${toolName}\\0${stableSerialize(parsedArgs)}`);\n if (seenToolCallHashes.has(sigHash)) {\n pollingDupCount += 1;\n } else {\n seenToolCallHashes.add(sigHash);\n }\n\n if (READ_FILE_TOOLS.has(toolName)) {\n readFileCount += 1;\n const paths = extractFilePathsFromArgs(parsedArgs);\n if (paths.length > 0) {\n let anyRedundant = false;\n for (const p of paths) {\n const ph = hashOpaqueValue(p);\n if (seenReadFileHashes.has(ph)) {\n anyRedundant = true;\n } else {\n seenReadFileHashes.add(ph);\n }\n }\n if (anyRedundant) {\n redundantReadFileCount += 1;\n }\n }\n } else if (WRITE_EDIT_TOOLS.has(toolName)) {\n const paths = extractFilePathsFromArgs(parsedArgs);\n for (const p of paths) {\n seenReadFileHashes.delete(hashOpaqueValue(p));\n }\n }\n };\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n totalSteps += 1;\n stepsSinceLastCompact += 1;\n\n const role = typeof parsed.role === \"string\" ? parsed.role.toLowerCase() : \"\";\n const eventType =\n typeof parsed.type === \"string\" ? parsed.type.toLowerCase() : \"\";\n const source =\n typeof parsed.source === \"string\" ? parsed.source.toUpperCase() : \"\";\n\n if (eventType === \"compact\" || eventType === \"compaction\") {\n hasCompactEvent = true;\n stepsSinceLastCompact = 0;\n seenReadFileHashes.clear();\n continue;\n }\n\n const usageObj =\n parsed.usage && typeof parsed.usage === \"object\" && !Array.isArray(parsed.usage)\n ? (parsed.usage as Record<string, unknown>)\n : {};\n const stepInput = firstNonNegInt(\n parsed.input_tokens,\n usageObj.input_tokens,\n usageObj.prompt_tokens,\n );\n const stepCacheRead = firstNonNegInt(\n parsed.cache_read_tokens,\n usageObj.cache_read_tokens,\n usageObj.cached_content_token_count,\n );\n const stepTotalInput = stepInput + stepCacheRead;\n if (stepTotalInput > 0) {\n latestInputTokens = stepTotalInput;\n if (stepTotalInput > peakInputTokens) {\n peakInputTokens = stepTotalInput;\n }\n }\n\n if (\n role === \"user\" ||\n eventType === \"user_message\" ||\n eventType === \"user_input\" ||\n source === \"USER_EXPLICIT\"\n ) {\n userTurns += 1;\n // Human intervention resets autonomous failure streak\n currentStreak = 0;\n currentStreakTool = null;\n } else if (\n role === \"assistant\" ||\n role === \"model\" ||\n eventType === \"assistant_message\" ||\n eventType === \"planner_response\"\n ) {\n assistantTurns += 1;\n }\n\n if (Array.isArray(parsed.tool_calls)) {\n toolCallCount += parsed.tool_calls.length;\n for (const tc of parsed.tool_calls) {\n if (!tc || typeof tc !== \"object\") {\n continue;\n }\n const tcObj = tc as Record<string, unknown>;\n const toolName = sanitizeToolCategory(tcObj.tool_name ?? tcObj.name);\n trackToolRedundancy(\n toolName,\n tcObj.arguments ?? tcObj.args ?? tcObj.input ?? tcObj.params,\n );\n const failed =\n tcObj.is_error === true ||\n tcObj.status === \"error\" ||\n tcObj.status === \"failed\" ||\n (typeof tcObj.exit_code === \"number\" && tcObj.exit_code !== 0);\n if (failed) {\n toolErrorCount += 1;\n if (currentStreakTool === toolName) {\n currentStreak += 1;\n } else {\n currentStreak = 1;\n currentStreakTool = toolName;\n }\n if (currentStreak > maxConsecutiveFailures) {\n maxConsecutiveFailures = currentStreak;\n maxFailureTool = toolName;\n }\n } else {\n currentStreak = 0;\n currentStreakTool = null;\n }\n }\n } else if (typeof parsed.tool_calls === \"number\" && Number.isFinite(parsed.tool_calls)) {\n toolCallCount += Math.max(0, Math.floor(parsed.tool_calls));\n }\n\n const isToolEvent =\n role === \"tool\" ||\n eventType === \"tool_call\" ||\n eventType === \"tool_result\" ||\n Boolean(parsed.tool_name);\n\n if (isToolEvent) {\n toolCallCount += 1;\n const toolName = sanitizeToolCategory(parsed.tool_name ?? parsed.name);\n trackToolRedundancy(\n toolName,\n parsed.arguments ?? parsed.args ?? parsed.input ?? parsed.params,\n );\n const failed =\n parsed.is_error === true ||\n parsed.status === \"error\" ||\n parsed.status === \"failed\" ||\n (typeof parsed.exit_code === \"number\" && parsed.exit_code !== 0);\n\n if (failed) {\n toolErrorCount += 1;\n if (currentStreakTool === toolName) {\n currentStreak += 1;\n } else {\n currentStreak = 1;\n currentStreakTool = toolName;\n }\n if (currentStreak > maxConsecutiveFailures) {\n maxConsecutiveFailures = currentStreak;\n maxFailureTool = toolName;\n }\n } else {\n currentStreak = 0;\n currentStreakTool = null;\n }\n }\n }\n\n return {\n total_steps: totalSteps,\n user_turns: userTurns,\n assistant_turns: assistantTurns,\n tool_call_count: toolCallCount,\n tool_error_count: toolErrorCount,\n max_consecutive_tool_failures: maxConsecutiveFailures,\n consecutive_failure_tool_type: maxFailureTool,\n has_compact_event: hasCompactEvent,\n steps_since_last_compact: stepsSinceLastCompact,\n loop_detected: maxConsecutiveFailures >= loopThreshold,\n redundant_read_file_count: redundantReadFileCount,\n redundant_read_file_pct:\n readFileCount > 0\n ? Math.round((redundantReadFileCount / readFileCount) * 1000) / 10\n : 0,\n polling_dup_count: pollingDupCount,\n polling_dup_rate_pct:\n toolCallCount > 0\n ? Math.round((pollingDupCount / toolCallCount) * 1000) / 10\n : 0,\n peak_input_tokens: peakInputTokens,\n latest_input_tokens: latestInputTokens,\n };\n}\n\nexport function emptyTranscriptMeta(): TranscriptStructuralMeta {\n return {\n total_steps: 0,\n user_turns: 0,\n assistant_turns: 0,\n tool_call_count: 0,\n tool_error_count: 0,\n max_consecutive_tool_failures: 0,\n consecutive_failure_tool_type: null,\n has_compact_event: false,\n steps_since_last_compact: 0,\n loop_detected: false,\n redundant_read_file_count: 0,\n redundant_read_file_pct: 0,\n polling_dup_count: 0,\n polling_dup_rate_pct: 0,\n peak_input_tokens: 0,\n latest_input_tokens: 0,\n };\n}\n\nexport interface TranscriptWindowSummary {\n session_count: number;\n turn_count: number;\n tool_call_count: number;\n earliest_turn_at: string | null;\n}\n\nexport interface TranscriptActivityFallback {\n source: \"transcript_timestamps\";\n note: string;\n timezone: string;\n window_5h: TranscriptWindowSummary & {\n estimated_5h_reset_at: string | null;\n estimated_5h_reset_local: string | null;\n };\n window_7d: TranscriptWindowSummary;\n earliest_turn_5h_ms: number | null;\n earliest_turn_7d_ms: number | null;\n}\n\nexport function extractStructuralTimestampMs(\n parsed: Record<string, unknown>,\n): number | null {\n const raw = parsed.created_at ?? parsed.timestamp ?? parsed.ts;\n if (typeof raw === \"string\") {\n const ms = Date.parse(raw);\n return Number.isNaN(ms) ? null : ms;\n }\n if (typeof raw === \"number\" && Number.isFinite(raw)) {\n return raw > 1e12 ? raw : raw * 1000;\n }\n return null;\n}\n\nfunction formatLocalIsoish(ms: number, timezone?: string): string {\n const tz = timezone || Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n try {\n return new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(new Date(ms));\n } catch {\n return new Date(ms).toISOString();\n }\n}\n\n/**\n * Scans ~/.gemini/antigravity-cli/brain/<session>/.system_generated/logs/transcript.jsonl\n * strictly for structural timestamps, step/turn counts, and tool-call indicators.\n * PRIVACY RED LINE: NEVER reads, stores, or returns prompt text, model responses,\n * code diffs, file paths, or session UUIDs.\n */\nexport async function scanTranscriptActivity(options?: {\n brainDir?: string;\n nowMs?: number;\n timezone?: string;\n}): Promise<TranscriptActivityFallback> {\n const explicitBrainDir = options?.brainDir;\n let brainDir: string | null;\n if (explicitBrainDir !== undefined) {\n const trimmed = explicitBrainDir.trim();\n brainDir =\n trimmed.length === 0 || isBrainScanDisabledValue(trimmed)\n ? null\n : resolve(trimmed);\n } else {\n brainDir = getAgyBrainDir();\n }\n\n const nowMs = options?.nowMs ?? Date.now();\n const tz = options?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n\n const cutoff5h = nowMs - 5 * 3600 * 1000;\n const cutoff7d = nowMs - 7 * 86400 * 1000;\n\n let sessions5h = 0;\n let turns5h = 0;\n let tools5h = 0;\n let earliest5h: number | null = null;\n\n let sessions7d = 0;\n let turns7d = 0;\n let tools7d = 0;\n let earliest7d: number | null = null;\n\n let sessionDirs: string[] = [];\n if (brainDir !== null) {\n try {\n const entries = await readdir(brainDir, { withFileTypes: true });\n sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch {\n sessionDirs = [];\n }\n }\n\n for (const dirName of sessionDirs) {\n const transcriptPath = join(brainDir!, dirName, \".system_generated\", \"logs\", \"transcript.jsonl\");\n let rawText: string;\n try {\n rawText = await readFile(transcriptPath, \"utf8\");\n } catch {\n continue;\n }\n\n let seenIn5h = false;\n let seenIn7d = false;\n\n for (const line of rawText.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n const tsMs = extractStructuralTimestampMs(parsed);\n if (tsMs === null || tsMs < cutoff7d || tsMs > nowMs + 60_000) {\n continue;\n }\n\n const typeStr = typeof parsed.type === \"string\" ? parsed.type.toUpperCase() : \"\";\n const sourceStr = typeof parsed.source === \"string\" ? parsed.source.toUpperCase() : \"\";\n const roleStr = typeof parsed.role === \"string\" ? parsed.role.toLowerCase() : \"\";\n\n const isTurn =\n typeStr === \"USER_INPUT\" ||\n typeStr === \"PLANNER_RESPONSE\" ||\n typeStr === \"USER_MESSAGE\" ||\n typeStr === \"ASSISTANT_MESSAGE\" ||\n sourceStr === \"USER_EXPLICIT\" ||\n sourceStr === \"MODEL\" ||\n roleStr === \"user\" ||\n roleStr === \"assistant\" ||\n roleStr === \"model\" ||\n typeof parsed.step_index === \"number\";\n\n const isTool =\n typeStr === \"TOOL_CALL\" ||\n typeStr === \"TOOL_RESULT\" ||\n roleStr === \"tool\" ||\n Boolean(parsed.tool_name);\n\n if (tsMs >= cutoff7d) {\n seenIn7d = true;\n if (isTurn) turns7d += 1;\n if (isTool) tools7d += 1;\n if (earliest7d === null || tsMs < earliest7d) {\n earliest7d = tsMs;\n }\n }\n\n if (tsMs >= cutoff5h) {\n seenIn5h = true;\n if (isTurn) turns5h += 1;\n if (isTool) tools5h += 1;\n if (earliest5h === null || tsMs < earliest5h) {\n earliest5h = tsMs;\n }\n }\n }\n\n if (seenIn5h) sessions5h += 1;\n if (seenIn7d) sessions7d += 1;\n }\n\n const reset5hMs = earliest5h !== null ? earliest5h + 5 * 3600 * 1000 : null;\n\n return {\n source: \"transcript_timestamps\",\n note: \"Estimated from local AGY session timestamps; run agycraft-mcp setup for exact token counts.\",\n timezone: tz,\n window_5h: {\n session_count: sessions5h,\n turn_count: turns5h,\n tool_call_count: tools5h,\n earliest_turn_at: earliest5h !== null ? new Date(earliest5h).toISOString() : null,\n estimated_5h_reset_at: reset5hMs !== null ? new Date(reset5hMs).toISOString() : null,\n estimated_5h_reset_local: reset5hMs !== null ? formatLocalIsoish(reset5hMs, tz) : null,\n },\n window_7d: {\n session_count: sessions7d,\n turn_count: turns7d,\n tool_call_count: tools7d,\n earliest_turn_at: earliest7d !== null ? new Date(earliest7d).toISOString() : null,\n },\n earliest_turn_5h_ms: earliest5h,\n earliest_turn_7d_ms: earliest7d,\n };\n}\n\n/**\n * Builds a Map<conversationId, project_hash> from AGY history.jsonl.\n * PRIVACY RED LINE:\n * - NEVER reads, stores, or returns `display` or any prompt/user text.\n * - Immediately hashes `workspace` with local `.salt` and discards the raw path.\n */\nexport async function buildConversationProjectIndex(\n historyPath: string | null,\n salt: string,\n): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n if (!historyPath) {\n return index;\n }\n\n let rawText: string;\n try {\n rawText = await readFile(historyPath, \"utf8\");\n } catch {\n return index;\n }\n\n for (const line of rawText.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n const convId =\n typeof parsed.conversationId === \"string\" ? parsed.conversationId.trim() : \"\";\n const workspace =\n typeof parsed.workspace === \"string\" ? parsed.workspace.trim() : \"\";\n if (convId.length > 0 && workspace.length > 0) {\n index.set(convId, hashProjectPath(workspace, salt));\n }\n } catch {\n // Skip malformed JSONL lines safely\n }\n }\n\n return index;\n}\n\nexport interface CollectTranscriptUsageOptions {\n brainDir?: string | null;\n historyPath?: string | null;\n salt?: string;\n saltPath?: string;\n sinceMs?: number;\n nowMs?: number;\n authMode?: AuthMode;\n cliLogEvents?: CliLogAuthEvent[];\n hasMixedAuth?: boolean;\n}\n\nexport interface TranscriptUsageCollection {\n records: UsageRecord[];\n attributed_session_count: number;\n unattributed_session_count: number;\n}\n\nfunction firstNonNegInt(...candidates: unknown[]): number {\n for (const val of candidates) {\n if (val === null || val === undefined || val === \"\") {\n continue;\n }\n const n = typeof val === \"number\" ? val : Number(val);\n if (Number.isFinite(n) && n >= 0) {\n return Math.floor(n);\n }\n }\n return 0;\n}\n\nfunction resolveOptionalPath(\n explicit: string | null | undefined,\n fallbackFn: () => string | null,\n): string | null {\n if (explicit === null) {\n return null;\n }\n if (explicit !== undefined) {\n const trimmed = explicit.trim();\n if (trimmed.length === 0 || isBrainScanDisabledValue(trimmed)) {\n return null;\n }\n return resolve(trimmed);\n }\n return fallbackFn();\n}\n\n/**\n * Extracts real token & model usage records from AGY brain transcript.jsonl files\n * (e.g. PLANNER_RESPONSE events) and attributes each session to its hashed workspace via history.jsonl.\n * Unattributed derived/subagent sessions receive `project_hash: null` and are counted in `unattributed_session_count`.\n */\nexport function isPlaceholderOrUnknownModel(raw: unknown): boolean {\n if (typeof raw !== \"string\") return true;\n const trimmed = raw.trim();\n if (!trimmed) return true;\n const upper = trimmed.toUpperCase();\n return upper === \"UNKNOWN\" || upper.startsWith(\"MODEL_PLACEHOLDER_\");\n}\n\nexport function extractTranscriptExplicitModel(\n parsed: Record<string, unknown>,\n usageObj: Record<string, unknown>,\n): string | null {\n const raw = parsed.model ?? usageObj.model;\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n if (!trimmed || trimmed.toLowerCase() === \"unknown\") return null;\n return trimmed;\n}\n\nexport async function collectTranscriptUsageRecords(\n options?: CollectTranscriptUsageOptions,\n): Promise<TranscriptUsageCollection> {\n const brainDir = resolveOptionalPath(options?.brainDir, getAgyBrainDir);\n const historyPath = resolveOptionalPath(options?.historyPath, getAgyHistoryPath);\n const salt = options?.salt ?? (await getOrCreateLocalSalt(options?.saltPath));\n const nowMs = options?.nowMs ?? Date.now();\n const sinceMs = options?.sinceMs;\n\n const projectIndex = await buildConversationProjectIndex(historyPath, salt);\n\n const records: UsageRecord[] = [];\n let attributedSessionCount = 0;\n let unattributedSessionCount = 0;\n\n if (brainDir === null) {\n return {\n records,\n attributed_session_count: 0,\n unattributed_session_count: 0,\n };\n }\n\n let sessionDirs: string[] = [];\n try {\n const entries = await readdir(brainDir, { withFileTypes: true });\n sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch {\n return {\n records,\n attributed_session_count: 0,\n unattributed_session_count: 0,\n };\n }\n\n for (const sessionId of sessionDirs) {\n const transcriptPath = join(\n brainDir,\n sessionId,\n \".system_generated\",\n \"logs\",\n \"transcript.jsonl\",\n );\n let rawText: string;\n try {\n rawText = await readFile(transcriptPath, \"utf8\");\n } catch {\n continue;\n }\n\n const projectHash = projectIndex.get(sessionId) ?? null;\n let sessionHadRecord = false;\n\n const parsedEvents: Record<string, unknown>[] = [];\n const modelFreq = new Map<string, number>();\n\n for (const line of rawText.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n parsedEvents.push(parsed);\n\n const uObj =\n parsed.usage && typeof parsed.usage === \"object\" && !Array.isArray(parsed.usage)\n ? (parsed.usage as Record<string, unknown>)\n : {};\n const typeUpper = typeof parsed.type === \"string\" ? parsed.type.toUpperCase() : \"\";\n const explicitModel = extractTranscriptExplicitModel(parsed, uObj);\n if (\n typeUpper !== \"CHECKPOINT\" &&\n explicitModel !== null &&\n !isPlaceholderOrUnknownModel(explicitModel)\n ) {\n modelFreq.set(explicitModel, (modelFreq.get(explicitModel) ?? 0) + 1);\n }\n }\n\n let dominantModel: string | null = null;\n let dominantCount = 0;\n for (const [m, count] of modelFreq.entries()) {\n if (count > dominantCount) {\n dominantCount = count;\n dominantModel = m;\n }\n }\n\n let lastSeenModel: string | null = null;\n\n for (const parsed of parsedEvents) {\n const usageObj =\n parsed.usage && typeof parsed.usage === \"object\" && !Array.isArray(parsed.usage)\n ? (parsed.usage as Record<string, unknown>)\n : {};\n const typeStr = typeof parsed.type === \"string\" ? parsed.type.toUpperCase() : \"\";\n const explicitModel = extractTranscriptExplicitModel(parsed, usageObj);\n\n if (\n typeStr !== \"CHECKPOINT\" &&\n explicitModel !== null &&\n !isPlaceholderOrUnknownModel(explicitModel)\n ) {\n lastSeenModel = explicitModel;\n }\n\n const tsMs = extractStructuralTimestampMs(parsed);\n if (tsMs === null || tsMs > nowMs + 60_000) {\n continue;\n }\n if (sinceMs !== undefined && tsMs < sinceMs) {\n continue;\n }\n\n const rawInput = firstNonNegInt(\n parsed.input_tokens,\n usageObj.input_tokens,\n usageObj.prompt_tokens,\n );\n const rawCacheRead = firstNonNegInt(\n parsed.cache_read_tokens,\n usageObj.cache_read_tokens,\n usageObj.cached_content_token_count,\n );\n const rawOutput = firstNonNegInt(\n parsed.output_tokens,\n usageObj.output_tokens,\n usageObj.completion_tokens,\n );\n\n const totalInput = rawInput + rawCacheRead;\n if (\n typeStr !== \"PLANNER_RESPONSE\" &&\n totalInput === 0 &&\n rawOutput === 0\n ) {\n continue;\n }\n if (totalInput === 0 && rawOutput === 0) {\n continue;\n }\n\n const attributedModel =\n typeStr === \"CHECKPOINT\" || !explicitModel\n ? (lastSeenModel ?? dominantModel ?? \"unknown\")\n : explicitModel;\n\n const resolvedAuthMode =\n (options?.cliLogEvents && options.cliLogEvents.length > 0) ||\n options?.hasMixedAuth\n ? resolveAuthModeFromCliLogs(options?.cliLogEvents ?? [], tsMs, {\n fallbackAuthMode: options?.authMode ?? \"unknown\",\n hasMixedAuth: options?.hasMixedAuth,\n })\n : (options?.authMode ?? \"unknown\");\n\n const record = sanitizeUsagePayload(\n {\n ts: new Date(tsMs).toISOString(),\n provider: \"antigravity\",\n product: \"agy\",\n session_id: sessionId,\n model: attributedModel,\n input_tokens: rawInput,\n cache_read_tokens: rawCacheRead,\n output_tokens: rawOutput,\n thinking_tokens: 0,\n tool_calls: 0,\n turn_index: typeof parsed.step_index === \"number\" ? parsed.step_index : 0,\n project_hash: projectHash,\n auth_mode: resolvedAuthMode,\n },\n salt,\n );\n\n records.push(record);\n sessionHadRecord = true;\n }\n\n if (sessionHadRecord) {\n if (projectHash !== null) {\n attributedSessionCount += 1;\n } else {\n unattributedSessionCount += 1;\n }\n }\n }\n\n return {\n records,\n attributed_session_count: attributedSessionCount,\n unattributed_session_count: unattributedSessionCount,\n };\n}\n","import type { SupportedLocale } from \"../i18n.js\";\n\nexport type LifecycleAction =\n | \"HOLD_CACHE\"\n | \"SUGGEST_COMPACT\"\n | \"SUGGEST_NEW_SESSION\"\n | \"URGENT_ROTATE\";\n\nexport type LifecycleReasonCode =\n | \"BELOW_THRESHOLD\"\n | \"WARM_CACHE_HOLD\"\n | \"LATENCY_INFLECTION_COMPACT\"\n | \"CACHE_EXPIRED_NEW_SESSION\"\n | \"HIGH_WATERMARK_NEW_SESSION\"\n | \"CRITICAL_CEILING_OR_ERROR\";\n\nexport interface SessionLifecycleMetrics {\n session_hash: string;\n is_interactive: boolean;\n planner_turns_since_compact: number;\n current_input_tokens: number;\n recent_cache_hit_pct: number;\n idle_gap_sec: number;\n recent_429_count: number;\n recent_overflow_count: number;\n model_context_limit: number;\n has_recent_compact?: boolean;\n previous_input_tokens?: number;\n}\n\nexport interface SessionLifecycleDecision {\n action: LifecycleAction;\n reason_code: LifecycleReasonCode;\n should_notify: boolean;\n message?: string;\n cooldown_until_turn?: number;\n subagent_anomaly?: boolean;\n reset_applied?: boolean;\n}\n\nexport interface AlertCooldownState {\n last_action: LifecycleAction;\n last_notified_turn: number;\n last_notified_ms: number;\n last_notified_tokens: number;\n last_observed_tokens?: number;\n}\n\nexport interface EvaluateLifecycleOptions {\n nowMs?: number;\n locale?: SupportedLocale;\n}\n\nconst ACTION_RANK: Record<LifecycleAction, number> = {\n HOLD_CACHE: 0,\n SUGGEST_COMPACT: 1,\n SUGGEST_NEW_SESSION: 2,\n URGENT_ROTATE: 3,\n};\n\nconst COOLDOWN_TURNS: Record<Exclude<LifecycleAction, \"HOLD_CACHE\">, number> = {\n SUGGEST_COMPACT: 15,\n SUGGEST_NEW_SESSION: 10,\n URGENT_ROTATE: 3,\n};\n\nfunction formatTokensK(tokens: number): string {\n if (tokens >= 1000) {\n return `${Math.round(tokens / 1000)}K`;\n }\n return `${tokens}`;\n}\n\nexport function formatLifecycleAdvice(\n action: LifecycleAction,\n reason: LifecycleReasonCode,\n m: SessionLifecycleMetrics,\n locale: SupportedLocale = \"zh\",\n): string | undefined {\n if (action === \"HOLD_CACHE\") {\n return undefined;\n }\n\n const cLabel = formatTokensK(m.current_input_tokens);\n const hitLabel = `${Math.round(m.recent_cache_hit_pct * 10) / 10}%`;\n\n if (locale === \"zh\") {\n switch (action) {\n case \"SUGGEST_COMPACT\":\n return `[agycraft] 当前上下文已达 ${cLabel} (KV 命中 ${hitLabel}),已跨过 150K 延迟拐点;建议在当前阶段收尾后运行 /compact(避免中断热缓存)。`;\n case \"SUGGEST_NEW_SESSION\":\n return reason === \"CACHE_EXPIRED_NEW_SESSION\"\n ? `[agycraft] 上下文 ${cLabel} 且 KV 缓存已冷 (空闲 ${Math.round(m.idle_gap_sec)}s / 命中 ${hitLabel});建议总结当前结论后新开会话,避免冷启动全额计费。`\n : `[agycraft] 上下文已达 ${cLabel} (≥240K 高水位);建议总结交接摘要后新开会话,比继续续聊或压缩更省 Token。`;\n case \"URGENT_ROTATE\":\n return `[agycraft] 高优告警:上下文 ${cLabel} 已触及硬上限或限流/溢出风险 (${m.recent_429_count}x 429, ${m.recent_overflow_count}x overflow),请立即 /compact 或导出状态新开会话止损。`;\n }\n }\n\n switch (action) {\n case \"SUGGEST_COMPACT\":\n return `[agycraft] Context reached ${cLabel} (KV cache hit ${hitLabel}), past the 150K latency inflection; run /compact at the next phase milestone to preserve warm cache.`;\n case \"SUGGEST_NEW_SESSION\":\n return reason === \"CACHE_EXPIRED_NEW_SESSION\"\n ? `[agycraft] Context is ${cLabel} with cold KV cache (idle ${Math.round(m.idle_gap_sec)}s / hit ${hitLabel}); start a new session with a short summary to avoid cold-start re-billing.`\n : `[agycraft] Context reached ${cLabel} (>=240K high watermark); start a new session with a brief handoff summary instead of snowballing.`;\n case \"URGENT_ROTATE\":\n return `[agycraft] URGENT: Context ${cLabel} hit critical ceiling or 429/overflow risk (${m.recent_429_count}x 429, ${m.recent_overflow_count}x overflow); /compact or rotate to a new session immediately.`;\n }\n}\n\nexport function evaluateSessionLifecycle(\n m: SessionLifecycleMetrics,\n prevState?: AlertCooldownState,\n nowMsOrOptions: number | EvaluateLifecycleOptions = Date.now(),\n): { decision: SessionLifecycleDecision; nextState: AlertCooldownState } {\n const nowMs =\n typeof nowMsOrOptions === \"number\"\n ? nowMsOrOptions\n : (nowMsOrOptions.nowMs ?? Date.now());\n const locale: SupportedLocale =\n typeof nowMsOrOptions === \"number\"\n ? \"zh\"\n : (nowMsOrOptions.locale ?? \"zh\");\n\n const c = Math.max(0, m.current_input_tokens);\n const h = Math.max(0, Math.min(100, m.recent_cache_hit_pct));\n const idle = Math.max(0, m.idle_gap_sec);\n const ceilingRatio = m.model_context_limit > 0 ? c / m.model_context_limit : 0;\n\n // Detect compaction or >=40% context drop -> reset state machine & cooldowns\n const prevTokens =\n m.previous_input_tokens ??\n prevState?.last_observed_tokens ??\n prevState?.last_notified_tokens ??\n 0;\n const dropped40Pct = prevTokens > 0 && (prevTokens - c) / prevTokens >= 0.4;\n const resetApplied = Boolean(m.has_recent_compact || dropped40Pct);\n const effectivePrevState = resetApplied ? undefined : prevState;\n\n let action: LifecycleAction = \"HOLD_CACHE\";\n let reason: LifecycleReasonCode = \"BELOW_THRESHOLD\";\n\n // 1. Highest priority: critical ceiling (>=360K or >=70% window), overflow, or large-context 429\n if (\n c >= 360_000 ||\n ceilingRatio >= 0.7 ||\n m.recent_overflow_count > 0 ||\n (m.recent_429_count > 0 && c >= 140_000)\n ) {\n action = \"URGENT_ROTATE\";\n reason = \"CRITICAL_CEILING_OR_ERROR\";\n }\n // 2. High watermark (>=240K) or cold cache (>=100K with >=300s idle or <50% hit) -> new session\n else if (c >= 240_000) {\n action = \"SUGGEST_NEW_SESSION\";\n reason = \"HIGH_WATERMARK_NEW_SESSION\";\n } else if (c >= 100_000 && (idle >= 300 || h < 50)) {\n action = \"SUGGEST_NEW_SESSION\";\n reason = \"CACHE_EXPIRED_NEW_SESSION\";\n }\n // 3. Latency inflection (160K-240K) with warm cache (>=85%, idle < 300s) & >=30 planner turns -> /compact\n else if (c >= 160_000 && h >= 85 && idle < 300 && m.planner_turns_since_compact >= 30) {\n action = \"SUGGEST_COMPACT\";\n reason = \"LATENCY_INFLECTION_COMPACT\";\n }\n // 4. Hysteresis: stay in SUGGEST_COMPACT between 120K and 160K until dropping below 120K\n else if (\n effectivePrevState?.last_action === \"SUGGEST_COMPACT\" &&\n c >= 120_000 &&\n c < 160_000\n ) {\n action = \"SUGGEST_COMPACT\";\n reason = \"LATENCY_INFLECTION_COMPACT\";\n } else if (c >= 120_000 && h >= 90 && idle < 300) {\n action = \"HOLD_CACHE\";\n reason = \"WARM_CACHE_HOLD\";\n }\n\n // Subagent silent policy: never suggest /compact for non-interactive sessions;\n // only surface URGENT_ROTATE, and flag >=200K subagents as anomaly.\n const subagentAnomaly = !m.is_interactive && c >= 200_000;\n if (!m.is_interactive && action !== \"URGENT_ROTATE\") {\n action = \"HOLD_CACHE\";\n reason =\n c >= 120_000 && h >= 90 && idle < 300 ? \"WARM_CACHE_HOLD\" : \"BELOW_THRESHOLD\";\n }\n\n // Cooldown & deduplication\n const turnGap =\n m.planner_turns_since_compact -\n (effectivePrevState?.last_notified_turn ?? -999);\n const secGap = (nowMs - (effectivePrevState?.last_notified_ms ?? 0)) / 1000;\n const upgraded = effectivePrevState\n ? ACTION_RANK[action] > ACTION_RANK[effectivePrevState.last_action]\n : action !== \"HOLD_CACHE\";\n\n let shouldNotify = false;\n if (action !== \"HOLD_CACHE\") {\n if (upgraded) {\n shouldNotify = true;\n } else if (action === \"URGENT_ROTATE\" && turnGap >= COOLDOWN_TURNS.URGENT_ROTATE) {\n shouldNotify = true;\n } else if (\n action === \"SUGGEST_NEW_SESSION\" &&\n turnGap >= COOLDOWN_TURNS.SUGGEST_NEW_SESSION &&\n secGap >= 300\n ) {\n shouldNotify = true;\n } else if (\n action === \"SUGGEST_COMPACT\" &&\n turnGap >= COOLDOWN_TURNS.SUGGEST_COMPACT &&\n secGap >= 600\n ) {\n shouldNotify = true;\n }\n }\n\n const nextState: AlertCooldownState = shouldNotify\n ? {\n last_action: action,\n last_notified_turn: m.planner_turns_since_compact,\n last_notified_ms: nowMs,\n last_notified_tokens: c,\n last_observed_tokens: c,\n }\n : {\n last_action: action,\n last_notified_turn: effectivePrevState?.last_notified_turn ?? 0,\n last_notified_ms: effectivePrevState?.last_notified_ms ?? 0,\n last_notified_tokens: effectivePrevState?.last_notified_tokens ?? 0,\n last_observed_tokens: c,\n };\n\n const cooldownUntilTurn =\n action !== \"HOLD_CACHE\"\n ? (shouldNotify\n ? m.planner_turns_since_compact\n : (effectivePrevState?.last_notified_turn ?? m.planner_turns_since_compact)) +\n COOLDOWN_TURNS[action]\n : undefined;\n\n return {\n decision: {\n action,\n reason_code: reason,\n should_notify: shouldNotify,\n ...(shouldNotify\n ? { message: formatLifecycleAdvice(action, reason, m, locale) }\n : {}),\n ...(cooldownUntilTurn !== undefined\n ? { cooldown_until_turn: cooldownUntilTurn }\n : {}),\n ...(subagentAnomaly ? { subagent_anomaly: true } : {}),\n ...(resetApplied ? { reset_applied: true } : {}),\n },\n nextState,\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, open, readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport {\n evaluateSessionLifecycle,\n type AlertCooldownState,\n type SessionLifecycleDecision,\n type SessionLifecycleMetrics,\n} from \"../analyzers/session-lifecycle.js\";\nimport { resolveLocale, type SupportedLocale } from \"../i18n.js\";\nimport { getAgyBrainDir, getCacheDir } from \"../paths.js\";\n\nconst DEFAULT_TAIL_BYTES = 32 * 1024;\nconst HEAD_PROBE_BYTES = 4 * 1024;\nconst FIVE_MINUTES_MS = 5 * 60 * 1000;\nconst MAX_STATE_SESSIONS = 50;\n\nexport interface HookCheckOptions {\n transcriptPath?: string;\n brainDir?: string | null;\n stateFilePath?: string;\n tailBytes?: number;\n nowMs?: number;\n lang?: string;\n}\n\nexport interface HookCheckResult {\n transcript_found: boolean;\n decision: SessionLifecycleDecision;\n metrics?: SessionLifecycleMetrics;\n state_file: string;\n}\n\ninterface PersistedAdviceState {\n sessions: Record<string, AlertCooldownState>;\n}\n\nfunction firstNonNegInt(...vals: unknown[]): number {\n for (const v of vals) {\n if (typeof v === \"number\" && Number.isFinite(v) && v >= 0) {\n return Math.floor(v);\n }\n }\n return 0;\n}\n\nfunction extractTsMs(parsed: Record<string, unknown>): number | null {\n const raw = parsed.created_at ?? parsed.timestamp ?? parsed.ts;\n if (typeof raw === \"string\") {\n const ms = Date.parse(raw);\n return Number.isNaN(ms) ? null : ms;\n }\n if (typeof raw === \"number\" && Number.isFinite(raw)) {\n return raw > 1e12 ? raw : raw * 1000;\n }\n return null;\n}\n\nfunction inferModelContextLimit(model: string | null): number {\n if (!model) {\n return 512_000;\n }\n const lower = model.toLowerCase();\n if (lower.includes(\"gemini-2.5\") || lower.includes(\"gemini-1.5\") || lower.includes(\"1m\")) {\n return 1_000_000;\n }\n return 512_000;\n}\n\nfunction isUserLine(parsed: Record<string, unknown>): boolean {\n const role = typeof parsed.role === \"string\" ? parsed.role.toLowerCase() : \"\";\n const eventType = typeof parsed.type === \"string\" ? parsed.type.toLowerCase() : \"\";\n const source = typeof parsed.source === \"string\" ? parsed.source.toUpperCase() : \"\";\n return (\n role === \"user\" ||\n eventType === \"user_message\" ||\n eventType === \"user_input\" ||\n source === \"USER_EXPLICIT\"\n );\n}\n\nexport async function findLatestTranscriptPath(\n brainDir?: string | null,\n): Promise<string | null> {\n const resolvedDir = brainDir !== undefined ? brainDir : getAgyBrainDir();\n if (!resolvedDir) {\n return null;\n }\n let entries;\n try {\n entries = await readdir(resolvedDir, { withFileTypes: true });\n } catch {\n return null;\n }\n\n let latestPath: string | null = null;\n let latestMtimeMs = -1;\n\n for (const entry of entries) {\n if (!entry.isDirectory()) {\n continue;\n }\n const candidate = join(\n resolvedDir,\n entry.name,\n \".system_generated\",\n \"logs\",\n \"transcript.jsonl\",\n );\n try {\n const s = await stat(candidate);\n if (s.isFile() && s.mtimeMs > latestMtimeMs) {\n latestMtimeMs = s.mtimeMs;\n latestPath = candidate;\n }\n } catch {\n // Ignore missing transcript\n }\n }\n\n return latestPath;\n}\n\nexport async function extractTranscriptTailLifecycleMetrics(\n transcriptPath: string,\n options?: { tailBytes?: number; nowMs?: number },\n): Promise<SessionLifecycleMetrics | null> {\n const tailBytes = options?.tailBytes ?? DEFAULT_TAIL_BYTES;\n const nowMs = options?.nowMs ?? Date.now();\n\n let handle;\n try {\n handle = await open(transcriptPath, \"r\");\n const fileStat = await handle.stat();\n if (!fileStat.isFile() || fileStat.size === 0) {\n return null;\n }\n\n const readStart = Math.max(0, fileStat.size - tailBytes);\n const readLen = Math.min(fileStat.size, tailBytes);\n const buf = Buffer.allocUnsafe(readLen);\n const { bytesRead } = await handle.read(buf, 0, readLen, readStart);\n let tailText = buf.subarray(0, bytesRead).toString(\"utf8\");\n\n if (readStart > 0) {\n const firstNewline = tailText.indexOf(\"\\n\");\n if (firstNewline !== -1) {\n tailText = tailText.slice(firstNewline + 1);\n } else {\n tailText = \"\";\n }\n }\n\n const lines = tailText.split(\"\\n\");\n let userTurns = 0;\n let plannerTurnsSinceCompact = 0;\n let maxStepIndex = 0;\n let hasRecentCompact = false;\n let lastEventTsMs: number | null = null;\n let latestModel: string | null = null;\n let recent429Count = 0;\n let recentOverflowCount = 0;\n\n const tokenEvents: Array<{ totalInput: number; cacheRead: number }> = [];\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n const tsMs = extractTsMs(parsed);\n if (tsMs !== null && (lastEventTsMs === null || tsMs > lastEventTsMs)) {\n lastEventTsMs = tsMs;\n }\n\n if (typeof parsed.step_index === \"number\" && parsed.step_index > maxStepIndex) {\n maxStepIndex = Math.floor(parsed.step_index);\n }\n\n const eventType =\n typeof parsed.type === \"string\" ? parsed.type.toLowerCase() : \"\";\n const role = typeof parsed.role === \"string\" ? parsed.role.toLowerCase() : \"\";\n\n if (eventType === \"compact\" || eventType === \"compaction\") {\n hasRecentCompact = true;\n plannerTurnsSinceCompact = 0;\n continue;\n }\n\n if (isUserLine(parsed)) {\n userTurns += 1;\n } else if (\n role === \"assistant\" ||\n role === \"model\" ||\n eventType === \"assistant_message\" ||\n eventType === \"planner_response\"\n ) {\n plannerTurnsSinceCompact += 1;\n }\n\n const usageObj =\n parsed.usage && typeof parsed.usage === \"object\" && !Array.isArray(parsed.usage)\n ? (parsed.usage as Record<string, unknown>)\n : {};\n const modelVal = parsed.model ?? usageObj.model;\n if (typeof modelVal === \"string\" && modelVal.trim().length > 0) {\n latestModel = modelVal.trim();\n }\n\n const inputTokens = firstNonNegInt(\n parsed.input_tokens,\n usageObj.input_tokens,\n usageObj.prompt_tokens,\n );\n const cacheReadTokens = firstNonNegInt(\n parsed.cache_read_tokens,\n usageObj.cache_read_tokens,\n usageObj.cached_content_token_count,\n );\n const totalInput = inputTokens + cacheReadTokens;\n if (totalInput > 0) {\n tokenEvents.push({ totalInput, cacheRead: cacheReadTokens });\n }\n\n const errRaw = String(\n parsed.error_code ?? parsed.error ?? parsed.status_code ?? \"\",\n ).toUpperCase();\n const within5m = tsMs === null || nowMs - tsMs <= FIVE_MINUTES_MS;\n if (within5m && errRaw.length > 0) {\n if (errRaw.includes(\"429\") || errRaw.includes(\"RESOURCE_EXHAUSTED\")) {\n recent429Count += 1;\n }\n if (\n errRaw.includes(\"CONTEXT_OVERFLOW\") ||\n errRaw.includes(\"OVERFLOW\") ||\n errRaw.includes(\"CONTEXT_LENGTH_EXCEEDED\") ||\n errRaw.includes(\"TOO_MANY_TOKENS\")\n ) {\n recentOverflowCount += 1;\n }\n }\n }\n\n // If file is larger than tailBytes and no user turn appeared in tail,\n // probe the first 4KB (O(1)) to distinguish interactive sessions from subagents.\n let hasUserInHead = false;\n if (readStart > 0 && userTurns === 0) {\n const headLen = Math.min(fileStat.size, HEAD_PROBE_BYTES);\n const headBuf = Buffer.allocUnsafe(headLen);\n const headRes = await handle.read(headBuf, 0, headLen, 0);\n const headText = headBuf.subarray(0, headRes.bytesRead).toString(\"utf8\");\n for (const line of headText.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n if (isUserLine(parsed)) {\n hasUserInHead = true;\n break;\n }\n } catch {\n // Ignore truncated last line of head probe\n }\n }\n }\n\n const latestTokens =\n tokenEvents.length > 0 ? tokenEvents[tokenEvents.length - 1]!.totalInput : 0;\n const prevTokens =\n tokenEvents.length >= 2 ? tokenEvents[tokenEvents.length - 2]!.totalInput : undefined;\n\n const last3 = tokenEvents.slice(-3);\n const sumInput3 = last3.reduce((s, e) => s + e.totalInput, 0);\n const sumCache3 = last3.reduce((s, e) => s + e.cacheRead, 0);\n const recentCacheHitPct =\n sumInput3 > 0 ? Math.round((sumCache3 / sumInput3) * 1000) / 10 : 0;\n\n const idleGapSec =\n lastEventTsMs !== null ? Math.max(0, (nowMs - lastEventTsMs) / 1000) : 0;\n\n const effectiveTurns = hasRecentCompact\n ? plannerTurnsSinceCompact\n : Math.max(plannerTurnsSinceCompact, maxStepIndex);\n\n return {\n session_hash: createHash(\"sha256\")\n .update(transcriptPath)\n .digest(\"hex\")\n .slice(0, 12),\n is_interactive: userTurns > 0 || hasUserInHead,\n planner_turns_since_compact: effectiveTurns,\n current_input_tokens: latestTokens,\n recent_cache_hit_pct: recentCacheHitPct,\n idle_gap_sec: idleGapSec,\n recent_429_count: recent429Count,\n recent_overflow_count: recentOverflowCount,\n model_context_limit: inferModelContextLimit(latestModel),\n ...(hasRecentCompact ? { has_recent_compact: true } : {}),\n ...(prevTokens !== undefined ? { previous_input_tokens: prevTokens } : {}),\n };\n } catch {\n return null;\n } finally {\n await handle?.close().catch(() => {});\n }\n}\n\nasync function loadAdviceState(stateFilePath: string): Promise<PersistedAdviceState> {\n try {\n const raw = await readFile(stateFilePath, \"utf8\");\n const parsed = JSON.parse(raw) as Partial<PersistedAdviceState>;\n if (parsed && typeof parsed.sessions === \"object\" && parsed.sessions !== null) {\n return { sessions: { ...parsed.sessions } };\n }\n } catch {\n // Missing or corrupt state file -> start fresh\n }\n return { sessions: {} };\n}\n\nasync function saveAdviceState(\n stateFilePath: string,\n state: PersistedAdviceState,\n): Promise<void> {\n try {\n const entries = Object.entries(state.sessions);\n if (entries.length > MAX_STATE_SESSIONS) {\n entries.sort((a, b) => b[1].last_notified_ms - a[1].last_notified_ms);\n state.sessions = Object.fromEntries(entries.slice(0, MAX_STATE_SESSIONS));\n }\n await mkdir(dirname(stateFilePath), { recursive: true });\n await writeFile(stateFilePath, JSON.stringify(state, null, 2), \"utf8\");\n } catch {\n // Never fail hook execution due to cache write issues\n }\n}\n\nexport async function runHookCheck(\n options?: HookCheckOptions,\n): Promise<HookCheckResult> {\n const nowMs = options?.nowMs ?? Date.now();\n const locale: SupportedLocale = resolveLocale(options?.lang, process.env);\n const stateFile =\n options?.stateFilePath ?? join(getCacheDir(), \"session_advice_state.json\");\n\n const transcriptPath =\n options?.transcriptPath ?? (await findLatestTranscriptPath(options?.brainDir));\n\n if (!transcriptPath) {\n return {\n transcript_found: false,\n decision: {\n action: \"HOLD_CACHE\",\n reason_code: \"BELOW_THRESHOLD\",\n should_notify: false,\n },\n state_file: stateFile,\n };\n }\n\n const metrics = await extractTranscriptTailLifecycleMetrics(transcriptPath, {\n tailBytes: options?.tailBytes,\n nowMs,\n });\n\n if (!metrics) {\n return {\n transcript_found: false,\n decision: {\n action: \"HOLD_CACHE\",\n reason_code: \"BELOW_THRESHOLD\",\n should_notify: false,\n },\n state_file: stateFile,\n };\n }\n\n const state = await loadAdviceState(stateFile);\n const prevState = state.sessions[metrics.session_hash];\n const { decision, nextState } = evaluateSessionLifecycle(metrics, prevState, {\n nowMs,\n locale,\n });\n\n state.sessions[metrics.session_hash] = nextState;\n await saveAdviceState(stateFile, state);\n\n return {\n transcript_found: true,\n decision,\n metrics,\n state_file: stateFile,\n };\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport {\n mkdir,\n open,\n readdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport {\n estimateTokenCosts,\n findModelEntry,\n isZeroTokenUnknownLifecycleEvent,\n normalizeModelId,\n WINDOW_MS,\n type UsageWindow,\n} from \"../analyzers/token-window.js\";\nimport {\n collectCliLogSignals,\n resolveAuthModeFromCliLogs,\n} from \"../collectors/cli-log.js\";\nimport {\n getAgyBrainDir,\n getAgyHistoryPath,\n getDefaultGeminiTelemetryPath,\n getPackageVersion,\n getRollupsDir,\n getSaltFilePath,\n getUsageLogPath,\n} from \"../paths.js\";\nimport {\n getOrCreateLocalSalt,\n hashSessionId,\n sanitizeUsagePayload,\n type UsageRecord,\n} from \"../privacy.js\";\nimport {\n buildConversationProjectIndex,\n extractStructuralTimestampMs,\n extractTranscriptExplicitModel,\n isPlaceholderOrUnknownModel,\n} from \"../collectors/transcript-meta.js\";\nimport type {\n AuthMode,\n ModelEntry,\n ModelsSnapshot,\n NormalizationRules,\n} from \"../types.js\";\n\nexport type TimeSeriesGranularity = \"hourly\" | \"daily\" | \"weekly\" | \"monthly\";\n\nexport interface RollupCounters {\n requests: number;\n uncached_input_tokens: number;\n cache_read_tokens: number;\n input_tokens: number;\n output_tokens: number;\n thinking_tokens: number;\n total_tokens: number;\n error_count: number;\n rate_limit_429_count: number;\n below_kv_cache_threshold_requests: number;\n estimated_total_usd: number;\n estimated_cache_savings_usd: number;\n}\n\nexport interface RollupBucketEntry extends RollupCounters {\n product: UsageRecord[\"product\"];\n project_hash: string | null;\n auth_mode: AuthMode;\n model?: string;\n estimated_requests?: number;\n session_hashes: string[];\n}\n\nexport interface HourlyRollupFile {\n v: number;\n month: string;\n updated_at: string;\n buckets: Record<string, RollupBucketEntry[]>;\n}\n\nexport interface SourceWatermark {\n mtime_ms: number;\n byte_offset: number;\n last_step_index?: number;\n last_ts_count?: number;\n last_model?: string;\n updated_at: string;\n}\n\nexport interface WatermarksFile {\n v: number;\n fingerprint?: string;\n pkg_version?: string;\n models_fingerprint?: string;\n salt_fingerprint?: string;\n sources: Record<string, SourceWatermark>;\n}\n\nexport interface TimeSeriesBucket extends RollupCounters {\n bucket: string;\n session_count: number;\n cache_hit_rate_pct: number;\n}\n\nexport interface TimeSeriesMeta {\n granularity: TimeSeriesGranularity;\n timezone: string;\n total_buckets: number;\n returned_buckets: number;\n max_buckets: number;\n truncated: boolean;\n source: \"rollups\" | \"memory_fallback\";\n}\n\nexport interface QueryRollupsOptions {\n rollupsDir?: string;\n usageLogPath?: string;\n geminiOtelPath?: string;\n brainDir?: string | null;\n historyPath?: string | null;\n saltPath?: string;\n salt?: string;\n models?: ModelEntry[];\n normalizationRules?: NormalizationRules;\n pkgVersion?: string;\n window: UsageWindow;\n granularity: TimeSeriesGranularity;\n product?: \"agy\" | \"gemini-cli\" | \"all\";\n scope?: \"global\" | \"project\";\n projectHash?: string;\n authMode?: AuthMode | \"all\";\n timezone?: string;\n maxBuckets?: number;\n nowMs?: number;\n readonly?: boolean;\n lockTimeoutMs?: number;\n coldBrainDays?: number;\n transcriptAuthMode?: AuthMode;\n cliLogDir?: string | null;\n hasMixedAuth?: boolean;\n}\n\nexport interface RollupQueryResult {\n time_series: TimeSeriesBucket[];\n time_series_meta: TimeSeriesMeta;\n summary_totals: RollupCounters & {\n session_count: number;\n cache_hit_rate_pct: number;\n unattributed_sessions_excluded: number;\n };\n cost_breakdown?: RollupWindowCostSummary;\n}\n\nconst STALE_LOCK_MS = 10_000;\nconst DEFAULT_COLD_BRAIN_DAYS = 30;\n\nfunction computeSaltFingerprint(salt: string): string {\n return createHash(\"sha256\").update(salt).digest(\"hex\").slice(0, 12);\n}\n\nexport function computeModelsFingerprint(\n input:\n | {\n models?: ModelEntry[];\n normalization_rules?: NormalizationRules;\n }\n | ModelsSnapshot,\n): string {\n const models = Array.isArray(input.models) ? input.models : [];\n const payload = {\n normalization_rules: input.normalization_rules ?? null,\n models: models\n .map((m) => ({\n id: m.id,\n api_model_id: m.api_model_id,\n aliases: m.aliases ?? [],\n lifecycle: m.lifecycle,\n pricing: m.pricing,\n }))\n .sort((a, b) => a.id.localeCompare(b.id)),\n };\n return createHash(\"sha256\").update(JSON.stringify(payload)).digest(\"hex\").slice(0, 12);\n}\n\nasync function cleanupRollupsDirKeepLock(rollupsDir: string): Promise<void> {\n try {\n const entries = await readdir(rollupsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name === \".rollup.lock\") {\n continue;\n }\n await rm(join(rollupsDir, entry.name), { recursive: true, force: true });\n }\n } catch {\n // Directory may not exist yet\n }\n}\n\nexport function isReadonlyEnv(explicit?: boolean): boolean {\n if (explicit === true) {\n return true;\n }\n const envVal = process.env.AGYCRAFT_READONLY?.trim().toLowerCase();\n return envVal === \"1\" || envVal === \"true\";\n}\n\nfunction emptyCounters(): RollupCounters {\n return {\n requests: 0,\n uncached_input_tokens: 0,\n cache_read_tokens: 0,\n input_tokens: 0,\n output_tokens: 0,\n thinking_tokens: 0,\n total_tokens: 0,\n error_count: 0,\n rate_limit_429_count: 0,\n below_kv_cache_threshold_requests: 0,\n estimated_total_usd: 0,\n estimated_cache_savings_usd: 0,\n };\n}\n\nfunction round4(n: number): number {\n return Math.round(n * 10000) / 10000;\n}\n\nexport function normalizeTimezone(tz?: string): string {\n if (!tz || tz.trim().length === 0) {\n return \"UTC\";\n }\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: tz.trim() });\n return tz.trim();\n } catch {\n return \"UTC\";\n }\n}\n\nfunction getDatePartsInTz(\n ms: number,\n timeZone: string,\n): { year: number; month: number; day: number; hour: number } {\n if (timeZone === \"UTC\") {\n const d = new Date(ms);\n return {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour: d.getUTCHours(),\n };\n }\n const fmt = new Intl.DateTimeFormat(\"en-CA\", {\n timeZone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n hour12: false,\n });\n const parts = fmt.formatToParts(new Date(ms));\n const map: Record<string, number> = {};\n for (const p of parts) {\n if (p.type !== \"literal\") {\n map[p.type] = Number(p.value);\n }\n }\n return {\n year: map.year ?? 1970,\n month: map.month ?? 1,\n day: map.day ?? 1,\n hour: (map.hour ?? 0) === 24 ? 0 : (map.hour ?? 0),\n };\n}\n\nfunction pad2(n: number): string {\n return String(n).padStart(2, \"0\");\n}\n\nfunction getIsoWeekKey(year: number, month: number, day: number): string {\n const d = new Date(Date.UTC(year, month - 1, day));\n const dayNum = d.getUTCDay() || 7;\n d.setUTCDate(d.getUTCDate() + 4 - dayNum);\n const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));\n const weekNo = Math.ceil(((d.getTime() - yearStart.getTime()) / 86400_000 + 1) / 7);\n return `${d.getUTCFullYear()}-W${pad2(weekNo)}`;\n}\n\nexport function formatBucketKey(\n ms: number,\n granularity: TimeSeriesGranularity,\n timeZone = \"UTC\",\n): string {\n const p = getDatePartsInTz(ms, timeZone);\n if (granularity === \"hourly\") {\n const suffix = timeZone === \"UTC\" ? \"Z\" : \"\";\n return `${p.year}-${pad2(p.month)}-${pad2(p.day)}T${pad2(p.hour)}:00:00${suffix}`;\n }\n if (granularity === \"daily\") {\n return `${p.year}-${pad2(p.month)}-${pad2(p.day)}`;\n }\n if (granularity === \"weekly\") {\n return getIsoWeekKey(p.year, p.month, p.day);\n }\n return `${p.year}-${pad2(p.month)}`;\n}\n\nfunction getUtcHourKey(ms: number): string {\n return formatBucketKey(ms, \"hourly\", \"UTC\");\n}\n\nfunction getUtcMonthKey(ms: number): string {\n return formatBucketKey(ms, \"monthly\", \"UTC\");\n}\n\nasync function atomicWriteJson(targetPath: string, data: unknown): Promise<void> {\n await mkdir(dirname(targetPath), { recursive: true });\n const tmpPath = `${targetPath}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`;\n await writeFile(tmpPath, JSON.stringify(data, null, 2), {\n encoding: \"utf8\",\n mode: 0o600,\n });\n await rename(tmpPath, targetPath);\n}\n\ntype ReadJsonResult<T> =\n | { status: \"ok\"; data: T }\n | { status: \"missing\" }\n | { status: \"corrupt\" };\n\nasync function safeReadJson<T>(filePath: string): Promise<ReadJsonResult<T>> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"ENOENT\") {\n return { status: \"missing\" };\n }\n return { status: \"corrupt\" };\n }\n try {\n const parsed = JSON.parse(raw) as T;\n if (!parsed || typeof parsed !== \"object\") {\n return { status: \"corrupt\" };\n }\n return { status: \"ok\", data: parsed };\n } catch {\n return { status: \"corrupt\" };\n }\n}\n\nasync function acquireRollupLock(\n rollupsDir: string,\n timeoutMs = 150,\n): Promise<string | null> {\n await mkdir(rollupsDir, { recursive: true });\n const lockPath = join(rollupsDir, \".rollup.lock\");\n const deadline = Date.now() + timeoutMs;\n\n while (true) {\n try {\n const fh = await open(lockPath, \"wx\", 0o600);\n await fh.writeFile(JSON.stringify({ pid: process.pid, ts: Date.now() }), \"utf8\");\n await fh.close();\n return lockPath;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code !== \"EEXIST\") {\n return null;\n }\n // Check stale lock (> 10s)\n try {\n const st = await stat(lockPath);\n let lockTs = st.mtimeMs;\n try {\n const raw = await readFile(lockPath, \"utf8\");\n const parsed = JSON.parse(raw) as { ts?: number };\n if (typeof parsed.ts === \"number\") {\n lockTs = parsed.ts;\n }\n } catch {\n // ignore corrupt lock content, rely on mtime\n }\n if (Date.now() - lockTs > STALE_LOCK_MS) {\n await unlink(lockPath).catch(() => {});\n continue;\n }\n } catch {\n // Lock disappeared concurrently\n continue;\n }\n\n if (Date.now() >= deadline) {\n return null;\n }\n await new Promise((r) => setTimeout(r, 25));\n }\n }\n}\n\nasync function releaseLock(lockPath: string | null): Promise<void> {\n if (!lockPath) {\n return;\n }\n await unlink(lockPath).catch(() => {});\n}\n\ninterface IncrementalLinesResult {\n lines: string[];\n newOffset: number;\n mtimeMs: number;\n resetRequired: boolean;\n}\n\nasync function readFileIncrementalLines(\n filePath: string,\n watermark?: SourceWatermark,\n): Promise<IncrementalLinesResult | null> {\n let st;\n try {\n st = await stat(filePath);\n } catch {\n return null;\n }\n\n if (watermark && st.size === watermark.byte_offset && st.mtimeMs === watermark.mtime_ms) {\n return { lines: [], newOffset: watermark.byte_offset, mtimeMs: st.mtimeMs, resetRequired: false };\n }\n\n const startOffset =\n watermark && st.size >= watermark.byte_offset ? watermark.byte_offset : 0;\n const resetRequired = Boolean(watermark && st.size < watermark.byte_offset);\n const bytesToRead = st.size - startOffset;\n\n if (bytesToRead <= 0) {\n return { lines: [], newOffset: st.size, mtimeMs: st.mtimeMs, resetRequired };\n }\n\n const fh = await open(filePath, \"r\");\n try {\n const buf = Buffer.alloc(bytesToRead);\n const { bytesRead } = await fh.read(buf, 0, bytesToRead, startOffset);\n const text = buf.subarray(0, bytesRead).toString(\"utf8\");\n const lastNewline = text.lastIndexOf(\"\\n\");\n\n if (lastNewline === -1) {\n // Single line without trailing newline: consume only if valid JSON\n const trimmed = text.trim();\n if (!trimmed) {\n return { lines: [], newOffset: startOffset + bytesRead, mtimeMs: st.mtimeMs, resetRequired };\n }\n try {\n JSON.parse(trimmed);\n return { lines: [trimmed], newOffset: startOffset + bytesRead, mtimeMs: st.mtimeMs, resetRequired };\n } catch {\n return { lines: [], newOffset: startOffset, mtimeMs: st.mtimeMs, resetRequired };\n }\n }\n\n const trailing = text.slice(lastNewline + 1);\n const trailingTrimmed = trailing.trim();\n if (trailingTrimmed.length > 0) {\n try {\n JSON.parse(trailingTrimmed);\n return {\n lines: text.split(\"\\n\"),\n newOffset: startOffset + bytesRead,\n mtimeMs: st.mtimeMs,\n resetRequired,\n };\n } catch {\n // Incomplete trailing line: keep byte_offset at lastNewline + 1\n const consumedBytes = Buffer.byteLength(text.slice(0, lastNewline + 1), \"utf8\");\n return {\n lines: text.slice(0, lastNewline + 1).split(\"\\n\"),\n newOffset: startOffset + consumedBytes,\n mtimeMs: st.mtimeMs,\n resetRequired,\n };\n }\n }\n\n return {\n lines: text.split(\"\\n\"),\n newOffset: startOffset + bytesRead,\n mtimeMs: st.mtimeMs,\n resetRequired,\n };\n } finally {\n await fh.close();\n }\n}\n\nfunction mergeRecordIntoBucket(\n bucketsMap: Record<string, RollupBucketEntry[]>,\n bucketKey: string,\n record: UsageRecord,\n catalog: ModelEntry[],\n rules?: NormalizationRules,\n): void {\n let entries = bucketsMap[bucketKey];\n if (!entries) {\n entries = [];\n bucketsMap[bucketKey] = entries;\n }\n const authMode = record.auth_mode ?? \"unknown\";\n const projectHash = record.project_hash ?? null;\n const modelKey = normalizeModelId(record.model || \"unknown\", catalog, rules);\n let target = entries.find(\n (e) =>\n e.product === record.product &&\n e.project_hash === projectHash &&\n e.auth_mode === authMode &&\n (e.model ?? \"unknown\") === modelKey,\n );\n if (!target) {\n target = {\n product: record.product,\n project_hash: projectHash,\n auth_mode: authMode,\n model: modelKey,\n session_hashes: [],\n ...emptyCounters(),\n };\n entries.push(target);\n }\n\n const uncached = record.input_tokens;\n const cacheRead = record.cache_read_tokens ?? 0;\n const thinking = record.thinking_tokens ?? 0;\n const reqInput = uncached + cacheRead;\n const reqTotal = reqInput + record.output_tokens;\n\n const {\n inputUsd: inUsd,\n cacheSavingsUsd,\n outputUsd: outUsd,\n } = estimateTokenCosts(\n {\n model: modelKey,\n uncachedInputTokens: uncached,\n cacheReadTokens: cacheRead,\n outputTokens: record.output_tokens,\n },\n catalog,\n rules,\n );\n\n const matchedEntry = findModelEntry(record.model, catalog, rules);\n const kvMinTokens = matchedEntry?.specs?.implicit_cache_min_tokens ?? 4096;\n const isColdBelowKv =\n kvMinTokens > 0 && reqInput > 0 && reqInput < kvMinTokens && cacheRead === 0;\n\n target.requests += 1;\n if (record.data_quality === \"estimated_from_cli_log\") {\n target.estimated_requests = (target.estimated_requests ?? 0) + 1;\n }\n target.uncached_input_tokens += uncached;\n target.cache_read_tokens += cacheRead;\n target.input_tokens += reqInput;\n target.output_tokens += record.output_tokens;\n target.thinking_tokens += thinking;\n target.total_tokens += reqTotal;\n if (record.error_code) {\n target.error_count += 1;\n if (\n record.error_code.includes(\"429\") ||\n record.error_code.includes(\"RESOURCE_EXHAUSTED\")\n ) {\n target.rate_limit_429_count += 1;\n }\n }\n if (isColdBelowKv) {\n target.below_kv_cache_threshold_requests += 1;\n }\n target.estimated_total_usd = round4(target.estimated_total_usd + inUsd + outUsd);\n target.estimated_cache_savings_usd = round4(\n target.estimated_cache_savings_usd + cacheSavingsUsd,\n );\n\n if (record.session_hash && !target.session_hashes.includes(record.session_hash)) {\n target.session_hashes.push(record.session_hash);\n }\n}\n\nfunction parseUsageLogLine(line: string, salt: string): UsageRecord | null {\n const trimmed = line.trim();\n if (!trimmed) {\n return null;\n }\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n return sanitizeUsagePayload(parsed, salt);\n } catch {\n return null;\n }\n}\n\nfunction parseOtelLine(line: string, salt: string): UsageRecord | null {\n const trimmed = line.trim();\n if (!trimmed) {\n return null;\n }\n try {\n const entry = JSON.parse(trimmed) as Record<string, unknown>;\n const rawAttrs = entry[\"attributes\"];\n const attrs =\n rawAttrs && typeof rawAttrs === \"object\" && !Array.isArray(rawAttrs)\n ? (rawAttrs as Record<string, unknown>)\n : {};\n const firstNum = (...cands: unknown[]): number => {\n for (const v of cands) {\n if (v === null || v === undefined || v === \"\") continue;\n const n = typeof v === \"number\" ? v : Number(v);\n if (Number.isFinite(n) && n >= 0) return Math.floor(n);\n }\n return 0;\n };\n const inputTokens = firstNum(\n attrs[\"gen_ai.usage.input_tokens\"],\n attrs[\"input_token_count\"],\n attrs[\"prompt_tokens\"],\n entry[\"input_tokens\"],\n entry[\"prompt_tokens\"],\n );\n const cacheReadTokens = firstNum(\n attrs[\"gen_ai.usage.cache_read_input_tokens\"],\n attrs[\"cache_read_tokens\"],\n attrs[\"cached_content_token_count\"],\n entry[\"cache_read_tokens\"],\n );\n const outputTokens = firstNum(\n attrs[\"gen_ai.usage.output_tokens\"],\n attrs[\"output_token_count\"],\n attrs[\"completion_tokens\"],\n entry[\"output_tokens\"],\n entry[\"completion_tokens\"],\n );\n const thinkingTokens = firstNum(\n attrs[\"gen_ai.usage.thinking_tokens\"],\n attrs[\"thinking_tokens\"],\n attrs[\"thoughts_token_count\"],\n entry[\"thinking_tokens\"],\n );\n const errorCode =\n attrs[\"error.type\"] ??\n attrs[\"http.response.status_code\"] ??\n entry[\"error_code\"] ??\n null;\n if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0 && !errorCode) {\n return null;\n }\n const rawSession = String(\n attrs[\"session.id\"] ?? entry[\"session_id\"] ?? \"gemini-cli-session\",\n );\n return sanitizeUsagePayload(\n {\n ts: entry[\"timestamp\"] ?? entry[\"ts\"] ?? entry[\"startTime\"],\n provider: \"google\",\n product: \"gemini-cli\",\n session_hash: hashSessionId(rawSession, salt),\n model:\n attrs[\"gen_ai.request.model\"] ??\n attrs[\"gen_ai.response.model\"] ??\n attrs[\"model\"] ??\n entry[\"model\"] ??\n \"unknown\",\n input_tokens: inputTokens,\n cache_read_tokens: cacheReadTokens,\n output_tokens: outputTokens,\n thinking_tokens: thinkingTokens,\n context_used_pct: attrs[\"context_used_pct\"] ?? null,\n tool_calls: firstNum(attrs[\"tool_calls\"], entry[\"tool_calls\"]),\n turn_index: firstNum(attrs[\"turn_index\"], entry[\"turn_index\"]),\n error_code: errorCode,\n },\n salt,\n );\n } catch {\n return null;\n }\n}\n\nexport async function queryRollups(\n options: QueryRollupsOptions,\n): Promise<RollupQueryResult> {\n const nowMs = options.nowMs ?? Date.now();\n const readonly = isReadonlyEnv(options.readonly);\n const rollupsDir = options.rollupsDir ?? getRollupsDir();\n const hourlyDir = join(rollupsDir, \"hourly\");\n const watermarksPath = join(rollupsDir, \"watermarks.json\");\n const catalog = options.models ?? [];\n const rules = options.normalizationRules;\n const tz = normalizeTimezone(options.timezone);\n const maxBuckets = Math.max(1, Math.min(90, options.maxBuckets ?? 31));\n\n // Obtain salt without writing to disk in readonly mode\n let salt = options.salt;\n if (!salt) {\n if (readonly) {\n try {\n salt = await getOrCreateLocalSalt(options.saltPath);\n } catch {\n salt = \"readonly-ephemeral-salt\";\n }\n } else {\n salt = await getOrCreateLocalSalt(options.saltPath);\n }\n }\n\n let lockPath: string | null = null;\n let canWrite = !readonly;\n if (canWrite) {\n lockPath = await acquireRollupLock(rollupsDir, options.lockTimeoutMs ?? 150);\n if (!lockPath) {\n // Lock contention timeout -> degrade gracefully to memory-only return\n canWrite = false;\n }\n }\n\n try {\n const pkgVersion = options.pkgVersion ?? getPackageVersion();\n const modelsFingerprint = computeModelsFingerprint({\n models: catalog,\n normalization_rules: rules,\n });\n const saltFingerprint = computeSaltFingerprint(salt);\n const currentFingerprint = `${pkgVersion}:${modelsFingerprint}:${saltFingerprint}`;\n const wmRes = await safeReadJson<WatermarksFile>(watermarksPath);\n\n let corruptDetected = wmRes.status === \"corrupt\";\n\n let existingHourlyFiles: string[] = [];\n try {\n const files = await readdir(hourlyDir);\n existingHourlyFiles = files.filter((f) => /^\\d{4}-\\d{2}\\.json$/.test(f)).sort();\n } catch {\n existingHourlyFiles = [];\n }\n\n let hasLegacyPeriodFiles = false;\n try {\n const rootFiles = await readdir(rollupsDir);\n hasLegacyPeriodFiles = rootFiles.some(\n (f) => f === \"daily.json\" || f === \"weekly.json\" || f === \"monthly.json\",\n );\n } catch {\n hasLegacyPeriodFiles = false;\n }\n\n let legacySchemaDetected = false;\n if (!corruptDetected) {\n for (const f of existingHourlyFiles) {\n const hRes = await safeReadJson<HourlyRollupFile>(join(hourlyDir, f));\n if (hRes.status === \"corrupt\") {\n corruptDetected = true;\n break;\n }\n if (hRes.status === \"ok\" && hRes.data.v !== 2) {\n legacySchemaDetected = true;\n }\n }\n }\n\n const hasExistingDiskRollups =\n wmRes.status === \"ok\" || existingHourlyFiles.length > 0 || hasLegacyPeriodFiles;\n\n const fingerprintMismatch =\n hasExistingDiskRollups &&\n (wmRes.status !== \"ok\" ||\n wmRes.data.v !== 2 ||\n wmRes.data.fingerprint !== currentFingerprint);\n\n const rebuildRequired =\n corruptDetected || fingerprintMismatch || legacySchemaDetected;\n\n interface PassResult {\n fallbackToCleanMemory: boolean;\n watermarks: WatermarksFile;\n hourlyCache: Map<string, HourlyRollupFile>;\n dirtyHourlyMonths: Set<string>;\n anyNewData: boolean;\n }\n\n const usageLogPath = options.usageLogPath ?? getUsageLogPath();\n const otelPath = options.geminiOtelPath ?? getDefaultGeminiTelemetryPath();\n const brainDir =\n options.brainDir === undefined ? getAgyBrainDir() : options.brainDir;\n const historyPath =\n options.historyPath === undefined ? getAgyHistoryPath() : options.historyPath;\n\n const runIngestionPass = async (useDiskRollups: boolean): Promise<PassResult> => {\n const watermarks: WatermarksFile =\n useDiskRollups && wmRes.status === \"ok\" && wmRes.data.sources\n ? {\n v: 2,\n fingerprint: currentFingerprint,\n pkg_version: pkgVersion,\n models_fingerprint: modelsFingerprint,\n salt_fingerprint: saltFingerprint,\n sources: { ...wmRes.data.sources },\n }\n : {\n v: 2,\n fingerprint: currentFingerprint,\n pkg_version: pkgVersion,\n models_fingerprint: modelsFingerprint,\n salt_fingerprint: saltFingerprint,\n sources: {},\n };\n\n const hourlyCache = new Map<string, HourlyRollupFile>();\n const dirtyHourlyMonths = new Set<string>();\n const diskSessionHashes = new Set<string>();\n\n const loadHourlyMonth = async (monthKey: string): Promise<HourlyRollupFile> => {\n const cached = hourlyCache.get(monthKey);\n if (cached) {\n return cached;\n }\n if (useDiskRollups) {\n const filePath = join(hourlyDir, `${monthKey}.json`);\n const res = await safeReadJson<HourlyRollupFile>(filePath);\n if (res.status === \"ok\" && res.data.buckets) {\n for (const entries of Object.values(res.data.buckets)) {\n for (const entry of entries) {\n for (const sh of entry.session_hashes) {\n diskSessionHashes.add(sh);\n }\n }\n }\n hourlyCache.set(monthKey, res.data);\n return res.data;\n }\n }\n const empty: HourlyRollupFile = {\n v: 2,\n month: monthKey,\n updated_at: new Date(nowMs).toISOString(),\n buckets: {},\n };\n hourlyCache.set(monthKey, empty);\n return empty;\n };\n\n if (useDiskRollups) {\n for (const file of existingHourlyFiles) {\n const monthKey = file.replace(/\\.json$/, \"\");\n await loadHourlyMonth(monthKey);\n }\n }\n\n let anyNewData = !useDiskRollups && rebuildRequired;\n\n const ingestRecords = async (newRecords: UsageRecord[]): Promise<void> => {\n for (const r of newRecords) {\n const tsMs = Date.parse(r.ts);\n if (Number.isNaN(tsMs)) {\n continue;\n }\n const monthKey = getUtcMonthKey(tsMs);\n const hourKey = getUtcHourKey(tsMs);\n\n const hourlyFile = await loadHourlyMonth(monthKey);\n mergeRecordIntoBucket(hourlyFile.buckets, hourKey, r, catalog, rules);\n hourlyFile.updated_at = new Date(nowMs).toISOString();\n dirtyHourlyMonths.add(monthKey);\n anyNewData = true;\n }\n };\n\n // 1. Incremental usage.jsonl\n const prevUsageWm = useDiskRollups ? watermarks.sources[\"usage_log\"] : undefined;\n const usageInc = await readFileIncrementalLines(usageLogPath, prevUsageWm);\n if (usageInc && usageInc.lines.length > 0) {\n const parsedRecords: UsageRecord[] = [];\n for (const line of usageInc.lines) {\n const rec = parseUsageLogLine(line, salt);\n if (rec) parsedRecords.push(rec);\n }\n if (\n !canWrite &&\n useDiskRollups &&\n hasExistingDiskRollups &&\n parsedRecords.length > 0 &&\n (!prevUsageWm || usageInc.resetRequired)\n ) {\n return {\n fallbackToCleanMemory: true,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n }\n await ingestRecords(parsedRecords);\n watermarks.sources[\"usage_log\"] = {\n mtime_ms: usageInc.mtimeMs,\n byte_offset: usageInc.newOffset,\n updated_at: new Date(nowMs).toISOString(),\n };\n anyNewData = true;\n }\n\n // 2. Incremental gemini-otel\n const prevOtelWm = useDiskRollups ? watermarks.sources[\"gemini_otel\"] : undefined;\n const otelInc = await readFileIncrementalLines(otelPath, prevOtelWm);\n if (otelInc && otelInc.lines.length > 0) {\n const parsedRecords: UsageRecord[] = [];\n for (const line of otelInc.lines) {\n const rec = parseOtelLine(line, salt);\n if (rec) parsedRecords.push(rec);\n }\n if (\n !canWrite &&\n useDiskRollups &&\n hasExistingDiskRollups &&\n parsedRecords.length > 0 &&\n (!prevOtelWm || otelInc.resetRequired)\n ) {\n return {\n fallbackToCleanMemory: true,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n }\n await ingestRecords(parsedRecords);\n watermarks.sources[\"gemini_otel\"] = {\n mtime_ms: otelInc.mtimeMs,\n byte_offset: otelInc.newOffset,\n updated_at: new Date(nowMs).toISOString(),\n };\n anyNewData = true;\n }\n\n // 2b. Collect cli-*.log auth channel signals & background lightweight calls\n const prevBgWm = useDiskRollups ? watermarks.sources[\"cli_log_bg\"] : undefined;\n const prevMaxTs = prevBgWm?.last_step_index ?? 0;\n const cliSinceMs = prevMaxTs > 0 ? Math.max(0, prevMaxTs - 60_000) : undefined;\n const effectiveCliLogDir =\n options.cliLogDir !== undefined\n ? options.cliLogDir\n : options.brainDir !== undefined && !process.env.AGYCRAFT_CLI_LOG_DIR\n ? null\n : undefined;\n const cliLogs =\n effectiveCliLogDir === null\n ? { authEvents: [], backgroundRecords: [], filesScanned: 0 }\n : await collectCliLogSignals({\n cliLogDir: effectiveCliLogDir,\n sinceMs: cliSinceMs,\n nowMs,\n salt,\n fallbackAuthMode: options.transcriptAuthMode,\n hasMixedAuth: options.hasMixedAuth,\n });\n\n if (cliLogs.backgroundRecords.length > 0) {\n const hasTsCount = prevBgWm?.last_ts_count !== undefined;\n const prevAtMaxCount = prevBgWm?.last_ts_count ?? 0;\n let seenAtPrevMax = 0;\n const freshBg = cliLogs.backgroundRecords.filter((r) => {\n const ts = Date.parse(r.ts);\n if (Number.isNaN(ts)) return false;\n if (ts > prevMaxTs) return true;\n if (hasTsCount && ts === prevMaxTs) {\n seenAtPrevMax += 1;\n return seenAtPrevMax > prevAtMaxCount;\n }\n return false;\n });\n if (freshBg.length > 0) {\n if (!canWrite && useDiskRollups && hasExistingDiskRollups && !prevBgWm) {\n return {\n fallbackToCleanMemory: true,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n }\n await ingestRecords(freshBg);\n const maxBgTs = freshBg.reduce((mx, r) => Math.max(mx, Date.parse(r.ts) || 0), prevMaxTs);\n const countAtMaxTs = cliLogs.backgroundRecords.reduce(\n (cnt, r) => (Date.parse(r.ts) === maxBgTs ? cnt + 1 : cnt),\n 0,\n );\n watermarks.sources[\"cli_log_bg\"] = {\n mtime_ms: maxBgTs,\n byte_offset: freshBg.length,\n last_step_index: maxBgTs,\n last_ts_count: countAtMaxTs,\n updated_at: new Date(nowMs).toISOString(),\n };\n anyNewData = true;\n }\n }\n\n // 3. Incremental AGY brain transcripts (skip cold > 30d dirs)\n if (brainDir) {\n const coldThresholdMs =\n nowMs - (options.coldBrainDays ?? DEFAULT_COLD_BRAIN_DAYS) * 86400_000;\n const projectIndex = await buildConversationProjectIndex(historyPath, salt);\n let sessionDirs: string[] = [];\n try {\n const entries = await readdir(brainDir, { withFileTypes: true });\n sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch {\n sessionDirs = [];\n }\n\n for (const sessionId of sessionDirs) {\n const transcriptPath = join(\n brainDir,\n sessionId,\n \".system_generated\",\n \"logs\",\n \"transcript.jsonl\",\n );\n let st;\n try {\n st = await stat(transcriptPath);\n } catch {\n continue;\n }\n if (st.mtimeMs < coldThresholdMs) {\n // Skip cold brain directories (> 30 days since last update)\n continue;\n }\n const sessionHash = hashSessionId(sessionId, salt);\n const wmKey = `transcript:${sessionHash}`;\n const prevWm = useDiskRollups ? watermarks.sources[wmKey] : undefined;\n const inc = await readFileIncrementalLines(transcriptPath, prevWm);\n if (!inc || inc.lines.length === 0) {\n continue;\n }\n\n if (\n !canWrite &&\n useDiskRollups &&\n (!prevWm || inc.resetRequired) &&\n diskSessionHashes.has(sessionHash)\n ) {\n return {\n fallbackToCleanMemory: true,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n }\n\n const projectHash = projectIndex.get(sessionId) ?? null;\n const prevLastStep = inc.resetRequired ? -1 : (prevWm?.last_step_index ?? -1);\n let maxStepIndex = prevLastStep;\n let lastSeenModel: string | null = inc.resetRequired ? null : (prevWm?.last_model ?? null);\n const parsedEvents: Record<string, unknown>[] = [];\n const modelFreq = new Map<string, number>();\n\n for (const line of inc.lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const obj = JSON.parse(trimmed) as Record<string, unknown>;\n parsedEvents.push(obj);\n const uObj =\n obj.usage && typeof obj.usage === \"object\" && !Array.isArray(obj.usage)\n ? (obj.usage as Record<string, unknown>)\n : {};\n const typeUpper = typeof obj.type === \"string\" ? obj.type.toUpperCase() : \"\";\n const em = extractTranscriptExplicitModel(obj, uObj);\n if (\n typeUpper !== \"CHECKPOINT\" &&\n em !== null &&\n !isPlaceholderOrUnknownModel(em)\n ) {\n modelFreq.set(em, (modelFreq.get(em) ?? 0) + 1);\n }\n } catch {\n continue;\n }\n }\n\n let dominantModel: string | null = null;\n let dominantCount = 0;\n for (const [m, count] of modelFreq.entries()) {\n if (count > dominantCount) {\n dominantCount = count;\n dominantModel = m;\n }\n }\n\n if (\n lastSeenModel === null &&\n dominantModel === null &&\n prevWm &&\n !inc.resetRequired &&\n prevWm.byte_offset > 0\n ) {\n try {\n const headText = await readFile(transcriptPath, \"utf8\");\n const headFreq = new Map<string, number>();\n for (const rawLine of headText.split(\"\\n\")) {\n const t = rawLine.trim();\n if (!t) continue;\n try {\n const hObj = JSON.parse(t) as Record<string, unknown>;\n const hUsage =\n hObj.usage && typeof hObj.usage === \"object\" && !Array.isArray(hObj.usage)\n ? (hObj.usage as Record<string, unknown>)\n : {};\n const hType = typeof hObj.type === \"string\" ? hObj.type.toUpperCase() : \"\";\n const hm = extractTranscriptExplicitModel(hObj, hUsage);\n if (hType !== \"CHECKPOINT\" && hm !== null && !isPlaceholderOrUnknownModel(hm)) {\n headFreq.set(hm, (headFreq.get(hm) ?? 0) + 1);\n }\n } catch {\n continue;\n }\n }\n let headTopCount = 0;\n for (const [hm, hCount] of headFreq.entries()) {\n if (hCount > headTopCount) {\n headTopCount = hCount;\n dominantModel = hm;\n }\n }\n } catch {\n // Ignore fallback read failure\n }\n }\n\n const parsedRecords: UsageRecord[] = [];\n\n for (const parsed of parsedEvents) {\n const usageObj =\n parsed.usage && typeof parsed.usage === \"object\" && !Array.isArray(parsed.usage)\n ? (parsed.usage as Record<string, unknown>)\n : {};\n const typeStr = typeof parsed.type === \"string\" ? parsed.type.toUpperCase() : \"\";\n const explicitModel = extractTranscriptExplicitModel(parsed, usageObj);\n if (\n typeStr !== \"CHECKPOINT\" &&\n explicitModel !== null &&\n !isPlaceholderOrUnknownModel(explicitModel)\n ) {\n lastSeenModel = explicitModel;\n }\n\n const stepIdx = typeof parsed.step_index === \"number\" ? parsed.step_index : undefined;\n if (\n stepIdx !== undefined &&\n prevLastStep >= 0 &&\n stepIdx <= prevLastStep\n ) {\n continue;\n }\n const tsMs = extractStructuralTimestampMs(parsed);\n if (tsMs === null || tsMs > nowMs + 60_000) continue;\n const num = (...vals: unknown[]): number => {\n for (const v of vals) {\n if (v === null || v === undefined || v === \"\") continue;\n const n = typeof v === \"number\" ? v : Number(v);\n if (Number.isFinite(n) && n >= 0) return Math.floor(n);\n }\n return 0;\n };\n const rawInput = num(parsed.input_tokens, usageObj.input_tokens, usageObj.prompt_tokens);\n const rawCacheRead = num(\n parsed.cache_read_tokens,\n usageObj.cache_read_tokens,\n usageObj.cached_content_token_count,\n );\n const rawOutput = num(\n parsed.output_tokens,\n usageObj.output_tokens,\n usageObj.completion_tokens,\n );\n if (typeStr !== \"PLANNER_RESPONSE\" && rawInput + rawCacheRead === 0 && rawOutput === 0) {\n continue;\n }\n if (rawInput + rawCacheRead === 0 && rawOutput === 0) {\n continue;\n }\n if (stepIdx !== undefined && stepIdx > maxStepIndex) {\n maxStepIndex = stepIdx;\n }\n\n const attributedModel =\n typeStr === \"CHECKPOINT\" || !explicitModel\n ? (lastSeenModel ?? dominantModel ?? \"unknown\")\n : explicitModel;\n\n const resolvedAuthMode =\n cliLogs.authEvents.length > 0 || options.hasMixedAuth\n ? resolveAuthModeFromCliLogs(cliLogs.authEvents, tsMs, {\n fallbackAuthMode: options.transcriptAuthMode ?? \"unknown\",\n hasMixedAuth: options.hasMixedAuth,\n })\n : (options.transcriptAuthMode ?? \"unknown\");\n\n parsedRecords.push(\n sanitizeUsagePayload(\n {\n ts: new Date(tsMs).toISOString(),\n provider: \"antigravity\",\n product: \"agy\",\n session_id: sessionId,\n model: attributedModel,\n input_tokens: rawInput,\n cache_read_tokens: rawCacheRead,\n output_tokens: rawOutput,\n thinking_tokens: 0,\n tool_calls: 0,\n turn_index: stepIdx ?? 0,\n project_hash: projectHash,\n auth_mode: resolvedAuthMode,\n },\n salt,\n ),\n );\n }\n\n await ingestRecords(parsedRecords);\n watermarks.sources[wmKey] = {\n mtime_ms: inc.mtimeMs,\n byte_offset: inc.newOffset,\n ...(maxStepIndex >= 0 ? { last_step_index: maxStepIndex } : {}),\n ...(lastSeenModel ? { last_model: lastSeenModel } : {}),\n updated_at: new Date(nowMs).toISOString(),\n };\n anyNewData = true;\n }\n }\n\n return {\n fallbackToCleanMemory: false,\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n };\n };\n\n let passResult = await runIngestionPass(!rebuildRequired);\n if (passResult.fallbackToCleanMemory) {\n passResult = await runIngestionPass(false);\n }\n\n const {\n watermarks,\n hourlyCache,\n dirtyHourlyMonths,\n anyNewData,\n } = passResult;\n\n // Persist dirty rollups and watermarks atomically if writable\n if (canWrite && anyNewData) {\n if (rebuildRequired) {\n await cleanupRollupsDirKeepLock(rollupsDir);\n }\n for (const monthKey of dirtyHourlyMonths) {\n const hf = hourlyCache.get(monthKey);\n if (hf) {\n await atomicWriteJson(join(hourlyDir, `${monthKey}.json`), hf);\n }\n }\n await atomicWriteJson(watermarksPath, watermarks);\n }\n\n const cutoffMs =\n options.window === \"all\"\n ? Number.NEGATIVE_INFINITY\n : nowMs - WINDOW_MS[options.window];\n\n // Aggregate from hourly UTC buckets into target granularity + timezone\n const aggregated = new Map<\n string,\n { counters: RollupCounters; sessions: Set<string> }\n >();\n const totalSessions = new Set<string>();\n const unattributedSessions = new Set<string>();\n const totals = emptyCounters();\n\n const productFilter = options.product ?? \"all\";\n const scope = options.scope ?? \"global\";\n const authFilter = options.authMode ?? \"all\";\n\n for (const hf of hourlyCache.values()) {\n for (const [hourUtcKey, entries] of Object.entries(hf.buckets)) {\n const hourMs = Date.parse(hourUtcKey);\n if (Number.isNaN(hourMs) || hourMs + 3600_000 <= cutoffMs || hourMs > nowMs + 3600_000) {\n continue;\n }\n const targetBucketKey = formatBucketKey(hourMs, options.granularity, tz);\n for (const entry of entries) {\n if (productFilter !== \"all\" && entry.product !== productFilter) {\n continue;\n }\n if (authFilter !== \"all\" && entry.auth_mode !== authFilter) {\n continue;\n }\n if (!entry.project_hash) {\n for (const sh of entry.session_hashes) {\n unattributedSessions.add(sh);\n }\n }\n if (scope === \"project\") {\n if (!options.projectHash || entry.project_hash !== options.projectHash) {\n continue;\n }\n }\n\n let bucketAgg = aggregated.get(targetBucketKey);\n if (!bucketAgg) {\n bucketAgg = { counters: emptyCounters(), sessions: new Set<string>() };\n aggregated.set(targetBucketKey, bucketAgg);\n }\n\n // Recompute USD estimates from current model catalog so pricing updates never drift from token-window\n const repriced = entry.model\n ? estimateTokenCosts(\n {\n model: normalizeModelId(entry.model, catalog, rules),\n uncachedInputTokens: entry.uncached_input_tokens,\n cacheReadTokens: entry.cache_read_tokens,\n outputTokens: entry.output_tokens,\n },\n catalog,\n rules,\n )\n : null;\n const entryTotalUsd = repriced ? repriced.totalUsd : entry.estimated_total_usd;\n const entryCacheSavingsUsd = repriced\n ? repriced.cacheSavingsUsd\n : entry.estimated_cache_savings_usd;\n\n const c = bucketAgg.counters;\n c.requests += entry.requests;\n c.uncached_input_tokens += entry.uncached_input_tokens;\n c.cache_read_tokens += entry.cache_read_tokens;\n c.input_tokens += entry.input_tokens;\n c.output_tokens += entry.output_tokens;\n c.thinking_tokens += entry.thinking_tokens;\n c.total_tokens += entry.total_tokens;\n c.error_count += entry.error_count;\n c.rate_limit_429_count += entry.rate_limit_429_count;\n c.below_kv_cache_threshold_requests += entry.below_kv_cache_threshold_requests;\n c.estimated_total_usd += entryTotalUsd;\n c.estimated_cache_savings_usd += entryCacheSavingsUsd;\n\n totals.requests += entry.requests;\n totals.uncached_input_tokens += entry.uncached_input_tokens;\n totals.cache_read_tokens += entry.cache_read_tokens;\n totals.input_tokens += entry.input_tokens;\n totals.output_tokens += entry.output_tokens;\n totals.thinking_tokens += entry.thinking_tokens;\n totals.total_tokens += entry.total_tokens;\n totals.error_count += entry.error_count;\n totals.rate_limit_429_count += entry.rate_limit_429_count;\n totals.below_kv_cache_threshold_requests +=\n entry.below_kv_cache_threshold_requests;\n totals.estimated_total_usd += entryTotalUsd;\n totals.estimated_cache_savings_usd += entryCacheSavingsUsd;\n\n for (const sh of entry.session_hashes) {\n bucketAgg.sessions.add(sh);\n totalSessions.add(sh);\n }\n }\n }\n }\n\n totals.estimated_total_usd = round4(totals.estimated_total_usd);\n totals.estimated_cache_savings_usd = round4(totals.estimated_cache_savings_usd);\n\n const allBuckets: TimeSeriesBucket[] = [...aggregated.entries()]\n .filter(([, v]) => v.counters.requests > 0)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([bucket, v]) => ({\n bucket,\n ...v.counters,\n estimated_total_usd: round4(v.counters.estimated_total_usd),\n estimated_cache_savings_usd: round4(v.counters.estimated_cache_savings_usd),\n session_count: v.sessions.size,\n cache_hit_rate_pct:\n v.counters.input_tokens > 0\n ? Math.round((v.counters.cache_read_tokens / v.counters.input_tokens) * 1000) / 10\n : 0,\n }));\n\n const truncated = allBuckets.length > maxBuckets;\n const returned = truncated ? allBuckets.slice(-maxBuckets) : allBuckets;\n\n const costBreakdown =\n options.window === \"5h\" || options.window === \"24h\" || options.window === \"7d\"\n ? aggregateHourlyFilesToCostWindow(\n [...hourlyCache.values()],\n options.window,\n catalog,\n nowMs,\n rules,\n )\n : undefined;\n\n return {\n time_series: returned,\n time_series_meta: {\n granularity: options.granularity,\n timezone: tz,\n total_buckets: allBuckets.length,\n returned_buckets: returned.length,\n max_buckets: maxBuckets,\n truncated,\n source: canWrite ? \"rollups\" : \"memory_fallback\",\n },\n summary_totals: {\n ...totals,\n session_count: totalSessions.size,\n cache_hit_rate_pct:\n totals.input_tokens > 0\n ? Math.round((totals.cache_read_tokens / totals.input_tokens) * 1000) / 10\n : 0,\n unattributed_sessions_excluded: unattributedSessions.size,\n },\n ...(costBreakdown ? { cost_breakdown: costBreakdown } : {}),\n };\n } finally {\n await releaseLock(lockPath);\n }\n}\n\nexport type CostSummaryWindow = \"5h\" | \"24h\" | \"7d\";\n\nexport interface ModelAuthCostRow {\n model: string;\n auth_mode: AuthMode;\n lifecycle: string;\n deprecated_date: string | null;\n replacement_model_id: string | null;\n requests: number;\n estimated_requests: number;\n uncached_input_tokens: number;\n cache_read_tokens: number;\n input_tokens: number;\n output_tokens: number;\n total_tokens: number;\n cache_hit_rate_pct: number;\n estimated_total_usd: number;\n estimated_cache_savings_usd: number;\n rate_limit_429_count: number;\n}\n\nexport interface AuthChannelCostGroup {\n auth_mode: AuthMode;\n label: string;\n requests: number;\n total_tokens: number;\n estimated_total_usd: number;\n estimated_cache_savings_usd: number;\n rate_limit_429_count: number;\n}\n\nexport interface DeprecatedModelInUse {\n model: string;\n lifecycle: string;\n deprecated_date: string | null;\n replacement_model_id: string | null;\n requests: number;\n}\n\nexport interface RollupWindowCostSummary {\n window: CostSummaryWindow;\n by_model_auth: ModelAuthCostRow[];\n by_auth_channel: AuthChannelCostGroup[];\n deprecated_models_in_use: DeprecatedModelInUse[];\n rate_limit_429_count: number;\n total_requests: number;\n total_tokens: number;\n}\n\nexport interface ReadRollupCostSummaryResult {\n has_cache: boolean;\n windows: Record<CostSummaryWindow, RollupWindowCostSummary>;\n}\n\nfunction getAuthChannelLabel(authMode: AuthMode): string {\n switch (authMode) {\n case \"google_oauth\":\n return \"Shadow Cost (Shared Quota Pressure)\";\n case \"gcp_adc\":\n case \"api_key\":\n return \"Estimated GCP / API Spend\";\n default:\n return \"Unattributed Est.\";\n }\n}\n\nexport function aggregateHourlyFilesToCostWindow(\n hourlyFiles: HourlyRollupFile[],\n window: CostSummaryWindow,\n catalog: ModelEntry[],\n nowMs: number,\n rules?: NormalizationRules,\n): RollupWindowCostSummary {\n const cutoffMs = nowMs - WINDOW_MS[window];\n const modelAuthMap = new Map<string, ModelAuthCostRow>();\n const authGroupMap = new Map<AuthMode, AuthChannelCostGroup>();\n const deprecatedMap = new Map<string, DeprecatedModelInUse>();\n\n let totalRequests = 0;\n let totalTokens = 0;\n let total429 = 0;\n\n for (const hf of hourlyFiles) {\n for (const [hourUtcKey, entries] of Object.entries(hf.buckets)) {\n const hourMs = Date.parse(hourUtcKey);\n if (\n Number.isNaN(hourMs) ||\n hourMs + 3600_000 <= cutoffMs ||\n hourMs > nowMs + 3600_000\n ) {\n continue;\n }\n\n for (const entry of entries) {\n const canonicalModel = normalizeModelId(entry.model ?? \"unknown\", catalog, rules);\n const matchedEntry = findModelEntry(canonicalModel, catalog, rules);\n const lifecycle = matchedEntry?.lifecycle ?? \"active\";\n const deprecatedDate = matchedEntry?.deprecated_date ?? null;\n const replacementModelId = matchedEntry?.replacement_model_id ?? null;\n\n const isZeroUnknown = isZeroTokenUnknownLifecycleEvent({\n model: canonicalModel,\n input_tokens: entry.input_tokens,\n cache_read_tokens: entry.cache_read_tokens,\n output_tokens: entry.output_tokens,\n });\n\n const repriced = isZeroUnknown\n ? { totalUsd: 0, cacheSavingsUsd: 0 }\n : estimateTokenCosts(\n {\n model: canonicalModel,\n uncachedInputTokens: entry.uncached_input_tokens,\n cacheReadTokens: entry.cache_read_tokens,\n outputTokens: entry.output_tokens,\n },\n catalog,\n rules,\n );\n\n const authMode: AuthMode = entry.auth_mode ?? \"unknown\";\n if (!isZeroUnknown) {\n const key = `${canonicalModel}\\u0000${authMode}`;\n let row = modelAuthMap.get(key);\n if (!row) {\n row = {\n model: canonicalModel,\n auth_mode: authMode,\n lifecycle,\n deprecated_date: deprecatedDate,\n replacement_model_id: replacementModelId,\n requests: 0,\n estimated_requests: 0,\n uncached_input_tokens: 0,\n cache_read_tokens: 0,\n input_tokens: 0,\n output_tokens: 0,\n total_tokens: 0,\n cache_hit_rate_pct: 0,\n estimated_total_usd: 0,\n estimated_cache_savings_usd: 0,\n rate_limit_429_count: 0,\n };\n modelAuthMap.set(key, row);\n }\n\n row.requests += entry.requests;\n row.estimated_requests += entry.estimated_requests ?? 0;\n row.uncached_input_tokens += entry.uncached_input_tokens;\n row.cache_read_tokens += entry.cache_read_tokens;\n row.input_tokens += entry.input_tokens;\n row.output_tokens += entry.output_tokens;\n row.total_tokens += entry.total_tokens;\n row.estimated_total_usd += repriced.totalUsd;\n row.estimated_cache_savings_usd += repriced.cacheSavingsUsd;\n row.rate_limit_429_count += entry.rate_limit_429_count;\n }\n\n let group = authGroupMap.get(authMode);\n if (!group) {\n group = {\n auth_mode: authMode,\n label: getAuthChannelLabel(authMode),\n requests: 0,\n total_tokens: 0,\n estimated_total_usd: 0,\n estimated_cache_savings_usd: 0,\n rate_limit_429_count: 0,\n };\n authGroupMap.set(authMode, group);\n }\n group.requests += entry.requests;\n group.total_tokens += entry.total_tokens;\n group.estimated_total_usd += repriced.totalUsd;\n group.estimated_cache_savings_usd += repriced.cacheSavingsUsd;\n group.rate_limit_429_count += entry.rate_limit_429_count;\n\n if (!isZeroUnknown && (lifecycle === \"deprecated\" || lifecycle === \"removed\")) {\n const dep = deprecatedMap.get(canonicalModel) ?? {\n model: canonicalModel,\n lifecycle,\n deprecated_date: deprecatedDate,\n replacement_model_id: replacementModelId,\n requests: 0,\n };\n dep.requests += entry.requests;\n deprecatedMap.set(canonicalModel, dep);\n }\n\n totalRequests += entry.requests;\n totalTokens += entry.total_tokens;\n total429 += entry.rate_limit_429_count;\n }\n }\n }\n\n const byModelAuth = [...modelAuthMap.values()]\n .map((r) => ({\n ...r,\n estimated_total_usd: round4(r.estimated_total_usd),\n estimated_cache_savings_usd: round4(r.estimated_cache_savings_usd),\n cache_hit_rate_pct:\n r.input_tokens > 0\n ? Math.round((r.cache_read_tokens / r.input_tokens) * 1000) / 10\n : 0,\n }))\n .sort((a, b) => b.estimated_total_usd - a.estimated_total_usd || b.total_tokens - a.total_tokens);\n\n const authOrder: Record<string, number> = {\n google_oauth: 0,\n gcp_vertex_adc: 1,\n gcp_adc: 1,\n gemini_api_key: 2,\n api_key: 2,\n vertex_express_key: 3,\n unknown: 99,\n };\n const byAuthChannel = [...authGroupMap.values()]\n .map((g) => ({\n ...g,\n estimated_total_usd: round4(g.estimated_total_usd),\n estimated_cache_savings_usd: round4(g.estimated_cache_savings_usd),\n }))\n .sort((a, b) => (authOrder[a.auth_mode] ?? 50) - (authOrder[b.auth_mode] ?? 50));\n\n return {\n window,\n by_model_auth: byModelAuth,\n by_auth_channel: byAuthChannel,\n deprecated_models_in_use: [...deprecatedMap.values()].sort(\n (a, b) => b.requests - a.requests,\n ),\n rate_limit_429_count: total429,\n total_requests: totalRequests,\n total_tokens: totalTokens,\n };\n}\n\nasync function readSaltReadonly(\n rollupsDir: string,\n explicitSalt?: string,\n explicitSaltPath?: string,\n): Promise<string | null> {\n if (explicitSalt && explicitSalt.trim().length > 0) {\n return explicitSalt.trim();\n }\n const candidates = [\n ...(explicitSaltPath ? [explicitSaltPath] : []),\n join(dirname(rollupsDir), \".salt\"),\n ...(rollupsDir === getRollupsDir() ? [getSaltFilePath()] : []),\n ];\n for (const candidate of candidates) {\n try {\n const content = (await readFile(candidate, \"utf8\")).trim();\n if (content.length > 0) {\n return content;\n }\n } catch {\n // Ignore missing candidate\n }\n }\n return null;\n}\n\n/**\n * Ultra-fast, zero-write, lock-free reader for doctor cost_summary.\n * Only reads current-month (and boundary previous-month) hourly/YYYY-MM.json files.\n * Never scans brainDir, never acquires locks, and never writes to disk.\n * Ignores stale/mismatched fingerprint caches cleanly without migration.\n */\nexport async function readRollupCostSummary(options?: {\n rollupsDir?: string;\n models?: ModelEntry[];\n normalizationRules?: NormalizationRules;\n pkgVersion?: string;\n saltPath?: string;\n salt?: string;\n nowMs?: number;\n}): Promise<ReadRollupCostSummaryResult> {\n const nowMs = options?.nowMs ?? Date.now();\n const rollupsDir = options?.rollupsDir ?? getRollupsDir();\n const hourlyDir = join(rollupsDir, \"hourly\");\n const watermarksPath = join(rollupsDir, \"watermarks.json\");\n const catalog = options?.models ?? [];\n const rules = options?.normalizationRules;\n const pkgVersion = options?.pkgVersion ?? getPackageVersion();\n const modelsFingerprint = computeModelsFingerprint({\n models: catalog,\n normalization_rules: rules,\n });\n\n const wmRes = await safeReadJson<WatermarksFile>(watermarksPath);\n let fingerprintValid = false;\n if (wmRes.status === \"ok\" && wmRes.data.v === 2 && typeof wmRes.data.fingerprint === \"string\") {\n const salt = await readSaltReadonly(rollupsDir, options?.salt, options?.saltPath);\n if (salt !== null) {\n const expectedFp = `${pkgVersion}:${modelsFingerprint}:${computeSaltFingerprint(salt)}`;\n fingerprintValid = wmRes.data.fingerprint === expectedFp;\n } else {\n fingerprintValid = wmRes.data.fingerprint.startsWith(`${pkgVersion}:${modelsFingerprint}:`);\n }\n }\n\n const hourlyFiles: HourlyRollupFile[] = [];\n if (fingerprintValid) {\n const monthKeys = [...new Set([getUtcMonthKey(nowMs), getUtcMonthKey(nowMs - WINDOW_MS[\"7d\"])])];\n for (const mk of monthKeys) {\n const res = await safeReadJson<HourlyRollupFile>(join(hourlyDir, `${mk}.json`));\n if (res.status === \"ok\" && res.data.v === 2 && res.data.buckets) {\n hourlyFiles.push(res.data);\n }\n }\n }\n\n const hasCache = fingerprintValid && hourlyFiles.length > 0;\n return {\n has_cache: hasCache,\n windows: {\n \"5h\": aggregateHourlyFilesToCostWindow(hourlyFiles, \"5h\", catalog, nowMs, rules),\n \"24h\": aggregateHourlyFilesToCostWindow(hourlyFiles, \"24h\", catalog, nowMs, rules),\n \"7d\": aggregateHourlyFilesToCostWindow(hourlyFiles, \"7d\", catalog, nowMs, rules),\n },\n };\n}\n","import type { StatusSnapshot } from \"../types.js\";\n\nconst DEFAULT_DATA_URL = \"https://modelcraft.dev/data/v1\";\n\nexport interface PreflightOptions {\n statusUrl?: string;\n env?: NodeJS.ProcessEnv;\n fetchFn?: typeof fetch;\n timeoutMs?: number;\n}\n\nexport interface PreflightResult {\n ok: boolean;\n exit_code: 0 | 1;\n url: string;\n checked_at: string;\n overall_status: string;\n active_incidents_count: number;\n degraded_surfaces: Array<{ id: string; name: string; status: string }>;\n flagged_sources: Array<{\n id: string;\n http_status: number | string | null;\n error: string | null;\n }>;\n reasons: string[];\n error?: string;\n}\n\nexport function resolvePreflightStatusUrl(options?: {\n statusUrl?: string;\n env?: NodeJS.ProcessEnv;\n}): string {\n if (options?.statusUrl && options.statusUrl.trim().length > 0) {\n return options.statusUrl.trim();\n }\n const env = options?.env ?? process.env;\n const statusUrl = env.MODELCRAFT_STATUS_URL?.trim();\n if (statusUrl) {\n return statusUrl;\n }\n const dataUrl = env.MODELCRAFT_DATA_URL?.trim();\n const base = (dataUrl || DEFAULT_DATA_URL).replace(/\\/+$/, \"\");\n return `${base}/status.json`;\n}\n\nfunction isRateOrCapacityError(status: unknown, errorText: unknown): boolean {\n if (status === 429 || status === 503 || status === \"429\" || status === \"503\") {\n return true;\n }\n if (typeof errorText === \"string\" && /\\b(429|503)\\b/.test(errorText)) {\n return true;\n }\n return false;\n}\n\n/**\n * Live cloud preflight guard against ModelCraft status.json.\n * Performs a single parameterless GET with zero user identifiers or credentials.\n * Returns exit_code 0 only when upstream is operational with no active incidents,\n * no degraded surfaces, and no 429/503 source errors.\n */\nexport async function runPreflight(\n options?: PreflightOptions,\n): Promise<PreflightResult> {\n const url = resolvePreflightStatusUrl(options);\n const fetchFn = options?.fetchFn ?? globalThis.fetch;\n const timeoutMs = options?.timeoutMs ?? 5000;\n const checkedAt = new Date().toISOString();\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n let data: StatusSnapshot;\n try {\n const resp = await fetchFn(url, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n });\n\n if (!resp.ok) {\n const reason = `HTTP ${resp.status} ${resp.statusText || \"\"}`.trim();\n return {\n ok: false,\n exit_code: 1,\n url,\n checked_at: checkedAt,\n overall_status: \"unknown\",\n active_incidents_count: 0,\n degraded_surfaces: [],\n flagged_sources: [],\n reasons: [`Failed to fetch status.json (${reason})`],\n error: reason,\n };\n }\n\n data = (await resp.json()) as StatusSnapshot;\n } catch (err) {\n const msg =\n err instanceof Error\n ? err.name === \"AbortError\"\n ? `Request timed out after ${timeoutMs}ms`\n : err.message\n : String(err);\n return {\n ok: false,\n exit_code: 1,\n url,\n checked_at: checkedAt,\n overall_status: \"unknown\",\n active_incidents_count: 0,\n degraded_surfaces: [],\n flagged_sources: [],\n reasons: [`Failed to fetch status.json: ${msg}`],\n error: msg,\n };\n } finally {\n clearTimeout(timer);\n }\n\n const reasons: string[] = [];\n const overallStatus =\n typeof data?.overall_status === \"string\" ? data.overall_status : \"unknown\";\n if (overallStatus !== \"operational\") {\n reasons.push(\n `overall_status is \"${overallStatus}\" (expected \"operational\")`,\n );\n }\n\n const incidents = Array.isArray(data?.active_incidents)\n ? data.active_incidents\n : [];\n if (incidents.length > 0) {\n const titles = incidents\n .map((inc) => inc?.title || inc?.id || \"unnamed incident\")\n .slice(0, 3)\n .join(\"; \");\n reasons.push(\n `${incidents.length} active incident(s) reported: ${titles}`,\n );\n }\n\n const surfaces = Array.isArray(data?.surfaces) ? data.surfaces : [];\n const degradedSurfaces = surfaces\n .filter((s) => s && s.status !== \"operational\")\n .map((s) => ({\n id: String(s.id ?? \"unknown\"),\n name: String(s.name ?? s.id ?? \"unknown\"),\n status: String(s.status ?? \"unknown\"),\n }));\n for (const s of degradedSurfaces) {\n reasons.push(`surface \"${s.id}\" is \"${s.status}\"`);\n }\n\n const sources = Array.isArray(data?.sources_checked)\n ? data.sources_checked\n : [];\n const flaggedSources: Array<{\n id: string;\n http_status: number | string | null;\n error: string | null;\n }> = [];\n\n for (const src of sources) {\n if (typeof src === \"string\") {\n if (/\\b(429|503)\\b/.test(src)) {\n flaggedSources.push({ id: src, http_status: null, error: src });\n reasons.push(`source \"${src}\" reported 429/503`);\n }\n continue;\n }\n if (src && typeof src === \"object\") {\n const rec = src as Record<string, unknown>;\n const id = String(rec[\"id\"] ?? rec[\"url\"] ?? \"unknown\");\n const httpStatus =\n typeof rec[\"http_status\"] === \"number\" ||\n typeof rec[\"http_status\"] === \"string\"\n ? rec[\"http_status\"]\n : null;\n const errStr = typeof rec[\"error\"] === \"string\" ? rec[\"error\"] : null;\n if (isRateOrCapacityError(httpStatus, errStr)) {\n flaggedSources.push({ id, http_status: httpStatus, error: errStr });\n reasons.push(\n `source \"${id}\" reported ${httpStatus !== null ? `HTTP ${httpStatus}` : errStr ?? \"429/503\"}`,\n );\n }\n }\n }\n\n const ok = reasons.length === 0;\n return {\n ok,\n exit_code: ok ? 0 : 1,\n url,\n checked_at: checkedAt,\n overall_status: overallStatus,\n active_incidents_count: incidents.length,\n degraded_surfaces: degradedSurfaces,\n flagged_sources: flaggedSources,\n reasons,\n };\n}\n\nexport function formatPreflightReport(result: PreflightResult): string {\n const lines: string[] = [\n `agycraft-mcp preflight (${result.url})`,\n \"================================================================\",\n `Status: ${result.ok ? \"[PASS]\" : \"[FAIL]\"} overall_status=${result.overall_status} active_incidents=${result.active_incidents_count}`,\n ];\n\n if (result.reasons.length > 0) {\n lines.push(\"Blocking checks:\");\n for (const reason of result.reasons) {\n lines.push(` - ${reason}`);\n }\n } else {\n lines.push(\"All surfaces operational; no active incidents or 429/503 source errors.\");\n }\n\n return lines.join(\"\\n\");\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport type HookTarget = \"agy\" | \"gemini\" | \"both\";\nexport type HookKind = \"stop\" | \"record\";\nexport type HookAction = \"enable\" | \"disable\" | \"status\";\n\nexport interface HookTargetConfig {\n target: \"agy\" | \"gemini\" | \"custom\";\n path: string;\n}\n\nexport interface HookEnableOptions {\n kind?: HookKind;\n target?: HookTarget;\n settingsPath?: string;\n command?: string;\n local?: boolean;\n lang?: string;\n dryRun?: boolean;\n homeDir?: string;\n argv1?: string;\n}\n\nexport interface HookDisableOptions {\n kind?: HookKind;\n target?: HookTarget;\n settingsPath?: string;\n dryRun?: boolean;\n homeDir?: string;\n}\n\nexport interface HookStatusOptions {\n kind?: HookKind;\n target?: HookTarget;\n settingsPath?: string;\n homeDir?: string;\n}\n\nexport interface HookTargetResult {\n target: \"agy\" | \"gemini\" | \"custom\";\n path: string;\n exists: boolean;\n enabled: boolean;\n status:\n | \"enabled\"\n | \"updated\"\n | \"unchanged\"\n | \"disabled\"\n | \"already_disabled\"\n | \"not_found\"\n | \"active\"\n | \"inactive\"\n | \"error\";\n commands: string[];\n error?: string;\n}\n\nexport interface HookManageResult {\n action: HookAction;\n kind: HookKind;\n dry_run: boolean;\n command?: string;\n targets: HookTargetResult[];\n ok: boolean;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isAgycraftSubcommand(\n command: unknown,\n subcommand: \"hook-check\" | \"record\",\n): command is string {\n if (typeof command !== \"string\") {\n return false;\n }\n const trimmed = command.trim();\n if (!trimmed) {\n return false;\n }\n const hasSubcommand = new RegExp(`(?:^|\\\\s)${subcommand}(?:\\\\s|$)`).test(trimmed);\n if (!hasSubcommand) {\n return false;\n }\n return (\n /(?:^|\\s|[\"'\\\\/])agycraft-mcp(?:\\s|[\"']|$)/.test(trimmed) ||\n /(?:^|\\s|[\"'\\\\/])dist[\\\\/]index\\.js(?:\\s|[\"']|$)/.test(trimmed)\n );\n}\n\n/**\n * Matches `agycraft-mcp hook-check` or `node .../dist/index.js hook-check` commands.\n */\nexport function isAgycraftHookCheckCommand(command: unknown): command is string {\n return isAgycraftSubcommand(command, \"hook-check\");\n}\n\n/**\n * Matches `agycraft-mcp record` or `node .../dist/index.js record` commands.\n */\nexport function isAgycraftHookRecordCommand(command: unknown): command is string {\n return isAgycraftSubcommand(command, \"record\");\n}\n\nexport function resolveTargetSettingsPaths(options?: {\n kind?: HookKind;\n target?: HookTarget;\n settingsPath?: string;\n homeDir?: string;\n}): HookTargetConfig[] {\n if (options?.settingsPath) {\n return [{ target: \"custom\", path: resolve(options.settingsPath) }];\n }\n const home = options?.homeDir ?? homedir();\n if (options?.kind === \"record\") {\n return [{ target: \"agy\", path: join(home, \".gemini\", \"config\", \"hooks.json\") }];\n }\n const target = options?.target ?? \"agy\";\n const agyPath = join(home, \".gemini\", \"antigravity-cli\", \"settings.json\");\n const geminiPath = join(home, \".gemini\", \"settings.json\");\n\n if (target === \"agy\") {\n return [{ target: \"agy\", path: agyPath }];\n }\n if (target === \"gemini\") {\n return [{ target: \"gemini\", path: geminiPath }];\n }\n return [\n { target: \"agy\", path: agyPath },\n { target: \"gemini\", path: geminiPath },\n ];\n}\n\nfunction quoteIfNeeded(filePath: string): string {\n return /\\s/.test(filePath) ? `\"${filePath}\"` : filePath;\n}\n\nexport function findLocalDistIndexPath(argv1?: string): string | null {\n if (argv1) {\n const resolvedArgv = resolve(argv1);\n if (\n /[\\\\/]dist[\\\\/]index\\.js$/.test(resolvedArgv) &&\n !resolvedArgv.includes(\"node_modules\") &&\n !resolvedArgv.includes(\"_npx\") &&\n existsSync(resolvedArgv)\n ) {\n return resolvedArgv;\n }\n }\n\n try {\n const currentFile = fileURLToPath(import.meta.url);\n const candidates = [\n resolve(dirname(currentFile), \"index.js\"),\n resolve(dirname(currentFile), \"../dist/index.js\"),\n resolve(dirname(currentFile), \"../../dist/index.js\"),\n ];\n for (const candidate of candidates) {\n if (\n /[\\\\/]dist[\\\\/]index\\.js$/.test(candidate) &&\n !candidate.includes(\"node_modules\") &&\n existsSync(candidate)\n ) {\n return candidate;\n }\n }\n } catch {\n // Ignore URL resolution errors\n }\n\n return null;\n}\n\nexport function resolveHookCommand(options?: {\n kind?: HookKind;\n command?: string;\n local?: boolean;\n lang?: string;\n argv1?: string;\n}): string {\n if (options?.command !== undefined) {\n const trimmed = options.command.trim();\n if (!trimmed) {\n throw new Error(\"--command cannot be empty.\");\n }\n return trimmed;\n }\n\n const kind: HookKind = options?.kind ?? \"stop\";\n const subcommand = kind === \"record\" ? \"record\" : \"hook-check\";\n const langSuffix = kind === \"stop\" && options?.lang ? ` --lang ${options.lang}` : \"\";\n const argv1 = options?.argv1 ?? process.argv[1];\n\n if (options?.local) {\n const localDist = findLocalDistIndexPath(argv1);\n if (!localDist) {\n throw new Error(\n \"Could not locate local dist/index.js. Run `npm run build` first or pass --command <cmd>.\",\n );\n }\n return `node ${quoteIfNeeded(localDist)} ${subcommand}${langSuffix}`;\n }\n\n if (argv1) {\n const resolvedArgv = resolve(argv1);\n if (\n /[\\\\/]dist[\\\\/]index\\.js$/.test(resolvedArgv) &&\n !resolvedArgv.includes(\"node_modules\") &&\n !resolvedArgv.includes(\"_npx\") &&\n existsSync(resolvedArgv)\n ) {\n return `node ${quoteIfNeeded(resolvedArgv)} ${subcommand}${langSuffix}`;\n }\n if (\n /[\\\\/]agycraft-mcp$/.test(resolvedArgv) &&\n !resolvedArgv.includes(\"_npx\")\n ) {\n return `agycraft-mcp ${subcommand}${langSuffix}`;\n }\n }\n\n return `npx -y agycraft-mcp ${subcommand}${langSuffix}`;\n}\n\nasync function readSettingsJson(\n filePath: string,\n): Promise<{ exists: boolean; data: Record<string, unknown> } | { exists: true; error: string }> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"ENOENT\") {\n return { exists: false, data: {} };\n }\n return {\n exists: true,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n\n if (raw.trim().length === 0) {\n return { exists: true, data: {} };\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!isPlainObject(parsed)) {\n return {\n exists: true,\n error: \"settings.json root must be a JSON object.\",\n };\n }\n return { exists: true, data: parsed };\n } catch (err) {\n return {\n exists: true,\n error: `Invalid JSON in ${filePath}: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n\nfunction collectMatchingHookCommands(\n entries: unknown[],\n matcher: (command: unknown) => command is string,\n): string[] {\n const found: string[] = [];\n for (const entry of entries) {\n if (!isPlainObject(entry)) {\n continue;\n }\n const innerHooks = entry[\"hooks\"];\n if (!Array.isArray(innerHooks)) {\n continue;\n }\n for (const h of innerHooks) {\n if (isPlainObject(h) && matcher(h[\"command\"])) {\n found.push(h[\"command\"]);\n }\n }\n }\n return found;\n}\n\nasync function writeSettingsJson(\n filePath: string,\n data: Record<string, unknown>,\n): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, `${JSON.stringify(data, null, 2)}\\n`, \"utf8\");\n}\n\nexport async function runHookEnable(\n options?: HookEnableOptions,\n): Promise<HookManageResult> {\n const kind: HookKind = options?.kind ?? \"stop\";\n const hookEventKey = kind === \"record\" ? \"PostInvocation\" : \"Stop\";\n const isMatchingCommand =\n kind === \"record\" ? isAgycraftHookRecordCommand : isAgycraftHookCheckCommand;\n\n const command = resolveHookCommand({\n kind,\n command: options?.command,\n local: options?.local,\n lang: options?.lang,\n argv1: options?.argv1,\n });\n const dryRun = Boolean(options?.dryRun);\n const targets = resolveTargetSettingsPaths({\n kind,\n target: options?.target,\n settingsPath: options?.settingsPath,\n homeDir: options?.homeDir,\n });\n\n const results: HookTargetResult[] = [];\n let ok = true;\n\n for (const t of targets) {\n const loaded = await readSettingsJson(t.path);\n if (\"error\" in loaded) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: loaded.exists,\n enabled: false,\n status: \"error\",\n commands: [],\n error: loaded.error,\n });\n continue;\n }\n\n const root = structuredClone(loaded.data);\n const rawHooks = root[\"hooks\"];\n if (rawHooks !== undefined && !isPlainObject(rawHooks)) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: loaded.exists,\n enabled: false,\n status: \"error\",\n commands: [],\n error: \"`hooks` field must be a JSON object.\",\n });\n continue;\n }\n\n const hooksObj: Record<string, unknown> = isPlainObject(rawHooks)\n ? rawHooks\n : {};\n const rawEventHooks = hooksObj[hookEventKey];\n if (rawEventHooks !== undefined && !Array.isArray(rawEventHooks)) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: loaded.exists,\n enabled: false,\n status: \"error\",\n commands: [],\n error: `\\`hooks.${hookEventKey}\\` field must be a JSON array.`,\n });\n continue;\n }\n\n const eventArr: unknown[] = Array.isArray(rawEventHooks) ? rawEventHooks : [];\n const existingCommands = collectMatchingHookCommands(eventArr, isMatchingCommand);\n\n if (existingCommands.length > 0) {\n let changed = false;\n for (const entry of eventArr) {\n if (!isPlainObject(entry) || !Array.isArray(entry[\"hooks\"])) {\n continue;\n }\n for (const h of entry[\"hooks\"]) {\n if (isPlainObject(h) && isMatchingCommand(h[\"command\"])) {\n if (h[\"command\"] !== command) {\n h[\"command\"] = command;\n changed = true;\n }\n if (kind === \"record\" && h[\"timeout\"] !== 3000) {\n h[\"timeout\"] = 3000;\n changed = true;\n }\n }\n }\n }\n\n if (changed && !dryRun) {\n await writeSettingsJson(t.path, root);\n }\n\n results.push({\n target: t.target,\n path: t.path,\n exists: loaded.exists,\n enabled: true,\n status: changed ? \"updated\" : \"unchanged\",\n commands: changed ? [command] : existingCommands,\n });\n continue;\n }\n\n if (kind === \"record\") {\n eventArr.push({\n matcher: \".*\",\n hooks: [\n {\n type: \"command\",\n command,\n timeout: 3000,\n },\n ],\n });\n } else {\n eventArr.push({\n hooks: [\n {\n type: \"command\",\n command,\n },\n ],\n });\n }\n hooksObj[hookEventKey] = eventArr;\n root[\"hooks\"] = hooksObj;\n\n if (!dryRun) {\n await writeSettingsJson(t.path, root);\n }\n\n results.push({\n target: t.target,\n path: t.path,\n exists: loaded.exists,\n enabled: true,\n status: \"enabled\",\n commands: [command],\n });\n }\n\n return {\n action: \"enable\",\n kind,\n dry_run: dryRun,\n command,\n targets: results,\n ok,\n };\n}\n\nexport async function runHookDisable(\n options?: HookDisableOptions,\n): Promise<HookManageResult> {\n const kind: HookKind = options?.kind ?? \"stop\";\n const hookEventKey = kind === \"record\" ? \"PostInvocation\" : \"Stop\";\n const isMatchingCommand =\n kind === \"record\" ? isAgycraftHookRecordCommand : isAgycraftHookCheckCommand;\n\n const dryRun = Boolean(options?.dryRun);\n const targets = resolveTargetSettingsPaths({\n kind,\n target: options?.target,\n settingsPath: options?.settingsPath,\n homeDir: options?.homeDir,\n });\n\n const results: HookTargetResult[] = [];\n let ok = true;\n\n for (const t of targets) {\n const loaded = await readSettingsJson(t.path);\n if (\"error\" in loaded) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: loaded.exists,\n enabled: false,\n status: \"error\",\n commands: [],\n error: loaded.error,\n });\n continue;\n }\n\n if (!loaded.exists) {\n results.push({\n target: t.target,\n path: t.path,\n exists: false,\n enabled: false,\n status: \"not_found\",\n commands: [],\n });\n continue;\n }\n\n const root = structuredClone(loaded.data);\n const rawHooks = root[\"hooks\"];\n if (rawHooks === undefined) {\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled: false,\n status: \"already_disabled\",\n commands: [],\n });\n continue;\n }\n if (!isPlainObject(rawHooks)) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled: false,\n status: \"error\",\n commands: [],\n error: \"`hooks` field must be a JSON object.\",\n });\n continue;\n }\n\n const rawEventHooks = rawHooks[hookEventKey];\n if (rawEventHooks === undefined) {\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled: false,\n status: \"already_disabled\",\n commands: [],\n });\n continue;\n }\n if (!Array.isArray(rawEventHooks)) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled: false,\n status: \"error\",\n commands: [],\n error: `\\`hooks.${hookEventKey}\\` field must be a JSON array.`,\n });\n continue;\n }\n\n const removedCommands: string[] = [];\n const nextEventHooks: unknown[] = [];\n\n for (const entry of rawEventHooks) {\n if (!isPlainObject(entry) || !Array.isArray(entry[\"hooks\"])) {\n nextEventHooks.push(entry);\n continue;\n }\n\n const keptHooks: unknown[] = [];\n let entryHadMatch = false;\n for (const h of entry[\"hooks\"]) {\n if (isPlainObject(h) && isMatchingCommand(h[\"command\"])) {\n removedCommands.push(h[\"command\"]);\n entryHadMatch = true;\n } else {\n keptHooks.push(h);\n }\n }\n\n if (!entryHadMatch) {\n nextEventHooks.push(entry);\n } else if (keptHooks.length > 0) {\n nextEventHooks.push({\n ...entry,\n hooks: keptHooks,\n });\n }\n // If entryHadMatch && keptHooks.length === 0, drop the empty wrapper group\n }\n\n if (removedCommands.length === 0) {\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled: false,\n status: \"already_disabled\",\n commands: [],\n });\n continue;\n }\n\n if (nextEventHooks.length > 0) {\n rawHooks[hookEventKey] = nextEventHooks;\n } else {\n delete rawHooks[hookEventKey];\n }\n\n if (Object.keys(rawHooks).length === 0) {\n delete root[\"hooks\"];\n }\n\n if (!dryRun) {\n await writeSettingsJson(t.path, root);\n }\n\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled: false,\n status: \"disabled\",\n commands: removedCommands,\n });\n }\n\n return {\n action: \"disable\",\n kind,\n dry_run: dryRun,\n targets: results,\n ok,\n };\n}\n\nexport async function runHookStatus(\n options?: HookStatusOptions,\n): Promise<HookManageResult> {\n const kind: HookKind = options?.kind ?? \"stop\";\n const hookEventKey = kind === \"record\" ? \"PostInvocation\" : \"Stop\";\n const isMatchingCommand =\n kind === \"record\" ? isAgycraftHookRecordCommand : isAgycraftHookCheckCommand;\n\n const targets = resolveTargetSettingsPaths({\n kind,\n target: options?.target,\n settingsPath: options?.settingsPath,\n homeDir: options?.homeDir,\n });\n\n const results: HookTargetResult[] = [];\n let ok = true;\n\n for (const t of targets) {\n const loaded = await readSettingsJson(t.path);\n if (\"error\" in loaded) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: loaded.exists,\n enabled: false,\n status: \"error\",\n commands: [],\n error: loaded.error,\n });\n continue;\n }\n\n if (!loaded.exists) {\n results.push({\n target: t.target,\n path: t.path,\n exists: false,\n enabled: false,\n status: \"not_found\",\n commands: [],\n });\n continue;\n }\n\n const rawHooks = loaded.data[\"hooks\"];\n if (rawHooks !== undefined && !isPlainObject(rawHooks)) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled: false,\n status: \"error\",\n commands: [],\n error: \"`hooks` field must be a JSON object.\",\n });\n continue;\n }\n\n const rawEventHooks = isPlainObject(rawHooks) ? rawHooks[hookEventKey] : undefined;\n if (rawEventHooks !== undefined && !Array.isArray(rawEventHooks)) {\n ok = false;\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled: false,\n status: \"error\",\n commands: [],\n error: `\\`hooks.${hookEventKey}\\` field must be a JSON array.`,\n });\n continue;\n }\n\n const commands = Array.isArray(rawEventHooks)\n ? collectMatchingHookCommands(rawEventHooks, isMatchingCommand)\n : [];\n const enabled = commands.length > 0;\n\n results.push({\n target: t.target,\n path: t.path,\n exists: true,\n enabled,\n status: enabled ? \"active\" : \"inactive\",\n commands,\n });\n }\n\n return {\n action: \"status\",\n kind,\n dry_run: false,\n targets: results,\n ok,\n };\n}\n\nexport function formatHookManageResult(result: HookManageResult): string {\n const lines: string[] = [];\n const dryPrefix = result.dry_run ? \"[dry-run] \" : \"\";\n const kindSuffix = result.kind === \"record\" ? \" (kind: record)\" : \"\";\n lines.push(`${dryPrefix}agycraft-mcp hook ${result.action}${kindSuffix}`);\n for (const t of result.targets) {\n if (t.status === \"error\") {\n lines.push(` [${t.target}] ERROR (${t.path}): ${t.error}`);\n continue;\n }\n const cmdInfo = t.commands.length > 0 ? ` -> ${t.commands.join(\", \")}` : \"\";\n lines.push(` [${t.target}] ${t.status} (${t.path})${cmdInfo}`);\n }\n return lines.join(\"\\n\");\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { GEMINIIGNORE_TEMPLATE } from \"./doctor.js\";\n\nexport type IgnoreInitStatus = \"created\" | \"updated\" | \"unchanged\" | \"error\";\n\nexport interface IgnoreInitOptions {\n dir?: string;\n dryRun?: boolean;\n json?: boolean;\n}\n\nexport interface IgnoreInitResult {\n ok: boolean;\n status: IgnoreInitStatus;\n target_path: string;\n added_rules: string[];\n dry_run: boolean;\n message: string;\n}\n\n/**\n * Extract non-empty, non-comment rule lines from a .geminiignore content string.\n */\nexport function extractIgnoreRules(content: string): string[] {\n const seen = new Set<string>();\n const rules: string[] = [];\n\n for (const rawLine of content.split(/\\r?\\n/)) {\n const trimmed = rawLine.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) {\n continue;\n }\n if (!seen.has(trimmed)) {\n seen.add(trimmed);\n rules.push(trimmed);\n }\n }\n\n return rules;\n}\n\nexport async function runIgnoreInit(options: IgnoreInitOptions = {}): Promise<IgnoreInitResult> {\n const targetDir = resolve(options.dir ?? process.cwd());\n const targetPath = join(targetDir, \".geminiignore\");\n const dryRun = Boolean(options.dryRun);\n const templateRules = extractIgnoreRules(GEMINIIGNORE_TEMPLATE);\n\n try {\n if (!existsSync(targetPath)) {\n const content = GEMINIIGNORE_TEMPLATE.endsWith(\"\\n\")\n ? GEMINIIGNORE_TEMPLATE\n : `${GEMINIIGNORE_TEMPLATE}\\n`;\n\n if (!dryRun) {\n await mkdir(dirname(targetPath), { recursive: true });\n await writeFile(targetPath, content, \"utf8\");\n }\n\n return {\n ok: true,\n status: \"created\",\n target_path: targetPath,\n added_rules: templateRules,\n dry_run: dryRun,\n message: dryRun\n ? `Would create ${targetPath} with ${templateRules.length} template rules.`\n : `Created ${targetPath} with ${templateRules.length} template rules.`,\n };\n }\n\n const existingContent = await readFile(targetPath, \"utf8\");\n const existingRules = new Set(extractIgnoreRules(existingContent));\n const missingRules = templateRules.filter((rule) => !existingRules.has(rule));\n\n if (missingRules.length === 0) {\n return {\n ok: true,\n status: \"unchanged\",\n target_path: targetPath,\n added_rules: [],\n dry_run: dryRun,\n message: `All template rules are already present in ${targetPath}.`,\n };\n }\n\n const prefix =\n existingContent.length === 0\n ? \"\"\n : existingContent.endsWith(\"\\n\\n\") || existingContent.endsWith(\"\\r\\n\\r\\n\")\n ? \"\"\n : existingContent.endsWith(\"\\n\")\n ? \"\\n\"\n : \"\\n\\n\";\n const appendBlock = `${prefix}# Added by agycraft-mcp ignore init\\n${missingRules.join(\"\\n\")}\\n`;\n const nextContent = `${existingContent}${appendBlock}`;\n\n if (!dryRun) {\n await writeFile(targetPath, nextContent, \"utf8\");\n }\n\n return {\n ok: true,\n status: \"updated\",\n target_path: targetPath,\n added_rules: missingRules,\n dry_run: dryRun,\n message: dryRun\n ? `Would append ${missingRules.length} missing rule(s) to ${targetPath}.`\n : `Appended ${missingRules.length} missing rule(s) to ${targetPath}.`,\n };\n } catch (err) {\n return {\n ok: false,\n status: \"error\",\n target_path: targetPath,\n added_rules: [],\n dry_run: dryRun,\n message: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport function formatIgnoreInitResult(result: IgnoreInitResult, json = false): string {\n if (json) {\n return JSON.stringify(result, null, 2);\n }\n\n const lines: string[] = [];\n const dryPrefix = result.dry_run ? \"[dry-run] \" : \"\";\n lines.push(`${dryPrefix}agycraft-mcp ignore init`);\n lines.push(` status: ${result.status}`);\n lines.push(` target: ${result.target_path}`);\n lines.push(` added_rules: ${result.added_rules.length}`);\n if (result.added_rules.length > 0) {\n for (const rule of result.added_rules) {\n lines.push(` + ${rule}`);\n }\n }\n lines.push(` message: ${result.message}`);\n return lines.join(\"\\n\");\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { getDefaultGeminiTelemetryPath } from \"../paths.js\";\n\nexport type TelemetryAction = \"enable\" | \"disable\" | \"status\";\nexport type TelemetryStatus =\n | \"enabled\"\n | \"updated\"\n | \"unchanged\"\n | \"disabled\"\n | \"already_disabled\"\n | \"not_found\"\n | \"active\"\n | \"inactive\"\n | \"error\";\n\nexport interface TelemetryConfig {\n enabled: boolean;\n target: \"local\";\n otlpEndpoint: \"\";\n logPrompts: false;\n outfile: string;\n}\n\nexport interface TelemetryEnableOptions {\n settingsPath?: string;\n homeDir?: string;\n outfile?: string;\n dryRun?: boolean;\n}\n\nexport interface TelemetryDisableOptions {\n settingsPath?: string;\n homeDir?: string;\n dryRun?: boolean;\n}\n\nexport interface TelemetryStatusOptions {\n settingsPath?: string;\n homeDir?: string;\n}\n\nexport interface TelemetryManageResult {\n action: TelemetryAction;\n dry_run: boolean;\n path: string;\n exists: boolean;\n enabled: boolean;\n safe: boolean;\n log_prompts_safe: boolean;\n outfile: string | null;\n status: TelemetryStatus;\n message: string;\n telemetry?: Record<string, unknown> | null;\n error?: string;\n ok: boolean;\n}\n\nconst DEFAULT_GEMINI_TELEMETRY_OUTFILE = \"~/.gemini/telemetry_stats.jsonl\";\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function resolveTelemetrySettingsPath(options?: {\n settingsPath?: string;\n homeDir?: string;\n}): string {\n if (options?.settingsPath && options.settingsPath.trim().length > 0) {\n return resolve(options.settingsPath.trim());\n }\n const home = options?.homeDir ?? homedir();\n return join(home, \".gemini\", \"settings.json\");\n}\n\nexport function resolveTelemetryOutfile(outfile?: string): string {\n if (outfile && outfile.trim().length > 0) {\n return outfile.trim();\n }\n const envOverride = process.env.AGYCRAFT_GEMINI_OTEL_PATH;\n if (envOverride && envOverride.trim().length > 0) {\n return getDefaultGeminiTelemetryPath();\n }\n return DEFAULT_GEMINI_TELEMETRY_OUTFILE;\n}\n\nexport function buildSafeTelemetryConfig(options?: { outfile?: string }): TelemetryConfig {\n return {\n enabled: true,\n target: \"local\",\n otlpEndpoint: \"\",\n logPrompts: false,\n outfile: resolveTelemetryOutfile(options?.outfile),\n };\n}\n\nasync function readSettingsJson(\n filePath: string,\n): Promise<{ exists: boolean; data: Record<string, unknown> } | { exists: true; error: string }> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"ENOENT\") {\n return { exists: false, data: {} };\n }\n return {\n exists: true,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n\n if (raw.trim().length === 0) {\n return { exists: true, data: {} };\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!isPlainObject(parsed)) {\n return {\n exists: true,\n error: \"settings.json root must be a JSON object.\",\n };\n }\n return { exists: true, data: parsed };\n } catch (err) {\n return {\n exists: true,\n error: `Invalid JSON in ${filePath}: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n\nasync function writeSettingsJson(\n filePath: string,\n data: Record<string, unknown>,\n): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, `${JSON.stringify(data, null, 2)}\\n`, \"utf8\");\n}\n\nexport async function runTelemetryEnable(\n options?: TelemetryEnableOptions,\n): Promise<TelemetryManageResult> {\n const dryRun = Boolean(options?.dryRun);\n const settingsPath = resolveTelemetrySettingsPath({\n settingsPath: options?.settingsPath,\n homeDir: options?.homeDir,\n });\n\n const loaded = await readSettingsJson(settingsPath);\n if (\"error\" in loaded) {\n return {\n action: \"enable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: loaded.exists,\n enabled: false,\n safe: false,\n log_prompts_safe: false,\n outfile: null,\n status: \"error\",\n message: loaded.error,\n error: loaded.error,\n ok: false,\n };\n }\n\n const root = structuredClone(loaded.data);\n const rawTelemetry = root[\"telemetry\"];\n if (rawTelemetry !== undefined && !isPlainObject(rawTelemetry)) {\n const errMsg = \"`telemetry` field must be a JSON object.\";\n return {\n action: \"enable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: loaded.exists,\n enabled: false,\n safe: false,\n log_prompts_safe: false,\n outfile: null,\n status: \"error\",\n message: errMsg,\n error: errMsg,\n ok: false,\n };\n }\n\n const safeConfig = buildSafeTelemetryConfig({ outfile: options?.outfile });\n\n if (rawTelemetry === undefined) {\n root[\"telemetry\"] = safeConfig;\n if (!dryRun) {\n await writeSettingsJson(settingsPath, root);\n }\n return {\n action: \"enable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: loaded.exists,\n enabled: true,\n safe: true,\n log_prompts_safe: true,\n outfile: safeConfig.outfile,\n status: \"enabled\",\n message: `Enabled privacy-safe local telemetry in ${settingsPath} (logPrompts=false).`,\n telemetry: safeConfig as unknown as Record<string, unknown>,\n ok: true,\n };\n }\n\n const nextTelemetry: Record<string, unknown> = {\n ...rawTelemetry,\n enabled: safeConfig.enabled,\n target: safeConfig.target,\n otlpEndpoint: safeConfig.otlpEndpoint,\n logPrompts: safeConfig.logPrompts,\n outfile: safeConfig.outfile,\n };\n\n const changed =\n rawTelemetry[\"enabled\"] !== safeConfig.enabled ||\n rawTelemetry[\"target\"] !== safeConfig.target ||\n rawTelemetry[\"otlpEndpoint\"] !== safeConfig.otlpEndpoint ||\n rawTelemetry[\"logPrompts\"] !== safeConfig.logPrompts ||\n rawTelemetry[\"outfile\"] !== safeConfig.outfile;\n\n if (!changed) {\n return {\n action: \"enable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: loaded.exists,\n enabled: true,\n safe: true,\n log_prompts_safe: true,\n outfile: safeConfig.outfile,\n status: \"unchanged\",\n message: `Privacy-safe local telemetry is already configured in ${settingsPath}.`,\n telemetry: nextTelemetry,\n ok: true,\n };\n }\n\n root[\"telemetry\"] = nextTelemetry;\n if (!dryRun) {\n await writeSettingsJson(settingsPath, root);\n }\n\n return {\n action: \"enable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: loaded.exists,\n enabled: true,\n safe: true,\n log_prompts_safe: true,\n outfile: safeConfig.outfile,\n status: \"updated\",\n message: `Updated telemetry config in ${settingsPath} with privacy-safe defaults (logPrompts=false).`,\n telemetry: nextTelemetry,\n ok: true,\n };\n}\n\n/**\n * Disables telemetry by removing the top-level `telemetry` field from settings.json\n * while preserving all other top-level fields (mcpServers, hooks, theme, etc.).\n * Removing the managed `telemetry` object ensures idempotent disable/re-enable cycles.\n */\nexport async function runTelemetryDisable(\n options?: TelemetryDisableOptions,\n): Promise<TelemetryManageResult> {\n const dryRun = Boolean(options?.dryRun);\n const settingsPath = resolveTelemetrySettingsPath({\n settingsPath: options?.settingsPath,\n homeDir: options?.homeDir,\n });\n\n const loaded = await readSettingsJson(settingsPath);\n if (\"error\" in loaded) {\n return {\n action: \"disable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: loaded.exists,\n enabled: false,\n safe: false,\n log_prompts_safe: false,\n outfile: null,\n status: \"error\",\n message: loaded.error,\n error: loaded.error,\n ok: false,\n };\n }\n\n if (!loaded.exists) {\n return {\n action: \"disable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: false,\n enabled: false,\n safe: true,\n log_prompts_safe: true,\n outfile: null,\n status: \"not_found\",\n message: `Settings file not found (${settingsPath}); nothing to disable.`,\n telemetry: null,\n ok: true,\n };\n }\n\n const root = structuredClone(loaded.data);\n const rawTelemetry = root[\"telemetry\"];\n if (rawTelemetry === undefined) {\n return {\n action: \"disable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: true,\n enabled: false,\n safe: true,\n log_prompts_safe: true,\n outfile: null,\n status: \"already_disabled\",\n message: `Telemetry is already absent/disabled in ${settingsPath}; no changes made.`,\n telemetry: null,\n ok: true,\n };\n }\n\n if (!isPlainObject(rawTelemetry)) {\n const errMsg = \"`telemetry` field must be a JSON object.\";\n return {\n action: \"disable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: true,\n enabled: false,\n safe: false,\n log_prompts_safe: false,\n outfile: null,\n status: \"error\",\n message: errMsg,\n error: errMsg,\n ok: false,\n };\n }\n\n delete root[\"telemetry\"];\n if (!dryRun) {\n await writeSettingsJson(settingsPath, root);\n }\n\n return {\n action: \"disable\",\n dry_run: dryRun,\n path: settingsPath,\n exists: true,\n enabled: false,\n safe: true,\n log_prompts_safe: true,\n outfile: null,\n status: \"disabled\",\n message: `Removed top-level \\`telemetry\\` field from ${settingsPath}; all other settings preserved.`,\n telemetry: null,\n ok: true,\n };\n}\n\nexport async function runTelemetryStatus(\n options?: TelemetryStatusOptions,\n): Promise<TelemetryManageResult> {\n const settingsPath = resolveTelemetrySettingsPath({\n settingsPath: options?.settingsPath,\n homeDir: options?.homeDir,\n });\n\n const loaded = await readSettingsJson(settingsPath);\n if (\"error\" in loaded) {\n return {\n action: \"status\",\n dry_run: false,\n path: settingsPath,\n exists: loaded.exists,\n enabled: false,\n safe: false,\n log_prompts_safe: false,\n outfile: null,\n status: \"error\",\n message: loaded.error,\n error: loaded.error,\n ok: false,\n };\n }\n\n if (!loaded.exists) {\n return {\n action: \"status\",\n dry_run: false,\n path: settingsPath,\n exists: false,\n enabled: false,\n safe: false,\n log_prompts_safe: true,\n outfile: null,\n status: \"not_found\",\n message: `Settings file not found (${settingsPath}).`,\n telemetry: null,\n ok: true,\n };\n }\n\n const rawTelemetry = loaded.data[\"telemetry\"];\n if (rawTelemetry === undefined) {\n return {\n action: \"status\",\n dry_run: false,\n path: settingsPath,\n exists: true,\n enabled: false,\n safe: true,\n log_prompts_safe: true,\n outfile: null,\n status: \"inactive\",\n message: `Telemetry is not configured in ${settingsPath}.`,\n telemetry: null,\n ok: true,\n };\n }\n\n if (!isPlainObject(rawTelemetry)) {\n const errMsg = \"`telemetry` field must be a JSON object.\";\n return {\n action: \"status\",\n dry_run: false,\n path: settingsPath,\n exists: true,\n enabled: false,\n safe: false,\n log_prompts_safe: false,\n outfile: null,\n status: \"error\",\n message: errMsg,\n error: errMsg,\n ok: false,\n };\n }\n\n const enabled = rawTelemetry[\"enabled\"] === true;\n const logPromptsSafe = rawTelemetry[\"logPrompts\"] === false;\n const targetLocal = rawTelemetry[\"target\"] === \"local\";\n const otlpEmpty =\n rawTelemetry[\"otlpEndpoint\"] === \"\" || rawTelemetry[\"otlpEndpoint\"] === undefined;\n const safe = logPromptsSafe && targetLocal && otlpEmpty;\n const outfile =\n typeof rawTelemetry[\"outfile\"] === \"string\" && rawTelemetry[\"outfile\"].trim().length > 0\n ? rawTelemetry[\"outfile\"].trim()\n : null;\n\n return {\n action: \"status\",\n dry_run: false,\n path: settingsPath,\n exists: true,\n enabled,\n safe,\n log_prompts_safe: logPromptsSafe,\n outfile,\n status: enabled ? \"active\" : \"inactive\",\n message: enabled\n ? `Telemetry is active in ${settingsPath} (logPrompts=${String(rawTelemetry[\"logPrompts\"])}, outfile=${outfile ?? \"unset\"}).`\n : `Telemetry is inactive in ${settingsPath}.`,\n telemetry: rawTelemetry,\n ok: true,\n };\n}\n\nexport function formatTelemetryManageResult(result: TelemetryManageResult): string {\n const dryPrefix = result.dry_run ? \"[dry-run] \" : \"\";\n const lines = [`${dryPrefix}agycraft-mcp telemetry ${result.action}`];\n if (result.status === \"error\") {\n lines.push(` ERROR (${result.path}): ${result.error ?? result.message}`);\n return lines.join(\"\\n\");\n }\n lines.push(` status: ${result.status} (${result.path})`);\n if (result.action === \"status\" && result.exists) {\n lines.push(\n ` enabled: ${result.enabled} | logPrompts===false: ${result.log_prompts_safe} | safe: ${result.safe} | outfile: ${result.outfile ?? \"unset\"}`,\n );\n } else if (result.message) {\n lines.push(` ${result.message}`);\n }\n return lines.join(\"\\n\");\n}\n","import { getUsageLogPath } from \"../paths.js\";\n\n/**\n * Generates non-destructive, opt-in setup instructions & snippets for\n * Antigravity (AGY) and Gemini CLI. Never modifies user files automatically.\n */\nexport function buildSetupInstructions(): string {\n const usagePath = getUsageLogPath();\n return [\n \"agycraft-mcp setup (non-destructive, opt-in instructions)\",\n \"================================================================\",\n \"No files have been modified automatically. Copy and paste only what you want.\",\n \"\",\n \"1. Register agycraft MCP Server:\",\n \"\",\n \" Option A — Antigravity CLI (`agy`) one-liner:\",\n \" agy mcp add agycraft npx -y agycraft-mcp\",\n \"\",\n \" (Local dev testing against a local ModelCraft server):\",\n \" agy mcp add --env MODELCRAFT_DATA_URL=http://127.0.0.1:4321/data/v1 agycraft agycraft-mcp\",\n \"\",\n \" Option B — Antigravity IDE (~/.gemini/antigravity/mcp_config.json)\",\n \" or Gemini CLI (~/.gemini/settings.json):\",\n \"\",\n JSON.stringify(\n {\n mcpServers: {\n agycraft: {\n command: \"npx\",\n args: [\"-y\", \"agycraft-mcp\"],\n },\n },\n },\n null,\n 2,\n ),\n \"\",\n \"2. (Optional) Enable Privacy-Safe Gemini CLI OpenTelemetry outfile (exact token & model metrics)\",\n \" Add to ~/.gemini/settings.json (logPrompts MUST remain false):\",\n \"\",\n JSON.stringify(\n {\n telemetry: {\n enabled: true,\n target: \"local\",\n otlpEndpoint: \"\",\n logPrompts: false,\n outfile: \"~/.gemini/telemetry_stats.jsonl\",\n },\n },\n null,\n 2,\n ),\n \"\",\n \"3. (Optional) Antigravity CLI Hook Recorder (numeric metadata ONLY)\",\n \" Add to ~/.gemini/config/hooks.json (leaves statusLine untouched):\",\n \"\",\n JSON.stringify(\n {\n hooks: {\n PostInvocation: [\n {\n matcher: \".*\",\n hooks: [\n {\n type: \"command\",\n command: \"npx -y agycraft-mcp record\",\n timeout: 3000,\n },\n ],\n },\n ],\n },\n },\n null,\n 2,\n ),\n \"\",\n ` Whitelisted numeric records are stored locally at: ${usagePath}`,\n \" (Strict whitelist: ts, provider, product, session_hash, model, input_tokens,\",\n \" output_tokens, context_used_pct, tool_calls, turn_index, error_code.\",\n \" Prompts, code, paths, and emails are NEVER written or uploaded.)\",\n \" Note: AGY PostInvocation hooks may only capture invocation timestamps/counts\",\n \" if token/model fields aren't emitted, whereas Gemini CLI OTel (step 2)\",\n \" provides exact token/model metrics.\",\n \"\",\n \"4. (Optional) Project-Scoped Sandbox Isolation (zero global ~/.config/agycraft writes):\",\n \" Set AGYCRAFT_CONFIG_DIR to isolate usage.jsonl, .salt, and cache/ inside your repo/sandbox:\",\n \" export AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft\",\n \"\",\n \" CLI one-liners:\",\n \" Gemini CLI (supports --scope project):\",\n \" gemini mcp add --scope project --env AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft agycraft npx -y agycraft-mcp\",\n \" Antigravity CLI:\",\n \" agy mcp add --env AGYCRAFT_CONFIG_DIR=./sandbox_repo/.agycraft agycraft npx -y agycraft-mcp\",\n \"\",\n \" Example sandboxed settings.json / mcp_config.json:\",\n JSON.stringify(\n {\n mcpServers: {\n agycraft: {\n command: \"npx\",\n args: [\"-y\", \"agycraft-mcp\"],\n env: {\n AGYCRAFT_CONFIG_DIR: \"./sandbox_repo/.agycraft\",\n },\n },\n },\n toolPermission: \"proceed-in-sandbox\",\n },\n null,\n 2,\n ),\n \" Note: \\\"toolPermission\\\": \\\"proceed-in-sandbox\\\" is an Antigravity top-level settings.json\",\n \" permission field (sibling to \\\"mcpServers\\\"). `agy mcp add` / `gemini mcp add` do not\",\n \" write this field automatically; add it manually at the top level if needed.\",\n \"\",\n \"5. Verify & Clear Local Data Anytime:\",\n \" npx agycraft-mcp doctor\",\n \" npx agycraft-mcp preflight\",\n \" npx agycraft-mcp clear-local-data\",\n ].join(\"\\n\");\n}\n","import { rm } from \"node:fs/promises\";\nimport {\n getCacheDir,\n getRollupsDir,\n getSaltFilePath,\n getUsageLogPath,\n} from \"../paths.js\";\nimport { resetSaltCache } from \"../collectors/agy-hook.js\";\n\nexport interface ClearLocalDataResult {\n removed: string[];\n}\n\n/**\n * Safely deletes local usage.jsonl, cache directory, rollups directory, and local salt file.\n */\nexport async function clearLocalData(options?: {\n usageLogPath?: string;\n cacheDir?: string;\n rollupsDir?: string;\n saltPath?: string;\n}): Promise<ClearLocalDataResult> {\n const usageLogPath = options?.usageLogPath ?? getUsageLogPath();\n const cacheDir = options?.cacheDir ?? getCacheDir();\n const rollupsDir = options?.rollupsDir ?? getRollupsDir();\n const saltPath = options?.saltPath ?? getSaltFilePath();\n\n const removed: string[] = [];\n\n for (const target of [usageLogPath, saltPath]) {\n try {\n await rm(target, { force: true });\n removed.push(target);\n } catch {\n // ignore if already absent\n }\n }\n\n for (const dir of [cacheDir, rollupsDir]) {\n try {\n await rm(dir, { recursive: true, force: true });\n removed.push(dir);\n } catch {\n // ignore if already absent\n }\n }\n\n resetSaltCache();\n return { removed };\n}\n","import { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { getUsageLogPath } from \"../paths.js\";\nimport {\n type UsageRecord,\n USAGE_RECORD_WHITELIST_KEYS,\n getOrCreateLocalSalt,\n hashProjectPath,\n hashSessionId,\n resetSaltCache,\n sanitizeAuthMode,\n sanitizeErrorCode,\n sanitizeModelName,\n sanitizeUsagePayload,\n} from \"../privacy.js\";\n\nexport {\n type UsageRecord,\n USAGE_RECORD_WHITELIST_KEYS,\n getOrCreateLocalSalt,\n hashProjectPath,\n hashSessionId,\n resetSaltCache,\n sanitizeAuthMode,\n sanitizeErrorCode,\n sanitizeModelName,\n sanitizeUsagePayload,\n};\n\nexport async function appendUsageRecord(\n rawPayload: Record<string, unknown>,\n options?: { logPath?: string; saltPath?: string },\n): Promise<UsageRecord> {\n const logPath = options?.logPath ?? getUsageLogPath();\n const salt = await getOrCreateLocalSalt(options?.saltPath);\n const record = sanitizeUsagePayload(rawPayload, salt);\n await mkdir(dirname(logPath), { recursive: true });\n await appendFile(logPath, `${JSON.stringify(record)}\\n`, {\n encoding: \"utf8\",\n mode: 0o600,\n });\n return record;\n}\n\nexport async function readUsageRecords(options?: {\n logPath?: string;\n sinceMs?: number;\n product?: \"agy\" | \"gemini-cli\" | \"api\" | \"web\" | \"all\";\n salt?: string;\n saltPath?: string;\n}): Promise<UsageRecord[]> {\n const logPath = options?.logPath ?? getUsageLogPath();\n let content: string;\n try {\n content = await readFile(logPath, \"utf8\");\n } catch {\n return [];\n }\n\n const salt = options?.salt ?? (await getOrCreateLocalSalt(options?.saltPath));\n const records: UsageRecord[] = [];\n const lines = content.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n // Re-validate strictly on read as well\n const safe = sanitizeUsagePayload(parsed, salt);\n if (options?.sinceMs !== undefined && Date.parse(safe.ts) < options.sinceMs) {\n continue;\n }\n if (\n options?.product &&\n options.product !== \"all\" &&\n safe.product !== options.product\n ) {\n continue;\n }\n records.push(safe);\n } catch {\n // Skip malformed JSONL lines safely\n }\n }\n\n return records;\n}\n","import { access } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport {\n getOrCreateLocalSalt,\n hashProjectPath,\n readUsageRecords,\n type UsageRecord,\n} from \"./collectors/agy-hook.js\";\nimport { detectAuthContext } from \"./collectors/auth-detector.js\";\nimport { ChannelRegistry } from \"./collectors/channel-registry.js\";\nimport { collectCliLogSignals } from \"./collectors/cli-log.js\";\nimport { readGeminiOtelRecords } from \"./collectors/gemini-otel.js\";\nimport {\n analyzeTranscriptStructure,\n collectTranscriptUsageRecords,\n scanTranscriptActivity,\n type TranscriptActivityFallback,\n} from \"./collectors/transcript-meta.js\";\nimport { analyzeTokenWindow, resolveDataMode } from \"./analyzers/token-window.js\";\nimport { analyzeAntipatterns } from \"./analyzers/antipatterns.js\";\nimport { diagnoseError } from \"./analyzers/error-diagnoser.js\";\nimport { computeResetCountdown } from \"./analyzers/countdown.js\";\nimport { SnapshotClient } from \"./remote/snapshot-client.js\";\nimport { isReadonlyEnv, queryRollups } from \"./storage/rollups.js\";\nimport {\n localizeModelEntry,\n localizeSnapshotText,\n resolveLocale,\n} from \"./i18n.js\";\nimport type { AuthContext, AuthMode } from \"./types.js\";\n\nexport interface ServerDependencies {\n snapshotClient?: SnapshotClient;\n usageLogPath?: string;\n geminiOtelPath?: string;\n brainDir?: string;\n historyPath?: string | null;\n cliLogDir?: string | null;\n saltPath?: string;\n rollupsDir?: string;\n readonly?: boolean;\n authContext?: AuthContext;\n defaultLang?: string;\n}\n\nasync function resolveSaltForServer(deps: ServerDependencies): Promise<string> {\n if (isReadonlyEnv(deps.readonly)) {\n try {\n return await getOrCreateLocalSalt(deps.saltPath);\n } catch {\n return \"readonly-ephemeral-salt\";\n }\n }\n return getOrCreateLocalSalt(deps.saltPath);\n}\n\nasync function resolveScopeProjectHash(\n scope: \"global\" | \"project\",\n workspaceDir: string | undefined,\n deps: ServerDependencies,\n): Promise<string | undefined> {\n if (scope !== \"project\") {\n return undefined;\n }\n const targetDir =\n workspaceDir && workspaceDir.trim().length > 0\n ? workspaceDir.trim()\n : process.cwd();\n const salt = await resolveSaltForServer(deps);\n return hashProjectPath(targetDir, salt);\n}\n\nfunction filterRecordsByScopeAndAuth(\n records: UsageRecord[],\n scope: \"global\" | \"project\",\n projectHash: string | undefined,\n authMode: AuthMode | \"all\",\n registry?: ChannelRegistry,\n): UsageRecord[] {\n return records.filter((r) => {\n if (authMode !== \"all\") {\n const recMode = r.auth_mode ?? \"unknown\";\n const matched = registry\n ? registry.matchesChannel(recMode, authMode)\n : recMode === authMode;\n if (!matched) {\n return false;\n }\n }\n if (scope === \"project\") {\n return Boolean(projectHash) && r.project_hash === projectHash;\n }\n return true;\n });\n}\n\nasync function loadCombinedLocalRecords(\n deps: ServerDependencies,\n sinceMs?: number,\n): Promise<UsageRecord[]> {\n const salt = await resolveSaltForServer(deps);\n const [agyRecords, otelRecords] = await Promise.all([\n readUsageRecords({ logPath: deps.usageLogPath, sinceMs, salt }),\n readGeminiOtelRecords({ otelPath: deps.geminiOtelPath, sinceMs, salt }),\n ]);\n return [...agyRecords, ...otelRecords];\n}\n\nasync function loadMergedUsageRecords(\n deps: ServerDependencies,\n options: {\n product: \"agy\" | \"gemini-cli\" | \"all\";\n activeAuthMode: AuthMode;\n hasMixedAuth?: boolean;\n sinceMs?: number;\n nowMs?: number;\n },\n): Promise<{ records: UsageRecord[]; dataModeOverride?: \"transcript_token_logs\" }> {\n const salt = await resolveSaltForServer(deps);\n const [agyHookRecords, otelRecords] = await Promise.all([\n readUsageRecords({ logPath: deps.usageLogPath, sinceMs: options.sinceMs, salt }),\n readGeminiOtelRecords({ otelPath: deps.geminiOtelPath, sinceMs: options.sinceMs, salt }),\n ]);\n\n const agyOnlyHooks = agyHookRecords.filter((r) => r.product === \"agy\");\n const nonAgyHooks = agyHookRecords.filter((r) => r.product !== \"agy\");\n const agyHasTokens = agyOnlyHooks.some(\n (r) => r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens > 0,\n );\n\n if (options.product === \"gemini-cli\") {\n return { records: [...otelRecords, ...nonAgyHooks] };\n }\n\n const effectiveCliLogDir =\n deps.cliLogDir !== undefined\n ? deps.cliLogDir\n : deps.brainDir !== undefined && !process.env.AGYCRAFT_CLI_LOG_DIR\n ? null\n : undefined;\n\n let transcriptRecords: UsageRecord[] = [];\n let cliBackgroundRecords: UsageRecord[] = [];\n if (!agyHasTokens) {\n const cliLogs = await collectCliLogSignals({\n cliLogDir: effectiveCliLogDir,\n sinceMs: options.sinceMs,\n nowMs: options.nowMs,\n salt,\n fallbackAuthMode: options.activeAuthMode,\n hasMixedAuth: options.hasMixedAuth,\n });\n const collected = await collectTranscriptUsageRecords({\n brainDir: deps.brainDir,\n historyPath: deps.historyPath,\n salt,\n sinceMs: options.sinceMs,\n nowMs: options.nowMs,\n authMode: options.activeAuthMode,\n cliLogEvents: cliLogs.authEvents,\n hasMixedAuth: options.hasMixedAuth,\n });\n transcriptRecords = collected.records;\n cliBackgroundRecords = cliLogs.backgroundRecords;\n }\n\n const combinedAgy = [...transcriptRecords, ...cliBackgroundRecords];\n const agySide = agyHasTokens\n ? agyOnlyHooks\n : combinedAgy.length > 0\n ? combinedAgy\n : agyOnlyHooks;\n\n const usedTranscriptOnly =\n !agyHasTokens &&\n combinedAgy.length > 0 &&\n (options.product === \"agy\" || otelRecords.length === 0);\n\n if (options.product === \"agy\") {\n return {\n records: agySide,\n ...(usedTranscriptOnly ? { dataModeOverride: \"transcript_token_logs\" } : {}),\n };\n }\n\n return {\n records: [...agySide, ...nonAgyHooks, ...otelRecords],\n ...(usedTranscriptOnly ? { dataModeOverride: \"transcript_token_logs\" } : {}),\n };\n}\n\nfunction buildActivitySummary(\n fallback: TranscriptActivityFallback,\n windowLabel: \"5h\" | \"7d\",\n): string | undefined {\n const stats = windowLabel === \"5h\" ? fallback.window_5h : fallback.window_7d;\n if (stats.session_count === 0 && stats.turn_count === 0) {\n return undefined;\n }\n const resetPart = fallback.window_5h.estimated_5h_reset_local\n ? `; estimated 5h rolling reset at ${fallback.window_5h.estimated_5h_reset_local}`\n : \"\";\n 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).`;\n}\n\nexport function createAgycraftServer(deps: ServerDependencies = {}): McpServer {\n const client = deps.snapshotClient ?? new SnapshotClient();\n\n const server = new McpServer({\n name: \"agycraft-mcp\",\n version: \"0.2.3\",\n });\n\n // 1. analyze_token_usage\n server.tool(\n \"analyze_token_usage\",\n \"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.\",\n {\n window: z.enum([\"5h\", \"24h\", \"7d\", \"30d\", \"all\"]).default(\"5h\"),\n granularity: z\n .enum([\"summary\", \"hourly\", \"daily\", \"weekly\", \"monthly\"])\n .default(\"summary\"),\n timezone: z\n .string()\n .optional()\n .describe(\"IANA timezone for time-series bucketing (default: UTC).\"),\n max_buckets: z\n .number()\n .int()\n .min(1)\n .max(90)\n .default(31)\n .describe(\"Maximum number of time-series buckets to return (1..90, default: 31).\"),\n product: z.enum([\"agy\", \"gemini-cli\", \"all\"]).default(\"all\"),\n scope: z.enum([\"global\", \"project\"]).default(\"global\"),\n workspace_dir: z\n .string()\n .optional()\n .describe(\n \"Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned).\",\n ),\n auth_mode: z\n .string()\n .default(\"all\")\n .describe(\"Optional auth channel filter ('all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', 'unknown', or any registered channel_id).\"),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ window, granularity, timezone, max_buckets, product, scope, workspace_dir, auth_mode, lang }) => {\n const locale = resolveLocale(lang, process.env);\n const effectiveLocale = lang === \"auto\" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : locale;\n const [modelsSnap, channelsSnap, projectHash] = await Promise.all([\n client.get(\"models\"),\n client.get(\"channels\"),\n resolveScopeProjectHash(scope, workspace_dir, deps),\n ]);\n const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);\n const authContext = deps.authContext\n ? deps.authContext\n : await detectAuthContext({ cliLogDir: deps.cliLogDir, registry });\n\n if (granularity !== \"summary\") {\n const salt = await resolveSaltForServer(deps);\n const rollupRes = await queryRollups({\n rollupsDir: deps.rollupsDir,\n usageLogPath: deps.usageLogPath,\n geminiOtelPath: deps.geminiOtelPath,\n brainDir: deps.brainDir,\n historyPath: deps.historyPath,\n saltPath: deps.saltPath,\n salt,\n models: modelsSnap.data.models,\n normalizationRules: modelsSnap.data.normalization_rules,\n window,\n granularity,\n product,\n scope,\n projectHash,\n authMode: auth_mode,\n timezone,\n maxBuckets: max_buckets,\n readonly: deps.readonly,\n transcriptAuthMode: authContext.active_auth_mode,\n cliLogDir: deps.cliLogDir,\n hasMixedAuth: authContext.has_mixed_auth,\n });\n\n const tot = rollupRes.summary_totals;\n const isSpecificAuthEmpty = auth_mode !== \"all\" && tot.requests === 0;\n const dataMode = resolveDataMode(tot.requests, tot.total_tokens);\n const usageNote = isSpecificAuthEmpty\n ? `No usage records matched auth_mode=\"${auth_mode}\" in the ${window} window (active local auth mode is \"${authContext.active_auth_mode}\").`\n : dataMode === \"hook_events_without_tokens\"\n ? `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.`\n : undefined;\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n window,\n granularity,\n product_filter: product,\n scope,\n ...(scope === \"project\" && projectHash\n ? {\n project_hash: projectHash,\n unattributed_sessions_excluded: tot.unattributed_sessions_excluded,\n }\n : {}),\n auth_mode_filter: auth_mode,\n data_mode: dataMode,\n ...(usageNote ? { usage_note: usageNote } : {}),\n record_count: tot.requests,\n session_count: isSpecificAuthEmpty ? 0 : tot.session_count,\n total_uncached_input_tokens: tot.uncached_input_tokens,\n total_cache_read_tokens: tot.cache_read_tokens,\n total_input_tokens: tot.input_tokens,\n total_output_tokens: tot.output_tokens,\n total_tokens: tot.total_tokens,\n cache_hit_rate_pct: tot.cache_hit_rate_pct,\n error_count: tot.error_count,\n rate_limit_429_count: tot.rate_limit_429_count,\n below_kv_cache_threshold_requests: tot.below_kv_cache_threshold_requests,\n estimated_total_usd: tot.estimated_total_usd,\n estimated_cache_savings_usd: tot.estimated_cache_savings_usd,\n time_series: rollupRes.time_series,\n time_series_meta: rollupRes.time_series_meta,\n models_snapshot_source: modelsSnap.source,\n locale: effectiveLocale,\n privacy_note:\n effectiveLocale === \"zh\"\n ? \"100% 本地数值聚合;零用户数据上传。\"\n : \"100% local numeric aggregation; zero user data uploaded.\",\n },\n null,\n 2,\n ),\n },\n ],\n };\n }\n\n const merged = await loadMergedUsageRecords(deps, {\n product,\n activeAuthMode: authContext.active_auth_mode,\n hasMixedAuth: authContext.has_mixed_auth,\n });\n\n const analysis = analyzeTokenWindow(merged.records, {\n window,\n product,\n models: modelsSnap.data.models,\n normalizationRules: modelsSnap.data.normalization_rules,\n scope,\n projectHash,\n authMode: auth_mode,\n activeAuthMode: authContext.active_auth_mode,\n dataModeOverride: merged.dataModeOverride,\n });\n\n const isSpecificAuthEmpty = auth_mode !== \"all\" && analysis.record_count === 0;\n const transcriptFallback =\n !isSpecificAuthEmpty && analysis.record_count === 0 && scope === \"global\"\n ? await scanTranscriptActivity({ brainDir: deps.brainDir })\n : undefined;\n\n const summaryWindow = window === \"5h\" ? \"5h\" : \"7d\";\n const activitySummary = transcriptFallback\n ? buildActivitySummary(transcriptFallback, summaryWindow)\n : undefined;\n const effectiveSessionCount = isSpecificAuthEmpty\n ? 0\n : analysis.record_count > 0\n ? analysis.session_count\n : summaryWindow === \"5h\"\n ? (transcriptFallback?.window_5h.session_count ?? 0)\n : (transcriptFallback?.window_7d.session_count ?? 0);\n\n const finalAnalysis = isSpecificAuthEmpty\n ? {\n ...analysis,\n usage_note: `No usage records matched auth_mode=\"${auth_mode}\" in the ${window} window (active local auth mode is \"${authContext.active_auth_mode}\").`,\n }\n : analysis;\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n ...(activitySummary ? { activity_summary: activitySummary } : {}),\n ...finalAnalysis,\n session_count: effectiveSessionCount,\n ...(transcriptFallback\n ? { transcript_activity_fallback: transcriptFallback }\n : {}),\n models_snapshot_source: modelsSnap.source,\n locale: effectiveLocale,\n privacy_note:\n effectiveLocale === \"zh\"\n ? \"100% 本地数值聚合;零用户数据上传。\"\n : \"100% local numeric aggregation; zero user data uploaded.\",\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // 2. get_saving_recommendations\n server.tool(\n \"get_saving_recommendations\",\n \"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.\",\n {\n window: z.enum([\"24h\", \"7d\"]).default(\"24h\"),\n scope: z.enum([\"global\", \"project\"]).default(\"global\"),\n transcript_path: z\n .string()\n .optional()\n .describe(\"Optional local transcript.jsonl path for structural step/loop counting only (never reads prompt/content).\"),\n loopThreshold: z\n .number()\n .int()\n .positive()\n .default(4)\n .describe(\"Consecutive tool-failure streak threshold for infinite-loop detection (default: 4).\"),\n workspace_dir: z\n .string()\n .optional()\n .describe(\"Optional workspace directory path for .geminiignore check and project-scoped filtering.\"),\n timezone: z\n .string()\n .optional()\n .describe(\"IANA timezone for peak_hours bucketing (default: UTC).\"),\n auth_mode: z\n .string()\n .default(\"auto\")\n .describe(\"Optional auth channel filter ('auto', 'all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id).\"),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ window, scope, transcript_path, loopThreshold, workspace_dir, timezone, auth_mode, lang }) => {\n const effectiveLocale =\n lang === \"auto\" && deps.defaultLang\n ? resolveLocale(deps.defaultLang, process.env)\n : resolveLocale(lang, process.env);\n const [modelsSnap, channelsSnap, projectHash, transcriptMeta, hasGeminiIgnore] =\n await Promise.all([\n client.get(\"models\"),\n client.get(\"channels\"),\n resolveScopeProjectHash(scope, workspace_dir, deps),\n transcript_path\n ? analyzeTranscriptStructure(transcript_path, loopThreshold)\n : Promise.resolve(null),\n workspace_dir\n ? access(join(workspace_dir, \".geminiignore\"))\n .then(() => true)\n .catch(() => false)\n : Promise.resolve(undefined),\n ]);\n const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);\n const authContext = deps.authContext\n ? deps.authContext\n : await detectAuthContext({ cliLogDir: deps.cliLogDir, registry });\n\n const merged = await loadMergedUsageRecords(deps, {\n product: \"all\",\n activeAuthMode: authContext.active_auth_mode,\n hasMixedAuth: authContext.has_mixed_auth,\n });\n\n const salt = await resolveSaltForServer(deps);\n const rollupHourly = await queryRollups({\n rollupsDir: deps.rollupsDir,\n usageLogPath: deps.usageLogPath,\n geminiOtelPath: deps.geminiOtelPath,\n brainDir: deps.brainDir,\n historyPath: deps.historyPath,\n cliLogDir: deps.cliLogDir,\n hasMixedAuth: authContext.has_mixed_auth,\n saltPath: deps.saltPath,\n salt,\n models: modelsSnap.data.models,\n normalizationRules: modelsSnap.data.normalization_rules,\n window,\n granularity: \"hourly\",\n product: \"all\",\n scope,\n projectHash,\n timezone,\n maxBuckets: 90,\n readonly: deps.readonly,\n transcriptAuthMode: authContext.active_auth_mode,\n }).catch(() => null);\n\n const report = analyzeAntipatterns(merged.records, {\n window,\n scope,\n projectHash,\n transcriptMeta,\n hasGeminiIgnore,\n hourlyBuckets: rollupHourly?.time_series,\n models: modelsSnap.data.models,\n timezone,\n authContext: {\n active_auth_mode: authContext.active_auth_mode,\n has_mixed_auth: authContext.has_mixed_auth,\n },\n authMode: auth_mode,\n channels: registry,\n locale: effectiveLocale,\n });\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n ...report,\n locale: effectiveLocale,\n transcript_structure: transcriptMeta,\n more_tips_url: \"https://modelcraft.dev/quotas\",\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // 3. diagnose_error\n server.tool(\n \"diagnose_error\",\n \"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.\",\n {\n error_text: z.string().min(1).describe(\"Raw error message or JSON snippet.\"),\n product: z.enum([\"agy\", \"cli\", \"api\", \"web\"]).optional(),\n doctor_summary: z.string().optional(),\n auth_mode: z\n .string()\n .default(\"auto\")\n .describe(\"Optional auth channel hint ('auto', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id).\"),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ error_text, product, auth_mode, lang }) => {\n const effectiveLocale =\n lang === \"auto\" && deps.defaultLang\n ? resolveLocale(deps.defaultLang, process.env)\n : resolveLocale(lang, process.env);\n const [records, statusSnap, diagnosisSnap, channelsSnap] = await Promise.all([\n loadCombinedLocalRecords(deps),\n client.get(\"status\"),\n client.get(\"diagnosis\"),\n client.get(\"channels\"),\n ]);\n const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);\n const [authContext, cliSignals] = await Promise.all([\n deps.authContext\n ? Promise.resolve(deps.authContext)\n : detectAuthContext({ registry }),\n deps.cliLogDir !== null\n ? collectCliLogSignals({ cliLogDir: deps.cliLogDir, registry }).catch(() => null)\n : Promise.resolve(null),\n ]);\n const latestCliEvent =\n cliSignals && cliSignals.authEvents.length > 0\n ? cliSignals.authEvents[cliSignals.authEvents.length - 1]\n : undefined;\n const cliChannel =\n latestCliEvent && Date.now() - latestCliEvent.tsMs <= 12 * 3600_000\n ? (latestCliEvent.channelId ?? latestCliEvent.authMode)\n : undefined;\n\n const result = diagnoseError({\n errorText: error_text,\n product,\n localRecords: records,\n statusSnapshot: statusSnap.data,\n diagnosisEntries: diagnosisSnap.data.entries,\n authMode: auth_mode,\n authContext,\n cliChannel,\n channels: registry,\n locale: effectiveLocale,\n });\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n ...result,\n locale: effectiveLocale,\n data_sources: {\n status: statusSnap.source,\n diagnosis: diagnosisSnap.source,\n },\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // 4. lookup_model_guide\n server.tool(\n \"lookup_model_guide\",\n \"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.\",\n {\n task: z.string().optional().describe(\"Task description (e.g. 'architecture', 'multi-file refactor', 'quick qa', 'batch').\"),\n model_id: z.string().optional().describe(\"Specific model id, api_model_id, or codename (e.g. 'neon', 'hydrogen', 'argon', 'gemini-3.8-flash').\"),\n provider: z.enum([\"google\", \"antigravity\", \"anthropic\", \"all\"]).default(\"all\"),\n include_history: z.boolean().default(false),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ task, model_id, provider, include_history, lang }) => {\n const effectiveLocale =\n lang === \"auto\" && deps.defaultLang\n ? resolveLocale(deps.defaultLang, process.env)\n : resolveLocale(lang, process.env);\n const [modelsSnap, chronicleSnap] = await Promise.all([\n client.get(\"models\"),\n include_history ? client.get(\"chronicle\") : Promise.resolve(null),\n ]);\n\n let models = modelsSnap.data.models;\n if (provider === \"antigravity\") {\n models = models.filter(\n (m) =>\n m.provider === \"antigravity\" ||\n Boolean(m.availability?.products?.includes(\"agy\")),\n );\n } else if (provider !== \"all\") {\n models = models.filter((m) => m.provider === provider);\n }\n\n let matched = models;\n if (model_id) {\n const needle = model_id.toLowerCase();\n matched = models.filter(\n (m) =>\n m.id.toLowerCase().includes(needle) ||\n m.api_model_id.toLowerCase().includes(needle) ||\n m.display_name.toLowerCase().includes(needle) ||\n Boolean(m.aliases?.some((a) => a.toLowerCase().includes(needle))) ||\n (m.codename && m.codename.toLowerCase().includes(needle)),\n );\n } else if (task) {\n const needle = task.toLowerCase();\n const scored = models\n .filter((m) => m.lifecycle !== \"deprecated\" && m.lifecycle !== \"removed\")\n .map((m) => {\n let score = 0;\n if (m.best_for.some((b) => b.toLowerCase().includes(needle) || needle.includes(b.toLowerCase()))) {\n score += 3;\n }\n if (m.summary.toLowerCase().includes(needle)) {\n score += 2;\n }\n if (needle.includes(\"plan\") || needle.includes(\"architect\") || needle.includes(\"debug\")) {\n if (m.specs.reasoning_tier === \"flagship\" || m.id.includes(\"neon\")) score += 4;\n }\n if (needle.includes(\"fast\") || needle.includes(\"cheap\") || needle.includes(\"edit\") || needle.includes(\"test\") || needle.includes(\"refactor\")) {\n if (m.quota_profile.shared_bucket_cost_tier === \"low\" || m.id.includes(\"hydrogen\") || m.id.includes(\"flash\")) score += 4;\n }\n if (needle.includes(\"batch\") || needle.includes(\"bulk\") || needle.includes(\"high-volume\")) {\n if (m.id.includes(\"flash-lite\") || m.id.includes(\"flash\")) score += 4;\n }\n return { model: m, score };\n })\n .sort((a, b) => b.score - a.score);\n matched = scored.slice(0, 3).map((s) => s.model);\n } else if (!include_history) {\n matched = models.filter(\n (m) => m.lifecycle !== \"deprecated\" && m.lifecycle !== \"removed\",\n );\n }\n\n const history =\n include_history && chronicleSnap\n ? chronicleSnap.data.entries.filter((e) => {\n if (!model_id) return true;\n const needle = model_id.toLowerCase();\n return (\n e.entity_ids.some((id) => id.toLowerCase().includes(needle)) ||\n e.title.toLowerCase().includes(needle)\n );\n })\n : undefined;\n\n const deprecationWarnings = matched\n .filter((m) => m.lifecycle === \"deprecated\" || m.lifecycle === \"removed\")\n .map((m) => ({\n model: m.id,\n lifecycle: m.lifecycle,\n deprecated_date: m.deprecated_date,\n replacement_model_id: m.replacement_model_id,\n }));\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n models: matched.map((m) => localizeModelEntry(m, effectiveLocale)),\n orchestrator_recipes: localizeSnapshotText(\n modelsSnap.data.orchestrator_recipes,\n effectiveLocale,\n ),\n deprecation_warnings: deprecationWarnings,\n chronicle_history: history?.map((h) => localizeSnapshotText(h, effectiveLocale)),\n locale: effectiveLocale,\n guide_url: \"https://modelcraft.dev/models\",\n official_source_urls: [\n ...new Set(matched.flatMap((m) => m.official_source_urls ?? [])),\n ],\n snapshot_source: modelsSnap.source,\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // 5. get_ecosystem_status\n server.tool(\n \"get_ecosystem_status\",\n \"Get live Gemini & Antigravity upstream status, latest CLI/SDK versions, recent official updates, quota rules, and local PT midnight + 5h/7d rolling reset countdowns.\",\n {\n plan: z.enum([\"free\", \"pro\", \"ultra\"]).optional(),\n product: z.enum([\"agy\", \"cli\", \"api\", \"web\"]).optional(),\n timezone: z.string().optional().describe(\"IANA timezone (e.g. 'Asia/Shanghai', 'America/Los_Angeles').\"),\n scope: z.enum([\"global\", \"project\"]).default(\"global\"),\n workspace_dir: z\n .string()\n .optional()\n .describe(\n \"Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned).\",\n ),\n auth_mode: z\n .string()\n .default(\"all\")\n .describe(\"Optional auth channel filter ('all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', 'unknown', or any registered channel_id).\"),\n lang: z\n .enum([\"en\", \"zh\", \"auto\"])\n .default(\"auto\")\n .describe(\"Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).\"),\n },\n async ({ plan, product, timezone, scope, workspace_dir, auth_mode, lang }) => {\n const effectiveLocale =\n lang === \"auto\" && deps.defaultLang\n ? resolveLocale(deps.defaultLang, process.env)\n : resolveLocale(lang, process.env);\n const nowMs = Date.now();\n const since7d = nowMs - 7 * 86400 * 1000;\n const [statusSnap, quotasSnap, updatesSnap, channelsSnap, projectHash] =\n await Promise.all([\n client.get(\"status\"),\n client.get(\"quotas\"),\n client.get(\"updates\"),\n client.get(\"channels\"),\n resolveScopeProjectHash(scope, workspace_dir, deps),\n ]);\n const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);\n const authContext = deps.authContext\n ? deps.authContext\n : await detectAuthContext({ cliLogDir: deps.cliLogDir, registry });\n\n const merged = await loadMergedUsageRecords(deps, {\n product: \"all\",\n activeAuthMode: authContext.active_auth_mode,\n hasMixedAuth: authContext.has_mixed_auth,\n sinceMs: since7d,\n nowMs,\n });\n\n const effectiveBase = filterRecordsByScopeAndAuth(\n merged.records,\n \"global\",\n undefined,\n auth_mode,\n registry,\n );\n const effectiveRecords = filterRecordsByScopeAndAuth(\n merged.records,\n scope,\n projectHash,\n auth_mode,\n registry,\n );\n const effectiveTotalTokens7d = effectiveRecords.reduce(\n (sum, r) => sum + r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens,\n 0,\n );\n const usingTranscriptTokenLogs = merged.dataModeOverride === \"transcript_token_logs\";\n const unattributedExcluded = new Set(\n effectiveBase\n .filter((r) => !r.project_hash)\n .map((r) => r.session_hash || \"default-session\"),\n ).size;\n\n const fiveHoursAgo = nowMs - 5 * 3600 * 1000;\n const in5h = effectiveRecords\n .map((r) => Date.parse(r.ts))\n .filter((t) => !Number.isNaN(t) && t >= fiveHoursAgo);\n const in7d = effectiveRecords\n .map((r) => Date.parse(r.ts))\n .filter((t) => !Number.isNaN(t));\n\n const isSpecificAuthEmpty = auth_mode !== \"all\" && effectiveRecords.length === 0;\n const transcriptFallback =\n !isSpecificAuthEmpty && effectiveRecords.length === 0 && scope === \"global\"\n ? await scanTranscriptActivity({\n brainDir: deps.brainDir,\n nowMs,\n timezone,\n })\n : undefined;\n\n const countdown = computeResetCountdown({\n now: new Date(nowMs),\n timezone,\n oldestEventIn5hMs:\n in5h.length > 0\n ? Math.min(...in5h)\n : transcriptFallback?.earliest_turn_5h_ms ?? null,\n oldestEventIn7dMs:\n in7d.length > 0\n ? Math.min(...in7d)\n : transcriptFallback?.earliest_turn_7d_ms ?? null,\n });\n\n const filteredPlans = plan\n ? quotasSnap.data.plans.filter(\n (p) =>\n p.id.toLowerCase().includes(plan) ||\n p.name.toLowerCase().includes(plan),\n )\n : quotasSnap.data.plans;\n\n const filteredUpdates = product\n ? updatesSnap.data.items.filter(\n (u) => u.product === product || u.product === \"all\",\n )\n : updatesSnap.data.items;\n\n const statusActivitySummary = transcriptFallback\n ? buildActivitySummary(transcriptFallback, \"5h\")\n : undefined;\n\n const statusDataMode = resolveDataMode(\n effectiveRecords.length,\n effectiveTotalTokens7d,\n usingTranscriptTokenLogs ? \"transcript_token_logs\" : undefined,\n );\n const statusUsageNote = isSpecificAuthEmpty\n ? `No usage records matched auth_mode=\"${auth_mode}\" in the 7d window (active local auth mode is \"${authContext.active_auth_mode}\").`\n : statusDataMode === \"hook_events_without_tokens\"\n ? `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.`\n : undefined;\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n ...(statusActivitySummary\n ? { activity_summary: statusActivitySummary }\n : {}),\n scope,\n ...(scope === \"project\" && projectHash\n ? {\n project_hash: projectHash,\n unattributed_sessions_excluded: unattributedExcluded,\n }\n : {}),\n auth_mode_filter: auth_mode,\n auth_context: authContext,\n data_mode: statusDataMode,\n ...(statusUsageNote ? { usage_note: statusUsageNote } : {}),\n session_count: isSpecificAuthEmpty\n ? 0\n : effectiveRecords.length > 0\n ? new Set(effectiveRecords.map((r) => r.session_hash)).size\n : (transcriptFallback?.window_5h.session_count ?? 0),\n overall_status: statusSnap.data.overall_status,\n surfaces: localizeSnapshotText(statusSnap.data.surfaces, effectiveLocale),\n active_incidents: localizeSnapshotText(\n statusSnap.data.active_incidents,\n effectiveLocale,\n ),\n latest_versions: statusSnap.data.latest_versions,\n countdown,\n ...(transcriptFallback\n ? { transcript_activity_fallback: transcriptFallback }\n : {}),\n quota_rules: localizeSnapshotText(\n {\n reset_rules: quotasSnap.data.reset_rules,\n ...(typeof quotasSnap.data.reset_rules_notes_zh === \"string\"\n ? { reset_rules_notes_zh: quotasSnap.data.reset_rules_notes_zh }\n : {}),\n },\n effectiveLocale,\n ).reset_rules,\n plans: filteredPlans.map((p) => localizeSnapshotText(p, effectiveLocale)),\n recent_updates: filteredUpdates\n .slice(0, 8)\n .map((u) => localizeSnapshotText(u, effectiveLocale)),\n locale: effectiveLocale,\n dashboard_url: \"https://modelcraft.dev\",\n official_source_urls: quotasSnap.data.official_source_urls ?? [],\n snapshot_sources: {\n status: statusSnap.source,\n quotas: quotasSnap.source,\n updates: updatesSnap.source,\n },\n },\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n return server;\n}\n\nexport async function startStdioServer(deps: ServerDependencies = {}): Promise<void> {\n const server = createAgycraftServer(deps);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { getDefaultGeminiTelemetryPath } from \"../paths.js\";\nimport {\n type UsageRecord,\n getOrCreateLocalSalt,\n hashSessionId,\n sanitizeUsagePayload,\n} from \"./agy-hook.js\";\n\n/**\n * Readonly parser for Gemini CLI OpenTelemetry outfile (~/.gemini/telemetry_stats.jsonl).\n * PRIVACY RED LINE: Only extracts numeric token counts, model name, timestamp, error code,\n * and hashed session ID. Explicitly ignores any prompt/completion body even if present.\n */\nexport async function readGeminiOtelRecords(options?: {\n otelPath?: string;\n sinceMs?: number;\n salt?: string;\n saltPath?: string;\n}): Promise<UsageRecord[]> {\n const otelPath = options?.otelPath ?? getDefaultGeminiTelemetryPath();\n const salt = options?.salt ?? (await getOrCreateLocalSalt(options?.saltPath));\n\n let content: string;\n try {\n content = await readFile(otelPath, \"utf8\");\n } catch {\n return [];\n }\n\n const records: UsageRecord[] = [];\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n try {\n const entry = JSON.parse(trimmed) as Record<string, unknown>;\n const attrs = extractOtelAttributes(entry);\n\n const inputTokens = firstNumber(\n attrs[\"gen_ai.usage.input_tokens\"],\n attrs[\"input_token_count\"],\n attrs[\"prompt_tokens\"],\n entry[\"input_tokens\"],\n entry[\"prompt_tokens\"],\n );\n const outputTokens = firstNumber(\n attrs[\"gen_ai.usage.output_tokens\"],\n attrs[\"output_token_count\"],\n attrs[\"completion_tokens\"],\n entry[\"output_tokens\"],\n entry[\"completion_tokens\"],\n );\n\n const cacheReadTokens = firstNumber(\n attrs[\"gen_ai.usage.cache_read_input_tokens\"],\n attrs[\"cache_read_tokens\"],\n attrs[\"cached_content_token_count\"],\n entry[\"cache_read_tokens\"],\n );\n const thinkingTokens = firstNumber(\n attrs[\"gen_ai.usage.thinking_tokens\"],\n attrs[\"thinking_tokens\"],\n attrs[\"thoughts_token_count\"],\n entry[\"thinking_tokens\"],\n );\n\n // Skip non-LLM spans that have no token usage and no error code\n const errorCode =\n attrs[\"error.type\"] ??\n attrs[\"http.response.status_code\"] ??\n entry[\"error_code\"] ??\n null;\n if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0 && !errorCode) {\n continue;\n }\n\n const rawSession = String(\n attrs[\"session.id\"] ?? entry[\"session_id\"] ?? \"gemini-cli-session\",\n );\n\n const record = sanitizeUsagePayload(\n {\n ts: entry[\"timestamp\"] ?? entry[\"ts\"] ?? entry[\"startTime\"],\n provider: \"google\",\n product: \"gemini-cli\",\n session_hash: hashSessionId(rawSession, salt),\n model:\n attrs[\"gen_ai.request.model\"] ??\n attrs[\"gen_ai.response.model\"] ??\n attrs[\"model\"] ??\n entry[\"model\"] ??\n \"unknown\",\n input_tokens: inputTokens,\n cache_read_tokens: cacheReadTokens,\n output_tokens: outputTokens,\n thinking_tokens: thinkingTokens,\n context_used_pct: attrs[\"context_used_pct\"] ?? null,\n tool_calls: firstNumber(attrs[\"tool_calls\"], entry[\"tool_calls\"]),\n turn_index: firstNumber(attrs[\"turn_index\"], entry[\"turn_index\"]),\n error_code: errorCode,\n },\n salt,\n );\n\n if (options?.sinceMs !== undefined && Date.parse(record.ts) < options.sinceMs) {\n continue;\n }\n records.push(record);\n } catch {\n // Skip malformed lines safely\n }\n }\n\n return records;\n}\n\nfunction extractOtelAttributes(\n entry: Record<string, unknown>,\n): Record<string, unknown> {\n const attrs = entry[\"attributes\"];\n if (attrs && typeof attrs === \"object\" && !Array.isArray(attrs)) {\n return attrs as Record<string, unknown>;\n }\n return {};\n}\n\nfunction firstNumber(...candidates: unknown[]): number {\n for (const val of candidates) {\n if (val === null || val === undefined || val === \"\") {\n continue;\n }\n const n = typeof val === \"number\" ? val : Number(val);\n if (Number.isFinite(n) && n >= 0) {\n return Math.floor(n);\n }\n }\n return 0;\n}\n","import type { UsageRecord } from \"../collectors/agy-hook.js\";\nimport {\n ChannelRegistry,\n loadBundledChannelRegistry,\n type CompiledAuthChannel,\n} from \"../collectors/channel-registry.js\";\nimport type { TranscriptStructuralMeta } from \"../collectors/transcript-meta.js\";\nimport { formatBucketKey, normalizeTimezone } from \"../storage/rollups.js\";\nimport type {\n AuthContext,\n AuthMode,\n ChannelsSnapshot,\n ModelEntry,\n} from \"../types.js\";\nimport { estimateTokenCosts } from \"./token-window.js\";\nimport { evaluateSessionLifecycle } from \"./session-lifecycle.js\";\n\nimport { getLocalizedBehavior, type SupportedLocale } from \"../i18n.js\";\n\nexport interface SavingRecommendation {\n id: string;\n severity: \"high\" | \"medium\" | \"low\";\n category:\n | \"long_session_snowball\"\n | \"heavy_model_mismatch\"\n | \"thinking_downgrade\"\n | \"infinite_loop_warning\"\n | \"redundant_tool_calls\"\n | \"missing_geminiignore\"\n | \"low_kv_cache_efficiency\"\n | \"peak_window_misalignment\"\n | \"burst_rpm_tpm_throttling\"\n | \"background_spend_warning\";\n title: string;\n evidence: string;\n action: string;\n estimated_savings_pct: string;\n}\n\nexport interface BehaviorSummaryTopModel {\n model: string;\n requests: number;\n token_share_pct: number;\n total_tokens: number;\n}\n\nexport interface BehaviorSummaryPeakHour {\n bucket: string;\n requests: number;\n total_tokens: number;\n cache_hit_rate_pct: number;\n}\n\nexport interface BehaviorSummary {\n avg_input_tokens_per_request: number;\n cache_hit_rate_pct: number;\n estimated_cache_savings_usd: number;\n light_model_request_share_pct: number;\n heavy_model_request_share_pct: number;\n top_models: BehaviorSummaryTopModel[];\n peak_hours: BehaviorSummaryPeakHour[];\n project_share_of_global_pct: number | null;\n auth_context: {\n active_auth_mode: AuthMode;\n has_mixed_auth: boolean;\n };\n}\n\nexport interface SavingRecommendationsReport {\n window: \"24h\" | \"7d\";\n scope?: \"global\" | \"project\";\n project_hash?: string;\n auth_mode_filter?: string;\n analyzed_records: number;\n recommendations: SavingRecommendation[];\n healthy: boolean;\n note?: string;\n behavior_summary: BehaviorSummary;\n executive_summary: string;\n channel_reports?: Record<string, SavingRecommendationsReport>;\n}\n\nexport interface HourlyDistributionBucket {\n bucket: string;\n total_tokens: number;\n rate_limit_429_count: number;\n requests?: number;\n cache_hit_rate_pct?: number;\n}\n\nconst HEAVY_MODEL_RE = /(neon|carbon|pro|ultra|opus)/i;\n\nexport function analyzeAntipatterns(\n records: UsageRecord[],\n options?: {\n window?: \"24h\" | \"7d\";\n scope?: \"global\" | \"project\";\n projectHash?: string;\n transcriptMeta?: TranscriptStructuralMeta | null;\n hasGeminiIgnore?: boolean;\n hourlyBuckets?: HourlyDistributionBucket[];\n models?: ModelEntry[];\n timezone?: string;\n authContext?: Pick<AuthContext, \"active_auth_mode\" | \"has_mixed_auth\">;\n authMode?: AuthMode | \"auto\" | \"all\";\n channels?: ChannelsSnapshot | ChannelRegistry;\n nowMs?: number;\n locale?: SupportedLocale;\n },\n): SavingRecommendationsReport {\n const window = options?.window ?? \"24h\";\n const scope = options?.scope ?? \"global\";\n const nowMs = options?.nowMs ?? Date.now();\n const locale = options?.locale ?? \"en\";\n const registry =\n options?.channels instanceof ChannelRegistry\n ? options.channels\n : options?.channels\n ? ChannelRegistry.fromSnapshot(options.channels)\n : loadBundledChannelRegistry();\n\n const requestedAuthMode = options?.authMode;\n const isSpecificAuthFilter = Boolean(\n requestedAuthMode &&\n requestedAuthMode !== \"auto\" &&\n requestedAuthMode !== \"all\" &&\n requestedAuthMode !== \"unknown\",\n );\n const resolvedFilterChannel = isSpecificAuthFilter && requestedAuthMode\n ? registry.resolveChannelId(requestedAuthMode)\n : undefined;\n\n const activeChannelForPolicy: CompiledAuthChannel | undefined = resolvedFilterChannel\n ? registry.getChannel(resolvedFilterChannel)\n : options?.authContext?.active_auth_mode &&\n options.authContext.active_auth_mode !== \"unknown\"\n ? registry.getChannel(options.authContext.active_auth_mode)\n : undefined;\n\n const cutoffMs = nowMs - (window === \"24h\" ? 86400_000 : 7 * 86400_000);\n const windowRecords = records.filter((r) => {\n const ts = Date.parse(r.ts);\n if (Number.isNaN(ts) || ts < cutoffMs) {\n return false;\n }\n if (resolvedFilterChannel) {\n return registry.matchesChannel(r.auth_mode, resolvedFilterChannel);\n }\n return true;\n });\n const filtered =\n scope === \"project\"\n ? windowRecords.filter(\n (r) => Boolean(options?.projectHash) && r.project_hash === options?.projectHash,\n )\n : windowRecords;\n\n const recs: SavingRecommendation[] = [];\n\n let totalUncachedInput = 0;\n let totalCacheRead = 0;\n for (const r of filtered) {\n totalUncachedInput += r.input_tokens;\n totalCacheRead += r.cache_read_tokens ?? 0;\n }\n const totalInputWithCache = totalUncachedInput + totalCacheRead;\n const cacheHitRatePct =\n totalInputWithCache > 0 ? (totalCacheRead / totalInputWithCache) * 100 : 0;\n\n // 1. Long-session snowball detection (joint token watermark + KV cache + lifecycle state machine)\n const longSessions = new Map<\n string,\n {\n sessionHash: string;\n maxTurn: number;\n maxCtxPct: number | null;\n totalInput: number;\n totalCacheRead: number;\n peakReqInput: number;\n latestReqInput: number;\n latestTsMs: number;\n maxIdleGapSec: number;\n recent429Count: number;\n recentWindows: Array<{ input: number; cacheRead: number }>;\n turns: number;\n }\n >();\n for (const r of filtered) {\n const cur = longSessions.get(r.session_hash) ?? {\n sessionHash: r.session_hash,\n maxTurn: 0,\n maxCtxPct: null,\n totalInput: 0,\n totalCacheRead: 0,\n peakReqInput: 0,\n latestReqInput: 0,\n latestTsMs: 0,\n maxIdleGapSec: 0,\n recent429Count: 0,\n recentWindows: [],\n turns: 0,\n };\n cur.maxTurn = Math.max(cur.maxTurn, r.turn_index);\n if (typeof r.context_used_pct === \"number\") {\n cur.maxCtxPct =\n cur.maxCtxPct === null\n ? r.context_used_pct\n : Math.max(cur.maxCtxPct, r.context_used_pct);\n }\n const cacheRead = r.cache_read_tokens ?? 0;\n const reqInput = r.input_tokens + cacheRead;\n cur.totalInput += reqInput;\n cur.totalCacheRead += cacheRead;\n if (reqInput > cur.peakReqInput) {\n cur.peakReqInput = reqInput;\n }\n const tsMs = Date.parse(r.ts);\n if (!Number.isNaN(tsMs)) {\n if (cur.latestTsMs > 0 && tsMs > cur.latestTsMs) {\n const gapSec = (tsMs - cur.latestTsMs) / 1000;\n if (gapSec > cur.maxIdleGapSec) {\n cur.maxIdleGapSec = gapSec;\n }\n }\n if (tsMs >= cur.latestTsMs) {\n cur.latestTsMs = tsMs;\n cur.latestReqInput = reqInput;\n }\n } else {\n cur.latestReqInput = reqInput;\n }\n if (\n r.error_code &&\n (r.error_code.includes(\"429\") || r.error_code.includes(\"RESOURCE_EXHAUSTED\"))\n ) {\n cur.recent429Count += 1;\n }\n cur.recentWindows.push({ input: r.input_tokens, cacheRead });\n if (cur.recentWindows.length > 3) {\n cur.recentWindows.shift();\n }\n cur.turns += 1;\n longSessions.set(r.session_hash, cur);\n }\n\n const snowballSessions = [...longSessions.values()].filter((s) => {\n const recentInputSum = s.recentWindows.reduce(\n (sum, w) => sum + w.input + w.cacheRead,\n 0,\n );\n const recentCacheSum = s.recentWindows.reduce((sum, w) => sum + w.cacheRead, 0);\n const recentHitPct =\n recentInputSum > 0 ? (recentCacheSum / recentInputSum) * 100 : 0;\n const sessionHitPct =\n s.totalInput > 0 ? (s.totalCacheRead / s.totalInput) * 100 : 0;\n\n const { decision } = evaluateSessionLifecycle(\n {\n session_hash: s.sessionHash,\n is_interactive: true,\n planner_turns_since_compact: Math.max(s.maxTurn, s.turns),\n current_input_tokens: Math.max(s.latestReqInput, s.peakReqInput),\n recent_cache_hit_pct: recentHitPct,\n idle_gap_sec: s.maxIdleGapSec,\n recent_429_count: s.recent429Count,\n recent_overflow_count: 0,\n model_context_limit: 512_000,\n },\n undefined,\n { nowMs, locale },\n );\n\n const highCtxUtilization = s.maxCtxPct !== null && s.maxCtxPct >= 70;\n const lifecycleFlagged = decision.action !== \"HOLD_CACHE\";\n const lowCacheMultiTurn =\n s.totalInput > 0 &&\n sessionHitPct < 85 &&\n (s.maxTurn >= 20 || s.turns >= 25);\n\n return highCtxUtilization || lifecycleFlagged || lowCacheMultiTurn;\n });\n\n const transcriptPeakInput = Math.max(\n options?.transcriptMeta?.peak_input_tokens ?? 0,\n options?.transcriptMeta?.latest_input_tokens ?? 0,\n );\n const allFilteredHealthySmallWarm =\n filtered.length > 0 &&\n snowballSessions.length === 0 &&\n cacheHitRatePct >= 85 &&\n [...longSessions.values()].every((s) => s.peakReqInput < 160_000);\n const transcriptUncompacted =\n Boolean(\n options?.transcriptMeta &&\n options.transcriptMeta.steps_since_last_compact >= 30 &&\n !allFilteredHealthySmallWarm &&\n (transcriptPeakInput >= 160_000 ||\n (transcriptPeakInput === 0 &&\n (snowballSessions.length > 0 || filtered.length === 0))),\n );\n\n if (snowballSessions.length > 0 || transcriptUncompacted) {\n const ctxValues = snowballSessions\n .map((s) => s.maxCtxPct)\n .filter((v): v is number => v !== null);\n const peakCtx = ctxValues.length > 0 ? Math.max(...ctxValues) : null;\n const peakTurn = Math.max(0, ...snowballSessions.map((s) => s.maxTurn));\n const snowballTotalInput = snowballSessions.reduce((s, v) => s + v.totalInput, 0);\n const snowballTotalTurns = snowballSessions.reduce((s, v) => s + v.turns, 0);\n const snowballAvgInput =\n snowballTotalTurns > 0 ? Math.round(snowballTotalInput / snowballTotalTurns) : 0;\n const avgInputLabel =\n snowballAvgInput >= 1000\n ? `~${Math.round(snowballAvgInput / 1000)}K`\n : `${snowballAvgInput}`;\n const highCacheHit = totalInputWithCache > 0 && cacheHitRatePct >= 85;\n const roundedHit = Math.round(cacheHitRatePct * 10) / 10;\n\n recs.push({\n id: \"long_session_snowball\",\n severity: \"high\",\n category: \"long_session_snowball\",\n title: \"Long-session context snowball detected\",\n evidence:\n snowballSessions.length > 0\n ? peakCtx !== null\n ? `${snowballSessions.length} session(s) reached turn ${peakTurn} / ${peakCtx}% context utilization without compacting.`\n : `${snowballSessions.length} session(s) reached turn ${peakTurn} (context % unavailable, avg ${avgInputLabel} input tokens/req) without compacting.`\n : `Transcript has ${options?.transcriptMeta?.steps_since_last_compact} steps since last /compact.`,\n action: highCacheHit\n ? `With ${roundedHit}% KV cache hit rate, avoid mechanical \\`/compact\\` every 12–15 turns (which breaks prefix caching); run \\`/compact\\` or start a fresh thread at phase milestones or when per-request input approaches 150K–200K tokens.`\n : \"Run `/compact` (or `/compress`) every 12–15 turns or start a fresh thread per subtask. Uncompacted histories re-bill growing prefixes every turn.\",\n estimated_savings_pct: highCacheHit ? \"15–30%\" : \"35–60%\",\n });\n }\n\n // 2. Heavy model mismatch (using Neon/Pro/Carbon for tiny low-complexity turns)\n const heavyTurns = filtered.filter((r) => HEAVY_MODEL_RE.test(r.model));\n const lightweightOnHeavy = heavyTurns.filter(\n (r) => r.output_tokens > 0 && r.output_tokens < 350 && r.tool_calls <= 1,\n );\n if (heavyTurns.length >= 4 && lightweightOnHeavy.length / heavyTurns.length >= 0.45) {\n const pct = Math.round((lightweightOnHeavy.length / heavyTurns.length) * 100);\n recs.push({\n id: \"heavy_model_mismatch\",\n severity: \"high\",\n category: \"heavy_model_mismatch\",\n title: \"Heavy flagship model used for lightweight turns\",\n evidence: `${lightweightOnHeavy.length}/${heavyTurns.length} (${pct}%) heavy-model turns produced <350 output tokens with <=1 tool call.`,\n action:\n \"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.\",\n estimated_savings_pct: \"50–75%\",\n });\n }\n\n // 3. Thinking downgrade opportunity (high output ratio on heavy models)\n const totalHeavyInput = heavyTurns.reduce((s, r) => s + r.input_tokens, 0);\n const totalHeavyOutput = heavyTurns.reduce((s, r) => s + r.output_tokens, 0);\n if (\n heavyTurns.length >= 3 &&\n totalHeavyOutput > 15_000 &&\n (totalHeavyInput === 0 || totalHeavyOutput / Math.max(1, totalHeavyInput) >= 0.15)\n ) {\n const policy = activeChannelForPolicy?.definition.quota_reset_policy;\n const behaviors = activeChannelForPolicy?.definition.recommended_behaviors;\n const multiplierNote = policy?.thinking_bucket_multiplier\n ? `billed at ${policy.thinking_bucket_multiplier} input rate in ${policy.window_type} buckets`\n : policy\n ? `billed under ${activeChannelForPolicy?.definition.billing_model} (${policy.window_type})`\n : \"billed at 4x–8x input rate in shared 5h/7d buckets\";\n recs.push({\n id: \"thinking_downgrade\",\n severity: \"medium\",\n category: \"thinking_downgrade\",\n title: \"High Thinking/output token burn on flagship models\",\n evidence: `${totalHeavyOutput.toLocaleString()} output/thinking tokens on heavy models (${multiplierNote}).`,\n action:\n getLocalizedBehavior(behaviors, \"thinking_guidance\", locale) ??\n \"Lower Thinking level (e.g. Medium/Low) for boilerplate coding & log parsing, reserving High Thinking strictly for multi-file debugging or architecture.\",\n estimated_savings_pct: \"25–45%\",\n });\n }\n\n // 4. Agent infinite loop warning (from pure structural transcript metadata)\n if (options?.transcriptMeta?.loop_detected) {\n const tool = options.transcriptMeta.consecutive_failure_tool_type ?? \"tool\";\n const streak = options.transcriptMeta.max_consecutive_tool_failures;\n recs.push({\n id: \"infinite_loop_warning\",\n severity: \"high\",\n category: \"infinite_loop_warning\",\n title: `Autonomous failure loop detected (${streak} consecutive \"${tool}\" errors)`,\n evidence: `Transcript recorded ${streak} consecutive failures on \"${tool}\" (${options.transcriptMeta.tool_error_count} total tool errors).`,\n action:\n \"Stop the agent immediately, inspect the failing command manually, fix the root cause or environment, and resume with a concise summary.\",\n estimated_savings_pct: \"40–80% on runaway turns\",\n });\n }\n\n // 4b. Redundant / polling tool calls (non-error context bloat)\n if (options?.transcriptMeta) {\n const redundantReads = options.transcriptMeta.redundant_read_file_count ?? 0;\n const redundantReadPct = options.transcriptMeta.redundant_read_file_pct ?? 0;\n const pollingDups = options.transcriptMeta.polling_dup_count ?? 0;\n const pollingDupPct = options.transcriptMeta.polling_dup_rate_pct ?? 0;\n const hasRedundantReads = redundantReadPct >= 20 && redundantReads >= 5;\n const hasPollingDups = pollingDupPct >= 15 && pollingDups >= 5;\n\n if (hasRedundantReads || hasPollingDups) {\n const parts: string[] = [];\n if (hasRedundantReads) {\n parts.push(\n `${redundantReads} unedited file re-reads (${redundantReadPct}% of read_file calls)`,\n );\n }\n if (hasPollingDups) {\n parts.push(\n `${pollingDups} exact-duplicate polling/tool calls (${pollingDupPct}% of all tool calls)`,\n );\n }\n recs.push({\n id: \"redundant_tool_calls\",\n severity:\n redundantReadPct >= 35 || pollingDupPct >= 30 ? \"high\" : \"medium\",\n category: \"redundant_tool_calls\",\n title: \"Redundant / polling tool calls inflating session context\",\n evidence: `Transcript recorded ${parts.join(\" and \")}.`,\n action:\n \"Use `quick_outline` + targeted line ranges instead of re-reading unchanged files, and avoid polling `manage_task` / `call_mcp_tool` / `read_board` with identical arguments in loops.\",\n estimated_savings_pct: \"15–35%\",\n });\n }\n }\n\n // 5. Missing .geminiignore context hygiene check (when workspace_dir is inspected)\n if (options?.hasGeminiIgnore === false) {\n recs.push({\n id: \"missing_geminiignore\",\n severity: \"medium\",\n category: \"missing_geminiignore\",\n title: \"Missing .geminiignore in workspace\",\n evidence: \"No .geminiignore file was found in the provided workspace_dir.\",\n action:\n \"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.\",\n estimated_savings_pct: \"15–35%\",\n });\n }\n\n // 6. Low KV cache efficiency (high uncached input ratio on multi-turn/long contexts)\n const hasLongTurns =\n snowballSessions.length > 0 ||\n [...longSessions.values()].some((s) => s.turns >= 5);\n\n if (\n filtered.length >= 4 &&\n totalInputWithCache >= 16_384 &&\n cacheHitRatePct < 30 &&\n (totalCacheRead > 0 || hasLongTurns)\n ) {\n const policy = activeChannelForPolicy?.definition.quota_reset_policy;\n const behaviors = activeChannelForPolicy?.definition.recommended_behaviors;\n const discountNote =\n policy?.supports_kv_cache_discount && policy.kv_cache_discount_rate\n ? ` (${policy.kv_cache_discount_rate} KV cache discount applies)`\n : \"\";\n recs.push({\n id: \"low_kv_cache_efficiency\",\n severity: \"medium\",\n category: \"low_kv_cache_efficiency\",\n title: `Low KV cache hit efficiency${discountNote}`,\n evidence: `KV cache hit rate is ${Math.round(cacheHitRatePct * 10) / 10}% (${totalCacheRead.toLocaleString()} cached / ${totalInputWithCache.toLocaleString()} total input tokens).`,\n action:\n getLocalizedBehavior(behaviors, \"kv_cache_guidance\", locale) ??\n \"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.\",\n estimated_savings_pct: \"20–50% on input cost\",\n });\n }\n\n // 7. Peak window misalignment (burst concentration in 2-3 hours accompanied by 429s)\n const tz = normalizeTimezone(options?.timezone);\n const hourlyMap = new Map<\n string,\n {\n tokens: number;\n count429: number;\n requests: number;\n uncachedInput: number;\n cacheRead: number;\n cacheHitRatePct?: number;\n }\n >();\n if (options?.hourlyBuckets && options.hourlyBuckets.length > 0) {\n for (const b of options.hourlyBuckets) {\n hourlyMap.set(b.bucket, {\n tokens: b.total_tokens,\n count429: b.rate_limit_429_count,\n requests: b.requests ?? 0,\n uncachedInput: 0,\n cacheRead: 0,\n cacheHitRatePct: b.cache_hit_rate_pct,\n });\n }\n } else {\n for (const r of filtered) {\n const tsMs = Date.parse(r.ts);\n if (Number.isNaN(tsMs)) continue;\n const hourKey = formatBucketKey(tsMs, \"hourly\", tz);\n const cur = hourlyMap.get(hourKey) ?? {\n tokens: 0,\n count429: 0,\n requests: 0,\n uncachedInput: 0,\n cacheRead: 0,\n };\n const cacheRead = r.cache_read_tokens ?? 0;\n cur.requests += 1;\n cur.uncachedInput += r.input_tokens;\n cur.cacheRead += cacheRead;\n cur.tokens += r.input_tokens + cacheRead + r.output_tokens;\n if (\n r.error_code &&\n (r.error_code.includes(\"429\") || r.error_code.includes(\"RESOURCE_EXHAUSTED\"))\n ) {\n cur.count429 += 1;\n }\n hourlyMap.set(hourKey, cur);\n }\n }\n\n const hourlyValues = [...hourlyMap.values()];\n const totalHourlyTokens = hourlyValues.reduce((s, v) => s + v.tokens, 0);\n const total429 = hourlyValues.reduce((s, v) => s + v.count429, 0);\n if (hourlyValues.length >= 3 && totalHourlyTokens > 0 && total429 > 0) {\n const sortedTokens = hourlyValues.map((v) => v.tokens).sort((a, b) => b - a);\n const top3Tokens = sortedTokens.slice(0, 3).reduce((s, t) => s + t, 0);\n const top3SharePct = Math.round((top3Tokens / totalHourlyTokens) * 1000) / 10;\n if (top3SharePct >= 70) {\n const policy = activeChannelForPolicy?.definition.quota_reset_policy;\n const behaviors = activeChannelForPolicy?.definition.recommended_behaviors;\n const isRollingBucket = !policy || policy.window_type === \"rolling_5h_7d\";\n if (isRollingBucket) {\n recs.push({\n id: \"peak_window_misalignment\",\n severity: \"medium\",\n category: \"peak_window_misalignment\",\n title: \"Peak window concentration causing 429 rate limits\",\n evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s).`,\n action:\n getLocalizedBehavior(behaviors, \"throttling_guidance\", locale) ??\n \"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.\",\n estimated_savings_pct: \"15–30% fewer 429 retries\",\n });\n } else {\n recs.push({\n id: \"burst_rpm_tpm_throttling\",\n severity: \"medium\",\n category: \"burst_rpm_tpm_throttling\",\n title: `Burst RPM/TPM concentration causing 429 throttling (${activeChannelForPolicy.definition.display_name})`,\n evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s) under ${policy.window_type}.`,\n action:\n getLocalizedBehavior(behaviors, \"throttling_guidance\", locale) ??\n \"Spread concurrent requests across regions or upgrade RPM/TPM quota.\",\n estimated_savings_pct: \"15–30% fewer 429 retries\",\n });\n }\n }\n }\n\n // 8. Background call spend warning (policy-driven: only when background_call_billed === true)\n if (activeChannelForPolicy?.definition.quota_reset_policy.background_call_billed) {\n const bgRecords = filtered.filter((r) => r.data_quality === \"estimated_from_cli_log\");\n const bgTokens = bgRecords.reduce((s, r) => s + r.input_tokens + r.output_tokens, 0);\n if (bgRecords.length >= 3 || bgTokens >= 10_000) {\n recs.push({\n id: \"background_spend_warning\",\n severity: \"medium\",\n category: \"background_spend_warning\",\n title: `Background monitor / checkpoint calls billed on ${activeChannelForPolicy.definition.display_name}`,\n evidence: `Detected ${bgRecords.length} estimated background CLI monitor call(s) (${bgTokens.toLocaleString()} tokens) on a pay-as-you-go/metered channel.`,\n action:\n getLocalizedBehavior(\n activeChannelForPolicy.definition.recommended_behaviors,\n \"background_spend_guidance\",\n locale,\n ) ??\n \"Background lightweight calls incur real metered usage on this channel; avoid idle polling loops.\",\n estimated_savings_pct: \"10–25% background spend\",\n });\n }\n }\n\n const hasTelemetry = filtered.some(\n (r) =>\n r.input_tokens > 0 ||\n (r.cache_read_tokens ?? 0) > 0 ||\n r.output_tokens > 0 ||\n r.turn_index > 0 ||\n (r.context_used_pct !== null && r.context_used_pct > 0),\n );\n const note =\n filtered.length > 0 && !hasTelemetry && !options?.transcriptMeta\n ? \"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.\"\n : undefined;\n\n // Behavior summary (100% numeric/enum/bucketed metadata)\n const catalog = options?.models ?? [];\n const totalOutput = filtered.reduce((s, r) => s + r.output_tokens, 0);\n const totalTokens = totalInputWithCache + totalOutput;\n const totalRequests = filtered.length;\n const avgInputTokensPerRequest =\n totalRequests > 0 ? Math.round(totalInputWithCache / totalRequests) : 0;\n const roundedCacheHitRatePct =\n totalInputWithCache > 0 ? Math.round(cacheHitRatePct * 10) / 10 : 0;\n\n const modelAgg = new Map<\n string,\n { requests: number; uncachedInput: number; cacheRead: number; output: number }\n >();\n for (const r of filtered) {\n const cur = modelAgg.get(r.model) ?? {\n requests: 0,\n uncachedInput: 0,\n cacheRead: 0,\n output: 0,\n };\n cur.requests += 1;\n cur.uncachedInput += r.input_tokens;\n cur.cacheRead += r.cache_read_tokens ?? 0;\n cur.output += r.output_tokens;\n modelAgg.set(r.model, cur);\n }\n\n let estimatedCacheSavingsUsd = 0;\n let lightModelRequests = 0;\n let heavyModelRequests = 0;\n const modelEntries: Array<{\n model: string;\n requests: number;\n total_tokens: number;\n }> = [];\n\n for (const [model, agg] of modelAgg.entries()) {\n const { pricing, cacheSavingsUsd } = estimateTokenCosts(\n {\n model,\n uncachedInputTokens: agg.uncachedInput,\n cacheReadTokens: agg.cacheRead,\n outputTokens: agg.output,\n },\n catalog,\n );\n estimatedCacheSavingsUsd += cacheSavingsUsd;\n if (pricing.tier === \"low\" || pricing.tier === \"minimal\") {\n lightModelRequests += agg.requests;\n } else if (\n pricing.tier === \"high\" ||\n pricing.tier === \"very-high\" ||\n pricing.tier === \"very_high\"\n ) {\n heavyModelRequests += agg.requests;\n }\n const modelTotalTokens = agg.uncachedInput + agg.cacheRead + agg.output;\n modelEntries.push({\n model,\n requests: agg.requests,\n total_tokens: modelTotalTokens,\n });\n }\n\n modelEntries.sort(\n (a, b) => b.total_tokens - a.total_tokens || b.requests - a.requests,\n );\n const topModels: BehaviorSummaryTopModel[] = modelEntries\n .slice(0, 3)\n .map((m) => ({\n model: m.model,\n requests: m.requests,\n token_share_pct:\n totalTokens > 0\n ? Math.round((m.total_tokens / totalTokens) * 1000) / 10\n : totalRequests > 0\n ? Math.round((m.requests / totalRequests) * 1000) / 10\n : 0,\n total_tokens: m.total_tokens,\n }));\n\n const lightModelRequestSharePct =\n totalRequests > 0\n ? Math.round((lightModelRequests / totalRequests) * 1000) / 10\n : 0;\n const heavyModelRequestSharePct =\n totalRequests > 0\n ? Math.round((heavyModelRequests / totalRequests) * 1000) / 10\n : 0;\n\n const hasBucketRequests = Boolean(\n options?.hourlyBuckets?.some((b) => typeof b.requests === \"number\"),\n );\n const peakHoursSource =\n options?.hourlyBuckets && options.hourlyBuckets.length > 0 && hasBucketRequests\n ? options.hourlyBuckets.map((b) => ({\n bucket: b.bucket,\n requests: b.requests ?? 0,\n total_tokens: b.total_tokens,\n cache_hit_rate_pct: b.cache_hit_rate_pct ?? 0,\n }))\n : [...hourlyMap.entries()].map(([bucket, v]) => {\n const inputTotal = v.uncachedInput + v.cacheRead;\n const hitPct =\n typeof v.cacheHitRatePct === \"number\"\n ? v.cacheHitRatePct\n : inputTotal > 0\n ? Math.round((v.cacheRead / inputTotal) * 1000) / 10\n : 0;\n return {\n bucket,\n requests: v.requests,\n total_tokens: v.tokens,\n cache_hit_rate_pct: hitPct,\n };\n });\n\n const peakHours: BehaviorSummaryPeakHour[] = peakHoursSource\n .filter((b) => b.requests > 0 || b.total_tokens > 0)\n .sort((a, b) => b.total_tokens - a.total_tokens || b.requests - a.requests)\n .slice(0, 3);\n\n const globalTotalTokens = windowRecords.reduce(\n (s, r) => s + r.input_tokens + (r.cache_read_tokens ?? 0) + r.output_tokens,\n 0,\n );\n const projectShareOfGlobalPct =\n scope === \"project\"\n ? globalTotalTokens > 0\n ? Math.round((totalTokens / globalTotalTokens) * 1000) / 10\n : 0\n : null;\n\n const roundedSavingsUsd = Math.round(estimatedCacheSavingsUsd * 10000) / 10000;\n const effectiveAuthMode: AuthMode = resolvedFilterChannel\n ? registry.toLegacyAuthMode(resolvedFilterChannel)\n : (options?.authContext?.active_auth_mode ?? \"unknown\");\n const authSummary = {\n active_auth_mode: effectiveAuthMode,\n has_mixed_auth: options?.authContext?.has_mixed_auth ?? false,\n };\n\n const behaviorSummary: BehaviorSummary = {\n avg_input_tokens_per_request: avgInputTokensPerRequest,\n cache_hit_rate_pct: roundedCacheHitRatePct,\n estimated_cache_savings_usd: roundedSavingsUsd,\n light_model_request_share_pct: lightModelRequestSharePct,\n heavy_model_request_share_pct: heavyModelRequestSharePct,\n top_models: topModels,\n peak_hours: peakHours,\n project_share_of_global_pct: projectShareOfGlobalPct,\n auth_context: authSummary,\n };\n\n const isShadowBucket =\n activeChannelForPolicy?.definition.quota_reset_policy.window_type === \"rolling_5h_7d\" ||\n authSummary.active_auth_mode === \"google_oauth\";\n\n const executiveSummary = buildExecutiveSummary({\n window,\n scope,\n requests: totalRequests,\n totalTokens,\n avgInputTokensPerRequest,\n cacheHitRatePct: roundedCacheHitRatePct,\n estimatedCacheSavingsUsd: roundedSavingsUsd,\n projectShareOfGlobalPct,\n isShadowBucket,\n recommendations: recs,\n hasMissingTelemetryNote: Boolean(note),\n });\n\n // Multi-channel split reports when authMode is \"all\" or \"auto\" with >=2 distinct channels\n let channelReports: Record<string, SavingRecommendationsReport> | undefined;\n if (!isSpecificAuthFilter && (!requestedAuthMode || requestedAuthMode === \"auto\" || requestedAuthMode === \"all\")) {\n const distinctChannelIds = new Set<string>();\n for (const r of filtered) {\n if (r.auth_mode && r.auth_mode !== \"unknown\") {\n distinctChannelIds.add(registry.resolveChannelId(r.auth_mode));\n }\n }\n if (distinctChannelIds.size >= 2 || (requestedAuthMode === \"all\" && distinctChannelIds.size >= 1)) {\n channelReports = {};\n for (const chId of distinctChannelIds) {\n channelReports[chId] = analyzeAntipatterns(records, {\n ...options,\n authMode: chId,\n channels: registry,\n hourlyBuckets: undefined,\n });\n }\n }\n }\n\n return {\n window,\n ...(options?.scope ? { scope } : {}),\n ...(scope === \"project\" && options?.projectHash\n ? { project_hash: options.projectHash }\n : {}),\n ...(requestedAuthMode ? { auth_mode_filter: requestedAuthMode } : {}),\n analyzed_records: filtered.length,\n recommendations: recs,\n healthy: recs.length === 0,\n ...(note ? { note } : {}),\n behavior_summary: behaviorSummary,\n executive_summary: executiveSummary,\n ...(channelReports ? { channel_reports: channelReports } : {}),\n };\n}\n\nfunction buildExecutiveSummary(params: {\n window: \"24h\" | \"7d\";\n scope: \"global\" | \"project\";\n requests: number;\n totalTokens: number;\n avgInputTokensPerRequest: number;\n cacheHitRatePct: number;\n estimatedCacheSavingsUsd: number;\n projectShareOfGlobalPct: number | null;\n isShadowBucket: boolean;\n recommendations: SavingRecommendation[];\n hasMissingTelemetryNote: boolean;\n}): string {\n const {\n window,\n scope,\n requests,\n totalTokens,\n avgInputTokensPerRequest,\n cacheHitRatePct,\n estimatedCacheSavingsUsd,\n projectShareOfGlobalPct,\n isShadowBucket,\n recommendations,\n hasMissingTelemetryNote,\n } = params;\n\n if (requests === 0) {\n return `No usage records found in the ${window} ${scope} window; run active sessions or enable Gemini CLI OTel to capture token telemetry.`;\n }\n\n const shareText =\n scope === \"project\" && projectShareOfGlobalPct !== null\n ? ` (${projectShareOfGlobalPct}% of global volume)`\n : \"\";\n const costLabel = isShadowBucket\n ? `$${estimatedCacheSavingsUsd.toFixed(2)} API-equivalent shadow cost saved`\n : `$${estimatedCacheSavingsUsd.toFixed(2)} saved`;\n 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}).`;\n\n if (recommendations.length === 0) {\n if (hasMissingTelemetryNote) {\n return `${usagePart} Token telemetry is incomplete; enable Gemini CLI OTel or pass transcript_path for deeper antipattern diagnostics.`;\n }\n return `${usagePart} Status: healthy with no quota-burning antipatterns detected; maintain stable prefixes and current model tier routing.`;\n }\n\n const rank: Record<SavingRecommendation[\"severity\"], number> = {\n high: 0,\n medium: 1,\n low: 2,\n };\n const sorted = [...recommendations].sort(\n (a, b) => rank[a.severity] - rank[b.severity],\n );\n const top = sorted[0]!;\n return `${usagePart} Primary bottleneck: ${top.title} (${recommendations.length} issue(s) flagged). Top action: ${top.action}`;\n}\n","import type {\n ChannelRegistry,\n CompiledAuthChannel,\n} from \"../collectors/channel-registry.js\";\nimport {\n getLocalizedBehavior,\n localizeDiagnosisEntry,\n type SupportedLocale,\n} from \"../i18n.js\";\nimport type {\n AuthContext,\n AuthMode,\n ChannelPrescriptionOverride,\n DiagnosisCommand,\n DiagnosisEntry,\n} from \"../types.js\";\n\nexport interface AuthChannelAnalysis {\n resolved_channel: string;\n resolution_source:\n | \"error_signature\"\n | \"explicit_auth_mode\"\n | \"cli_log\"\n | \"auth_context\"\n | \"mixed_ambiguous\"\n | \"unknown\";\n cross_talk_detected: boolean;\n expected_channel?: string;\n isolation_commands?: string[];\n note: string;\n}\n\nexport interface ChannelResolutionOutput {\n resolvedChannel: string;\n analysis: AuthChannelAnalysis;\n}\n\nfunction normalizeCandidateChannel(\n raw: string | undefined | null,\n registry: ChannelRegistry,\n): string | undefined {\n if (!raw || typeof raw !== \"string\") {\n return undefined;\n }\n const trimmed = raw.trim();\n if (!trimmed || trimmed === \"auto\" || trimmed === \"unknown\") {\n return undefined;\n }\n return registry.resolveChannelId(trimmed);\n}\n\nexport function resolveErrorAuthChannel(params: {\n errorText: string;\n authMode?: AuthMode | \"auto\";\n authContext?: AuthContext;\n cliChannel?: string;\n registry: ChannelRegistry;\n}): ChannelResolutionOutput {\n const { errorText, authMode, authContext, cliChannel, registry } = params;\n\n const explicitChannel = normalizeCandidateChannel(authMode, registry);\n const logChannel = normalizeCandidateChannel(cliChannel, registry);\n const staticChannel = normalizeCandidateChannel(\n authContext?.active_channel_id ?? authContext?.active_auth_mode,\n registry,\n );\n const expectedChannel = explicitChannel ?? logChannel ?? staticChannel;\n\n // Level 1: Error text strong signature match\n const signatureMatch = registry.matchErrorText(errorText);\n if (signatureMatch) {\n const resolved = signatureMatch.channelId;\n const crossTalk = Boolean(\n expectedChannel && !registry.matchesChannel(expectedChannel, resolved),\n );\n const isolationCommands =\n signatureMatch.definition.recommended_behaviors.isolation_commands;\n return {\n resolvedChannel: resolved,\n analysis: {\n resolved_channel: resolved,\n resolution_source: \"error_signature\",\n cross_talk_detected: crossTalk,\n ...(expectedChannel ? { expected_channel: expectedChannel } : {}),\n ...(crossTalk || authContext?.has_mixed_auth\n ? { isolation_commands: isolationCommands }\n : {}),\n note: crossTalk\n ? `Cross-talk detected: expected/active channel \"${expectedChannel}\", but error signature matched \"${resolved}\" (${signatureMatch.definition.display_name}). Isolate env vars before retrying.`\n : `Error signature matched auth channel \"${resolved}\" (${signatureMatch.definition.display_name}).`,\n },\n };\n }\n\n // Level 2: Explicit auth_mode != \"auto\"\n if (explicitChannel) {\n const ch = registry.getChannel(explicitChannel);\n const mixedWithStatic = Boolean(\n authContext?.has_mixed_auth ||\n (staticChannel && !registry.matchesChannel(explicitChannel, staticChannel)),\n );\n return {\n resolvedChannel: explicitChannel,\n analysis: {\n resolved_channel: explicitChannel,\n resolution_source: \"explicit_auth_mode\",\n cross_talk_detected: false,\n ...(mixedWithStatic && ch\n ? { isolation_commands: ch.definition.recommended_behaviors.isolation_commands }\n : {}),\n note: ch\n ? `Using explicit auth_mode \"${explicitChannel}\" (${ch.definition.display_name}).`\n : `Using explicit auth_mode \"${explicitChannel}\".`,\n },\n };\n }\n\n // Level 3: Recent active cli-*.log channel\n if (logChannel) {\n const ch = registry.getChannel(logChannel);\n return {\n resolvedChannel: logChannel,\n analysis: {\n resolved_channel: logChannel,\n resolution_source: \"cli_log\",\n cross_talk_detected: false,\n ...(authContext?.has_mixed_auth && ch\n ? { isolation_commands: ch.definition.recommended_behaviors.isolation_commands }\n : {}),\n note: ch\n ? `Resolved active channel \"${logChannel}\" (${ch.definition.display_name}) from recent cli-*.log.`\n : `Resolved active channel \"${logChannel}\" from recent cli-*.log.`,\n },\n };\n }\n\n // Level 4: Static authContext\n if (authContext?.has_mixed_auth) {\n const fallback = staticChannel ?? \"mixed_ambiguous\";\n const ch = staticChannel ? registry.getChannel(staticChannel) : undefined;\n const detectedList = authContext.detected_channels ?? authContext.detected_modes;\n return {\n resolvedChannel: fallback,\n analysis: {\n resolved_channel: fallback,\n resolution_source: \"mixed_ambiguous\",\n cross_talk_detected: false,\n ...(ch\n ? { isolation_commands: ch.definition.recommended_behaviors.isolation_commands }\n : {}),\n note: `Mixed auth contexts detected (${detectedList.join(\", \")}) with no channel-specific error signature or cli-*.log event. Verify active auth channel to avoid cross-channel misattribution.`,\n },\n };\n }\n\n if (staticChannel) {\n const ch = registry.getChannel(staticChannel);\n return {\n resolvedChannel: staticChannel,\n analysis: {\n resolved_channel: staticChannel,\n resolution_source: \"auth_context\",\n cross_talk_detected: false,\n note: ch\n ? `Resolved single local auth channel \"${staticChannel}\" (${ch.definition.display_name}).`\n : `Resolved local auth channel \"${staticChannel}\".`,\n },\n };\n }\n\n return {\n resolvedChannel: \"unknown\",\n analysis: {\n resolved_channel: \"unknown\",\n resolution_source: \"unknown\",\n cross_talk_detected: false,\n note: \"No specific auth channel resolved; using channel-agnostic diagnostics.\",\n },\n };\n}\n\nexport function findChannelVariant(\n entry: DiagnosisEntry,\n resolvedChannel: string,\n registry: ChannelRegistry,\n): ChannelPrescriptionOverride | undefined {\n if (!entry.channel_variants || resolvedChannel === \"unknown\") {\n return undefined;\n }\n if (entry.channel_variants[resolvedChannel]) {\n return entry.channel_variants[resolvedChannel];\n }\n const compiled = registry.getChannel(resolvedChannel);\n if (compiled) {\n if (compiled.legacyId && entry.channel_variants[compiled.legacyId]) {\n return entry.channel_variants[compiled.legacyId];\n }\n for (const alias of compiled.aliases) {\n if (entry.channel_variants[alias]) {\n return entry.channel_variants[alias];\n }\n }\n }\n return undefined;\n}\n\nexport function isEntryApplicableToChannel(\n entry: DiagnosisEntry,\n resolvedChannel: string,\n registry: ChannelRegistry,\n): boolean {\n if (\n !entry.applicable_auth_modes ||\n entry.applicable_auth_modes.length === 0 ||\n resolvedChannel === \"unknown\" ||\n resolvedChannel === \"mixed_ambiguous\"\n ) {\n return true;\n }\n return entry.applicable_auth_modes.some((m) =>\n registry.matchesChannel(m, resolvedChannel),\n );\n}\n\nconst GENERIC_CHANNEL_SENSITIVE_RULE_IDS = new Set([\n \"429-desync\",\n \"google-429-desync\",\n \"weekly-cap\",\n \"403-auth-mismatch\",\n \"google-403-auth-mismatch\",\n]);\n\nfunction buildIsolationCommands(channel: CompiledAuthChannel): DiagnosisCommand[] {\n const cmds: DiagnosisCommand[] = channel.definition.recommended_behaviors.isolation_commands.map(\n (cmd, idx) => ({\n label:\n idx === 0\n ? `Isolate ${channel.definition.display_name} env`\n : `Configure ${channel.definition.display_name} env`,\n os: \"unix\",\n command: cmd,\n }),\n );\n cmds.push({\n label: `Verify ${channel.definition.display_name}`,\n os: \"all\",\n command: channel.definition.recommended_behaviors.verify_command,\n });\n return cmds;\n}\n\nexport function applyChannelPrescription(params: {\n chosen: DiagnosisEntry;\n resolvedChannel: string;\n registry: ChannelRegistry;\n locale?: SupportedLocale;\n}): DiagnosisEntry {\n const { chosen, resolvedChannel, registry, locale = \"en\" } = params;\n const variant = findChannelVariant(chosen, resolvedChannel, registry);\n if (variant) {\n const localizedVariant = localizeDiagnosisEntry(variant, locale);\n const localizedChosen = localizeDiagnosisEntry(chosen, locale);\n return {\n ...localizedChosen,\n title: localizedVariant.title ?? localizedChosen.title,\n root_cause: localizedVariant.root_cause ?? localizedChosen.root_cause,\n steps: localizedVariant.steps ?? localizedChosen.steps,\n commands: localizedVariant.commands ?? localizedChosen.commands,\n verify_command: localizedVariant.verify_command ?? localizedChosen.verify_command,\n dont_dos: localizedVariant.dont_dos ?? localizedChosen.dont_dos,\n deep_link: localizedVariant.deep_link ?? localizedChosen.deep_link,\n };\n }\n\n const channel =\n resolvedChannel !== \"unknown\" && resolvedChannel !== \"mixed_ambiguous\"\n ? registry.getChannel(resolvedChannel)\n : undefined;\n if (!channel) {\n return chosen;\n }\n\n // Only adapt generic cross-channel rules (leave specific GCP rules like gcp-vertex-api-disabled intact)\n const isGenericChannelSensitive =\n GENERIC_CHANNEL_SENSITIVE_RULE_IDS.has(chosen.id) ||\n GENERIC_CHANNEL_SENSITIVE_RULE_IDS.has(chosen.slug);\n\n if (!isGenericChannelSensitive) {\n return chosen;\n }\n\n const localizedChosen = localizeDiagnosisEntry(chosen, locale);\n const behaviors = channel.definition.recommended_behaviors;\n const policy = channel.definition.quota_reset_policy;\n const isoCommands = buildIsolationCommands(channel);\n const displayName =\n locale === \"zh\" && channel.definition.display_name_zh\n ? channel.definition.display_name_zh\n : channel.definition.display_name;\n const throttlingGuidance =\n getLocalizedBehavior(behaviors, \"throttling_guidance\", locale) ?? behaviors.throttling_guidance;\n const kvCacheGuidance =\n getLocalizedBehavior(behaviors, \"kv_cache_guidance\", locale) ?? behaviors.kv_cache_guidance;\n const backgroundSpendGuidance = getLocalizedBehavior(\n behaviors,\n \"background_spend_guidance\",\n locale,\n );\n\n if (localizedChosen.domain === \"quota\") {\n if (policy.window_type === \"rolling_5h_7d\") {\n // Consumer OAuth track: strip any cloud-billing / gcloud / AI Studio cross-contamination\n const cleanSteps = localizedChosen.steps.filter(\n (s) => !/gcloud|aiplatform|cloud\\s*billing|aistudio\\.google\\.com/i.test(s),\n );\n return {\n ...localizedChosen,\n root_cause:\n locale === \"zh\"\n ? `${displayName} 的 ${policy.window_type} 共享配额桶已耗尽或权益失步。${throttlingGuidance}`\n : `Shared ${policy.window_type} quota bucket exhausted or entitlement desync on ${displayName}. ${throttlingGuidance}`,\n steps:\n cleanSteps.length > 0\n ? cleanSteps\n : [throttlingGuidance, kvCacheGuidance],\n commands: isoCommands,\n verify_command: behaviors.verify_command,\n };\n }\n\n // Non-rolling-5h channels (Vertex ADC, Gemini API Key, Vertex Express, custom OIDC/WIF, etc.)\n const steps = [\n throttlingGuidance,\n kvCacheGuidance,\n ...(backgroundSpendGuidance ? [backgroundSpendGuidance] : []),\n ];\n return {\n ...localizedChosen,\n title:\n locale === \"zh\"\n ? `429 限流 / 配额耗尽(${displayName})`\n : `429 Rate Limit / Quota Exhausted (${displayName})`,\n root_cause: `${displayName} (${channel.definition.billing_model}, ${policy.window_type}): ${throttlingGuidance}`,\n steps,\n commands: isoCommands,\n verify_command: behaviors.verify_command,\n dont_dos: [\n locale === \"zh\"\n ? \"不要对该认证通道执行个人 OAuth 共享配额桶的 Reset Onboarding 重置操作。\"\n : \"Do NOT apply consumer OAuth shared-bucket onboarding resets to this auth channel.\",\n ...localizedChosen.dont_dos.filter(\n (d) => !/reset\\s*onboarding|5h\\/7d/i.test(d),\n ),\n ],\n };\n }\n\n if (localizedChosen.domain === \"auth\") {\n return {\n ...localizedChosen,\n title:\n locale === \"zh\"\n ? `401/403 认证与权益不匹配(${displayName})`\n : `401/403 Auth & Entitlement Mismatch (${displayName})`,\n root_cause:\n locale === \"zh\"\n ? `${displayName} 存在认证或权益不匹配,请确认已清理其他通道的冲突环境变量。`\n : `Authentication or entitlement mismatch on ${displayName}. Ensure conflicting credentials from other channels are unset.`,\n steps: [\n locale === \"zh\"\n ? `为 ${displayName} 隔离冲突环境变量。`\n : `Isolate environment variables for ${displayName}.`,\n throttlingGuidance,\n locale === \"zh\"\n ? `运行校验命令确认连通性:${behaviors.verify_command}`\n : `Verify connectivity with: ${behaviors.verify_command}`,\n ],\n commands: isoCommands,\n verify_command: behaviors.verify_command,\n };\n }\n\n return localizedChosen;\n}\n","import type { UsageRecord } from \"../collectors/agy-hook.js\";\nimport {\n ChannelRegistry,\n loadBundledChannelRegistry,\n} from \"../collectors/channel-registry.js\";\nimport {\n getLocalizedBehavior,\n localizeDiagnosisEntry,\n type SupportedLocale,\n} from \"../i18n.js\";\nimport type {\n AuthContext,\n AuthMode,\n ChannelsSnapshot,\n DiagnosisCommand,\n DiagnosisEntry,\n StatusSnapshot,\n} from \"../types.js\";\nimport {\n applyChannelPrescription,\n findChannelVariant,\n isEntryApplicableToChannel,\n resolveErrorAuthChannel,\n type AuthChannelAnalysis,\n} from \"./channel-diagnosis.js\";\n\nexport interface DiagnosisResult {\n matched: boolean;\n domain: string;\n diagnosis_id: string;\n title: string;\n confidence: \"high\" | \"medium\" | \"low\";\n attribution: string;\n root_cause: string;\n steps: string[];\n commands: DiagnosisCommand[];\n verify_command: string;\n dont_dos: string[];\n deep_link: string;\n official_source_url: string | null;\n upstream_status: string;\n extracted_signals: {\n http_status: string | null;\n retry_delay: string | null;\n quota_metric: string | null;\n };\n auth_channel_analysis?: AuthChannelAnalysis;\n}\n\ninterface PatternRule {\n id: string;\n domain: string;\n regex: RegExp;\n fallback: DiagnosisEntry;\n}\n\nconst EXTERNAL_GCP_DATA_PLANE_403_RE =\n /\\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;\n\nconst MODEL_AUTH_CONFLICT_RE =\n /cloudaicompanion|generativelanguage|aiplatform|gemini|antigravity|ACCESS_TOKEN_TYPE_UNSUPPORTED|API_KEY_INVALID|GEMINI_API_KEY|GOOGLE_CLOUD_PROJECT/i;\n\nfunction isExternalGcpDataPlane403(text: string): boolean {\n return (\n EXTERNAL_GCP_DATA_PLANE_403_RE.test(text) &&\n !MODEL_AUTH_CONFLICT_RE.test(text)\n );\n}\n\nconst SPECIFIC_GCP_RULE_IDS = new Set([\n \"gcp-vertex-api-disabled\",\n \"gcp-adc-expired\",\n \"gcp-vertex-iam-or-location\",\n \"gcp-vpc-sc-blocked\",\n]);\n\nconst BUILTIN_RULES: PatternRule[] = [\n {\n id: \"weekly-cap\",\n domain: \"quota\",\n regex:\n /weekly\\s*(?:cap|limit)|WEEKLY_LIMIT_EXCEEDED|5-?hour|rolling\\s*(?:5h|7d)|reached\\s+your\\s+usage\\s+limit/i,\n fallback: {\n id: \"weekly-cap\",\n slug: \"weekly-cap\",\n provider: \"antigravity\",\n route_provider: \"agy\",\n domain: \"quota\",\n title: \"Shared 5h / 7d Weekly Quota Cap Reached\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"web\"],\n error_codes: [\"429\", \"WEEKLY_LIMIT_EXCEEDED\", \"RATE_LIMIT_EXCEEDED\"],\n error_patterns: [\"weekly limit\", \"5-hour\", \"Try again later\", \"reached your usage limit\"],\n root_cause:\n \"You have exhausted the shared 5-hour or 7-day rolling quota bucket across Antigravity / Gemini CLI.\",\n steps: [\n \"Check `get_ecosystem_status` for local 5h/7d rolling window estimates and the official AGY/CLI quota UI for authoritative remaining %.\",\n \"Switch to a lighter model (Gemini 4 Hydrogen or Gemini 3.8 Flash) or run `/compact` to reduce per-turn token burn.\",\n ],\n commands: [\n { label: \"Switch Gemini CLI to Flash\", os: \"all\", command: \"gemini --model gemini-3.8-flash\" },\n ],\n verify_command: \"gemini --version && npx agycraft-mcp doctor\",\n dont_dos: [\n \"Do NOT hammer retry in a tight loop while capped.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/quota/weekly-cap\",\n },\n },\n {\n id: \"429-desync\",\n domain: \"quota\",\n regex: /\\b429\\b|RESOURCE_EXHAUSTED|quotaMetric|limit:\\s*0|rate\\s*limit/i,\n fallback: {\n id: \"429-desync\",\n slug: \"429-desync\",\n provider: \"antigravity\",\n route_provider: \"agy\",\n domain: \"quota\",\n title: \"429 RESOURCE_EXHAUSTED / Quota Desync or Shared Bucket Cap\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"429\", \"RESOURCE_EXHAUSTED\"],\n error_patterns: [\"429\", \"RESOURCE_EXHAUSTED\", \"limit: 0\"],\n root_cause:\n \"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).\",\n steps: [\n \"Compare local 5h token consumption against the error to separate real cap vs entitlement/billing desync.\",\n \"If desynced: run Reset Onboarding in Antigravity or verify Google Cloud Billing / AI Pro subscription binding.\",\n \"If real cap: switch to Gemini 4 Hydrogen or Gemini 3.8 Flash, run `/compact`, and wait for the rolling 5h window relief.\",\n ],\n commands: [\n { label: \"Run local preflight doctor\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n { label: \"Switch Gemini CLI to lighter Flash model\", os: \"all\", command: \"gemini --model gemini-3.8-flash\" },\n ],\n verify_command: \"gemini --version && npx agycraft-mcp doctor\",\n dont_dos: [\n \"Do NOT hammer retry in a tight loop — repeated 429 bursts can trigger automated abuse cooldowns.\",\n \"Do NOT rotate multiple personal API keys to bypass free-tier limits.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/quota/429-desync\",\n },\n },\n {\n id: \"gcp-vertex-api-disabled\",\n domain: \"auth\",\n regex:\n /\\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,\n fallback: {\n id: \"gcp-vertex-api-disabled\",\n slug: \"gcp-vertex-api-disabled\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"auth\",\n title: \"GCP Vertex AI / Companion API Disabled (SERVICE_DISABLED)\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"403\", \"PERMISSION_DENIED\", \"SERVICE_DISABLED\"],\n error_patterns: [\n \"SERVICE_DISABLED\",\n \"aiplatform.googleapis.com\",\n \"cloudaicompanion.googleapis.com\",\n \"Vertex AI API has not been used\",\n ],\n root_cause:\n \"The target GCP project does not have the Vertex AI API (`aiplatform.googleapis.com`) or Gemini Code Assist API (`cloudaicompanion.googleapis.com`) enabled.\",\n steps: [\n \"Enable `aiplatform.googleapis.com` on your active `GOOGLE_CLOUD_PROJECT`.\",\n \"If using Gemini CLI / Code Assist enterprise seats, also enable `cloudaicompanion.googleapis.com` as needed.\",\n \"Wait 1-2 minutes for GCP service enablement propagation, then retry.\",\n ],\n commands: [\n {\n label: \"Enable Vertex AI API\",\n os: \"all\",\n command:\n \"gcloud services enable aiplatform.googleapis.com --project=${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id}\",\n },\n {\n label: \"Enable Gemini Code Assist API (if needed)\",\n os: \"all\",\n command:\n \"gcloud services enable cloudaicompanion.googleapis.com --project=${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id}\",\n },\n ],\n verify_command:\n \"gcloud services list --enabled --filter=\\\"config.name:(aiplatform.googleapis.com OR cloudaicompanion.googleapis.com)\\\"\",\n dont_dos: [\n \"Do NOT switch to an unrelated personal API key to work around a disabled project API.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/auth/gcp-vertex-api-disabled\",\n },\n },\n {\n id: \"gcp-adc-expired\",\n domain: \"auth\",\n regex:\n /\\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,\n fallback: {\n id: \"gcp-adc-expired\",\n slug: \"gcp-adc-expired\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"auth\",\n title: \"GCP Application Default Credentials (ADC) Expired / Reauth Required\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"401\", \"403\", \"UNAUTHENTICATED\", \"invalid_grant\"],\n error_patterns: [\n \"invalid_grant\",\n \"reauth related error\",\n \"Refreshing credentials failed\",\n \"Getting metadata from plugin failed\",\n \"application-default login\",\n ],\n root_cause:\n \"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.\",\n steps: [\n \"Re-authenticate Application Default Credentials via `gcloud auth application-default login`.\",\n \"Check whether `GOOGLE_APPLICATION_CREDENTIALS` is set to a stale or deleted file path (without printing secret contents).\",\n ],\n commands: [\n {\n label: \"Refresh Application Default Credentials\",\n os: \"all\",\n command: \"gcloud auth application-default login\",\n },\n {\n label: \"Check GOOGLE_APPLICATION_CREDENTIALS path existence\",\n os: \"unix\",\n command: \"test -n \\\"$GOOGLE_APPLICATION_CREDENTIALS\\\" && ls -l \\\"$GOOGLE_APPLICATION_CREDENTIALS\\\" || echo \\\"unset\\\"\",\n },\n ],\n verify_command: \"gcloud auth application-default print-access-token >/dev/null && echo OK\",\n dont_dos: [\n \"Do NOT read, print, or paste raw service account JSON keys or OAuth refresh tokens.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/auth/gcp-adc-expired\",\n },\n },\n {\n id: \"gcp-vertex-iam-or-location\",\n domain: \"auth\",\n regex:\n /roles\\/aiplatform\\.user|aiplatform\\.endpoints\\.predict|not\\s+found\\s+in\\s+location|Publisher\\s+Model.*(?:not\\s+found|permission)/i,\n fallback: {\n id: \"gcp-vertex-iam-or-location\",\n slug: \"gcp-vertex-iam-or-location\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"auth\",\n title: \"Vertex AI IAM Role (roles/aiplatform.user) or Location Mismatch\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"403\", \"404\", \"PERMISSION_DENIED\", \"NOT_FOUND\"],\n error_patterns: [\n \"roles/aiplatform.user\",\n \"aiplatform.endpoints.predict\",\n \"not found in location\",\n \"Publisher Model\",\n ],\n root_cause:\n \"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.\",\n steps: [\n \"Verify `GOOGLE_CLOUD_LOCATION` matches a supported region for the target model (e.g. `us-central1` or `global`).\",\n \"Confirm your user or service account has `roles/aiplatform.user` (including `aiplatform.endpoints.predict`) on the target project.\",\n ],\n commands: [\n {\n label: \"Set supported Vertex AI location\",\n os: \"unix\",\n command: \"export GOOGLE_CLOUD_LOCATION=us-central1\",\n },\n {\n label: \"Inspect project IAM policy for active account\",\n os: \"all\",\n command:\n \"gcloud projects get-iam-policy ${GOOGLE_CLOUD_PROJECT:-your-gcp-project-id} --flatten=\\\"bindings[].members\\\" --format=\\\"table(bindings.role,bindings.members)\\\"\",\n },\n ],\n verify_command: \"echo \\\"GOOGLE_CLOUD_LOCATION=${GOOGLE_CLOUD_LOCATION:-unset}\\\"\",\n dont_dos: [\n \"Do NOT grant `roles/owner` when `roles/aiplatform.user` is sufficient.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/auth/gcp-vertex-iam-or-location\",\n },\n },\n {\n id: \"gcp-vpc-sc-blocked\",\n domain: \"network\",\n regex:\n /VPC\\s+Service\\s+Controls|prohibited\\s+by\\s+organization(?:'s)?\\s+policy|vpcServiceControlsUniqueIdentifier|Request\\s+is\\s+prohibited\\s+by\\s+organization/i,\n fallback: {\n id: \"gcp-vpc-sc-blocked\",\n slug: \"gcp-vpc-sc-blocked\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"network\",\n title: \"Blocked by GCP VPC Service Controls / Organization Policy\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"403\", \"PERMISSION_DENIED\", \"VPC_SERVICE_CONTROLS\"],\n error_patterns: [\n \"VPC Service Controls\",\n \"prohibited by organization's policy\",\n \"vpcServiceControlsUniqueIdentifier\",\n \"Request is prohibited by organization\",\n ],\n root_cause:\n \"The request was blocked at the enterprise GCP VPC Service Controls perimeter or organization policy boundary.\",\n steps: [\n \"Record the `vpcServiceControlsUniqueIdentifier` (if present) from the error payload.\",\n \"Contact your GCP security/network administrator to review VPC-SC ingress/egress rules, or run from an authorized corporate network/perimeter.\",\n ],\n commands: [\n {\n label: \"Verify active gcloud account and project\",\n os: \"all\",\n command: \"gcloud config list --format=\\\"table(core.account,core.project)\\\"\",\n },\n ],\n verify_command: \"gcloud config get-value project\",\n dont_dos: [\n \"Do NOT attempt to bypass corporate VPC Service Controls with unapproved proxies or personal projects.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/network/gcp-vpc-sc-blocked\",\n },\n },\n {\n id: \"403-auth-mismatch\",\n domain: \"auth\",\n regex:\n /\\b401\\b|\\b403\\b|UNAUTHENTICATED|Permission\\s*Denied|cloudaicompanion.*denied|ACCESS_TOKEN_TYPE_UNSUPPORTED|API_KEY_INVALID/i,\n fallback: {\n id: \"403-auth-mismatch\",\n slug: \"403-auth-mismatch\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"auth\",\n title: \"401/403 Auth & Entitlement Mismatch\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"401\", \"403\", \"UNAUTHENTICATED\", \"PERMISSION_DENIED\"],\n error_patterns: [\"401\", \"403\", \"UNAUTHENTICATED\", \"ACCESS_TOKEN_TYPE_UNSUPPORTED\"],\n root_cause:\n \"Mixed authentication state (e.g., GEMINI_API_KEY colliding with GOOGLE_CLOUD_PROJECT OAuth) or stale local OAuth consent/ADC cache.\",\n steps: [\n \"Unset conflicting env vars so only ONE auth mode (API Key OR Google Cloud OAuth) is active.\",\n \"Revoke stale third-party authorization at https://myaccount.google.com/connections if OAuth is stuck.\",\n \"Clear local auth cache and re-authenticate cleanly.\",\n ],\n commands: [\n { label: \"Unset conflicting API key vars\", os: \"unix\", command: \"unset GEMINI_API_KEY GOOGLE_API_KEY\" },\n { label: \"Set GCP project for OAuth/Vertex\", os: \"unix\", command: \"export GOOGLE_CLOUD_PROJECT=your-gcp-project-id\" },\n { label: \"Refresh Application Default Credentials\", os: \"all\", command: \"gcloud auth application-default login\" },\n ],\n verify_command: \"gcloud auth application-default print-access-token >/dev/null && echo OK\",\n dont_dos: [\n \"Do NOT paste OAuth tokens or API keys into public issue trackers or MCP logs.\",\n \"Do NOT mix Vertex AI GOOGLE_CLOUD_PROJECT with AI Studio GEMINI_API_KEY in the same shell.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/auth/403-auth-mismatch\",\n },\n },\n {\n id: \"503-504-stall\",\n domain: \"capacity\",\n regex:\n /\\b503\\b|\\b504\\b|No\\s*capacity|DEADLINE_EXCEEDED|UNAVAILABLE|antigravity-unleash\\.goog|overloaded/i,\n fallback: {\n id: \"503-504-stall\",\n slug: \"503-504-stall\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"capacity\",\n title: \"503 No Capacity / 504 DEADLINE_EXCEEDED / Stall\",\n severity: \"high\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"503\", \"504\", \"UNAVAILABLE\", \"DEADLINE_EXCEEDED\"],\n error_patterns: [\"503\", \"504\", \"DEADLINE_EXCEEDED\", \"No capacity\"],\n root_cause:\n \"Upstream model capacity saturation (503) or oversized uncompacted prompt context exceeding backend deadline (504).\",\n steps: [\n \"Check ModelCraft live upstream status to confirm whether a global 503 wave is active.\",\n \"If upstream is healthy and you hit 504: add a `.geminiignore` file, run `/compact`, and split the task.\",\n \"Temporarily switch from flagship Neon to Hydrogen or Flash until capacity recovers.\",\n ],\n commands: [\n { label: \"Check context hygiene & .geminiignore\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n ],\n verify_command: \"curl -sI https://modelcraft.dev/data/v1/status.json | head -n 1\",\n dont_dos: [\n \"Do NOT keep retrying massive 500k+ token prompts on 504 without compacting context first.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/capacity/503-504-stall\",\n },\n },\n {\n id: \"mcp-disconnected\",\n domain: \"mcp\",\n regex:\n /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,\n fallback: {\n id: \"mcp-disconnected\",\n slug: \"mcp-disconnected\",\n provider: \"antigravity\",\n route_provider: \"agy\",\n domain: \"mcp\",\n title: \"MCP Disconnected / Transport Mismatch / Env Stripped\",\n severity: \"high\",\n products: [\"agy\", \"cli\"],\n error_codes: [\"EADDRINUSE\", \"MCP_DISCONNECTED\"],\n error_patterns: [\"MCP Disconnected\", \"EADDRINUSE\", \"httpUrl\"],\n root_cause:\n \"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.\",\n steps: [\n \"Trust the workspace directory with `gemini trust`.\",\n \"Run `npx agycraft-mcp doctor` to check JSON syntax, `url` vs `httpUrl`, and env key stripping.\",\n \"Pass required credentials explicitly inside the server's `env` block in mcp_config.json / settings.json.\",\n ],\n commands: [\n { label: \"Trust workspace\", os: \"all\", command: \"gemini trust\" },\n { label: \"Run offline config doctor\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n { label: \"List active MCP servers\", os: \"all\", command: \"gemini mcp list\" },\n ],\n verify_command: \"gemini mcp list\",\n dont_dos: [\n \"Do NOT log debug text to stdout in stdio MCP servers — stdout is reserved for JSON-RPC frames.\",\n \"Do NOT set both `url` and `httpUrl` on the same MCP server entry.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/mcp/mcp-disconnected\",\n },\n },\n {\n id: \"ssl-proxy\",\n domain: \"network\",\n regex:\n /UNABLE_TO_GET_ISSUER_CERT_LOCALLY|UNABLE_TO_VERIFY_LEAF_SIGNATURE|SELF_SIGNED_CERT_IN_CHAIN|CERT_HAS_EXPIRED|ECONNRESET|ETIMEDOUT|ECONNREFUSED/i,\n fallback: {\n id: \"ssl-proxy\",\n slug: \"ssl-proxy\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"network\",\n title: \"Corporate Proxy / SSL Certificate Verification Failure\",\n severity: \"medium\",\n products: [\"agy\", \"cli\", \"api\"],\n error_codes: [\"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\", \"SELF_SIGNED_CERT_IN_CHAIN\"],\n error_patterns: [\"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\", \"SELF_SIGNED_CERT_IN_CHAIN\"],\n root_cause:\n \"Node.js does not automatically trust corporate TLS-inspecting proxy root certificates unless NODE_EXTRA_CA_CERTS is configured.\",\n steps: [\n \"Export your corporate root CA bundle in PEM format.\",\n \"Set `NODE_EXTRA_CA_CERTS` in your shell profile and verify the file is readable.\",\n \"Verify `HTTP_PROXY` / `HTTPS_PROXY` URLs are reachable.\",\n ],\n commands: [\n { label: \"Configure Node extra CA bundle\", os: \"unix\", command: \"export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem\" },\n { label: \"Verify SSL & proxy setup\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n ],\n verify_command: \"node -e \\\"fetch('https://modelcraft.dev/data/v1/status.json').then(r => console.log(r.status))\\\"\",\n dont_dos: [\n \"Do NOT permanently set `NODE_TLS_REJECT_UNAUTHORIZED=0` — it disables all TLS verification.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/network/ssl-proxy\",\n },\n },\n {\n id: \"function-calling-state\",\n domain: \"protocol\",\n regex:\n /thought_signature|function[\\s_]+call|function[\\s_]+response|FunctionCall|MALFORMED_FUNCTION_CALL|INVALID_ARGUMENT.*turn|tool_call_id/i,\n fallback: {\n id: \"function-calling-state\",\n slug: \"function-calling-state\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"protocol\",\n title: \"Function Calling Turn Alignment / Missing thought_signature\",\n severity: \"medium\",\n products: [\"api\", \"cli\", \"agy\"],\n error_codes: [\"INVALID_ARGUMENT\"],\n error_patterns: [\"thought_signature\", \"function_call\", \"function_response\"],\n root_cause:\n \"Tool call/response turn sequence is misaligned, or Thinking-model `thought_signature` was stripped when replaying assistant tool calls.\",\n steps: [\n \"Preserve the exact `thought_signature` field on model `functionCall` parts when sending back `functionResponse` turns.\",\n \"Ensure every `functionCall` turn is immediately followed by matching `functionResponse` parts in the next user/tool turn.\",\n \"Upgrade `@google/genai` or `@google/gemini-cli` to the latest release.\",\n ],\n commands: [\n { label: \"Check latest Gemini CLI version\", os: \"all\", command: \"npm view @google/gemini-cli version\" },\n ],\n verify_command: \"Replay a single 2-turn tool call with unmodified model parts including thought_signature.\",\n dont_dos: [\n \"Do NOT manually reconstruct or strip unknown fields from model `parts` during multi-turn tool calling.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/protocol/function-calling-state\",\n },\n },\n {\n id: \"structured-output-schema\",\n domain: \"protocol\",\n regex:\n /(?: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,\n fallback: {\n id: \"structured-output-schema\",\n slug: \"structured-output-schema\",\n provider: \"google\",\n route_provider: \"google\",\n domain: \"protocol\",\n title: \"Structured Output JSON Schema Too Deep or Unsupported Keyword\",\n severity: \"medium\",\n products: [\"api\", \"cli\"],\n error_codes: [\"INVALID_ARGUMENT\"],\n error_patterns: [\"response_schema\", \"nesting depth\", \"too many states\"],\n root_cause:\n \"Gemini constrained decoding rejects deeply nested schemas, recursive `$ref` cycles, or excessive union branches ('too many states').\",\n steps: [\n \"Flatten nested objects to <= 4 levels and remove recursive `$ref` definitions.\",\n \"Replace large `oneOf`/`anyOf` unions with a flat discriminator string enum + optional fields.\",\n \"Keep property descriptions concise so grammar compilation stays within state limits.\",\n ],\n commands: [\n { label: \"Run doctor preflight\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n ],\n verify_command: \"Re-run the API call with flattened JSON schema (depth <= 4, no recursive $ref).\",\n dont_dos: [\n \"Do NOT pass unconstrained TypeScript ASTs or OpenAPI specs directly as `response_schema`.\",\n ],\n deep_link: \"https://modelcraft.dev/fix/protocol/structured-output-schema\",\n },\n },\n];\n\nfunction extractSignals(errorText: string): {\n http_status: string | null;\n retry_delay: string | null;\n quota_metric: string | null;\n} {\n const httpMatch = errorText.match(/\\b(400|401|403|404|408|429|500|502|503|504)\\b/);\n const retryMatch = errorText.match(/retryDelay[\"']?\\s*[:=]\\s*[\"']?([0-9.]+s?)/i);\n const metricMatch = errorText.match(/quotaMetric[\"']?\\s*[:=]\\s*[\"']?([a-zA-Z0-9._/-]+)/i);\n\n return {\n http_status: httpMatch?.[1] ?? null,\n retry_delay: retryMatch?.[1] ?? null,\n quota_metric: metricMatch?.[1] ?? null,\n };\n}\n\nexport function diagnoseError(options: {\n errorText: string;\n product?: string;\n localRecords?: UsageRecord[];\n statusSnapshot?: StatusSnapshot | null;\n diagnosisEntries?: DiagnosisEntry[];\n authMode?: AuthMode | \"auto\";\n authContext?: AuthContext;\n cliChannel?: string;\n channels?: ChannelsSnapshot | ChannelRegistry;\n nowMs?: number;\n locale?: SupportedLocale;\n}): DiagnosisResult {\n const locale = options.locale ?? \"en\";\n const text = options.errorText;\n const lowerText = text.toLowerCase();\n const signals = extractSignals(text);\n const nowMs = options.nowMs ?? Date.now();\n const registry =\n options.channels instanceof ChannelRegistry\n ? options.channels\n : options.channels\n ? ChannelRegistry.fromSnapshot(options.channels)\n : loadBundledChannelRegistry();\n\n const { resolvedChannel, analysis: authChannelAnalysis } = resolveErrorAuthChannel({\n errorText: text,\n authMode: options.authMode,\n authContext: options.authContext,\n cliChannel: options.cliChannel,\n registry,\n });\n\n const upstreamStatus = options.statusSnapshot?.overall_status ?? \"unknown\";\n const hasActiveIncident =\n upstreamStatus === \"degraded\" ||\n upstreamStatus === \"outage\" ||\n (options.statusSnapshot?.active_incidents?.some(\n (i) => i.status !== \"resolved\",\n ) ??\n false);\n\n const skip403AuthMismatch = isExternalGcpDataPlane403(text);\n\n // Match against built-in regex rules first for precision, then enrich from remote diagnosis entries\n let matchedRule: PatternRule | null = null;\n for (const rule of BUILTIN_RULES) {\n if (skip403AuthMismatch && rule.id === \"403-auth-mismatch\") {\n continue;\n }\n if (rule.regex.test(text)) {\n matchedRule = rule;\n break;\n }\n }\n\n const GENERIC_ERROR_CODES = new Set([\n \"400\",\n \"401\",\n \"403\",\n \"404\",\n \"500\",\n \"502\",\n \"503\",\n \"504\",\n \"invalid_argument\",\n ]);\n\n const skipGeneric403 =\n skip403AuthMismatch ||\n (matchedRule !== null && SPECIFIC_GCP_RULE_IDS.has(matchedRule.id));\n\n let remoteMatch: DiagnosisEntry | null = null;\n let bestScore = 0;\n for (const entry of options.diagnosisEntries ?? []) {\n if (\n skipGeneric403 &&\n (entry.id === \"google-403-auth-mismatch\" || entry.slug === \"403-auth-mismatch\")\n ) {\n continue;\n }\n if (!isEntryApplicableToChannel(entry, resolvedChannel, registry)) {\n continue;\n }\n let score = 0;\n let hasSpecificSignal = false;\n const codeSet = new Set((entry.error_codes ?? []).map((c) => c.toLowerCase()));\n for (const p of entry.error_patterns ?? []) {\n const lp = p.toLowerCase();\n if (lowerText.includes(lp)) {\n if (codeSet.has(lp) || GENERIC_ERROR_CODES.has(lp)) {\n score += 2;\n } else {\n score += 10;\n hasSpecificSignal = true;\n }\n }\n }\n for (const c of entry.error_codes ?? []) {\n const lc = c.toLowerCase();\n if (lowerText.includes(lc)) {\n score += 2;\n if (!GENERIC_ERROR_CODES.has(lc)) {\n hasSpecificSignal = true;\n }\n }\n }\n if (matchedRule && (entry.id === matchedRule.id || entry.slug === matchedRule.id)) {\n score += 25;\n hasSpecificSignal = true;\n }\n if (\n resolvedChannel !== \"unknown\" &&\n resolvedChannel !== \"mixed_ambiguous\" &&\n entry.applicable_auth_modes?.some((m) => registry.matchesChannel(m, resolvedChannel))\n ) {\n score += 20;\n }\n if (findChannelVariant(entry, resolvedChannel, registry)) {\n score += 15;\n }\n if (hasSpecificSignal && score > bestScore) {\n bestScore = score;\n remoteMatch = entry;\n }\n }\n\n const rawChosen = remoteMatch ?? matchedRule?.fallback ?? null;\n const chosen = rawChosen\n ? applyChannelPrescription({\n chosen: rawChosen,\n resolvedChannel,\n registry,\n locale,\n })\n : null;\n\n if (!chosen) {\n return {\n matched: false,\n domain: \"unknown\",\n diagnosis_id: \"unclassified\",\n title: \"Unclassified Error\",\n confidence: \"low\",\n attribution: hasActiveIncident\n ? `Upstream status is currently \"${upstreamStatus}\" — this may be related to an active provider incident.`\n : \"No known fault signature matched. Run `npx agycraft-mcp doctor` to check local environment hygiene.\",\n root_cause:\n \"Error text did not match the 5 primary fault domains (quota, auth, capacity, mcp, network) or protocol signatures.\",\n steps: [\n \"Run `npx agycraft-mcp doctor` to inspect local config syntax, auth env booleans, and proxy settings.\",\n \"Check https://modelcraft.dev/fix for the latest community-verified troubleshooting guides.\",\n ],\n commands: [\n { label: \"Run local preflight doctor\", os: \"all\", command: \"npx agycraft-mcp doctor\" },\n ],\n verify_command: \"npx agycraft-mcp doctor\",\n dont_dos: [\n \"Do NOT paste raw API keys, OAuth tokens, or private code when asking for help.\",\n ],\n deep_link: \"https://modelcraft.dev/fix\",\n official_source_url: \"https://aistudio.google.com/docs/troubleshooting\",\n upstream_status: upstreamStatus,\n extracted_signals: signals,\n auth_channel_analysis: authChannelAnalysis,\n };\n }\n\n // Cross-correlate local 5h usage (strictly isolated by resolvedChannel) & upstream status for attribution\n const resolvedChannelDef =\n resolvedChannel !== \"unknown\" && resolvedChannel !== \"mixed_ambiguous\"\n ? registry.getChannel(resolvedChannel)\n : undefined;\n const windowType = resolvedChannelDef?.definition.quota_reset_policy.window_type;\n const isRollingBucketChannel = !windowType || windowType === \"rolling_5h_7d\";\n\n let attribution = `Matched fault domain: ${chosen.domain}.`;\n if (chosen.domain === \"quota\") {\n const fiveHoursAgo = nowMs - 5 * 3600 * 1000;\n const recentRecords = (options.localRecords ?? []).filter((r) => {\n if (Date.parse(r.ts) < fiveHoursAgo) {\n return false;\n }\n if (resolvedChannel !== \"unknown\" && resolvedChannel !== \"mixed_ambiguous\" && r.auth_mode) {\n return registry.matchesChannel(r.auth_mode, resolvedChannel);\n }\n return true;\n });\n const recentTokens = recentRecords.reduce(\n (sum, r) => sum + r.input_tokens + r.output_tokens,\n 0,\n );\n\n if (!isRollingBucketChannel && resolvedChannelDef) {\n const displayName =\n locale === \"zh\" && resolvedChannelDef.definition.display_name_zh\n ? resolvedChannelDef.definition.display_name_zh\n : resolvedChannelDef.definition.display_name;\n const throttlingGuidance =\n getLocalizedBehavior(\n resolvedChannelDef.definition.recommended_behaviors,\n \"throttling_guidance\",\n locale,\n ) ?? resolvedChannelDef.definition.recommended_behaviors.throttling_guidance;\n attribution = hasActiveIncident\n ? `POSSIBLE UPSTREAM INCIDENT (${upstreamStatus}) on ${displayName}: ${throttlingGuidance}`\n : `${displayName} (${resolvedChannelDef.definition.billing_model}, ${recentRecords.length} recent channel turns / ${recentTokens.toLocaleString()} tokens): ${throttlingGuidance}`;\n } else if (lowerText.includes(\"limit: 0\") || (recentRecords.length > 0 && recentTokens < 50_000)) {\n attribution =\n \"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.\";\n } else if (recentTokens >= 500_000) {\n 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.`;\n } else if (hasActiveIncident) {\n attribution = `POSSIBLE UPSTREAM INCIDENT: Upstream status is \"${upstreamStatus}\" — 429s may be caused by upstream throttling.`;\n } else {\n attribution =\n \"QUOTA / RATE LIMIT HIT: Enable local numeric usage logging (`npx agycraft-mcp setup`) to distinguish real 5h/7d exhaustion from entitlement desync.\";\n }\n } else if (chosen.domain === \"capacity\") {\n attribution = hasActiveIncident\n ? `UPSTREAM OUTAGE/DEGRADATION CONFIRMED (${upstreamStatus}): Not a local machine issue. Wait for recovery or temporarily switch to Flash/Hydrogen.`\n : \"LOCAL CONTEXT OR TRANSIENT CAPACITY SPIKE: Upstream status appears operational; check for oversized context (>200k tokens) and add `.geminiignore`.\";\n }\n\n return localizeDiagnosisEntry(\n {\n matched: true,\n domain: chosen.domain,\n diagnosis_id: chosen.id,\n title: chosen.title,\n confidence: \"high\",\n attribution,\n root_cause: chosen.root_cause,\n steps: chosen.steps,\n commands: chosen.commands,\n verify_command: chosen.verify_command,\n dont_dos: chosen.dont_dos,\n deep_link: chosen.deep_link.startsWith(\"/\")\n ? `https://modelcraft.dev${chosen.deep_link}`\n : chosen.deep_link,\n official_source_url: chosen.official_source_url ?? null,\n upstream_status: upstreamStatus,\n extracted_signals: signals,\n auth_channel_analysis: authChannelAnalysis,\n },\n locale,\n );\n}\n","/**\n * Pure local reset countdown calculator for Gemini API / AI Studio PT midnight\n * and AGY 5-hour / 7-day rolling shared quota windows.\n */\nexport interface ResetCountdown {\n timezone: string;\n now_iso: string;\n pt_midnight: {\n next_reset_iso: string;\n next_reset_local: string;\n remaining_seconds: number;\n remaining_human: string;\n };\n rolling_5h: {\n window_hours: 5;\n is_local_estimate: true;\n estimate_note: string;\n oldest_active_event_iso: string | null;\n estimated_relief_iso: string | null;\n estimated_relief_local: string | null;\n remaining_seconds: number | null;\n remaining_human: string;\n };\n rolling_7d: {\n window_days: 7;\n is_local_estimate: true;\n estimate_note: string;\n oldest_active_event_iso: string | null;\n estimated_relief_iso: string | null;\n estimated_relief_local: string | null;\n remaining_seconds: number | null;\n remaining_human: string;\n };\n}\n\nconst ROLLING_ESTIMATE_NOTE =\n \"Approximated solely from the earliest local event timestamp in this window; does not reflect server-side multi-device usage or official remaining quota percentages.\";\n\nexport function formatDuration(seconds: number): string {\n const clamped = Math.max(0, Math.floor(seconds));\n const days = Math.floor(clamped / 86400);\n const hours = Math.floor((clamped % 86400) / 3600);\n const mins = Math.floor((clamped % 3600) / 60);\n if (days > 0) {\n return `${days}d ${hours}h ${mins}m`;\n }\n if (hours > 0) {\n return `${hours}h ${mins}m`;\n }\n return `${mins}m`;\n}\n\nfunction validateTimezone(tz?: string): string {\n if (!tz) {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n }\n try {\n Intl.DateTimeFormat(\"en-US\", { timeZone: tz });\n return tz;\n } catch {\n return \"UTC\";\n }\n}\n\nfunction getPtDateParts(now: Date): {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n} {\n const fmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: \"America/Los_Angeles\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n const parts = fmt.formatToParts(now);\n const get = (type: string): number =>\n Number(parts.find((p) => p.type === type)?.value ?? \"0\");\n return {\n year: get(\"year\"),\n month: get(\"month\"),\n day: get(\"day\"),\n hour: get(\"hour\") === 24 ? 0 : get(\"hour\"),\n minute: get(\"minute\"),\n second: get(\"second\"),\n };\n}\n\n/**\n * Computes the exact next midnight in America/Los_Angeles (handles PST/PDT transitions).\n */\nexport function computeNextPtMidnight(now: Date): Date {\n const pt = getPtDateParts(now);\n const remainingTodaySec =\n (23 - pt.hour) * 3600 + (59 - pt.minute) * 60 + (60 - pt.second);\n // Step forward to approximate next PT midnight, then refine to exact 00:00:00 PT\n let candidate = new Date(now.getTime() + remainingTodaySec * 1000);\n // Adjust by up to +/-1h if DST switched overnight\n for (let i = 0; i < 3; i++) {\n const check = getPtDateParts(candidate);\n if (check.hour === 0 && check.minute === 0 && check.second === 0) {\n break;\n }\n if (check.hour >= 22) {\n candidate = new Date(\n candidate.getTime() + ((24 - check.hour) * 3600 - check.minute * 60 - check.second) * 1000,\n );\n } else if (check.hour <= 2) {\n candidate = new Date(\n candidate.getTime() - (check.hour * 3600 + check.minute * 60 + check.second) * 1000,\n );\n }\n }\n return candidate;\n}\n\nexport function computeResetCountdown(options?: {\n now?: Date;\n timezone?: string;\n oldestEventIn5hMs?: number | null;\n oldestEventIn7dMs?: number | null;\n}): ResetCountdown {\n const now = options?.now ?? new Date();\n const tz = validateTimezone(options?.timezone);\n\n const nextPt = computeNextPtMidnight(now);\n const ptRemainingSec = Math.max(\n 0,\n Math.floor((nextPt.getTime() - now.getTime()) / 1000),\n );\n const nextPtLocal = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(nextPt);\n\n const fiveHoursMs = 5 * 3600 * 1000;\n const sevenDaysMs = 7 * 86400 * 1000;\n\n let relief5hIso: string | null = null;\n let relief5hLocal: string | null = null;\n let relief5hSec: number | null = null;\n if (options?.oldestEventIn5hMs) {\n const reliefMs = options.oldestEventIn5hMs + fiveHoursMs;\n relief5hIso = new Date(reliefMs).toISOString();\n relief5hLocal = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(new Date(reliefMs));\n relief5hSec = Math.max(0, Math.floor((reliefMs - now.getTime()) / 1000));\n }\n\n let relief7dIso: string | null = null;\n let relief7dLocal: string | null = null;\n let relief7dSec: number | null = null;\n if (options?.oldestEventIn7dMs) {\n const reliefMs = options.oldestEventIn7dMs + sevenDaysMs;\n relief7dIso = new Date(reliefMs).toISOString();\n relief7dLocal = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(new Date(reliefMs));\n relief7dSec = Math.max(0, Math.floor((reliefMs - now.getTime()) / 1000));\n }\n\n return {\n timezone: tz,\n now_iso: now.toISOString(),\n pt_midnight: {\n next_reset_iso: nextPt.toISOString(),\n next_reset_local: nextPtLocal,\n remaining_seconds: ptRemainingSec,\n remaining_human: formatDuration(ptRemainingSec),\n },\n rolling_5h: {\n window_hours: 5,\n is_local_estimate: true,\n estimate_note: ROLLING_ESTIMATE_NOTE,\n oldest_active_event_iso: options?.oldestEventIn5hMs\n ? new Date(options.oldestEventIn5hMs).toISOString()\n : null,\n estimated_relief_iso: relief5hIso,\n estimated_relief_local: relief5hLocal,\n remaining_seconds: relief5hSec,\n remaining_human:\n relief5hSec !== null\n ? formatDuration(relief5hSec)\n : \"No active usage recorded in last 5h\",\n },\n rolling_7d: {\n window_days: 7,\n is_local_estimate: true,\n estimate_note: ROLLING_ESTIMATE_NOTE,\n oldest_active_event_iso: options?.oldestEventIn7dMs\n ? new Date(options.oldestEventIn7dMs).toISOString()\n : null,\n estimated_relief_iso: relief7dIso,\n estimated_relief_local: relief7dLocal,\n remaining_seconds: relief7dSec,\n remaining_human:\n relief7dSec !== null\n ? formatDuration(relief7dSec)\n : \"No active usage recorded in last 7d\",\n },\n };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { getCacheDir, getPackageVersion, getSnapshotsDir } from \"../paths.js\";\nimport type {\n ModelsSnapshot,\n NormalizationRules,\n SnapshotMap,\n SnapshotName,\n} from \"../types.js\";\n\nconst DEFAULT_DATA_URL = \"https://modelcraft.dev/data/v1\";\n\nconst TTL_MS: Record<SnapshotName, number> = {\n status: 5 * 60 * 1000,\n updates: 15 * 60 * 1000,\n models: 6 * 60 * 60 * 1000,\n chronicle: 6 * 60 * 60 * 1000,\n diagnosis: 6 * 60 * 60 * 1000,\n quotas: 6 * 60 * 60 * 1000,\n channels: 6 * 60 * 60 * 1000,\n};\n\ninterface CacheMeta {\n etag: string | null;\n fetched_at_ms: number;\n pkg_version?: string;\n}\n\nexport interface SnapshotFetchResult<T> {\n data: T;\n source: \"remote\" | \"cache\" | \"bundled_fallback\";\n}\n\nexport interface SnapshotClientOptions {\n baseUrl?: string;\n cacheDir?: string;\n snapshotsDir?: string;\n fetchFn?: typeof fetch;\n offlineOnly?: boolean;\n timeoutMs?: number;\n pkgVersion?: string;\n}\n\nfunction getProviderId(p: string | { id: string }): string {\n return typeof p === \"string\" ? p : p.id;\n}\n\nfunction mergeNormalizationRules(\n remote?: NormalizationRules,\n fallback?: NormalizationRules,\n): NormalizationRules | undefined {\n if (!remote) return fallback;\n if (!fallback) return remote;\n return {\n rules_version: remote.rules_version ?? fallback.rules_version,\n placeholder_prefixes: remote.placeholder_prefixes ?? fallback.placeholder_prefixes,\n enum_mappings: remote.enum_mappings ?? fallback.enum_mappings,\n prefix_strip_patterns: remote.prefix_strip_patterns ?? fallback.prefix_strip_patterns,\n suffix_strip_patterns: remote.suffix_strip_patterns ?? fallback.suffix_strip_patterns,\n version_format_rules: remote.version_format_rules ?? fallback.version_format_rules,\n fallback_pricing: remote.fallback_pricing ?? fallback.fallback_pricing,\n };\n}\n\n/**\n * Anti-regression merge for remote models.json:\n * Keeps all remote entries as authoritative, while backfilling any missing\n * providers or historical/anthropic models from bundledFallback.\n */\nexport function mergeModelsSnapshotWithFallback(\n remote: ModelsSnapshot,\n fallback: ModelsSnapshot,\n): ModelsSnapshot {\n const remoteProviders = Array.isArray(remote.providers) ? remote.providers : [];\n const fallbackProviders = Array.isArray(fallback.providers) ? fallback.providers : [];\n const seenProviderIds = new Set(remoteProviders.map((p) => getProviderId(p).toLowerCase()));\n const mergedProviders = [\n ...remoteProviders,\n ...fallbackProviders.filter((p) => !seenProviderIds.has(getProviderId(p).toLowerCase())),\n ];\n\n const remoteModels = Array.isArray(remote.models) ? remote.models : [];\n const fallbackModels = Array.isArray(fallback.models) ? fallback.models : [];\n const seenIds = new Set(remoteModels.map((m) => m.id.toLowerCase()));\n const seenApiIds = new Set(remoteModels.map((m) => m.api_model_id.toLowerCase()));\n const mergedModels = [\n ...remoteModels,\n ...fallbackModels.filter(\n (m) =>\n !seenIds.has(m.id.toLowerCase()) &&\n !seenApiIds.has(m.api_model_id.toLowerCase()),\n ),\n ];\n\n const mergedRules = mergeNormalizationRules(\n remote.normalization_rules,\n fallback.normalization_rules,\n );\n\n const mergedRecipes =\n Array.isArray(remote.orchestrator_recipes) && remote.orchestrator_recipes.length > 0\n ? remote.orchestrator_recipes\n : (fallback.orchestrator_recipes ?? []);\n\n return {\n ...remote,\n providers: mergedProviders,\n models: mergedModels,\n ...(mergedRules ? { normalization_rules: mergedRules } : {}),\n orchestrator_recipes: mergedRecipes,\n };\n}\n\nfunction isCachedNewerThanBundled(cachedData: unknown, bundledData: unknown): boolean {\n const cachedTs =\n cachedData &&\n typeof cachedData === \"object\" &&\n \"generated_at\" in cachedData &&\n typeof (cachedData as { generated_at?: unknown }).generated_at === \"string\"\n ? Date.parse((cachedData as { generated_at: string }).generated_at)\n : Number.NaN;\n const bundledTs =\n bundledData &&\n typeof bundledData === \"object\" &&\n \"generated_at\" in bundledData &&\n typeof (bundledData as { generated_at?: unknown }).generated_at === \"string\"\n ? Date.parse((bundledData as { generated_at: string }).generated_at)\n : Number.NaN;\n\n if (Number.isNaN(cachedTs) || Number.isNaN(bundledTs)) {\n return false;\n }\n return cachedTs > bundledTs;\n}\n\n/**\n * One-way read-only snapshot client.\n * PRIVACY RED LINE:\n * - Only performs GET requests to public static JSON at MODELCRAFT_DATA_URL (default https://modelcraft.dev/data/v1).\n * - NEVER sends user identifiers, telemetry, query params, cookies, or authorization headers.\n * - NEVER contacts Google/AGY internal endpoints.\n */\nexport class SnapshotClient {\n private readonly baseUrl: string;\n private readonly cacheDir: string;\n private readonly snapshotsDir: string;\n private readonly fetchFn: typeof fetch;\n private readonly offlineOnly: boolean;\n private readonly timeoutMs: number;\n private readonly pkgVersion: string;\n\n constructor(options?: SnapshotClientOptions) {\n const envUrl = process.env.MODELCRAFT_DATA_URL?.trim();\n this.baseUrl = (options?.baseUrl || envUrl || DEFAULT_DATA_URL).replace(\n /\\/+$/,\n \"\",\n );\n this.cacheDir = options?.cacheDir ?? getCacheDir();\n this.snapshotsDir = options?.snapshotsDir ?? getSnapshotsDir();\n this.fetchFn = options?.fetchFn ?? globalThis.fetch;\n this.offlineOnly =\n options?.offlineOnly ?? process.env.AGYCRAFT_OFFLINE === \"1\";\n this.timeoutMs = options?.timeoutMs ?? 4000;\n this.pkgVersion = options?.pkgVersion ?? getPackageVersion();\n }\n\n async get<K extends SnapshotName>(\n name: K,\n ): Promise<SnapshotFetchResult<SnapshotMap[K]>> {\n const cacheFile = join(this.cacheDir, `${name}.json`);\n const metaFile = join(this.cacheDir, `${name}.meta.json`);\n const ttl = TTL_MS[name];\n\n const cached = await this.readCache<SnapshotMap[K]>(cacheFile, metaFile);\n const versionMatches = cached?.meta.pkg_version === this.pkgVersion;\n const now = Date.now();\n\n if (cached && versionMatches && now - cached.meta.fetched_at_ms < ttl) {\n return { data: cached.data, source: \"cache\" };\n }\n\n if (!this.offlineOnly) {\n const remoteResult = await this.fetchRemote<SnapshotMap[K]>(\n name,\n versionMatches ? (cached?.meta.etag ?? null) : null,\n cacheFile,\n metaFile,\n versionMatches ? (cached?.data ?? null) : null,\n );\n if (remoteResult) {\n return remoteResult;\n }\n }\n\n const fallback = await this.readBundledFallback<SnapshotMap[K]>(name);\n if (cached && versionMatches && isCachedNewerThanBundled(cached.data, fallback)) {\n return { data: cached.data, source: \"cache\" };\n }\n\n return { data: fallback, source: \"bundled_fallback\" };\n }\n\n private async readCache<T>(\n cacheFile: string,\n metaFile: string,\n ): Promise<{ data: T; meta: CacheMeta } | null> {\n try {\n const [rawJson, rawMeta] = await Promise.all([\n readFile(cacheFile, \"utf8\"),\n readFile(metaFile, \"utf8\"),\n ]);\n const data = JSON.parse(rawJson) as T;\n const meta = JSON.parse(rawMeta) as CacheMeta;\n return { data, meta };\n } catch {\n return null;\n }\n }\n\n private async writeCache<T>(\n cacheFile: string,\n metaFile: string,\n data: T,\n etag: string | null,\n ): Promise<void> {\n try {\n await mkdir(this.cacheDir, { recursive: true });\n const meta: CacheMeta = {\n etag,\n fetched_at_ms: Date.now(),\n pkg_version: this.pkgVersion,\n };\n await Promise.all([\n writeFile(cacheFile, JSON.stringify(data), \"utf8\"),\n writeFile(metaFile, JSON.stringify(meta), \"utf8\"),\n ]);\n } catch {\n // Cache write failure is non-fatal\n }\n }\n\n private async fetchRemote<T>(\n name: SnapshotName,\n etag: string | null,\n cacheFile: string,\n metaFile: string,\n cachedData: T | null,\n ): Promise<SnapshotFetchResult<T> | null> {\n const url = `${this.baseUrl}/${name}.json`;\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n };\n if (etag) {\n headers[\"If-None-Match\"] = etag;\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const resp = await this.fetchFn(url, {\n method: \"GET\",\n headers,\n signal: controller.signal,\n });\n\n if (resp.status === 304 && cachedData !== null) {\n await this.writeCache(cacheFile, metaFile, cachedData, etag);\n return { data: cachedData, source: \"cache\" };\n }\n\n if (!resp.ok) {\n return null;\n }\n\n let data = (await resp.json()) as T;\n if (name === \"models\") {\n const modelsData = data as unknown as ModelsSnapshot;\n if (!modelsData || !Array.isArray(modelsData.models) || modelsData.models.length === 0) {\n return null;\n }\n try {\n const fallback = await this.readBundledFallback<ModelsSnapshot>(\"models\");\n data = mergeModelsSnapshotWithFallback(modelsData, fallback) as unknown as T;\n } catch {\n // Proceed with remote models snapshot if bundled fallback is unavailable\n }\n }\n\n const newEtag = resp.headers.get(\"etag\");\n await this.writeCache(cacheFile, metaFile, data, newEtag);\n return { data, source: \"remote\" };\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async readBundledFallback<T>(name: SnapshotName): Promise<T> {\n const filePath = join(this.snapshotsDir, `${name}.json`);\n const raw = await readFile(filePath, \"utf8\");\n return JSON.parse(raw) as T;\n }\n}\n","import {\n formatDoctorCostReport,\n formatDoctorReport,\n runDoctor,\n runDoctorCost,\n} from \"./cli/doctor.js\";\nimport type { CostSummaryWindow } from \"./storage/rollups.js\";\nimport { runPreflight, formatPreflightReport } from \"./cli/preflight.js\";\nimport { runHookCheck } from \"./cli/hook-check.js\";\nimport {\n formatHookManageResult,\n runHookDisable,\n runHookEnable,\n runHookStatus,\n type HookKind,\n type HookTarget,\n} from \"./cli/hook-manage.js\";\nimport { formatIgnoreInitResult, runIgnoreInit } from \"./cli/ignore-manage.js\";\nimport {\n formatTelemetryManageResult,\n runTelemetryDisable,\n runTelemetryEnable,\n runTelemetryStatus,\n} from \"./cli/telemetry-manage.js\";\nimport { buildSetupInstructions } from \"./cli/setup.js\";\nimport { clearLocalData } from \"./cli/clear-local-data.js\";\nimport { appendUsageRecord } from \"./collectors/agy-hook.js\";\nimport { startStdioServer } from \"./server.js\";\n\nasync function readStdinText(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction printPreflightHelp(): void {\n console.log(\n [\n \"agycraft-mcp preflight — Live ModelCraft cloud status guard\",\n \"\",\n \"Usage:\",\n \" agycraft-mcp preflight [--json]\",\n \"\",\n \"Environment:\",\n \" MODELCRAFT_STATUS_URL Full URL override for status.json\",\n \" MODELCRAFT_DATA_URL Base URL override (default: https://modelcraft.dev/data/v1)\",\n \"\",\n \"Exit codes:\",\n \" 0 overall_status is operational, no active_incidents, all surfaces operational, no 429/503 sources\",\n \" 1 degraded, active incident, 429/503 source error, or network/timeout failure\",\n ].join(\"\\n\"),\n );\n}\n\nfunction printIgnoreHelp(): void {\n console.log(\n [\n \"agycraft-mcp ignore — Manage .geminiignore rules\",\n \"\",\n \"Usage:\",\n \" agycraft-mcp ignore init [--dir <path>] [--dry-run] [--json]\",\n \"\",\n \"Options:\",\n \" --dir <path> Target directory containing .geminiignore (default: cwd)\",\n \" --dry-run Preview changes without writing .geminiignore\",\n \" --json Output structured JSON\",\n ].join(\"\\n\"),\n );\n}\n\nfunction printTelemetryHelp(): void {\n console.log(\n [\n \"agycraft-mcp telemetry — Manage privacy-safe local Gemini CLI telemetry in settings.json\",\n \"\",\n \"Usage:\",\n \" agycraft-mcp telemetry enable [--settings <path>] [--dry-run] [--json]\",\n \" agycraft-mcp telemetry disable [--settings <path>] [--dry-run] [--json]\",\n \" agycraft-mcp telemetry status [--settings <path>] [--json]\",\n \"\",\n \"Options:\",\n \" --settings <path> Override target settings.json path (default: ~/.gemini/settings.json)\",\n \" --dry-run Preview changes without writing files\",\n \" --json Output structured JSON\",\n ].join(\"\\n\"),\n );\n}\n\nfunction printHookHelp(): void {\n console.log(\n [\n \"agycraft-mcp hook — Manage Stop / PostInvocation lifecycle hooks in settings.json / hooks.json\",\n \"\",\n \"Usage:\",\n \" agycraft-mcp hook enable [--kind stop|record] [--target agy|gemini|both] [--settings <path>] [--command <cmd>] [--local] [--lang en|zh|auto] [--dry-run] [--json]\",\n \" agycraft-mcp hook disable [--kind stop|record] [--target agy|gemini|both] [--settings <path>] [--dry-run] [--json]\",\n \" agycraft-mcp hook status [--kind stop|record] [--target agy|gemini|both] [--settings <path>] [--json]\",\n \"\",\n \"Options:\",\n \" --kind <name> Hook kind: stop (default, settings.json Stop) or record (~/.gemini/config/hooks.json PostInvocation)\",\n \" --target <name> Target settings.json: agy (default), gemini, or both (stop kind)\",\n \" --settings <path> Override target settings.json / hooks.json path directly\",\n \" --command <cmd> Custom hook command string (enable only)\",\n \" --local Use local dist/index.js path instead of npx (enable only)\",\n \" --lang <val> Append --lang en|zh|auto to generated hook-check command\",\n \" --dry-run Preview changes without writing files\",\n \" --json Output structured JSON\",\n ].join(\"\\n\"),\n );\n}\n\nfunction printHelp(): void {\n console.log(\n [\n \"agycraft-mcp — Privacy-first local MCP server & CLI doctor for Antigravity (AGY) & Gemini CLI\",\n \"\",\n \"Usage:\",\n \" agycraft-mcp [--lang en|zh|auto] Start Stdio MCP Server (default)\",\n \" agycraft-mcp doctor [--cost] [--window 5h|24h|7d] [--lang en|zh|auto] [--json]\",\n \" Run offline preflight & hygiene check or readonly cost breakdown\",\n \" agycraft-mcp preflight [--json] Check live ModelCraft status.json (exits 1 if degraded/429/503)\",\n \" agycraft-mcp ignore init [--dir <path>] [--dry-run] [--json]\",\n \" Initialize or append missing .geminiignore rules\",\n \" agycraft-mcp telemetry <enable|disable|status> [--settings <path>] [--dry-run] [--json]\",\n \" Manage privacy-safe local Gemini CLI telemetry\",\n \" agycraft-mcp hook <enable|disable|status> [--kind stop|record] [options]\",\n \" Manage Stop / PostInvocation record hook registration\",\n \" agycraft-mcp hook-check [--transcript <path>] [--state-file <path>] [--json] [--lang en|zh|auto]\",\n \" Lightweight O(1) Stop/PostToolUse lifecycle check (always exits 0)\",\n \" agycraft-mcp setup Print non-destructive, opt-in AGY / Gemini CLI setup snippets\",\n \" agycraft-mcp record Read hook JSON from stdin and append strictly whitelisted numeric metrics\",\n \" agycraft-mcp clear-local-data Safely delete ~/.config/agycraft/usage.jsonl and cache\",\n \" agycraft-mcp --help Show this help message\",\n \"\",\n \"Independent community project (ModelCraft). Not affiliated with or endorsed by Google.\",\n ].join(\"\\n\"),\n );\n}\n\nfunction extractLangArg(argv: string[]): { lang?: string; rest: string[] } {\n const rest: string[] = [];\n let lang: string | undefined;\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i];\n if (arg === undefined) {\n continue;\n }\n if (arg === \"--lang\") {\n const next = argv[i + 1];\n if (next !== \"en\" && next !== \"zh\" && next !== \"auto\") {\n throw new Error(`Invalid --lang value \"${next ?? \"\"}\". Expected: en, zh, or auto.`);\n }\n lang = next;\n i += 1;\n continue;\n }\n if (arg.startsWith(\"--lang=\")) {\n const val = arg.slice(\"--lang=\".length);\n if (val !== \"en\" && val !== \"zh\" && val !== \"auto\") {\n throw new Error(`Invalid --lang value \"${val}\". Expected: en, zh, or auto.`);\n }\n lang = val;\n continue;\n }\n rest.push(arg);\n }\n return { lang, rest };\n}\n\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<void> {\n let langArg: string | undefined;\n let restArgv: string[];\n try {\n const parsed = extractLangArg(argv);\n langArg = parsed.lang;\n restArgv = parsed.rest;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n return;\n }\n const cmd = restArgv[0];\n\n if (!cmd) {\n await startStdioServer({ defaultLang: langArg });\n return;\n }\n\n switch (cmd) {\n case \"doctor\": {\n const asJson = restArgv.includes(\"--json\");\n const withCost = restArgv.includes(\"--cost\");\n if (withCost) {\n let windowArg: CostSummaryWindow = \"24h\";\n const winIdx = restArgv.indexOf(\"--window\");\n if (winIdx !== -1) {\n const val = restArgv[winIdx + 1];\n if (val !== \"5h\" && val !== \"24h\" && val !== \"7d\") {\n console.error(`Invalid --window value \"${val ?? \"\"}\". Expected: 5h, 24h, or 7d.`);\n process.exitCode = 1;\n return;\n }\n windowArg = val;\n }\n const costReport = await runDoctorCost({ window: windowArg });\n if (asJson) {\n console.log(JSON.stringify(costReport, null, 2));\n } else {\n console.log(formatDoctorCostReport(costReport));\n }\n return;\n }\n\n let authModeArg: string | undefined;\n const authIdx = restArgv.indexOf(\"--auth-mode\");\n if (authIdx !== -1 && restArgv[authIdx + 1]) {\n authModeArg = restArgv[authIdx + 1];\n }\n const report = await runDoctor({\n ...(authModeArg ? { authMode: authModeArg } : {}),\n ...(langArg ? { lang: langArg } : {}),\n });\n if (asJson) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(formatDoctorReport(report));\n }\n return;\n }\n\n case \"preflight\": {\n if (restArgv.includes(\"--help\") || restArgv.includes(\"-h\")) {\n printPreflightHelp();\n return;\n }\n const asJson = restArgv.includes(\"--json\");\n const result = await runPreflight();\n if (asJson) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(formatPreflightReport(result));\n }\n process.exitCode = result.exit_code;\n return;\n }\n\n case \"ignore\": {\n const sub = restArgv[1];\n if (!sub || sub === \"--help\" || sub === \"-h\" || sub === \"help\") {\n printIgnoreHelp();\n return;\n }\n if (sub !== \"init\") {\n console.error(`Unknown ignore subcommand: ${sub}`);\n printIgnoreHelp();\n process.exitCode = 1;\n return;\n }\n\n const subArgs = restArgv.slice(2);\n if (subArgs.includes(\"--help\") || subArgs.includes(\"-h\")) {\n printIgnoreHelp();\n return;\n }\n\n let dir: string | undefined;\n let dryRun = false;\n let asJson = false;\n\n try {\n for (let i = 0; i < subArgs.length; i += 1) {\n const arg = subArgs[i];\n if (arg === undefined) {\n continue;\n }\n if (arg === \"--json\") {\n asJson = true;\n continue;\n }\n if (arg === \"--dry-run\") {\n dryRun = true;\n continue;\n }\n if (arg === \"--dir\" || arg.startsWith(\"--dir=\")) {\n const val = arg === \"--dir\" ? subArgs[++i] : arg.slice(\"--dir=\".length);\n if (!val) {\n throw new Error(\"Missing value for --dir.\");\n }\n dir = val;\n continue;\n }\n throw new Error(`Unknown option for ignore init: ${arg}`);\n }\n\n const result = await runIgnoreInit({\n ...(dir ? { dir } : {}),\n ...(dryRun ? { dryRun: true } : {}),\n ...(asJson ? { json: true } : {}),\n });\n\n console.log(formatIgnoreInitResult(result, asJson));\n process.exitCode = result.ok ? 0 : 1;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n return;\n }\n\n case \"telemetry\": {\n const sub = restArgv[1];\n if (!sub || sub === \"--help\" || sub === \"-h\" || sub === \"help\") {\n printTelemetryHelp();\n return;\n }\n if (sub !== \"enable\" && sub !== \"disable\" && sub !== \"status\") {\n console.error(`Unknown telemetry subcommand: ${sub}`);\n printTelemetryHelp();\n process.exitCode = 1;\n return;\n }\n\n const subArgs = restArgv.slice(2);\n if (subArgs.includes(\"--help\") || subArgs.includes(\"-h\")) {\n printTelemetryHelp();\n return;\n }\n\n let settingsPath: string | undefined;\n let dryRun = false;\n let asJson = false;\n\n try {\n for (let i = 0; i < subArgs.length; i += 1) {\n const arg = subArgs[i];\n if (arg === undefined) {\n continue;\n }\n if (arg === \"--json\") {\n asJson = true;\n continue;\n }\n if (arg === \"--dry-run\") {\n dryRun = true;\n continue;\n }\n if (arg === \"--settings\" || arg.startsWith(\"--settings=\")) {\n const val = arg === \"--settings\" ? subArgs[++i] : arg.slice(\"--settings=\".length);\n if (!val) {\n throw new Error(\"Missing value for --settings.\");\n }\n settingsPath = val;\n continue;\n }\n throw new Error(`Unknown option for telemetry ${sub}: ${arg}`);\n }\n\n const result =\n sub === \"enable\"\n ? await runTelemetryEnable({\n ...(settingsPath ? { settingsPath } : {}),\n ...(dryRun ? { dryRun: true } : {}),\n })\n : sub === \"disable\"\n ? await runTelemetryDisable({\n ...(settingsPath ? { settingsPath } : {}),\n ...(dryRun ? { dryRun: true } : {}),\n })\n : await runTelemetryStatus({\n ...(settingsPath ? { settingsPath } : {}),\n });\n\n if (asJson) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(formatTelemetryManageResult(result));\n }\n process.exitCode = result.ok ? 0 : 1;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n return;\n }\n\n case \"hook\": {\n const sub = restArgv[1];\n if (!sub || sub === \"--help\" || sub === \"-h\" || sub === \"help\") {\n printHookHelp();\n return;\n }\n if (sub !== \"enable\" && sub !== \"disable\" && sub !== \"status\") {\n console.error(`Unknown hook subcommand: ${sub}`);\n printHookHelp();\n process.exitCode = 1;\n return;\n }\n\n const subArgs = restArgv.slice(2);\n if (subArgs.includes(\"--help\") || subArgs.includes(\"-h\")) {\n printHookHelp();\n return;\n }\n\n let kind: HookKind = \"stop\";\n let target: HookTarget = \"agy\";\n let settingsPath: string | undefined;\n let command: string | undefined;\n let local = false;\n let dryRun = false;\n let asJson = false;\n\n try {\n for (let i = 0; i < subArgs.length; i += 1) {\n const arg = subArgs[i];\n if (arg === undefined) {\n continue;\n }\n if (arg === \"--json\") {\n asJson = true;\n continue;\n }\n if (arg === \"--dry-run\") {\n dryRun = true;\n continue;\n }\n if (arg === \"--local\") {\n local = true;\n continue;\n }\n if (arg === \"--kind\" || arg.startsWith(\"--kind=\")) {\n const val = arg === \"--kind\" ? subArgs[++i] : arg.slice(\"--kind=\".length);\n if (val !== \"stop\" && val !== \"record\") {\n throw new Error(`Invalid --kind value \"${val ?? \"\"}\". Expected: stop or record.`);\n }\n kind = val;\n continue;\n }\n if (arg === \"--target\" || arg.startsWith(\"--target=\")) {\n const val = arg === \"--target\" ? subArgs[++i] : arg.slice(\"--target=\".length);\n if (val !== \"agy\" && val !== \"gemini\" && val !== \"both\") {\n throw new Error(`Invalid --target value \"${val ?? \"\"}\". Expected: agy, gemini, or both.`);\n }\n target = val;\n continue;\n }\n if (arg === \"--settings\" || arg.startsWith(\"--settings=\")) {\n const val = arg === \"--settings\" ? subArgs[++i] : arg.slice(\"--settings=\".length);\n if (!val) {\n throw new Error(\"Missing value for --settings.\");\n }\n settingsPath = val;\n continue;\n }\n if (arg === \"--command\" || arg.startsWith(\"--command=\")) {\n const val = arg === \"--command\" ? subArgs[++i] : arg.slice(\"--command=\".length);\n if (val === undefined) {\n throw new Error(\"Missing value for --command.\");\n }\n command = val;\n continue;\n }\n throw new Error(`Unknown option for hook ${sub}: ${arg}`);\n }\n\n const result =\n sub === \"enable\"\n ? await runHookEnable({\n kind,\n target,\n ...(settingsPath ? { settingsPath } : {}),\n ...(command !== undefined ? { command } : {}),\n ...(local ? { local: true } : {}),\n ...(langArg ? { lang: langArg } : {}),\n ...(dryRun ? { dryRun: true } : {}),\n })\n : sub === \"disable\"\n ? await runHookDisable({\n kind,\n target,\n ...(settingsPath ? { settingsPath } : {}),\n ...(dryRun ? { dryRun: true } : {}),\n })\n : await runHookStatus({\n kind,\n target,\n ...(settingsPath ? { settingsPath } : {}),\n });\n\n if (asJson) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(formatHookManageResult(result));\n }\n process.exitCode = result.ok ? 0 : 1;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n return;\n }\n\n case \"hook-check\": {\n const asJson = restArgv.includes(\"--json\");\n let transcriptPath: string | undefined;\n let stateFilePath: string | undefined;\n\n const tIdx = restArgv.indexOf(\"--transcript\");\n if (tIdx !== -1 && restArgv[tIdx + 1]) {\n transcriptPath = restArgv[tIdx + 1];\n }\n const sIdx = restArgv.indexOf(\"--state-file\");\n if (sIdx !== -1 && restArgv[sIdx + 1]) {\n stateFilePath = restArgv[sIdx + 1];\n }\n\n try {\n const result = await runHookCheck({\n ...(transcriptPath ? { transcriptPath } : {}),\n ...(stateFilePath ? { stateFilePath } : {}),\n ...(langArg ? { lang: langArg } : {}),\n });\n if (asJson) {\n console.log(\n JSON.stringify({\n ...result.decision,\n transcript_found: result.transcript_found,\n ...(result.metrics\n ? {\n session_hash: result.metrics.session_hash,\n current_input_tokens: result.metrics.current_input_tokens,\n recent_cache_hit_pct: result.metrics.recent_cache_hit_pct,\n }\n : {}),\n }),\n );\n } else if (result.decision.should_notify && result.decision.message) {\n console.error(result.decision.message);\n }\n } catch {\n // Non-blocking hook: always exit 0\n }\n process.exitCode = 0;\n return;\n }\n\n case \"setup\": {\n console.log(buildSetupInstructions());\n return;\n }\n\n case \"clear-local-data\": {\n const result = await clearLocalData();\n console.log(\n `Cleared local agycraft data (${result.removed.length} path(s) processed).`,\n );\n return;\n }\n\n case \"record\": {\n const raw = (await readStdinText()).trim();\n if (!raw) {\n return;\n }\n try {\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n await appendUsageRecord(parsed);\n } catch {\n // Ignore malformed stdin payloads silently so hooks never break AGY turns\n }\n return;\n }\n\n case \"-h\":\n case \"--help\":\n case \"help\": {\n printHelp();\n return;\n }\n\n default: {\n console.error(`Unknown subcommand: ${cmd}`);\n printHelp();\n process.exitCode = 1;\n }\n }\n}\n\n// Run when invoked directly as CLI binary\nconst isDirectRun =\n process.argv[1] &&\n (process.argv[1].endsWith(\"index.js\") ||\n process.argv[1].endsWith(\"index.ts\") ||\n process.argv[1].endsWith(\"agycraft-mcp\"));\n\nif (isDirectRun) {\n main().catch((err) => {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n });\n}\n"],"mappings":";;;AAAA,SAAS,QAAQ,YAAAA,WAAU,QAAAC,aAAY;AACvC,SAAS,aAAa,mBAAmB;AACzC,SAAS,WAAAC,gBAAe;AACxB,SAAS,QAAAC,aAAY;AACrB,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;;;ACL1B,SAAS,kBAAkB;AAC3B,SAAS,YAAAC,iBAAgB;AACzB,SAAS,WAAAC,gBAAe;AACxB,SAAS,QAAAC,aAAY;;;ACHrB,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,QAAAC,aAAY;;;ACDrB,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAE9B,IAAI,mBAAkC;AAE/B,SAAS,oBAA4B;AAC1C,MAAI,kBAAkB;AACpB,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,UAAU,IAAI,IAAI,mBAAmB,YAAY,GAAG;AAC1D,UAAM,MAAM,aAAa,SAAS,MAAM;AACxC,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,QAAI,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,KAAK,EAAE,SAAS,GAAG;AAC1E,yBAAmB,OAAO,QAAQ,KAAK;AACvC,aAAO;AAAA,IACT;AAAA,EACF,QAAQ;AAAA,EAER;AACA,qBAAmB;AACnB,SAAO;AACT;AAEO,SAAS,eAAuB;AACrC,QAAM,WAAW,QAAQ,IAAI;AAC7B,MAAI,YAAY,SAAS,KAAK,EAAE,SAAS,GAAG;AAC1C,WAAO,QAAQ,SAAS,KAAK,CAAC;AAAA,EAChC;AACA,Q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A,IACF;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,QAAQ;AACX,gBAAU;AACV;AAAA,IACF;AAAA,IAEA,SAAS;AACP,cAAQ,MAAM,uBAAuB,GAAG,EAAE;AAC1C,gBAAU;AACV,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF;AAGA,IAAM,cACJ,QAAQ,KAAK,CAAC,MACb,QAAQ,KAAK,CAAC,EAAE,SAAS,UAAU,KAClC,QAAQ,KAAK,CAAC,EAAE,SAAS,UAAU,KACnC,QAAQ,KAAK,CAAC,EAAE,SAAS,cAAc;AAE3C,IAAI,aAAa;AACf,OAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,YAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAC9D,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;","names":["readFile","stat","homedir","join","readFile","homedir","join","readFileSync","join","readFileSync","join","readFile","join","resolve","resolve","resolve","resolve","join","readFile","readFile","join","homedir","createHash","readdir","readFile","join","resolve","createHash","readFile","resolve","readdir","join","createHash","mkdir","readdir","readFile","stat","writeFile","dirname","join","firstNonNegInt","readdir","join","stat","createHash","readFile","mkdir","dirname","writeFile","createHash","randomBytes","mkdir","open","readdir","readFile","stat","writeFile","dirname","join","createHash","readdir","join","round4","mkdir","dirname","randomBytes","writeFile","readFile","open","stat","watermarks","hourlyCache","dirtyHourlyMonths","anyNewData","readFile","join","homedir","stat","existsSync","mkdir","readFile","writeFile","homedir","dirname","join","resolve","existsSync","mkdir","readFile","writeFile","dirname","join","resolve","resolve","join","existsSync","mkdir","dirname","writeFile","readFile","mkdir","readFile","writeFile","homedir","dirname","join","resolve","isPlainObject","resolve","homedir","join","readSettingsJson","readFile","writeSettingsJson","mkdir","dirname","writeFile","rm","mkdir","readFile","dirname","mkdir","dirname","readFile","rm","access","join","readFile","readFile","localizedChosen","mkdir","readFile","writeFile","join","DEFAULT_DATA_URL","join","readFile","mkdir","writeFile","isSpecificAuthEmpty","access","join"]}
|