agycraft-mcp 0.2.1 → 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/README.md +4 -0
- package/dist/index.js +2478 -182
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/snapshots/channels.json +50 -27
- package/snapshots/chronicle.json +1 -1
- package/snapshots/diagnosis.json +290 -3
- package/snapshots/models.json +534 -56
- package/snapshots/quotas.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/cli/doctor.ts
|
|
4
|
-
import { access, readFile as
|
|
4
|
+
import { access, readFile as readFile7, stat as stat4 } from "fs/promises";
|
|
5
5
|
import { constants as fsConstants } from "fs";
|
|
6
6
|
import { homedir as homedir3 } from "os";
|
|
7
|
-
import { join as
|
|
7
|
+
import { join as join8 } from "path";
|
|
8
8
|
import { execFile } from "child_process";
|
|
9
9
|
import { promisify } from "util";
|
|
10
10
|
|
|
@@ -37,7 +37,7 @@ function getPackageVersion() {
|
|
|
37
37
|
}
|
|
38
38
|
} catch {
|
|
39
39
|
}
|
|
40
|
-
cachedPkgVersion = "0.2.
|
|
40
|
+
cachedPkgVersion = "0.2.3";
|
|
41
41
|
return cachedPkgVersion;
|
|
42
42
|
}
|
|
43
43
|
function getConfigDir() {
|
|
@@ -1426,25 +1426,178 @@ async function detectAuthContext(options) {
|
|
|
1426
1426
|
};
|
|
1427
1427
|
}
|
|
1428
1428
|
|
|
1429
|
-
// src/
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1429
|
+
// src/i18n.ts
|
|
1430
|
+
function normalizeExplicitLang(raw) {
|
|
1431
|
+
if (typeof raw !== "string") {
|
|
1432
|
+
return void 0;
|
|
1433
|
+
}
|
|
1434
|
+
const normalized = raw.trim().toLowerCase();
|
|
1435
|
+
if (!normalized || normalized === "auto") {
|
|
1436
|
+
return void 0;
|
|
1437
|
+
}
|
|
1438
|
+
if (normalized === "zh" || normalized.startsWith("zh-") || normalized.startsWith("zh_")) {
|
|
1439
|
+
return "zh";
|
|
1440
|
+
}
|
|
1441
|
+
if (normalized === "en" || normalized.startsWith("en-") || normalized.startsWith("en_")) {
|
|
1442
|
+
return "en";
|
|
1443
|
+
}
|
|
1444
|
+
return void 0;
|
|
1445
|
+
}
|
|
1446
|
+
function resolveLocale(explicitLang, env = process.env) {
|
|
1447
|
+
const fromArg = normalizeExplicitLang(explicitLang);
|
|
1448
|
+
if (fromArg) {
|
|
1449
|
+
return fromArg;
|
|
1450
|
+
}
|
|
1451
|
+
const fromEnv = normalizeExplicitLang(env.AGYCRAFT_LANG);
|
|
1452
|
+
if (fromEnv) {
|
|
1453
|
+
return fromEnv;
|
|
1454
|
+
}
|
|
1455
|
+
const sysLocale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || "").trim().toLowerCase();
|
|
1456
|
+
if (sysLocale.includes("zh")) {
|
|
1457
|
+
return "zh";
|
|
1458
|
+
}
|
|
1459
|
+
return "en";
|
|
1460
|
+
}
|
|
1461
|
+
function hasNonEmptyValue(val) {
|
|
1462
|
+
if (typeof val === "string") {
|
|
1463
|
+
return val.trim().length > 0;
|
|
1464
|
+
}
|
|
1465
|
+
if (Array.isArray(val)) {
|
|
1466
|
+
return val.length > 0;
|
|
1467
|
+
}
|
|
1468
|
+
return val !== void 0 && val !== null;
|
|
1469
|
+
}
|
|
1470
|
+
function localizeSnapshotText(value, locale) {
|
|
1471
|
+
if (value === null || value === void 0 || typeof value !== "object") {
|
|
1472
|
+
return value;
|
|
1473
|
+
}
|
|
1474
|
+
if (Array.isArray(value)) {
|
|
1475
|
+
return value.map((item) => localizeSnapshotText(item, locale));
|
|
1476
|
+
}
|
|
1477
|
+
const record = value;
|
|
1478
|
+
const out = {};
|
|
1479
|
+
for (const [key, val] of Object.entries(record)) {
|
|
1480
|
+
if (key.endsWith("_zh")) {
|
|
1481
|
+
continue;
|
|
1482
|
+
}
|
|
1483
|
+
out[key] = localizeSnapshotText(val, locale);
|
|
1484
|
+
}
|
|
1485
|
+
if (locale === "zh") {
|
|
1486
|
+
for (const [key, val] of Object.entries(record)) {
|
|
1487
|
+
if (!key.endsWith("_zh") || !hasNonEmptyValue(val)) {
|
|
1488
|
+
continue;
|
|
1489
|
+
}
|
|
1490
|
+
if (key === "reset_rules_notes_zh" && out.reset_rules && typeof out.reset_rules === "object") {
|
|
1491
|
+
out.reset_rules.notes = val;
|
|
1492
|
+
continue;
|
|
1493
|
+
}
|
|
1494
|
+
const baseKey = key.slice(0, -3);
|
|
1495
|
+
if (baseKey === "fix_steps" && !("fix_steps" in out) && "steps" in out) {
|
|
1496
|
+
out.steps = localizeSnapshotText(val, locale);
|
|
1497
|
+
} else {
|
|
1498
|
+
out[baseKey] = localizeSnapshotText(val, locale);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
return out;
|
|
1503
|
+
}
|
|
1504
|
+
function localizeDiagnosisEntry(entry, locale) {
|
|
1505
|
+
return localizeSnapshotText(entry, locale);
|
|
1506
|
+
}
|
|
1507
|
+
function localizeModelEntry(entry, locale) {
|
|
1508
|
+
return localizeSnapshotText(entry, locale);
|
|
1509
|
+
}
|
|
1510
|
+
function getLocalizedBehavior(behaviors, key, locale) {
|
|
1511
|
+
if (!behaviors) {
|
|
1512
|
+
return void 0;
|
|
1513
|
+
}
|
|
1514
|
+
if (locale === "zh") {
|
|
1515
|
+
const zhKey = `${key}_zh`;
|
|
1516
|
+
const zhVal = behaviors[zhKey];
|
|
1517
|
+
if (typeof zhVal === "string" && zhVal.trim().length > 0) {
|
|
1518
|
+
return zhVal;
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
const enVal = behaviors[key];
|
|
1522
|
+
return typeof enVal === "string" ? enVal : void 0;
|
|
1523
|
+
}
|
|
1443
1524
|
|
|
1444
1525
|
// src/collectors/transcript-meta.ts
|
|
1526
|
+
import { createHash as createHash2 } from "crypto";
|
|
1445
1527
|
import { readdir as readdir2, readFile as readFile4 } from "fs/promises";
|
|
1446
1528
|
import { join as join5, resolve as resolve4 } from "path";
|
|
1447
1529
|
var SAFE_TOOL_NAME_RE = /^[a-zA-Z0-9._-]{1,48}$/;
|
|
1530
|
+
var READ_FILE_TOOLS = /* @__PURE__ */ new Set(["read_file", "view_file"]);
|
|
1531
|
+
var WRITE_EDIT_TOOLS = /* @__PURE__ */ new Set([
|
|
1532
|
+
"edit_file",
|
|
1533
|
+
"write_file",
|
|
1534
|
+
"replace_file_content",
|
|
1535
|
+
"multi_replace_file_content",
|
|
1536
|
+
"mcp_agy-fast_fast_apply_edits"
|
|
1537
|
+
]);
|
|
1538
|
+
function hashOpaqueValue(raw) {
|
|
1539
|
+
return createHash2("sha256").update(raw).digest("hex");
|
|
1540
|
+
}
|
|
1541
|
+
function stableSerialize(val) {
|
|
1542
|
+
if (val === null || val === void 0) {
|
|
1543
|
+
return "null";
|
|
1544
|
+
}
|
|
1545
|
+
if (typeof val !== "object") {
|
|
1546
|
+
return JSON.stringify(val);
|
|
1547
|
+
}
|
|
1548
|
+
if (Array.isArray(val)) {
|
|
1549
|
+
return `[${val.map((item) => stableSerialize(item)).join(",")}]`;
|
|
1550
|
+
}
|
|
1551
|
+
const obj = val;
|
|
1552
|
+
const keys = Object.keys(obj).sort();
|
|
1553
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableSerialize(obj[k])}`).join(",")}}`;
|
|
1554
|
+
}
|
|
1555
|
+
function parseMaybeJsonArgs(raw) {
|
|
1556
|
+
if (typeof raw === "string") {
|
|
1557
|
+
const trimmed = raw.trim();
|
|
1558
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
1559
|
+
try {
|
|
1560
|
+
return JSON.parse(trimmed);
|
|
1561
|
+
} catch {
|
|
1562
|
+
return raw;
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
return raw ?? null;
|
|
1567
|
+
}
|
|
1568
|
+
function extractFilePathsFromArgs(args) {
|
|
1569
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) {
|
|
1570
|
+
return [];
|
|
1571
|
+
}
|
|
1572
|
+
const obj = args;
|
|
1573
|
+
const paths = [];
|
|
1574
|
+
for (const key of [
|
|
1575
|
+
"Path",
|
|
1576
|
+
"path",
|
|
1577
|
+
"file_path",
|
|
1578
|
+
"AbsolutePath",
|
|
1579
|
+
"target_file",
|
|
1580
|
+
"TargetFile",
|
|
1581
|
+
"file"
|
|
1582
|
+
]) {
|
|
1583
|
+
const val = obj[key];
|
|
1584
|
+
if (typeof val === "string" && val.trim().length > 0) {
|
|
1585
|
+
paths.push(val.trim());
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
if (Array.isArray(obj.edits)) {
|
|
1589
|
+
for (const item of obj.edits) {
|
|
1590
|
+
if (item && typeof item === "object") {
|
|
1591
|
+
const itemObj = item;
|
|
1592
|
+
const p = itemObj.path ?? itemObj.file_path ?? itemObj.Path;
|
|
1593
|
+
if (typeof p === "string" && p.trim().length > 0) {
|
|
1594
|
+
paths.push(p.trim());
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
return paths;
|
|
1600
|
+
}
|
|
1448
1601
|
function sanitizeToolCategory(raw) {
|
|
1449
1602
|
if (typeof raw !== "string") {
|
|
1450
1603
|
return "unknown_tool";
|
|
@@ -1476,6 +1629,45 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1476
1629
|
let currentStreakTool = null;
|
|
1477
1630
|
let maxConsecutiveFailures = 0;
|
|
1478
1631
|
let maxFailureTool = null;
|
|
1632
|
+
const seenReadFileHashes = /* @__PURE__ */ new Set();
|
|
1633
|
+
const seenToolCallHashes = /* @__PURE__ */ new Set();
|
|
1634
|
+
let readFileCount = 0;
|
|
1635
|
+
let redundantReadFileCount = 0;
|
|
1636
|
+
let pollingDupCount = 0;
|
|
1637
|
+
let peakInputTokens = 0;
|
|
1638
|
+
let latestInputTokens = 0;
|
|
1639
|
+
const trackToolRedundancy = (toolName, rawArgs) => {
|
|
1640
|
+
const parsedArgs = parseMaybeJsonArgs(rawArgs);
|
|
1641
|
+
const sigHash = hashOpaqueValue(`${toolName}\0${stableSerialize(parsedArgs)}`);
|
|
1642
|
+
if (seenToolCallHashes.has(sigHash)) {
|
|
1643
|
+
pollingDupCount += 1;
|
|
1644
|
+
} else {
|
|
1645
|
+
seenToolCallHashes.add(sigHash);
|
|
1646
|
+
}
|
|
1647
|
+
if (READ_FILE_TOOLS.has(toolName)) {
|
|
1648
|
+
readFileCount += 1;
|
|
1649
|
+
const paths = extractFilePathsFromArgs(parsedArgs);
|
|
1650
|
+
if (paths.length > 0) {
|
|
1651
|
+
let anyRedundant = false;
|
|
1652
|
+
for (const p of paths) {
|
|
1653
|
+
const ph = hashOpaqueValue(p);
|
|
1654
|
+
if (seenReadFileHashes.has(ph)) {
|
|
1655
|
+
anyRedundant = true;
|
|
1656
|
+
} else {
|
|
1657
|
+
seenReadFileHashes.add(ph);
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
if (anyRedundant) {
|
|
1661
|
+
redundantReadFileCount += 1;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
} else if (WRITE_EDIT_TOOLS.has(toolName)) {
|
|
1665
|
+
const paths = extractFilePathsFromArgs(parsedArgs);
|
|
1666
|
+
for (const p of paths) {
|
|
1667
|
+
seenReadFileHashes.delete(hashOpaqueValue(p));
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
};
|
|
1479
1671
|
for (const line of lines) {
|
|
1480
1672
|
const trimmed = line.trim();
|
|
1481
1673
|
if (!trimmed) {
|
|
@@ -1495,8 +1687,27 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1495
1687
|
if (eventType === "compact" || eventType === "compaction") {
|
|
1496
1688
|
hasCompactEvent = true;
|
|
1497
1689
|
stepsSinceLastCompact = 0;
|
|
1690
|
+
seenReadFileHashes.clear();
|
|
1498
1691
|
continue;
|
|
1499
1692
|
}
|
|
1693
|
+
const usageObj = parsed.usage && typeof parsed.usage === "object" && !Array.isArray(parsed.usage) ? parsed.usage : {};
|
|
1694
|
+
const stepInput = firstNonNegInt(
|
|
1695
|
+
parsed.input_tokens,
|
|
1696
|
+
usageObj.input_tokens,
|
|
1697
|
+
usageObj.prompt_tokens
|
|
1698
|
+
);
|
|
1699
|
+
const stepCacheRead = firstNonNegInt(
|
|
1700
|
+
parsed.cache_read_tokens,
|
|
1701
|
+
usageObj.cache_read_tokens,
|
|
1702
|
+
usageObj.cached_content_token_count
|
|
1703
|
+
);
|
|
1704
|
+
const stepTotalInput = stepInput + stepCacheRead;
|
|
1705
|
+
if (stepTotalInput > 0) {
|
|
1706
|
+
latestInputTokens = stepTotalInput;
|
|
1707
|
+
if (stepTotalInput > peakInputTokens) {
|
|
1708
|
+
peakInputTokens = stepTotalInput;
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1500
1711
|
if (role === "user" || eventType === "user_message" || eventType === "user_input" || source === "USER_EXPLICIT") {
|
|
1501
1712
|
userTurns += 1;
|
|
1502
1713
|
currentStreak = 0;
|
|
@@ -1512,6 +1723,10 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1512
1723
|
}
|
|
1513
1724
|
const tcObj = tc;
|
|
1514
1725
|
const toolName = sanitizeToolCategory(tcObj.tool_name ?? tcObj.name);
|
|
1726
|
+
trackToolRedundancy(
|
|
1727
|
+
toolName,
|
|
1728
|
+
tcObj.arguments ?? tcObj.args ?? tcObj.input ?? tcObj.params
|
|
1729
|
+
);
|
|
1515
1730
|
const failed = tcObj.is_error === true || tcObj.status === "error" || tcObj.status === "failed" || typeof tcObj.exit_code === "number" && tcObj.exit_code !== 0;
|
|
1516
1731
|
if (failed) {
|
|
1517
1732
|
toolErrorCount += 1;
|
|
@@ -1537,6 +1752,10 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1537
1752
|
if (isToolEvent) {
|
|
1538
1753
|
toolCallCount += 1;
|
|
1539
1754
|
const toolName = sanitizeToolCategory(parsed.tool_name ?? parsed.name);
|
|
1755
|
+
trackToolRedundancy(
|
|
1756
|
+
toolName,
|
|
1757
|
+
parsed.arguments ?? parsed.args ?? parsed.input ?? parsed.params
|
|
1758
|
+
);
|
|
1540
1759
|
const failed = parsed.is_error === true || parsed.status === "error" || parsed.status === "failed" || typeof parsed.exit_code === "number" && parsed.exit_code !== 0;
|
|
1541
1760
|
if (failed) {
|
|
1542
1761
|
toolErrorCount += 1;
|
|
@@ -1566,7 +1785,13 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1566
1785
|
consecutive_failure_tool_type: maxFailureTool,
|
|
1567
1786
|
has_compact_event: hasCompactEvent,
|
|
1568
1787
|
steps_since_last_compact: stepsSinceLastCompact,
|
|
1569
|
-
loop_detected: maxConsecutiveFailures >= loopThreshold
|
|
1788
|
+
loop_detected: maxConsecutiveFailures >= loopThreshold,
|
|
1789
|
+
redundant_read_file_count: redundantReadFileCount,
|
|
1790
|
+
redundant_read_file_pct: readFileCount > 0 ? Math.round(redundantReadFileCount / readFileCount * 1e3) / 10 : 0,
|
|
1791
|
+
polling_dup_count: pollingDupCount,
|
|
1792
|
+
polling_dup_rate_pct: toolCallCount > 0 ? Math.round(pollingDupCount / toolCallCount * 1e3) / 10 : 0,
|
|
1793
|
+
peak_input_tokens: peakInputTokens,
|
|
1794
|
+
latest_input_tokens: latestInputTokens
|
|
1570
1795
|
};
|
|
1571
1796
|
}
|
|
1572
1797
|
function emptyTranscriptMeta() {
|
|
@@ -1580,7 +1805,13 @@ function emptyTranscriptMeta() {
|
|
|
1580
1805
|
consecutive_failure_tool_type: null,
|
|
1581
1806
|
has_compact_event: false,
|
|
1582
1807
|
steps_since_last_compact: 0,
|
|
1583
|
-
loop_detected: false
|
|
1808
|
+
loop_detected: false,
|
|
1809
|
+
redundant_read_file_count: 0,
|
|
1810
|
+
redundant_read_file_pct: 0,
|
|
1811
|
+
polling_dup_count: 0,
|
|
1812
|
+
polling_dup_rate_pct: 0,
|
|
1813
|
+
peak_input_tokens: 0,
|
|
1814
|
+
latest_input_tokens: 0
|
|
1584
1815
|
};
|
|
1585
1816
|
}
|
|
1586
1817
|
function extractStructuralTimestampMs(parsed) {
|
|
@@ -1927,11 +2158,437 @@ async function collectTranscriptUsageRecords(options) {
|
|
|
1927
2158
|
};
|
|
1928
2159
|
}
|
|
1929
2160
|
|
|
2161
|
+
// src/analyzers/session-lifecycle.ts
|
|
2162
|
+
var ACTION_RANK = {
|
|
2163
|
+
HOLD_CACHE: 0,
|
|
2164
|
+
SUGGEST_COMPACT: 1,
|
|
2165
|
+
SUGGEST_NEW_SESSION: 2,
|
|
2166
|
+
URGENT_ROTATE: 3
|
|
2167
|
+
};
|
|
2168
|
+
var COOLDOWN_TURNS = {
|
|
2169
|
+
SUGGEST_COMPACT: 15,
|
|
2170
|
+
SUGGEST_NEW_SESSION: 10,
|
|
2171
|
+
URGENT_ROTATE: 3
|
|
2172
|
+
};
|
|
2173
|
+
function formatTokensK(tokens) {
|
|
2174
|
+
if (tokens >= 1e3) {
|
|
2175
|
+
return `${Math.round(tokens / 1e3)}K`;
|
|
2176
|
+
}
|
|
2177
|
+
return `${tokens}`;
|
|
2178
|
+
}
|
|
2179
|
+
function formatLifecycleAdvice(action, reason, m, locale = "zh") {
|
|
2180
|
+
if (action === "HOLD_CACHE") {
|
|
2181
|
+
return void 0;
|
|
2182
|
+
}
|
|
2183
|
+
const cLabel = formatTokensK(m.current_input_tokens);
|
|
2184
|
+
const hitLabel = `${Math.round(m.recent_cache_hit_pct * 10) / 10}%`;
|
|
2185
|
+
if (locale === "zh") {
|
|
2186
|
+
switch (action) {
|
|
2187
|
+
case "SUGGEST_COMPACT":
|
|
2188
|
+
return `[agycraft] \u5F53\u524D\u4E0A\u4E0B\u6587\u5DF2\u8FBE ${cLabel} (KV \u547D\u4E2D ${hitLabel})\uFF0C\u5DF2\u8DE8\u8FC7 150K \u5EF6\u8FDF\u62D0\u70B9\uFF1B\u5EFA\u8BAE\u5728\u5F53\u524D\u9636\u6BB5\u6536\u5C3E\u540E\u8FD0\u884C /compact\uFF08\u907F\u514D\u4E2D\u65AD\u70ED\u7F13\u5B58\uFF09\u3002`;
|
|
2189
|
+
case "SUGGEST_NEW_SESSION":
|
|
2190
|
+
return reason === "CACHE_EXPIRED_NEW_SESSION" ? `[agycraft] \u4E0A\u4E0B\u6587 ${cLabel} \u4E14 KV \u7F13\u5B58\u5DF2\u51B7 (\u7A7A\u95F2 ${Math.round(m.idle_gap_sec)}s / \u547D\u4E2D ${hitLabel})\uFF1B\u5EFA\u8BAE\u603B\u7ED3\u5F53\u524D\u7ED3\u8BBA\u540E\u65B0\u5F00\u4F1A\u8BDD\uFF0C\u907F\u514D\u51B7\u542F\u52A8\u5168\u989D\u8BA1\u8D39\u3002` : `[agycraft] \u4E0A\u4E0B\u6587\u5DF2\u8FBE ${cLabel} (\u2265240K \u9AD8\u6C34\u4F4D)\uFF1B\u5EFA\u8BAE\u603B\u7ED3\u4EA4\u63A5\u6458\u8981\u540E\u65B0\u5F00\u4F1A\u8BDD\uFF0C\u6BD4\u7EE7\u7EED\u7EED\u804A\u6216\u538B\u7F29\u66F4\u7701 Token\u3002`;
|
|
2191
|
+
case "URGENT_ROTATE":
|
|
2192
|
+
return `[agycraft] \u9AD8\u4F18\u544A\u8B66\uFF1A\u4E0A\u4E0B\u6587 ${cLabel} \u5DF2\u89E6\u53CA\u786C\u4E0A\u9650\u6216\u9650\u6D41/\u6EA2\u51FA\u98CE\u9669 (${m.recent_429_count}x 429, ${m.recent_overflow_count}x overflow)\uFF0C\u8BF7\u7ACB\u5373 /compact \u6216\u5BFC\u51FA\u72B6\u6001\u65B0\u5F00\u4F1A\u8BDD\u6B62\u635F\u3002`;
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
switch (action) {
|
|
2196
|
+
case "SUGGEST_COMPACT":
|
|
2197
|
+
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.`;
|
|
2198
|
+
case "SUGGEST_NEW_SESSION":
|
|
2199
|
+
return reason === "CACHE_EXPIRED_NEW_SESSION" ? `[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.` : `[agycraft] Context reached ${cLabel} (>=240K high watermark); start a new session with a brief handoff summary instead of snowballing.`;
|
|
2200
|
+
case "URGENT_ROTATE":
|
|
2201
|
+
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.`;
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
function evaluateSessionLifecycle(m, prevState, nowMsOrOptions = Date.now()) {
|
|
2205
|
+
const nowMs = typeof nowMsOrOptions === "number" ? nowMsOrOptions : nowMsOrOptions.nowMs ?? Date.now();
|
|
2206
|
+
const locale = typeof nowMsOrOptions === "number" ? "zh" : nowMsOrOptions.locale ?? "zh";
|
|
2207
|
+
const c = Math.max(0, m.current_input_tokens);
|
|
2208
|
+
const h = Math.max(0, Math.min(100, m.recent_cache_hit_pct));
|
|
2209
|
+
const idle = Math.max(0, m.idle_gap_sec);
|
|
2210
|
+
const ceilingRatio = m.model_context_limit > 0 ? c / m.model_context_limit : 0;
|
|
2211
|
+
const prevTokens = m.previous_input_tokens ?? prevState?.last_observed_tokens ?? prevState?.last_notified_tokens ?? 0;
|
|
2212
|
+
const dropped40Pct = prevTokens > 0 && (prevTokens - c) / prevTokens >= 0.4;
|
|
2213
|
+
const resetApplied = Boolean(m.has_recent_compact || dropped40Pct);
|
|
2214
|
+
const effectivePrevState = resetApplied ? void 0 : prevState;
|
|
2215
|
+
let action = "HOLD_CACHE";
|
|
2216
|
+
let reason = "BELOW_THRESHOLD";
|
|
2217
|
+
if (c >= 36e4 || ceilingRatio >= 0.7 || m.recent_overflow_count > 0 || m.recent_429_count > 0 && c >= 14e4) {
|
|
2218
|
+
action = "URGENT_ROTATE";
|
|
2219
|
+
reason = "CRITICAL_CEILING_OR_ERROR";
|
|
2220
|
+
} else if (c >= 24e4) {
|
|
2221
|
+
action = "SUGGEST_NEW_SESSION";
|
|
2222
|
+
reason = "HIGH_WATERMARK_NEW_SESSION";
|
|
2223
|
+
} else if (c >= 1e5 && (idle >= 300 || h < 50)) {
|
|
2224
|
+
action = "SUGGEST_NEW_SESSION";
|
|
2225
|
+
reason = "CACHE_EXPIRED_NEW_SESSION";
|
|
2226
|
+
} else if (c >= 16e4 && h >= 85 && idle < 300 && m.planner_turns_since_compact >= 30) {
|
|
2227
|
+
action = "SUGGEST_COMPACT";
|
|
2228
|
+
reason = "LATENCY_INFLECTION_COMPACT";
|
|
2229
|
+
} else if (effectivePrevState?.last_action === "SUGGEST_COMPACT" && c >= 12e4 && c < 16e4) {
|
|
2230
|
+
action = "SUGGEST_COMPACT";
|
|
2231
|
+
reason = "LATENCY_INFLECTION_COMPACT";
|
|
2232
|
+
} else if (c >= 12e4 && h >= 90 && idle < 300) {
|
|
2233
|
+
action = "HOLD_CACHE";
|
|
2234
|
+
reason = "WARM_CACHE_HOLD";
|
|
2235
|
+
}
|
|
2236
|
+
const subagentAnomaly = !m.is_interactive && c >= 2e5;
|
|
2237
|
+
if (!m.is_interactive && action !== "URGENT_ROTATE") {
|
|
2238
|
+
action = "HOLD_CACHE";
|
|
2239
|
+
reason = c >= 12e4 && h >= 90 && idle < 300 ? "WARM_CACHE_HOLD" : "BELOW_THRESHOLD";
|
|
2240
|
+
}
|
|
2241
|
+
const turnGap = m.planner_turns_since_compact - (effectivePrevState?.last_notified_turn ?? -999);
|
|
2242
|
+
const secGap = (nowMs - (effectivePrevState?.last_notified_ms ?? 0)) / 1e3;
|
|
2243
|
+
const upgraded = effectivePrevState ? ACTION_RANK[action] > ACTION_RANK[effectivePrevState.last_action] : action !== "HOLD_CACHE";
|
|
2244
|
+
let shouldNotify = false;
|
|
2245
|
+
if (action !== "HOLD_CACHE") {
|
|
2246
|
+
if (upgraded) {
|
|
2247
|
+
shouldNotify = true;
|
|
2248
|
+
} else if (action === "URGENT_ROTATE" && turnGap >= COOLDOWN_TURNS.URGENT_ROTATE) {
|
|
2249
|
+
shouldNotify = true;
|
|
2250
|
+
} else if (action === "SUGGEST_NEW_SESSION" && turnGap >= COOLDOWN_TURNS.SUGGEST_NEW_SESSION && secGap >= 300) {
|
|
2251
|
+
shouldNotify = true;
|
|
2252
|
+
} else if (action === "SUGGEST_COMPACT" && turnGap >= COOLDOWN_TURNS.SUGGEST_COMPACT && secGap >= 600) {
|
|
2253
|
+
shouldNotify = true;
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
const nextState = shouldNotify ? {
|
|
2257
|
+
last_action: action,
|
|
2258
|
+
last_notified_turn: m.planner_turns_since_compact,
|
|
2259
|
+
last_notified_ms: nowMs,
|
|
2260
|
+
last_notified_tokens: c,
|
|
2261
|
+
last_observed_tokens: c
|
|
2262
|
+
} : {
|
|
2263
|
+
last_action: action,
|
|
2264
|
+
last_notified_turn: effectivePrevState?.last_notified_turn ?? 0,
|
|
2265
|
+
last_notified_ms: effectivePrevState?.last_notified_ms ?? 0,
|
|
2266
|
+
last_notified_tokens: effectivePrevState?.last_notified_tokens ?? 0,
|
|
2267
|
+
last_observed_tokens: c
|
|
2268
|
+
};
|
|
2269
|
+
const cooldownUntilTurn = action !== "HOLD_CACHE" ? (shouldNotify ? m.planner_turns_since_compact : effectivePrevState?.last_notified_turn ?? m.planner_turns_since_compact) + COOLDOWN_TURNS[action] : void 0;
|
|
2270
|
+
return {
|
|
2271
|
+
decision: {
|
|
2272
|
+
action,
|
|
2273
|
+
reason_code: reason,
|
|
2274
|
+
should_notify: shouldNotify,
|
|
2275
|
+
...shouldNotify ? { message: formatLifecycleAdvice(action, reason, m, locale) } : {},
|
|
2276
|
+
...cooldownUntilTurn !== void 0 ? { cooldown_until_turn: cooldownUntilTurn } : {},
|
|
2277
|
+
...subagentAnomaly ? { subagent_anomaly: true } : {},
|
|
2278
|
+
...resetApplied ? { reset_applied: true } : {}
|
|
2279
|
+
},
|
|
2280
|
+
nextState
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
// src/cli/hook-check.ts
|
|
2285
|
+
import { createHash as createHash3 } from "crypto";
|
|
2286
|
+
import { mkdir as mkdir2, open, readdir as readdir3, readFile as readFile5, stat as stat2, writeFile as writeFile2 } from "fs/promises";
|
|
2287
|
+
import { dirname as dirname2, join as join6 } from "path";
|
|
2288
|
+
var DEFAULT_TAIL_BYTES = 32 * 1024;
|
|
2289
|
+
var HEAD_PROBE_BYTES = 4 * 1024;
|
|
2290
|
+
var FIVE_MINUTES_MS = 5 * 60 * 1e3;
|
|
2291
|
+
var MAX_STATE_SESSIONS = 50;
|
|
2292
|
+
function firstNonNegInt2(...vals) {
|
|
2293
|
+
for (const v of vals) {
|
|
2294
|
+
if (typeof v === "number" && Number.isFinite(v) && v >= 0) {
|
|
2295
|
+
return Math.floor(v);
|
|
2296
|
+
}
|
|
2297
|
+
}
|
|
2298
|
+
return 0;
|
|
2299
|
+
}
|
|
2300
|
+
function extractTsMs(parsed) {
|
|
2301
|
+
const raw = parsed.created_at ?? parsed.timestamp ?? parsed.ts;
|
|
2302
|
+
if (typeof raw === "string") {
|
|
2303
|
+
const ms = Date.parse(raw);
|
|
2304
|
+
return Number.isNaN(ms) ? null : ms;
|
|
2305
|
+
}
|
|
2306
|
+
if (typeof raw === "number" && Number.isFinite(raw)) {
|
|
2307
|
+
return raw > 1e12 ? raw : raw * 1e3;
|
|
2308
|
+
}
|
|
2309
|
+
return null;
|
|
2310
|
+
}
|
|
2311
|
+
function inferModelContextLimit(model) {
|
|
2312
|
+
if (!model) {
|
|
2313
|
+
return 512e3;
|
|
2314
|
+
}
|
|
2315
|
+
const lower = model.toLowerCase();
|
|
2316
|
+
if (lower.includes("gemini-2.5") || lower.includes("gemini-1.5") || lower.includes("1m")) {
|
|
2317
|
+
return 1e6;
|
|
2318
|
+
}
|
|
2319
|
+
return 512e3;
|
|
2320
|
+
}
|
|
2321
|
+
function isUserLine(parsed) {
|
|
2322
|
+
const role = typeof parsed.role === "string" ? parsed.role.toLowerCase() : "";
|
|
2323
|
+
const eventType = typeof parsed.type === "string" ? parsed.type.toLowerCase() : "";
|
|
2324
|
+
const source = typeof parsed.source === "string" ? parsed.source.toUpperCase() : "";
|
|
2325
|
+
return role === "user" || eventType === "user_message" || eventType === "user_input" || source === "USER_EXPLICIT";
|
|
2326
|
+
}
|
|
2327
|
+
async function findLatestTranscriptPath(brainDir) {
|
|
2328
|
+
const resolvedDir = brainDir !== void 0 ? brainDir : getAgyBrainDir();
|
|
2329
|
+
if (!resolvedDir) {
|
|
2330
|
+
return null;
|
|
2331
|
+
}
|
|
2332
|
+
let entries;
|
|
2333
|
+
try {
|
|
2334
|
+
entries = await readdir3(resolvedDir, { withFileTypes: true });
|
|
2335
|
+
} catch {
|
|
2336
|
+
return null;
|
|
2337
|
+
}
|
|
2338
|
+
let latestPath = null;
|
|
2339
|
+
let latestMtimeMs = -1;
|
|
2340
|
+
for (const entry of entries) {
|
|
2341
|
+
if (!entry.isDirectory()) {
|
|
2342
|
+
continue;
|
|
2343
|
+
}
|
|
2344
|
+
const candidate = join6(
|
|
2345
|
+
resolvedDir,
|
|
2346
|
+
entry.name,
|
|
2347
|
+
".system_generated",
|
|
2348
|
+
"logs",
|
|
2349
|
+
"transcript.jsonl"
|
|
2350
|
+
);
|
|
2351
|
+
try {
|
|
2352
|
+
const s = await stat2(candidate);
|
|
2353
|
+
if (s.isFile() && s.mtimeMs > latestMtimeMs) {
|
|
2354
|
+
latestMtimeMs = s.mtimeMs;
|
|
2355
|
+
latestPath = candidate;
|
|
2356
|
+
}
|
|
2357
|
+
} catch {
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
return latestPath;
|
|
2361
|
+
}
|
|
2362
|
+
async function extractTranscriptTailLifecycleMetrics(transcriptPath, options) {
|
|
2363
|
+
const tailBytes = options?.tailBytes ?? DEFAULT_TAIL_BYTES;
|
|
2364
|
+
const nowMs = options?.nowMs ?? Date.now();
|
|
2365
|
+
let handle;
|
|
2366
|
+
try {
|
|
2367
|
+
handle = await open(transcriptPath, "r");
|
|
2368
|
+
const fileStat = await handle.stat();
|
|
2369
|
+
if (!fileStat.isFile() || fileStat.size === 0) {
|
|
2370
|
+
return null;
|
|
2371
|
+
}
|
|
2372
|
+
const readStart = Math.max(0, fileStat.size - tailBytes);
|
|
2373
|
+
const readLen = Math.min(fileStat.size, tailBytes);
|
|
2374
|
+
const buf = Buffer.allocUnsafe(readLen);
|
|
2375
|
+
const { bytesRead } = await handle.read(buf, 0, readLen, readStart);
|
|
2376
|
+
let tailText = buf.subarray(0, bytesRead).toString("utf8");
|
|
2377
|
+
if (readStart > 0) {
|
|
2378
|
+
const firstNewline = tailText.indexOf("\n");
|
|
2379
|
+
if (firstNewline !== -1) {
|
|
2380
|
+
tailText = tailText.slice(firstNewline + 1);
|
|
2381
|
+
} else {
|
|
2382
|
+
tailText = "";
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
const lines = tailText.split("\n");
|
|
2386
|
+
let userTurns = 0;
|
|
2387
|
+
let plannerTurnsSinceCompact = 0;
|
|
2388
|
+
let maxStepIndex = 0;
|
|
2389
|
+
let hasRecentCompact = false;
|
|
2390
|
+
let lastEventTsMs = null;
|
|
2391
|
+
let latestModel = null;
|
|
2392
|
+
let recent429Count = 0;
|
|
2393
|
+
let recentOverflowCount = 0;
|
|
2394
|
+
const tokenEvents = [];
|
|
2395
|
+
for (const line of lines) {
|
|
2396
|
+
const trimmed = line.trim();
|
|
2397
|
+
if (!trimmed) {
|
|
2398
|
+
continue;
|
|
2399
|
+
}
|
|
2400
|
+
let parsed;
|
|
2401
|
+
try {
|
|
2402
|
+
parsed = JSON.parse(trimmed);
|
|
2403
|
+
} catch {
|
|
2404
|
+
continue;
|
|
2405
|
+
}
|
|
2406
|
+
const tsMs = extractTsMs(parsed);
|
|
2407
|
+
if (tsMs !== null && (lastEventTsMs === null || tsMs > lastEventTsMs)) {
|
|
2408
|
+
lastEventTsMs = tsMs;
|
|
2409
|
+
}
|
|
2410
|
+
if (typeof parsed.step_index === "number" && parsed.step_index > maxStepIndex) {
|
|
2411
|
+
maxStepIndex = Math.floor(parsed.step_index);
|
|
2412
|
+
}
|
|
2413
|
+
const eventType = typeof parsed.type === "string" ? parsed.type.toLowerCase() : "";
|
|
2414
|
+
const role = typeof parsed.role === "string" ? parsed.role.toLowerCase() : "";
|
|
2415
|
+
if (eventType === "compact" || eventType === "compaction") {
|
|
2416
|
+
hasRecentCompact = true;
|
|
2417
|
+
plannerTurnsSinceCompact = 0;
|
|
2418
|
+
continue;
|
|
2419
|
+
}
|
|
2420
|
+
if (isUserLine(parsed)) {
|
|
2421
|
+
userTurns += 1;
|
|
2422
|
+
} else if (role === "assistant" || role === "model" || eventType === "assistant_message" || eventType === "planner_response") {
|
|
2423
|
+
plannerTurnsSinceCompact += 1;
|
|
2424
|
+
}
|
|
2425
|
+
const usageObj = parsed.usage && typeof parsed.usage === "object" && !Array.isArray(parsed.usage) ? parsed.usage : {};
|
|
2426
|
+
const modelVal = parsed.model ?? usageObj.model;
|
|
2427
|
+
if (typeof modelVal === "string" && modelVal.trim().length > 0) {
|
|
2428
|
+
latestModel = modelVal.trim();
|
|
2429
|
+
}
|
|
2430
|
+
const inputTokens = firstNonNegInt2(
|
|
2431
|
+
parsed.input_tokens,
|
|
2432
|
+
usageObj.input_tokens,
|
|
2433
|
+
usageObj.prompt_tokens
|
|
2434
|
+
);
|
|
2435
|
+
const cacheReadTokens = firstNonNegInt2(
|
|
2436
|
+
parsed.cache_read_tokens,
|
|
2437
|
+
usageObj.cache_read_tokens,
|
|
2438
|
+
usageObj.cached_content_token_count
|
|
2439
|
+
);
|
|
2440
|
+
const totalInput = inputTokens + cacheReadTokens;
|
|
2441
|
+
if (totalInput > 0) {
|
|
2442
|
+
tokenEvents.push({ totalInput, cacheRead: cacheReadTokens });
|
|
2443
|
+
}
|
|
2444
|
+
const errRaw = String(
|
|
2445
|
+
parsed.error_code ?? parsed.error ?? parsed.status_code ?? ""
|
|
2446
|
+
).toUpperCase();
|
|
2447
|
+
const within5m = tsMs === null || nowMs - tsMs <= FIVE_MINUTES_MS;
|
|
2448
|
+
if (within5m && errRaw.length > 0) {
|
|
2449
|
+
if (errRaw.includes("429") || errRaw.includes("RESOURCE_EXHAUSTED")) {
|
|
2450
|
+
recent429Count += 1;
|
|
2451
|
+
}
|
|
2452
|
+
if (errRaw.includes("CONTEXT_OVERFLOW") || errRaw.includes("OVERFLOW") || errRaw.includes("CONTEXT_LENGTH_EXCEEDED") || errRaw.includes("TOO_MANY_TOKENS")) {
|
|
2453
|
+
recentOverflowCount += 1;
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
let hasUserInHead = false;
|
|
2458
|
+
if (readStart > 0 && userTurns === 0) {
|
|
2459
|
+
const headLen = Math.min(fileStat.size, HEAD_PROBE_BYTES);
|
|
2460
|
+
const headBuf = Buffer.allocUnsafe(headLen);
|
|
2461
|
+
const headRes = await handle.read(headBuf, 0, headLen, 0);
|
|
2462
|
+
const headText = headBuf.subarray(0, headRes.bytesRead).toString("utf8");
|
|
2463
|
+
for (const line of headText.split("\n")) {
|
|
2464
|
+
const trimmed = line.trim();
|
|
2465
|
+
if (!trimmed) continue;
|
|
2466
|
+
try {
|
|
2467
|
+
const parsed = JSON.parse(trimmed);
|
|
2468
|
+
if (isUserLine(parsed)) {
|
|
2469
|
+
hasUserInHead = true;
|
|
2470
|
+
break;
|
|
2471
|
+
}
|
|
2472
|
+
} catch {
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
const latestTokens = tokenEvents.length > 0 ? tokenEvents[tokenEvents.length - 1].totalInput : 0;
|
|
2477
|
+
const prevTokens = tokenEvents.length >= 2 ? tokenEvents[tokenEvents.length - 2].totalInput : void 0;
|
|
2478
|
+
const last3 = tokenEvents.slice(-3);
|
|
2479
|
+
const sumInput3 = last3.reduce((s, e) => s + e.totalInput, 0);
|
|
2480
|
+
const sumCache3 = last3.reduce((s, e) => s + e.cacheRead, 0);
|
|
2481
|
+
const recentCacheHitPct = sumInput3 > 0 ? Math.round(sumCache3 / sumInput3 * 1e3) / 10 : 0;
|
|
2482
|
+
const idleGapSec = lastEventTsMs !== null ? Math.max(0, (nowMs - lastEventTsMs) / 1e3) : 0;
|
|
2483
|
+
const effectiveTurns = hasRecentCompact ? plannerTurnsSinceCompact : Math.max(plannerTurnsSinceCompact, maxStepIndex);
|
|
2484
|
+
return {
|
|
2485
|
+
session_hash: createHash3("sha256").update(transcriptPath).digest("hex").slice(0, 12),
|
|
2486
|
+
is_interactive: userTurns > 0 || hasUserInHead,
|
|
2487
|
+
planner_turns_since_compact: effectiveTurns,
|
|
2488
|
+
current_input_tokens: latestTokens,
|
|
2489
|
+
recent_cache_hit_pct: recentCacheHitPct,
|
|
2490
|
+
idle_gap_sec: idleGapSec,
|
|
2491
|
+
recent_429_count: recent429Count,
|
|
2492
|
+
recent_overflow_count: recentOverflowCount,
|
|
2493
|
+
model_context_limit: inferModelContextLimit(latestModel),
|
|
2494
|
+
...hasRecentCompact ? { has_recent_compact: true } : {},
|
|
2495
|
+
...prevTokens !== void 0 ? { previous_input_tokens: prevTokens } : {}
|
|
2496
|
+
};
|
|
2497
|
+
} catch {
|
|
2498
|
+
return null;
|
|
2499
|
+
} finally {
|
|
2500
|
+
await handle?.close().catch(() => {
|
|
2501
|
+
});
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
async function loadAdviceState(stateFilePath) {
|
|
2505
|
+
try {
|
|
2506
|
+
const raw = await readFile5(stateFilePath, "utf8");
|
|
2507
|
+
const parsed = JSON.parse(raw);
|
|
2508
|
+
if (parsed && typeof parsed.sessions === "object" && parsed.sessions !== null) {
|
|
2509
|
+
return { sessions: { ...parsed.sessions } };
|
|
2510
|
+
}
|
|
2511
|
+
} catch {
|
|
2512
|
+
}
|
|
2513
|
+
return { sessions: {} };
|
|
2514
|
+
}
|
|
2515
|
+
async function saveAdviceState(stateFilePath, state) {
|
|
2516
|
+
try {
|
|
2517
|
+
const entries = Object.entries(state.sessions);
|
|
2518
|
+
if (entries.length > MAX_STATE_SESSIONS) {
|
|
2519
|
+
entries.sort((a, b) => b[1].last_notified_ms - a[1].last_notified_ms);
|
|
2520
|
+
state.sessions = Object.fromEntries(entries.slice(0, MAX_STATE_SESSIONS));
|
|
2521
|
+
}
|
|
2522
|
+
await mkdir2(dirname2(stateFilePath), { recursive: true });
|
|
2523
|
+
await writeFile2(stateFilePath, JSON.stringify(state, null, 2), "utf8");
|
|
2524
|
+
} catch {
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
async function runHookCheck(options) {
|
|
2528
|
+
const nowMs = options?.nowMs ?? Date.now();
|
|
2529
|
+
const locale = resolveLocale(options?.lang, process.env);
|
|
2530
|
+
const stateFile = options?.stateFilePath ?? join6(getCacheDir(), "session_advice_state.json");
|
|
2531
|
+
const transcriptPath = options?.transcriptPath ?? await findLatestTranscriptPath(options?.brainDir);
|
|
2532
|
+
if (!transcriptPath) {
|
|
2533
|
+
return {
|
|
2534
|
+
transcript_found: false,
|
|
2535
|
+
decision: {
|
|
2536
|
+
action: "HOLD_CACHE",
|
|
2537
|
+
reason_code: "BELOW_THRESHOLD",
|
|
2538
|
+
should_notify: false
|
|
2539
|
+
},
|
|
2540
|
+
state_file: stateFile
|
|
2541
|
+
};
|
|
2542
|
+
}
|
|
2543
|
+
const metrics = await extractTranscriptTailLifecycleMetrics(transcriptPath, {
|
|
2544
|
+
tailBytes: options?.tailBytes,
|
|
2545
|
+
nowMs
|
|
2546
|
+
});
|
|
2547
|
+
if (!metrics) {
|
|
2548
|
+
return {
|
|
2549
|
+
transcript_found: false,
|
|
2550
|
+
decision: {
|
|
2551
|
+
action: "HOLD_CACHE",
|
|
2552
|
+
reason_code: "BELOW_THRESHOLD",
|
|
2553
|
+
should_notify: false
|
|
2554
|
+
},
|
|
2555
|
+
state_file: stateFile
|
|
2556
|
+
};
|
|
2557
|
+
}
|
|
2558
|
+
const state = await loadAdviceState(stateFile);
|
|
2559
|
+
const prevState = state.sessions[metrics.session_hash];
|
|
2560
|
+
const { decision, nextState } = evaluateSessionLifecycle(metrics, prevState, {
|
|
2561
|
+
nowMs,
|
|
2562
|
+
locale
|
|
2563
|
+
});
|
|
2564
|
+
state.sessions[metrics.session_hash] = nextState;
|
|
2565
|
+
await saveAdviceState(stateFile, state);
|
|
2566
|
+
return {
|
|
2567
|
+
transcript_found: true,
|
|
2568
|
+
decision,
|
|
2569
|
+
metrics,
|
|
2570
|
+
state_file: stateFile
|
|
2571
|
+
};
|
|
2572
|
+
}
|
|
2573
|
+
|
|
1930
2574
|
// src/storage/rollups.ts
|
|
2575
|
+
import { createHash as createHash4, randomBytes as randomBytes2 } from "crypto";
|
|
2576
|
+
import {
|
|
2577
|
+
mkdir as mkdir3,
|
|
2578
|
+
open as open2,
|
|
2579
|
+
readdir as readdir4,
|
|
2580
|
+
readFile as readFile6,
|
|
2581
|
+
rename,
|
|
2582
|
+
rm,
|
|
2583
|
+
stat as stat3,
|
|
2584
|
+
unlink,
|
|
2585
|
+
writeFile as writeFile3
|
|
2586
|
+
} from "fs/promises";
|
|
2587
|
+
import { dirname as dirname3, join as join7 } from "path";
|
|
1931
2588
|
var STALE_LOCK_MS = 1e4;
|
|
1932
2589
|
var DEFAULT_COLD_BRAIN_DAYS = 30;
|
|
1933
2590
|
function computeSaltFingerprint(salt) {
|
|
1934
|
-
return
|
|
2591
|
+
return createHash4("sha256").update(salt).digest("hex").slice(0, 12);
|
|
1935
2592
|
}
|
|
1936
2593
|
function computeModelsFingerprint(input) {
|
|
1937
2594
|
const models = Array.isArray(input.models) ? input.models : [];
|
|
@@ -1945,16 +2602,16 @@ function computeModelsFingerprint(input) {
|
|
|
1945
2602
|
pricing: m.pricing
|
|
1946
2603
|
})).sort((a, b) => a.id.localeCompare(b.id))
|
|
1947
2604
|
};
|
|
1948
|
-
return
|
|
2605
|
+
return createHash4("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 12);
|
|
1949
2606
|
}
|
|
1950
2607
|
async function cleanupRollupsDirKeepLock(rollupsDir) {
|
|
1951
2608
|
try {
|
|
1952
|
-
const entries = await
|
|
2609
|
+
const entries = await readdir4(rollupsDir, { withFileTypes: true });
|
|
1953
2610
|
for (const entry of entries) {
|
|
1954
2611
|
if (entry.name === ".rollup.lock") {
|
|
1955
2612
|
continue;
|
|
1956
2613
|
}
|
|
1957
|
-
await rm(
|
|
2614
|
+
await rm(join7(rollupsDir, entry.name), { recursive: true, force: true });
|
|
1958
2615
|
}
|
|
1959
2616
|
} catch {
|
|
1960
2617
|
}
|
|
@@ -2060,9 +2717,9 @@ function getUtcMonthKey(ms) {
|
|
|
2060
2717
|
return formatBucketKey(ms, "monthly", "UTC");
|
|
2061
2718
|
}
|
|
2062
2719
|
async function atomicWriteJson(targetPath, data) {
|
|
2063
|
-
await
|
|
2720
|
+
await mkdir3(dirname3(targetPath), { recursive: true });
|
|
2064
2721
|
const tmpPath = `${targetPath}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
|
|
2065
|
-
await
|
|
2722
|
+
await writeFile3(tmpPath, JSON.stringify(data, null, 2), {
|
|
2066
2723
|
encoding: "utf8",
|
|
2067
2724
|
mode: 384
|
|
2068
2725
|
});
|
|
@@ -2071,7 +2728,7 @@ async function atomicWriteJson(targetPath, data) {
|
|
|
2071
2728
|
async function safeReadJson(filePath) {
|
|
2072
2729
|
let raw;
|
|
2073
2730
|
try {
|
|
2074
|
-
raw = await
|
|
2731
|
+
raw = await readFile6(filePath, "utf8");
|
|
2075
2732
|
} catch (err) {
|
|
2076
2733
|
const code = err?.code;
|
|
2077
2734
|
if (code === "ENOENT") {
|
|
@@ -2090,12 +2747,12 @@ async function safeReadJson(filePath) {
|
|
|
2090
2747
|
}
|
|
2091
2748
|
}
|
|
2092
2749
|
async function acquireRollupLock(rollupsDir, timeoutMs = 150) {
|
|
2093
|
-
await
|
|
2094
|
-
const lockPath =
|
|
2750
|
+
await mkdir3(rollupsDir, { recursive: true });
|
|
2751
|
+
const lockPath = join7(rollupsDir, ".rollup.lock");
|
|
2095
2752
|
const deadline = Date.now() + timeoutMs;
|
|
2096
2753
|
while (true) {
|
|
2097
2754
|
try {
|
|
2098
|
-
const fh = await
|
|
2755
|
+
const fh = await open2(lockPath, "wx", 384);
|
|
2099
2756
|
await fh.writeFile(JSON.stringify({ pid: process.pid, ts: Date.now() }), "utf8");
|
|
2100
2757
|
await fh.close();
|
|
2101
2758
|
return lockPath;
|
|
@@ -2105,10 +2762,10 @@ async function acquireRollupLock(rollupsDir, timeoutMs = 150) {
|
|
|
2105
2762
|
return null;
|
|
2106
2763
|
}
|
|
2107
2764
|
try {
|
|
2108
|
-
const st = await
|
|
2765
|
+
const st = await stat3(lockPath);
|
|
2109
2766
|
let lockTs = st.mtimeMs;
|
|
2110
2767
|
try {
|
|
2111
|
-
const raw = await
|
|
2768
|
+
const raw = await readFile6(lockPath, "utf8");
|
|
2112
2769
|
const parsed = JSON.parse(raw);
|
|
2113
2770
|
if (typeof parsed.ts === "number") {
|
|
2114
2771
|
lockTs = parsed.ts;
|
|
@@ -2140,7 +2797,7 @@ async function releaseLock(lockPath) {
|
|
|
2140
2797
|
async function readFileIncrementalLines(filePath, watermark) {
|
|
2141
2798
|
let st;
|
|
2142
2799
|
try {
|
|
2143
|
-
st = await
|
|
2800
|
+
st = await stat3(filePath);
|
|
2144
2801
|
} catch {
|
|
2145
2802
|
return null;
|
|
2146
2803
|
}
|
|
@@ -2153,7 +2810,7 @@ async function readFileIncrementalLines(filePath, watermark) {
|
|
|
2153
2810
|
if (bytesToRead <= 0) {
|
|
2154
2811
|
return { lines: [], newOffset: st.size, mtimeMs: st.mtimeMs, resetRequired };
|
|
2155
2812
|
}
|
|
2156
|
-
const fh = await
|
|
2813
|
+
const fh = await open2(filePath, "r");
|
|
2157
2814
|
try {
|
|
2158
2815
|
const buf = Buffer.alloc(bytesToRead);
|
|
2159
2816
|
const { bytesRead } = await fh.read(buf, 0, bytesToRead, startOffset);
|
|
@@ -2362,8 +3019,8 @@ async function queryRollups(options) {
|
|
|
2362
3019
|
const nowMs = options.nowMs ?? Date.now();
|
|
2363
3020
|
const readonly = isReadonlyEnv(options.readonly);
|
|
2364
3021
|
const rollupsDir = options.rollupsDir ?? getRollupsDir();
|
|
2365
|
-
const hourlyDir =
|
|
2366
|
-
const watermarksPath =
|
|
3022
|
+
const hourlyDir = join7(rollupsDir, "hourly");
|
|
3023
|
+
const watermarksPath = join7(rollupsDir, "watermarks.json");
|
|
2367
3024
|
const catalog = options.models ?? [];
|
|
2368
3025
|
const rules = options.normalizationRules;
|
|
2369
3026
|
const tz = normalizeTimezone(options.timezone);
|
|
@@ -2400,14 +3057,14 @@ async function queryRollups(options) {
|
|
|
2400
3057
|
let corruptDetected = wmRes.status === "corrupt";
|
|
2401
3058
|
let existingHourlyFiles = [];
|
|
2402
3059
|
try {
|
|
2403
|
-
const files = await
|
|
3060
|
+
const files = await readdir4(hourlyDir);
|
|
2404
3061
|
existingHourlyFiles = files.filter((f) => /^\d{4}-\d{2}\.json$/.test(f)).sort();
|
|
2405
3062
|
} catch {
|
|
2406
3063
|
existingHourlyFiles = [];
|
|
2407
3064
|
}
|
|
2408
3065
|
let hasLegacyPeriodFiles = false;
|
|
2409
3066
|
try {
|
|
2410
|
-
const rootFiles = await
|
|
3067
|
+
const rootFiles = await readdir4(rollupsDir);
|
|
2411
3068
|
hasLegacyPeriodFiles = rootFiles.some(
|
|
2412
3069
|
(f) => f === "daily.json" || f === "weekly.json" || f === "monthly.json"
|
|
2413
3070
|
);
|
|
@@ -2417,7 +3074,7 @@ async function queryRollups(options) {
|
|
|
2417
3074
|
let legacySchemaDetected = false;
|
|
2418
3075
|
if (!corruptDetected) {
|
|
2419
3076
|
for (const f of existingHourlyFiles) {
|
|
2420
|
-
const hRes = await safeReadJson(
|
|
3077
|
+
const hRes = await safeReadJson(join7(hourlyDir, f));
|
|
2421
3078
|
if (hRes.status === "corrupt") {
|
|
2422
3079
|
corruptDetected = true;
|
|
2423
3080
|
break;
|
|
@@ -2459,7 +3116,7 @@ async function queryRollups(options) {
|
|
|
2459
3116
|
return cached;
|
|
2460
3117
|
}
|
|
2461
3118
|
if (useDiskRollups) {
|
|
2462
|
-
const filePath =
|
|
3119
|
+
const filePath = join7(hourlyDir, `${monthKey}.json`);
|
|
2463
3120
|
const res = await safeReadJson(filePath);
|
|
2464
3121
|
if (res.status === "ok" && res.data.buckets) {
|
|
2465
3122
|
for (const entries of Object.values(res.data.buckets)) {
|
|
@@ -2611,13 +3268,13 @@ async function queryRollups(options) {
|
|
|
2611
3268
|
const projectIndex = await buildConversationProjectIndex(historyPath, salt);
|
|
2612
3269
|
let sessionDirs = [];
|
|
2613
3270
|
try {
|
|
2614
|
-
const entries = await
|
|
3271
|
+
const entries = await readdir4(brainDir, { withFileTypes: true });
|
|
2615
3272
|
sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
2616
3273
|
} catch {
|
|
2617
3274
|
sessionDirs = [];
|
|
2618
3275
|
}
|
|
2619
3276
|
for (const sessionId of sessionDirs) {
|
|
2620
|
-
const transcriptPath =
|
|
3277
|
+
const transcriptPath = join7(
|
|
2621
3278
|
brainDir,
|
|
2622
3279
|
sessionId,
|
|
2623
3280
|
".system_generated",
|
|
@@ -2626,7 +3283,7 @@ async function queryRollups(options) {
|
|
|
2626
3283
|
);
|
|
2627
3284
|
let st;
|
|
2628
3285
|
try {
|
|
2629
|
-
st = await
|
|
3286
|
+
st = await stat3(transcriptPath);
|
|
2630
3287
|
} catch {
|
|
2631
3288
|
continue;
|
|
2632
3289
|
}
|
|
@@ -2681,7 +3338,7 @@ async function queryRollups(options) {
|
|
|
2681
3338
|
}
|
|
2682
3339
|
if (lastSeenModel === null && dominantModel === null && prevWm && !inc.resetRequired && prevWm.byte_offset > 0) {
|
|
2683
3340
|
try {
|
|
2684
|
-
const headText = await
|
|
3341
|
+
const headText = await readFile6(transcriptPath, "utf8");
|
|
2685
3342
|
const headFreq = /* @__PURE__ */ new Map();
|
|
2686
3343
|
for (const rawLine of headText.split("\n")) {
|
|
2687
3344
|
const t = rawLine.trim();
|
|
@@ -2812,7 +3469,7 @@ async function queryRollups(options) {
|
|
|
2812
3469
|
for (const monthKey of dirtyHourlyMonths) {
|
|
2813
3470
|
const hf = hourlyCache.get(monthKey);
|
|
2814
3471
|
if (hf) {
|
|
2815
|
-
await atomicWriteJson(
|
|
3472
|
+
await atomicWriteJson(join7(hourlyDir, `${monthKey}.json`), hf);
|
|
2816
3473
|
}
|
|
2817
3474
|
}
|
|
2818
3475
|
await atomicWriteJson(watermarksPath, watermarks);
|
|
@@ -3096,12 +3753,12 @@ async function readSaltReadonly(rollupsDir, explicitSalt, explicitSaltPath) {
|
|
|
3096
3753
|
}
|
|
3097
3754
|
const candidates = [
|
|
3098
3755
|
...explicitSaltPath ? [explicitSaltPath] : [],
|
|
3099
|
-
|
|
3756
|
+
join7(dirname3(rollupsDir), ".salt"),
|
|
3100
3757
|
...rollupsDir === getRollupsDir() ? [getSaltFilePath()] : []
|
|
3101
3758
|
];
|
|
3102
3759
|
for (const candidate of candidates) {
|
|
3103
3760
|
try {
|
|
3104
|
-
const content = (await
|
|
3761
|
+
const content = (await readFile6(candidate, "utf8")).trim();
|
|
3105
3762
|
if (content.length > 0) {
|
|
3106
3763
|
return content;
|
|
3107
3764
|
}
|
|
@@ -3113,8 +3770,8 @@ async function readSaltReadonly(rollupsDir, explicitSalt, explicitSaltPath) {
|
|
|
3113
3770
|
async function readRollupCostSummary(options) {
|
|
3114
3771
|
const nowMs = options?.nowMs ?? Date.now();
|
|
3115
3772
|
const rollupsDir = options?.rollupsDir ?? getRollupsDir();
|
|
3116
|
-
const hourlyDir =
|
|
3117
|
-
const watermarksPath =
|
|
3773
|
+
const hourlyDir = join7(rollupsDir, "hourly");
|
|
3774
|
+
const watermarksPath = join7(rollupsDir, "watermarks.json");
|
|
3118
3775
|
const catalog = options?.models ?? [];
|
|
3119
3776
|
const rules = options?.normalizationRules;
|
|
3120
3777
|
const pkgVersion = options?.pkgVersion ?? getPackageVersion();
|
|
@@ -3137,7 +3794,7 @@ async function readRollupCostSummary(options) {
|
|
|
3137
3794
|
if (fingerprintValid) {
|
|
3138
3795
|
const monthKeys = [.../* @__PURE__ */ new Set([getUtcMonthKey(nowMs), getUtcMonthKey(nowMs - WINDOW_MS["7d"])])];
|
|
3139
3796
|
for (const mk of monthKeys) {
|
|
3140
|
-
const res = await safeReadJson(
|
|
3797
|
+
const res = await safeReadJson(join7(hourlyDir, `${mk}.json`));
|
|
3141
3798
|
if (res.status === "ok" && res.data.v === 2 && res.data.buckets) {
|
|
3142
3799
|
hourlyFiles.push(res.data);
|
|
3143
3800
|
}
|
|
@@ -3197,7 +3854,7 @@ tmp/
|
|
|
3197
3854
|
async function loadOfflineModelsSnapshot(snapshotsDir) {
|
|
3198
3855
|
const dir = snapshotsDir ?? getSnapshotsDir();
|
|
3199
3856
|
try {
|
|
3200
|
-
const raw = await
|
|
3857
|
+
const raw = await readFile7(join8(dir, "models.json"), "utf8");
|
|
3201
3858
|
const parsed = JSON.parse(raw);
|
|
3202
3859
|
return {
|
|
3203
3860
|
models: Array.isArray(parsed.models) ? parsed.models : [],
|
|
@@ -3246,7 +3903,7 @@ async function inspectJsonConfig(filePath, kind) {
|
|
|
3246
3903
|
}
|
|
3247
3904
|
let parsed;
|
|
3248
3905
|
try {
|
|
3249
|
-
const raw = await
|
|
3906
|
+
const raw = await readFile7(filePath, "utf8");
|
|
3250
3907
|
parsed = JSON.parse(raw);
|
|
3251
3908
|
} catch (err) {
|
|
3252
3909
|
const msg = err instanceof Error ? err.message : "Invalid JSON syntax";
|
|
@@ -3358,6 +4015,7 @@ async function runDoctor(options) {
|
|
|
3358
4015
|
const cwd = options?.cwd ?? process.cwd();
|
|
3359
4016
|
const home = options?.homeDir ?? homedir3();
|
|
3360
4017
|
const env = options?.env ?? process.env;
|
|
4018
|
+
const locale = resolveLocale(options?.lang, env);
|
|
3361
4019
|
const registry = options?.channels instanceof ChannelRegistry ? options.channels : options?.channels ? ChannelRegistry.fromSnapshot(options.channels) : loadBundledChannelRegistry(options?.snapshotsDir);
|
|
3362
4020
|
const authContext = await detectAuthContext({
|
|
3363
4021
|
homeDir: home,
|
|
@@ -3399,12 +4057,12 @@ async function runDoctor(options) {
|
|
|
3399
4057
|
});
|
|
3400
4058
|
}
|
|
3401
4059
|
const mcpPaths = options?.mcpConfigPaths ?? [
|
|
3402
|
-
|
|
3403
|
-
|
|
4060
|
+
join8(home, ".gemini", "antigravity", "mcp_config.json"),
|
|
4061
|
+
join8(cwd, "mcp_config.json")
|
|
3404
4062
|
];
|
|
3405
4063
|
const settingsPaths = options?.settingsJsonPaths ?? [
|
|
3406
|
-
|
|
3407
|
-
|
|
4064
|
+
join8(home, ".gemini", "settings.json"),
|
|
4065
|
+
join8(cwd, ".gemini", "settings.json")
|
|
3408
4066
|
];
|
|
3409
4067
|
let foundAnyConfig = false;
|
|
3410
4068
|
for (const p of mcpPaths) {
|
|
@@ -3531,7 +4189,7 @@ async function runDoctor(options) {
|
|
|
3531
4189
|
detail: "Direct HTTPS connection environment."
|
|
3532
4190
|
});
|
|
3533
4191
|
}
|
|
3534
|
-
const hasGeminiIgnore = await fileExists(
|
|
4192
|
+
const hasGeminiIgnore = await fileExists(join8(cwd, ".geminiignore"));
|
|
3535
4193
|
checks.push({
|
|
3536
4194
|
id: "geminiignore_check",
|
|
3537
4195
|
category: "context_hygiene",
|
|
@@ -3541,15 +4199,15 @@ async function runDoctor(options) {
|
|
|
3541
4199
|
fix_hint: hasGeminiIgnore ? void 0 : "Create a `.geminiignore` file using the recommended template below."
|
|
3542
4200
|
});
|
|
3543
4201
|
const ruleCandidates = [
|
|
3544
|
-
{ label: "~/.gemini/GEMINI.md", path:
|
|
3545
|
-
{ label: "./GEMINI.md", path:
|
|
3546
|
-
{ label: "./AGENTS.md", path:
|
|
4202
|
+
{ label: "~/.gemini/GEMINI.md", path: join8(home, ".gemini", "GEMINI.md") },
|
|
4203
|
+
{ label: "./GEMINI.md", path: join8(cwd, "GEMINI.md") },
|
|
4204
|
+
{ label: "./AGENTS.md", path: join8(cwd, "AGENTS.md") }
|
|
3547
4205
|
];
|
|
3548
4206
|
let totalRuleBytes = 0;
|
|
3549
4207
|
let foundRuleFiles = 0;
|
|
3550
4208
|
for (const candidate of ruleCandidates) {
|
|
3551
4209
|
try {
|
|
3552
|
-
const s = await
|
|
4210
|
+
const s = await stat4(candidate.path);
|
|
3553
4211
|
if (s.isFile()) {
|
|
3554
4212
|
totalRuleBytes += s.size;
|
|
3555
4213
|
foundRuleFiles += 1;
|
|
@@ -3559,7 +4217,7 @@ async function runDoctor(options) {
|
|
|
3559
4217
|
}
|
|
3560
4218
|
const estimatedRuleTokens = Math.ceil(totalRuleBytes / 4);
|
|
3561
4219
|
if (estimatedRuleTokens > 3e3) {
|
|
3562
|
-
const channelHint = activeChannel ? ` Active channel (${activeChannel.channelId}): ${activeChannel.definition.recommended_behaviors.kv_cache_guidance}` : "";
|
|
4220
|
+
const channelHint = activeChannel ? ` Active channel (${activeChannel.channelId}): ${getLocalizedBehavior(activeChannel.definition.recommended_behaviors, "kv_cache_guidance", locale) ?? activeChannel.definition.recommended_behaviors.kv_cache_guidance}` : "";
|
|
3563
4221
|
checks.push({
|
|
3564
4222
|
id: "global_rules_bloat",
|
|
3565
4223
|
category: "context_hygiene",
|
|
@@ -3603,7 +4261,7 @@ async function runDoctor(options) {
|
|
|
3603
4261
|
title: has429 ? `Cost summary (5h: ${w5h.total_requests} reqs, ${w5h.rate_limit_429_count} x 429; 24h: ${w24h.total_requests} reqs)` : `Cost summary (5h: ${w5h.total_requests} reqs | 24h: ${w24h.total_requests} reqs)`,
|
|
3604
4262
|
detail: `5h -> ${formatChannelSummaryText(w5h)} || 24h -> ${formatChannelSummaryText(w24h)}`,
|
|
3605
4263
|
...has429 ? {
|
|
3606
|
-
fix_hint: activeChannel ? `429 rate limits detected in last 5h (${activeChannel.channelId}): ${activeChannel.definition.recommended_behaviors.throttling_guidance}` : "429 rate limits detected in last 5h. Run `npx agycraft-mcp preflight` to inspect live upstream status.json."
|
|
4264
|
+
fix_hint: activeChannel ? `429 rate limits detected in last 5h (${activeChannel.channelId}): ${getLocalizedBehavior(activeChannel.definition.recommended_behaviors, "throttling_guidance", locale) ?? activeChannel.definition.recommended_behaviors.throttling_guidance}` : "429 rate limits detected in last 5h. Run `npx agycraft-mcp preflight` to inspect live upstream status.json."
|
|
3607
4265
|
} : {}
|
|
3608
4266
|
});
|
|
3609
4267
|
if (w24h.deprecated_models_in_use.length > 0) {
|
|
@@ -3623,6 +4281,70 @@ async function runDoctor(options) {
|
|
|
3623
4281
|
});
|
|
3624
4282
|
}
|
|
3625
4283
|
}
|
|
4284
|
+
const effectiveBrainDir = options?.brainDir !== void 0 ? options.brainDir : options?.homeDir ? join8(options.homeDir, ".gemini", "antigravity-cli", "brain") : void 0;
|
|
4285
|
+
const latestTranscript = await findLatestTranscriptPath(effectiveBrainDir);
|
|
4286
|
+
if (!latestTranscript) {
|
|
4287
|
+
checks.push({
|
|
4288
|
+
id: "session_redundant_tool_calls",
|
|
4289
|
+
category: "context_hygiene",
|
|
4290
|
+
severity: "info",
|
|
4291
|
+
title: "Session tool-call hygiene: no local AGY transcript found",
|
|
4292
|
+
detail: "No active transcript.jsonl found to audit redundant file re-reads or polling duplicates."
|
|
4293
|
+
});
|
|
4294
|
+
checks.push({
|
|
4295
|
+
id: "session_context_watermark",
|
|
4296
|
+
category: "cost_usage",
|
|
4297
|
+
severity: "info",
|
|
4298
|
+
title: "Session context watermark: no active transcript found",
|
|
4299
|
+
detail: "No active transcript.jsonl found to inspect per-request token watermarks (160K/240K/360K)."
|
|
4300
|
+
});
|
|
4301
|
+
} else {
|
|
4302
|
+
const [transcriptMeta, tailMetrics] = await Promise.all([
|
|
4303
|
+
analyzeTranscriptStructure(latestTranscript),
|
|
4304
|
+
extractTranscriptTailLifecycleMetrics(latestTranscript, {
|
|
4305
|
+
nowMs: options?.nowMs
|
|
4306
|
+
})
|
|
4307
|
+
]);
|
|
4308
|
+
const redundantReads = transcriptMeta.redundant_read_file_count ?? 0;
|
|
4309
|
+
const redundantReadPct = transcriptMeta.redundant_read_file_pct ?? 0;
|
|
4310
|
+
const pollingDups = transcriptMeta.polling_dup_count ?? 0;
|
|
4311
|
+
const pollingDupPct = transcriptMeta.polling_dup_rate_pct ?? 0;
|
|
4312
|
+
const hasRedundancyRisk = redundantReadPct >= 20 && redundantReads >= 5 || pollingDupPct >= 15 && pollingDups >= 5;
|
|
4313
|
+
checks.push({
|
|
4314
|
+
id: "session_redundant_tool_calls",
|
|
4315
|
+
category: "context_hygiene",
|
|
4316
|
+
severity: hasRedundancyRisk ? "warn" : "ok",
|
|
4317
|
+
title: hasRedundancyRisk ? `Redundant tool calls detected in latest session (${redundantReads} re-reads / ${pollingDups} exact dups)` : "Latest session tool-call redundancy is healthy",
|
|
4318
|
+
detail: `Redundant unedited read_file: ${redundantReads} (${redundantReadPct}%); exact-duplicate polling calls: ${pollingDups} (${pollingDupPct}% across ${transcriptMeta.tool_call_count} tool calls).`,
|
|
4319
|
+
...hasRedundancyRisk ? {
|
|
4320
|
+
fix_hint: "Use `quick_outline` + targeted line ranges instead of re-reading unchanged files, and avoid polling `manage_task` / `call_mcp_tool` / `read_board` in loops."
|
|
4321
|
+
} : {}
|
|
4322
|
+
});
|
|
4323
|
+
if (tailMetrics && tailMetrics.current_input_tokens > 0) {
|
|
4324
|
+
const { decision } = evaluateSessionLifecycle(tailMetrics, void 0, {
|
|
4325
|
+
nowMs: options?.nowMs,
|
|
4326
|
+
locale
|
|
4327
|
+
});
|
|
4328
|
+
const highWatermark = decision.action !== "HOLD_CACHE";
|
|
4329
|
+
const kTokens = Math.round(tailMetrics.current_input_tokens / 1e3);
|
|
4330
|
+
checks.push({
|
|
4331
|
+
id: "session_context_watermark",
|
|
4332
|
+
category: "cost_usage",
|
|
4333
|
+
severity: highWatermark ? "warn" : "ok",
|
|
4334
|
+
title: highWatermark ? `Latest session context watermark elevated (~${kTokens}K tokens -> ${decision.action})` : `Latest session context watermark healthy (~${kTokens}K tokens, ${tailMetrics.recent_cache_hit_pct}% KV hit)`,
|
|
4335
|
+
detail: `Current input: ${tailMetrics.current_input_tokens.toLocaleString()} tokens | Recent KV cache hit: ${tailMetrics.recent_cache_hit_pct}% | Lifecycle: ${decision.action} (${decision.reason_code}).`,
|
|
4336
|
+
...highWatermark && decision.message ? { fix_hint: decision.message } : {}
|
|
4337
|
+
});
|
|
4338
|
+
} else {
|
|
4339
|
+
checks.push({
|
|
4340
|
+
id: "session_context_watermark",
|
|
4341
|
+
category: "cost_usage",
|
|
4342
|
+
severity: "info",
|
|
4343
|
+
title: "Session context watermark: no token telemetry in latest transcript",
|
|
4344
|
+
detail: "Latest transcript.jsonl has no per-request input/cache token fields yet."
|
|
4345
|
+
});
|
|
4346
|
+
}
|
|
4347
|
+
}
|
|
3626
4348
|
checks.push({
|
|
3627
4349
|
id: "git_safety_guardrail",
|
|
3628
4350
|
category: "safety_guardrail",
|
|
@@ -3925,12 +4647,1059 @@ function formatPreflightReport(result) {
|
|
|
3925
4647
|
return lines.join("\n");
|
|
3926
4648
|
}
|
|
3927
4649
|
|
|
3928
|
-
// src/cli/
|
|
3929
|
-
|
|
3930
|
-
|
|
4650
|
+
// src/cli/hook-manage.ts
|
|
4651
|
+
import { existsSync as existsSync2 } from "fs";
|
|
4652
|
+
import { mkdir as mkdir4, readFile as readFile8, writeFile as writeFile4 } from "fs/promises";
|
|
4653
|
+
import { homedir as homedir4 } from "os";
|
|
4654
|
+
import { dirname as dirname4, join as join9, resolve as resolve5 } from "path";
|
|
4655
|
+
import { fileURLToPath } from "url";
|
|
4656
|
+
function isPlainObject(value) {
|
|
4657
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4658
|
+
}
|
|
4659
|
+
function isAgycraftSubcommand(command, subcommand) {
|
|
4660
|
+
if (typeof command !== "string") {
|
|
4661
|
+
return false;
|
|
4662
|
+
}
|
|
4663
|
+
const trimmed = command.trim();
|
|
4664
|
+
if (!trimmed) {
|
|
4665
|
+
return false;
|
|
4666
|
+
}
|
|
4667
|
+
const hasSubcommand = new RegExp(`(?:^|\\s)${subcommand}(?:\\s|$)`).test(trimmed);
|
|
4668
|
+
if (!hasSubcommand) {
|
|
4669
|
+
return false;
|
|
4670
|
+
}
|
|
4671
|
+
return /(?:^|\s|["'\\/])agycraft-mcp(?:\s|["']|$)/.test(trimmed) || /(?:^|\s|["'\\/])dist[\\/]index\.js(?:\s|["']|$)/.test(trimmed);
|
|
4672
|
+
}
|
|
4673
|
+
function isAgycraftHookCheckCommand(command) {
|
|
4674
|
+
return isAgycraftSubcommand(command, "hook-check");
|
|
4675
|
+
}
|
|
4676
|
+
function isAgycraftHookRecordCommand(command) {
|
|
4677
|
+
return isAgycraftSubcommand(command, "record");
|
|
4678
|
+
}
|
|
4679
|
+
function resolveTargetSettingsPaths(options) {
|
|
4680
|
+
if (options?.settingsPath) {
|
|
4681
|
+
return [{ target: "custom", path: resolve5(options.settingsPath) }];
|
|
4682
|
+
}
|
|
4683
|
+
const home = options?.homeDir ?? homedir4();
|
|
4684
|
+
if (options?.kind === "record") {
|
|
4685
|
+
return [{ target: "agy", path: join9(home, ".gemini", "config", "hooks.json") }];
|
|
4686
|
+
}
|
|
4687
|
+
const target = options?.target ?? "agy";
|
|
4688
|
+
const agyPath = join9(home, ".gemini", "antigravity-cli", "settings.json");
|
|
4689
|
+
const geminiPath = join9(home, ".gemini", "settings.json");
|
|
4690
|
+
if (target === "agy") {
|
|
4691
|
+
return [{ target: "agy", path: agyPath }];
|
|
4692
|
+
}
|
|
4693
|
+
if (target === "gemini") {
|
|
4694
|
+
return [{ target: "gemini", path: geminiPath }];
|
|
4695
|
+
}
|
|
3931
4696
|
return [
|
|
3932
|
-
|
|
3933
|
-
"
|
|
4697
|
+
{ target: "agy", path: agyPath },
|
|
4698
|
+
{ target: "gemini", path: geminiPath }
|
|
4699
|
+
];
|
|
4700
|
+
}
|
|
4701
|
+
function quoteIfNeeded(filePath) {
|
|
4702
|
+
return /\s/.test(filePath) ? `"${filePath}"` : filePath;
|
|
4703
|
+
}
|
|
4704
|
+
function findLocalDistIndexPath(argv1) {
|
|
4705
|
+
if (argv1) {
|
|
4706
|
+
const resolvedArgv = resolve5(argv1);
|
|
4707
|
+
if (/[\\/]dist[\\/]index\.js$/.test(resolvedArgv) && !resolvedArgv.includes("node_modules") && !resolvedArgv.includes("_npx") && existsSync2(resolvedArgv)) {
|
|
4708
|
+
return resolvedArgv;
|
|
4709
|
+
}
|
|
4710
|
+
}
|
|
4711
|
+
try {
|
|
4712
|
+
const currentFile = fileURLToPath(import.meta.url);
|
|
4713
|
+
const candidates = [
|
|
4714
|
+
resolve5(dirname4(currentFile), "index.js"),
|
|
4715
|
+
resolve5(dirname4(currentFile), "../dist/index.js"),
|
|
4716
|
+
resolve5(dirname4(currentFile), "../../dist/index.js")
|
|
4717
|
+
];
|
|
4718
|
+
for (const candidate of candidates) {
|
|
4719
|
+
if (/[\\/]dist[\\/]index\.js$/.test(candidate) && !candidate.includes("node_modules") && existsSync2(candidate)) {
|
|
4720
|
+
return candidate;
|
|
4721
|
+
}
|
|
4722
|
+
}
|
|
4723
|
+
} catch {
|
|
4724
|
+
}
|
|
4725
|
+
return null;
|
|
4726
|
+
}
|
|
4727
|
+
function resolveHookCommand(options) {
|
|
4728
|
+
if (options?.command !== void 0) {
|
|
4729
|
+
const trimmed = options.command.trim();
|
|
4730
|
+
if (!trimmed) {
|
|
4731
|
+
throw new Error("--command cannot be empty.");
|
|
4732
|
+
}
|
|
4733
|
+
return trimmed;
|
|
4734
|
+
}
|
|
4735
|
+
const kind = options?.kind ?? "stop";
|
|
4736
|
+
const subcommand = kind === "record" ? "record" : "hook-check";
|
|
4737
|
+
const langSuffix = kind === "stop" && options?.lang ? ` --lang ${options.lang}` : "";
|
|
4738
|
+
const argv1 = options?.argv1 ?? process.argv[1];
|
|
4739
|
+
if (options?.local) {
|
|
4740
|
+
const localDist = findLocalDistIndexPath(argv1);
|
|
4741
|
+
if (!localDist) {
|
|
4742
|
+
throw new Error(
|
|
4743
|
+
"Could not locate local dist/index.js. Run `npm run build` first or pass --command <cmd>."
|
|
4744
|
+
);
|
|
4745
|
+
}
|
|
4746
|
+
return `node ${quoteIfNeeded(localDist)} ${subcommand}${langSuffix}`;
|
|
4747
|
+
}
|
|
4748
|
+
if (argv1) {
|
|
4749
|
+
const resolvedArgv = resolve5(argv1);
|
|
4750
|
+
if (/[\\/]dist[\\/]index\.js$/.test(resolvedArgv) && !resolvedArgv.includes("node_modules") && !resolvedArgv.includes("_npx") && existsSync2(resolvedArgv)) {
|
|
4751
|
+
return `node ${quoteIfNeeded(resolvedArgv)} ${subcommand}${langSuffix}`;
|
|
4752
|
+
}
|
|
4753
|
+
if (/[\\/]agycraft-mcp$/.test(resolvedArgv) && !resolvedArgv.includes("_npx")) {
|
|
4754
|
+
return `agycraft-mcp ${subcommand}${langSuffix}`;
|
|
4755
|
+
}
|
|
4756
|
+
}
|
|
4757
|
+
return `npx -y agycraft-mcp ${subcommand}${langSuffix}`;
|
|
4758
|
+
}
|
|
4759
|
+
async function readSettingsJson(filePath) {
|
|
4760
|
+
let raw;
|
|
4761
|
+
try {
|
|
4762
|
+
raw = await readFile8(filePath, "utf8");
|
|
4763
|
+
} catch (err) {
|
|
4764
|
+
const code = err?.code;
|
|
4765
|
+
if (code === "ENOENT") {
|
|
4766
|
+
return { exists: false, data: {} };
|
|
4767
|
+
}
|
|
4768
|
+
return {
|
|
4769
|
+
exists: true,
|
|
4770
|
+
error: err instanceof Error ? err.message : String(err)
|
|
4771
|
+
};
|
|
4772
|
+
}
|
|
4773
|
+
if (raw.trim().length === 0) {
|
|
4774
|
+
return { exists: true, data: {} };
|
|
4775
|
+
}
|
|
4776
|
+
try {
|
|
4777
|
+
const parsed = JSON.parse(raw);
|
|
4778
|
+
if (!isPlainObject(parsed)) {
|
|
4779
|
+
return {
|
|
4780
|
+
exists: true,
|
|
4781
|
+
error: "settings.json root must be a JSON object."
|
|
4782
|
+
};
|
|
4783
|
+
}
|
|
4784
|
+
return { exists: true, data: parsed };
|
|
4785
|
+
} catch (err) {
|
|
4786
|
+
return {
|
|
4787
|
+
exists: true,
|
|
4788
|
+
error: `Invalid JSON in ${filePath}: ${err instanceof Error ? err.message : String(err)}`
|
|
4789
|
+
};
|
|
4790
|
+
}
|
|
4791
|
+
}
|
|
4792
|
+
function collectMatchingHookCommands(entries, matcher) {
|
|
4793
|
+
const found = [];
|
|
4794
|
+
for (const entry of entries) {
|
|
4795
|
+
if (!isPlainObject(entry)) {
|
|
4796
|
+
continue;
|
|
4797
|
+
}
|
|
4798
|
+
const innerHooks = entry["hooks"];
|
|
4799
|
+
if (!Array.isArray(innerHooks)) {
|
|
4800
|
+
continue;
|
|
4801
|
+
}
|
|
4802
|
+
for (const h of innerHooks) {
|
|
4803
|
+
if (isPlainObject(h) && matcher(h["command"])) {
|
|
4804
|
+
found.push(h["command"]);
|
|
4805
|
+
}
|
|
4806
|
+
}
|
|
4807
|
+
}
|
|
4808
|
+
return found;
|
|
4809
|
+
}
|
|
4810
|
+
async function writeSettingsJson(filePath, data) {
|
|
4811
|
+
await mkdir4(dirname4(filePath), { recursive: true });
|
|
4812
|
+
await writeFile4(filePath, `${JSON.stringify(data, null, 2)}
|
|
4813
|
+
`, "utf8");
|
|
4814
|
+
}
|
|
4815
|
+
async function runHookEnable(options) {
|
|
4816
|
+
const kind = options?.kind ?? "stop";
|
|
4817
|
+
const hookEventKey = kind === "record" ? "PostInvocation" : "Stop";
|
|
4818
|
+
const isMatchingCommand = kind === "record" ? isAgycraftHookRecordCommand : isAgycraftHookCheckCommand;
|
|
4819
|
+
const command = resolveHookCommand({
|
|
4820
|
+
kind,
|
|
4821
|
+
command: options?.command,
|
|
4822
|
+
local: options?.local,
|
|
4823
|
+
lang: options?.lang,
|
|
4824
|
+
argv1: options?.argv1
|
|
4825
|
+
});
|
|
4826
|
+
const dryRun = Boolean(options?.dryRun);
|
|
4827
|
+
const targets = resolveTargetSettingsPaths({
|
|
4828
|
+
kind,
|
|
4829
|
+
target: options?.target,
|
|
4830
|
+
settingsPath: options?.settingsPath,
|
|
4831
|
+
homeDir: options?.homeDir
|
|
4832
|
+
});
|
|
4833
|
+
const results = [];
|
|
4834
|
+
let ok = true;
|
|
4835
|
+
for (const t of targets) {
|
|
4836
|
+
const loaded = await readSettingsJson(t.path);
|
|
4837
|
+
if ("error" in loaded) {
|
|
4838
|
+
ok = false;
|
|
4839
|
+
results.push({
|
|
4840
|
+
target: t.target,
|
|
4841
|
+
path: t.path,
|
|
4842
|
+
exists: loaded.exists,
|
|
4843
|
+
enabled: false,
|
|
4844
|
+
status: "error",
|
|
4845
|
+
commands: [],
|
|
4846
|
+
error: loaded.error
|
|
4847
|
+
});
|
|
4848
|
+
continue;
|
|
4849
|
+
}
|
|
4850
|
+
const root = structuredClone(loaded.data);
|
|
4851
|
+
const rawHooks = root["hooks"];
|
|
4852
|
+
if (rawHooks !== void 0 && !isPlainObject(rawHooks)) {
|
|
4853
|
+
ok = false;
|
|
4854
|
+
results.push({
|
|
4855
|
+
target: t.target,
|
|
4856
|
+
path: t.path,
|
|
4857
|
+
exists: loaded.exists,
|
|
4858
|
+
enabled: false,
|
|
4859
|
+
status: "error",
|
|
4860
|
+
commands: [],
|
|
4861
|
+
error: "`hooks` field must be a JSON object."
|
|
4862
|
+
});
|
|
4863
|
+
continue;
|
|
4864
|
+
}
|
|
4865
|
+
const hooksObj = isPlainObject(rawHooks) ? rawHooks : {};
|
|
4866
|
+
const rawEventHooks = hooksObj[hookEventKey];
|
|
4867
|
+
if (rawEventHooks !== void 0 && !Array.isArray(rawEventHooks)) {
|
|
4868
|
+
ok = false;
|
|
4869
|
+
results.push({
|
|
4870
|
+
target: t.target,
|
|
4871
|
+
path: t.path,
|
|
4872
|
+
exists: loaded.exists,
|
|
4873
|
+
enabled: false,
|
|
4874
|
+
status: "error",
|
|
4875
|
+
commands: [],
|
|
4876
|
+
error: `\`hooks.${hookEventKey}\` field must be a JSON array.`
|
|
4877
|
+
});
|
|
4878
|
+
continue;
|
|
4879
|
+
}
|
|
4880
|
+
const eventArr = Array.isArray(rawEventHooks) ? rawEventHooks : [];
|
|
4881
|
+
const existingCommands = collectMatchingHookCommands(eventArr, isMatchingCommand);
|
|
4882
|
+
if (existingCommands.length > 0) {
|
|
4883
|
+
let changed = false;
|
|
4884
|
+
for (const entry of eventArr) {
|
|
4885
|
+
if (!isPlainObject(entry) || !Array.isArray(entry["hooks"])) {
|
|
4886
|
+
continue;
|
|
4887
|
+
}
|
|
4888
|
+
for (const h of entry["hooks"]) {
|
|
4889
|
+
if (isPlainObject(h) && isMatchingCommand(h["command"])) {
|
|
4890
|
+
if (h["command"] !== command) {
|
|
4891
|
+
h["command"] = command;
|
|
4892
|
+
changed = true;
|
|
4893
|
+
}
|
|
4894
|
+
if (kind === "record" && h["timeout"] !== 3e3) {
|
|
4895
|
+
h["timeout"] = 3e3;
|
|
4896
|
+
changed = true;
|
|
4897
|
+
}
|
|
4898
|
+
}
|
|
4899
|
+
}
|
|
4900
|
+
}
|
|
4901
|
+
if (changed && !dryRun) {
|
|
4902
|
+
await writeSettingsJson(t.path, root);
|
|
4903
|
+
}
|
|
4904
|
+
results.push({
|
|
4905
|
+
target: t.target,
|
|
4906
|
+
path: t.path,
|
|
4907
|
+
exists: loaded.exists,
|
|
4908
|
+
enabled: true,
|
|
4909
|
+
status: changed ? "updated" : "unchanged",
|
|
4910
|
+
commands: changed ? [command] : existingCommands
|
|
4911
|
+
});
|
|
4912
|
+
continue;
|
|
4913
|
+
}
|
|
4914
|
+
if (kind === "record") {
|
|
4915
|
+
eventArr.push({
|
|
4916
|
+
matcher: ".*",
|
|
4917
|
+
hooks: [
|
|
4918
|
+
{
|
|
4919
|
+
type: "command",
|
|
4920
|
+
command,
|
|
4921
|
+
timeout: 3e3
|
|
4922
|
+
}
|
|
4923
|
+
]
|
|
4924
|
+
});
|
|
4925
|
+
} else {
|
|
4926
|
+
eventArr.push({
|
|
4927
|
+
hooks: [
|
|
4928
|
+
{
|
|
4929
|
+
type: "command",
|
|
4930
|
+
command
|
|
4931
|
+
}
|
|
4932
|
+
]
|
|
4933
|
+
});
|
|
4934
|
+
}
|
|
4935
|
+
hooksObj[hookEventKey] = eventArr;
|
|
4936
|
+
root["hooks"] = hooksObj;
|
|
4937
|
+
if (!dryRun) {
|
|
4938
|
+
await writeSettingsJson(t.path, root);
|
|
4939
|
+
}
|
|
4940
|
+
results.push({
|
|
4941
|
+
target: t.target,
|
|
4942
|
+
path: t.path,
|
|
4943
|
+
exists: loaded.exists,
|
|
4944
|
+
enabled: true,
|
|
4945
|
+
status: "enabled",
|
|
4946
|
+
commands: [command]
|
|
4947
|
+
});
|
|
4948
|
+
}
|
|
4949
|
+
return {
|
|
4950
|
+
action: "enable",
|
|
4951
|
+
kind,
|
|
4952
|
+
dry_run: dryRun,
|
|
4953
|
+
command,
|
|
4954
|
+
targets: results,
|
|
4955
|
+
ok
|
|
4956
|
+
};
|
|
4957
|
+
}
|
|
4958
|
+
async function runHookDisable(options) {
|
|
4959
|
+
const kind = options?.kind ?? "stop";
|
|
4960
|
+
const hookEventKey = kind === "record" ? "PostInvocation" : "Stop";
|
|
4961
|
+
const isMatchingCommand = kind === "record" ? isAgycraftHookRecordCommand : isAgycraftHookCheckCommand;
|
|
4962
|
+
const dryRun = Boolean(options?.dryRun);
|
|
4963
|
+
const targets = resolveTargetSettingsPaths({
|
|
4964
|
+
kind,
|
|
4965
|
+
target: options?.target,
|
|
4966
|
+
settingsPath: options?.settingsPath,
|
|
4967
|
+
homeDir: options?.homeDir
|
|
4968
|
+
});
|
|
4969
|
+
const results = [];
|
|
4970
|
+
let ok = true;
|
|
4971
|
+
for (const t of targets) {
|
|
4972
|
+
const loaded = await readSettingsJson(t.path);
|
|
4973
|
+
if ("error" in loaded) {
|
|
4974
|
+
ok = false;
|
|
4975
|
+
results.push({
|
|
4976
|
+
target: t.target,
|
|
4977
|
+
path: t.path,
|
|
4978
|
+
exists: loaded.exists,
|
|
4979
|
+
enabled: false,
|
|
4980
|
+
status: "error",
|
|
4981
|
+
commands: [],
|
|
4982
|
+
error: loaded.error
|
|
4983
|
+
});
|
|
4984
|
+
continue;
|
|
4985
|
+
}
|
|
4986
|
+
if (!loaded.exists) {
|
|
4987
|
+
results.push({
|
|
4988
|
+
target: t.target,
|
|
4989
|
+
path: t.path,
|
|
4990
|
+
exists: false,
|
|
4991
|
+
enabled: false,
|
|
4992
|
+
status: "not_found",
|
|
4993
|
+
commands: []
|
|
4994
|
+
});
|
|
4995
|
+
continue;
|
|
4996
|
+
}
|
|
4997
|
+
const root = structuredClone(loaded.data);
|
|
4998
|
+
const rawHooks = root["hooks"];
|
|
4999
|
+
if (rawHooks === void 0) {
|
|
5000
|
+
results.push({
|
|
5001
|
+
target: t.target,
|
|
5002
|
+
path: t.path,
|
|
5003
|
+
exists: true,
|
|
5004
|
+
enabled: false,
|
|
5005
|
+
status: "already_disabled",
|
|
5006
|
+
commands: []
|
|
5007
|
+
});
|
|
5008
|
+
continue;
|
|
5009
|
+
}
|
|
5010
|
+
if (!isPlainObject(rawHooks)) {
|
|
5011
|
+
ok = false;
|
|
5012
|
+
results.push({
|
|
5013
|
+
target: t.target,
|
|
5014
|
+
path: t.path,
|
|
5015
|
+
exists: true,
|
|
5016
|
+
enabled: false,
|
|
5017
|
+
status: "error",
|
|
5018
|
+
commands: [],
|
|
5019
|
+
error: "`hooks` field must be a JSON object."
|
|
5020
|
+
});
|
|
5021
|
+
continue;
|
|
5022
|
+
}
|
|
5023
|
+
const rawEventHooks = rawHooks[hookEventKey];
|
|
5024
|
+
if (rawEventHooks === void 0) {
|
|
5025
|
+
results.push({
|
|
5026
|
+
target: t.target,
|
|
5027
|
+
path: t.path,
|
|
5028
|
+
exists: true,
|
|
5029
|
+
enabled: false,
|
|
5030
|
+
status: "already_disabled",
|
|
5031
|
+
commands: []
|
|
5032
|
+
});
|
|
5033
|
+
continue;
|
|
5034
|
+
}
|
|
5035
|
+
if (!Array.isArray(rawEventHooks)) {
|
|
5036
|
+
ok = false;
|
|
5037
|
+
results.push({
|
|
5038
|
+
target: t.target,
|
|
5039
|
+
path: t.path,
|
|
5040
|
+
exists: true,
|
|
5041
|
+
enabled: false,
|
|
5042
|
+
status: "error",
|
|
5043
|
+
commands: [],
|
|
5044
|
+
error: `\`hooks.${hookEventKey}\` field must be a JSON array.`
|
|
5045
|
+
});
|
|
5046
|
+
continue;
|
|
5047
|
+
}
|
|
5048
|
+
const removedCommands = [];
|
|
5049
|
+
const nextEventHooks = [];
|
|
5050
|
+
for (const entry of rawEventHooks) {
|
|
5051
|
+
if (!isPlainObject(entry) || !Array.isArray(entry["hooks"])) {
|
|
5052
|
+
nextEventHooks.push(entry);
|
|
5053
|
+
continue;
|
|
5054
|
+
}
|
|
5055
|
+
const keptHooks = [];
|
|
5056
|
+
let entryHadMatch = false;
|
|
5057
|
+
for (const h of entry["hooks"]) {
|
|
5058
|
+
if (isPlainObject(h) && isMatchingCommand(h["command"])) {
|
|
5059
|
+
removedCommands.push(h["command"]);
|
|
5060
|
+
entryHadMatch = true;
|
|
5061
|
+
} else {
|
|
5062
|
+
keptHooks.push(h);
|
|
5063
|
+
}
|
|
5064
|
+
}
|
|
5065
|
+
if (!entryHadMatch) {
|
|
5066
|
+
nextEventHooks.push(entry);
|
|
5067
|
+
} else if (keptHooks.length > 0) {
|
|
5068
|
+
nextEventHooks.push({
|
|
5069
|
+
...entry,
|
|
5070
|
+
hooks: keptHooks
|
|
5071
|
+
});
|
|
5072
|
+
}
|
|
5073
|
+
}
|
|
5074
|
+
if (removedCommands.length === 0) {
|
|
5075
|
+
results.push({
|
|
5076
|
+
target: t.target,
|
|
5077
|
+
path: t.path,
|
|
5078
|
+
exists: true,
|
|
5079
|
+
enabled: false,
|
|
5080
|
+
status: "already_disabled",
|
|
5081
|
+
commands: []
|
|
5082
|
+
});
|
|
5083
|
+
continue;
|
|
5084
|
+
}
|
|
5085
|
+
if (nextEventHooks.length > 0) {
|
|
5086
|
+
rawHooks[hookEventKey] = nextEventHooks;
|
|
5087
|
+
} else {
|
|
5088
|
+
delete rawHooks[hookEventKey];
|
|
5089
|
+
}
|
|
5090
|
+
if (Object.keys(rawHooks).length === 0) {
|
|
5091
|
+
delete root["hooks"];
|
|
5092
|
+
}
|
|
5093
|
+
if (!dryRun) {
|
|
5094
|
+
await writeSettingsJson(t.path, root);
|
|
5095
|
+
}
|
|
5096
|
+
results.push({
|
|
5097
|
+
target: t.target,
|
|
5098
|
+
path: t.path,
|
|
5099
|
+
exists: true,
|
|
5100
|
+
enabled: false,
|
|
5101
|
+
status: "disabled",
|
|
5102
|
+
commands: removedCommands
|
|
5103
|
+
});
|
|
5104
|
+
}
|
|
5105
|
+
return {
|
|
5106
|
+
action: "disable",
|
|
5107
|
+
kind,
|
|
5108
|
+
dry_run: dryRun,
|
|
5109
|
+
targets: results,
|
|
5110
|
+
ok
|
|
5111
|
+
};
|
|
5112
|
+
}
|
|
5113
|
+
async function runHookStatus(options) {
|
|
5114
|
+
const kind = options?.kind ?? "stop";
|
|
5115
|
+
const hookEventKey = kind === "record" ? "PostInvocation" : "Stop";
|
|
5116
|
+
const isMatchingCommand = kind === "record" ? isAgycraftHookRecordCommand : isAgycraftHookCheckCommand;
|
|
5117
|
+
const targets = resolveTargetSettingsPaths({
|
|
5118
|
+
kind,
|
|
5119
|
+
target: options?.target,
|
|
5120
|
+
settingsPath: options?.settingsPath,
|
|
5121
|
+
homeDir: options?.homeDir
|
|
5122
|
+
});
|
|
5123
|
+
const results = [];
|
|
5124
|
+
let ok = true;
|
|
5125
|
+
for (const t of targets) {
|
|
5126
|
+
const loaded = await readSettingsJson(t.path);
|
|
5127
|
+
if ("error" in loaded) {
|
|
5128
|
+
ok = false;
|
|
5129
|
+
results.push({
|
|
5130
|
+
target: t.target,
|
|
5131
|
+
path: t.path,
|
|
5132
|
+
exists: loaded.exists,
|
|
5133
|
+
enabled: false,
|
|
5134
|
+
status: "error",
|
|
5135
|
+
commands: [],
|
|
5136
|
+
error: loaded.error
|
|
5137
|
+
});
|
|
5138
|
+
continue;
|
|
5139
|
+
}
|
|
5140
|
+
if (!loaded.exists) {
|
|
5141
|
+
results.push({
|
|
5142
|
+
target: t.target,
|
|
5143
|
+
path: t.path,
|
|
5144
|
+
exists: false,
|
|
5145
|
+
enabled: false,
|
|
5146
|
+
status: "not_found",
|
|
5147
|
+
commands: []
|
|
5148
|
+
});
|
|
5149
|
+
continue;
|
|
5150
|
+
}
|
|
5151
|
+
const rawHooks = loaded.data["hooks"];
|
|
5152
|
+
if (rawHooks !== void 0 && !isPlainObject(rawHooks)) {
|
|
5153
|
+
ok = false;
|
|
5154
|
+
results.push({
|
|
5155
|
+
target: t.target,
|
|
5156
|
+
path: t.path,
|
|
5157
|
+
exists: true,
|
|
5158
|
+
enabled: false,
|
|
5159
|
+
status: "error",
|
|
5160
|
+
commands: [],
|
|
5161
|
+
error: "`hooks` field must be a JSON object."
|
|
5162
|
+
});
|
|
5163
|
+
continue;
|
|
5164
|
+
}
|
|
5165
|
+
const rawEventHooks = isPlainObject(rawHooks) ? rawHooks[hookEventKey] : void 0;
|
|
5166
|
+
if (rawEventHooks !== void 0 && !Array.isArray(rawEventHooks)) {
|
|
5167
|
+
ok = false;
|
|
5168
|
+
results.push({
|
|
5169
|
+
target: t.target,
|
|
5170
|
+
path: t.path,
|
|
5171
|
+
exists: true,
|
|
5172
|
+
enabled: false,
|
|
5173
|
+
status: "error",
|
|
5174
|
+
commands: [],
|
|
5175
|
+
error: `\`hooks.${hookEventKey}\` field must be a JSON array.`
|
|
5176
|
+
});
|
|
5177
|
+
continue;
|
|
5178
|
+
}
|
|
5179
|
+
const commands = Array.isArray(rawEventHooks) ? collectMatchingHookCommands(rawEventHooks, isMatchingCommand) : [];
|
|
5180
|
+
const enabled = commands.length > 0;
|
|
5181
|
+
results.push({
|
|
5182
|
+
target: t.target,
|
|
5183
|
+
path: t.path,
|
|
5184
|
+
exists: true,
|
|
5185
|
+
enabled,
|
|
5186
|
+
status: enabled ? "active" : "inactive",
|
|
5187
|
+
commands
|
|
5188
|
+
});
|
|
5189
|
+
}
|
|
5190
|
+
return {
|
|
5191
|
+
action: "status",
|
|
5192
|
+
kind,
|
|
5193
|
+
dry_run: false,
|
|
5194
|
+
targets: results,
|
|
5195
|
+
ok
|
|
5196
|
+
};
|
|
5197
|
+
}
|
|
5198
|
+
function formatHookManageResult(result) {
|
|
5199
|
+
const lines = [];
|
|
5200
|
+
const dryPrefix = result.dry_run ? "[dry-run] " : "";
|
|
5201
|
+
const kindSuffix = result.kind === "record" ? " (kind: record)" : "";
|
|
5202
|
+
lines.push(`${dryPrefix}agycraft-mcp hook ${result.action}${kindSuffix}`);
|
|
5203
|
+
for (const t of result.targets) {
|
|
5204
|
+
if (t.status === "error") {
|
|
5205
|
+
lines.push(` [${t.target}] ERROR (${t.path}): ${t.error}`);
|
|
5206
|
+
continue;
|
|
5207
|
+
}
|
|
5208
|
+
const cmdInfo = t.commands.length > 0 ? ` -> ${t.commands.join(", ")}` : "";
|
|
5209
|
+
lines.push(` [${t.target}] ${t.status} (${t.path})${cmdInfo}`);
|
|
5210
|
+
}
|
|
5211
|
+
return lines.join("\n");
|
|
5212
|
+
}
|
|
5213
|
+
|
|
5214
|
+
// src/cli/ignore-manage.ts
|
|
5215
|
+
import { existsSync as existsSync3 } from "fs";
|
|
5216
|
+
import { mkdir as mkdir5, readFile as readFile9, writeFile as writeFile5 } from "fs/promises";
|
|
5217
|
+
import { dirname as dirname5, join as join10, resolve as resolve6 } from "path";
|
|
5218
|
+
function extractIgnoreRules(content) {
|
|
5219
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5220
|
+
const rules = [];
|
|
5221
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
5222
|
+
const trimmed = rawLine.trim();
|
|
5223
|
+
if (!trimmed || trimmed.startsWith("#")) {
|
|
5224
|
+
continue;
|
|
5225
|
+
}
|
|
5226
|
+
if (!seen.has(trimmed)) {
|
|
5227
|
+
seen.add(trimmed);
|
|
5228
|
+
rules.push(trimmed);
|
|
5229
|
+
}
|
|
5230
|
+
}
|
|
5231
|
+
return rules;
|
|
5232
|
+
}
|
|
5233
|
+
async function runIgnoreInit(options = {}) {
|
|
5234
|
+
const targetDir = resolve6(options.dir ?? process.cwd());
|
|
5235
|
+
const targetPath = join10(targetDir, ".geminiignore");
|
|
5236
|
+
const dryRun = Boolean(options.dryRun);
|
|
5237
|
+
const templateRules = extractIgnoreRules(GEMINIIGNORE_TEMPLATE);
|
|
5238
|
+
try {
|
|
5239
|
+
if (!existsSync3(targetPath)) {
|
|
5240
|
+
const content = GEMINIIGNORE_TEMPLATE.endsWith("\n") ? GEMINIIGNORE_TEMPLATE : `${GEMINIIGNORE_TEMPLATE}
|
|
5241
|
+
`;
|
|
5242
|
+
if (!dryRun) {
|
|
5243
|
+
await mkdir5(dirname5(targetPath), { recursive: true });
|
|
5244
|
+
await writeFile5(targetPath, content, "utf8");
|
|
5245
|
+
}
|
|
5246
|
+
return {
|
|
5247
|
+
ok: true,
|
|
5248
|
+
status: "created",
|
|
5249
|
+
target_path: targetPath,
|
|
5250
|
+
added_rules: templateRules,
|
|
5251
|
+
dry_run: dryRun,
|
|
5252
|
+
message: dryRun ? `Would create ${targetPath} with ${templateRules.length} template rules.` : `Created ${targetPath} with ${templateRules.length} template rules.`
|
|
5253
|
+
};
|
|
5254
|
+
}
|
|
5255
|
+
const existingContent = await readFile9(targetPath, "utf8");
|
|
5256
|
+
const existingRules = new Set(extractIgnoreRules(existingContent));
|
|
5257
|
+
const missingRules = templateRules.filter((rule) => !existingRules.has(rule));
|
|
5258
|
+
if (missingRules.length === 0) {
|
|
5259
|
+
return {
|
|
5260
|
+
ok: true,
|
|
5261
|
+
status: "unchanged",
|
|
5262
|
+
target_path: targetPath,
|
|
5263
|
+
added_rules: [],
|
|
5264
|
+
dry_run: dryRun,
|
|
5265
|
+
message: `All template rules are already present in ${targetPath}.`
|
|
5266
|
+
};
|
|
5267
|
+
}
|
|
5268
|
+
const prefix = existingContent.length === 0 ? "" : existingContent.endsWith("\n\n") || existingContent.endsWith("\r\n\r\n") ? "" : existingContent.endsWith("\n") ? "\n" : "\n\n";
|
|
5269
|
+
const appendBlock = `${prefix}# Added by agycraft-mcp ignore init
|
|
5270
|
+
${missingRules.join("\n")}
|
|
5271
|
+
`;
|
|
5272
|
+
const nextContent = `${existingContent}${appendBlock}`;
|
|
5273
|
+
if (!dryRun) {
|
|
5274
|
+
await writeFile5(targetPath, nextContent, "utf8");
|
|
5275
|
+
}
|
|
5276
|
+
return {
|
|
5277
|
+
ok: true,
|
|
5278
|
+
status: "updated",
|
|
5279
|
+
target_path: targetPath,
|
|
5280
|
+
added_rules: missingRules,
|
|
5281
|
+
dry_run: dryRun,
|
|
5282
|
+
message: dryRun ? `Would append ${missingRules.length} missing rule(s) to ${targetPath}.` : `Appended ${missingRules.length} missing rule(s) to ${targetPath}.`
|
|
5283
|
+
};
|
|
5284
|
+
} catch (err) {
|
|
5285
|
+
return {
|
|
5286
|
+
ok: false,
|
|
5287
|
+
status: "error",
|
|
5288
|
+
target_path: targetPath,
|
|
5289
|
+
added_rules: [],
|
|
5290
|
+
dry_run: dryRun,
|
|
5291
|
+
message: err instanceof Error ? err.message : String(err)
|
|
5292
|
+
};
|
|
5293
|
+
}
|
|
5294
|
+
}
|
|
5295
|
+
function formatIgnoreInitResult(result, json = false) {
|
|
5296
|
+
if (json) {
|
|
5297
|
+
return JSON.stringify(result, null, 2);
|
|
5298
|
+
}
|
|
5299
|
+
const lines = [];
|
|
5300
|
+
const dryPrefix = result.dry_run ? "[dry-run] " : "";
|
|
5301
|
+
lines.push(`${dryPrefix}agycraft-mcp ignore init`);
|
|
5302
|
+
lines.push(` status: ${result.status}`);
|
|
5303
|
+
lines.push(` target: ${result.target_path}`);
|
|
5304
|
+
lines.push(` added_rules: ${result.added_rules.length}`);
|
|
5305
|
+
if (result.added_rules.length > 0) {
|
|
5306
|
+
for (const rule of result.added_rules) {
|
|
5307
|
+
lines.push(` + ${rule}`);
|
|
5308
|
+
}
|
|
5309
|
+
}
|
|
5310
|
+
lines.push(` message: ${result.message}`);
|
|
5311
|
+
return lines.join("\n");
|
|
5312
|
+
}
|
|
5313
|
+
|
|
5314
|
+
// src/cli/telemetry-manage.ts
|
|
5315
|
+
import { mkdir as mkdir6, readFile as readFile10, writeFile as writeFile6 } from "fs/promises";
|
|
5316
|
+
import { homedir as homedir5 } from "os";
|
|
5317
|
+
import { dirname as dirname6, join as join11, resolve as resolve7 } from "path";
|
|
5318
|
+
var DEFAULT_GEMINI_TELEMETRY_OUTFILE = "~/.gemini/telemetry_stats.jsonl";
|
|
5319
|
+
function isPlainObject2(value) {
|
|
5320
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5321
|
+
}
|
|
5322
|
+
function resolveTelemetrySettingsPath(options) {
|
|
5323
|
+
if (options?.settingsPath && options.settingsPath.trim().length > 0) {
|
|
5324
|
+
return resolve7(options.settingsPath.trim());
|
|
5325
|
+
}
|
|
5326
|
+
const home = options?.homeDir ?? homedir5();
|
|
5327
|
+
return join11(home, ".gemini", "settings.json");
|
|
5328
|
+
}
|
|
5329
|
+
function resolveTelemetryOutfile(outfile) {
|
|
5330
|
+
if (outfile && outfile.trim().length > 0) {
|
|
5331
|
+
return outfile.trim();
|
|
5332
|
+
}
|
|
5333
|
+
const envOverride = process.env.AGYCRAFT_GEMINI_OTEL_PATH;
|
|
5334
|
+
if (envOverride && envOverride.trim().length > 0) {
|
|
5335
|
+
return getDefaultGeminiTelemetryPath();
|
|
5336
|
+
}
|
|
5337
|
+
return DEFAULT_GEMINI_TELEMETRY_OUTFILE;
|
|
5338
|
+
}
|
|
5339
|
+
function buildSafeTelemetryConfig(options) {
|
|
5340
|
+
return {
|
|
5341
|
+
enabled: true,
|
|
5342
|
+
target: "local",
|
|
5343
|
+
otlpEndpoint: "",
|
|
5344
|
+
logPrompts: false,
|
|
5345
|
+
outfile: resolveTelemetryOutfile(options?.outfile)
|
|
5346
|
+
};
|
|
5347
|
+
}
|
|
5348
|
+
async function readSettingsJson2(filePath) {
|
|
5349
|
+
let raw;
|
|
5350
|
+
try {
|
|
5351
|
+
raw = await readFile10(filePath, "utf8");
|
|
5352
|
+
} catch (err) {
|
|
5353
|
+
const code = err?.code;
|
|
5354
|
+
if (code === "ENOENT") {
|
|
5355
|
+
return { exists: false, data: {} };
|
|
5356
|
+
}
|
|
5357
|
+
return {
|
|
5358
|
+
exists: true,
|
|
5359
|
+
error: err instanceof Error ? err.message : String(err)
|
|
5360
|
+
};
|
|
5361
|
+
}
|
|
5362
|
+
if (raw.trim().length === 0) {
|
|
5363
|
+
return { exists: true, data: {} };
|
|
5364
|
+
}
|
|
5365
|
+
try {
|
|
5366
|
+
const parsed = JSON.parse(raw);
|
|
5367
|
+
if (!isPlainObject2(parsed)) {
|
|
5368
|
+
return {
|
|
5369
|
+
exists: true,
|
|
5370
|
+
error: "settings.json root must be a JSON object."
|
|
5371
|
+
};
|
|
5372
|
+
}
|
|
5373
|
+
return { exists: true, data: parsed };
|
|
5374
|
+
} catch (err) {
|
|
5375
|
+
return {
|
|
5376
|
+
exists: true,
|
|
5377
|
+
error: `Invalid JSON in ${filePath}: ${err instanceof Error ? err.message : String(err)}`
|
|
5378
|
+
};
|
|
5379
|
+
}
|
|
5380
|
+
}
|
|
5381
|
+
async function writeSettingsJson2(filePath, data) {
|
|
5382
|
+
await mkdir6(dirname6(filePath), { recursive: true });
|
|
5383
|
+
await writeFile6(filePath, `${JSON.stringify(data, null, 2)}
|
|
5384
|
+
`, "utf8");
|
|
5385
|
+
}
|
|
5386
|
+
async function runTelemetryEnable(options) {
|
|
5387
|
+
const dryRun = Boolean(options?.dryRun);
|
|
5388
|
+
const settingsPath = resolveTelemetrySettingsPath({
|
|
5389
|
+
settingsPath: options?.settingsPath,
|
|
5390
|
+
homeDir: options?.homeDir
|
|
5391
|
+
});
|
|
5392
|
+
const loaded = await readSettingsJson2(settingsPath);
|
|
5393
|
+
if ("error" in loaded) {
|
|
5394
|
+
return {
|
|
5395
|
+
action: "enable",
|
|
5396
|
+
dry_run: dryRun,
|
|
5397
|
+
path: settingsPath,
|
|
5398
|
+
exists: loaded.exists,
|
|
5399
|
+
enabled: false,
|
|
5400
|
+
safe: false,
|
|
5401
|
+
log_prompts_safe: false,
|
|
5402
|
+
outfile: null,
|
|
5403
|
+
status: "error",
|
|
5404
|
+
message: loaded.error,
|
|
5405
|
+
error: loaded.error,
|
|
5406
|
+
ok: false
|
|
5407
|
+
};
|
|
5408
|
+
}
|
|
5409
|
+
const root = structuredClone(loaded.data);
|
|
5410
|
+
const rawTelemetry = root["telemetry"];
|
|
5411
|
+
if (rawTelemetry !== void 0 && !isPlainObject2(rawTelemetry)) {
|
|
5412
|
+
const errMsg = "`telemetry` field must be a JSON object.";
|
|
5413
|
+
return {
|
|
5414
|
+
action: "enable",
|
|
5415
|
+
dry_run: dryRun,
|
|
5416
|
+
path: settingsPath,
|
|
5417
|
+
exists: loaded.exists,
|
|
5418
|
+
enabled: false,
|
|
5419
|
+
safe: false,
|
|
5420
|
+
log_prompts_safe: false,
|
|
5421
|
+
outfile: null,
|
|
5422
|
+
status: "error",
|
|
5423
|
+
message: errMsg,
|
|
5424
|
+
error: errMsg,
|
|
5425
|
+
ok: false
|
|
5426
|
+
};
|
|
5427
|
+
}
|
|
5428
|
+
const safeConfig = buildSafeTelemetryConfig({ outfile: options?.outfile });
|
|
5429
|
+
if (rawTelemetry === void 0) {
|
|
5430
|
+
root["telemetry"] = safeConfig;
|
|
5431
|
+
if (!dryRun) {
|
|
5432
|
+
await writeSettingsJson2(settingsPath, root);
|
|
5433
|
+
}
|
|
5434
|
+
return {
|
|
5435
|
+
action: "enable",
|
|
5436
|
+
dry_run: dryRun,
|
|
5437
|
+
path: settingsPath,
|
|
5438
|
+
exists: loaded.exists,
|
|
5439
|
+
enabled: true,
|
|
5440
|
+
safe: true,
|
|
5441
|
+
log_prompts_safe: true,
|
|
5442
|
+
outfile: safeConfig.outfile,
|
|
5443
|
+
status: "enabled",
|
|
5444
|
+
message: `Enabled privacy-safe local telemetry in ${settingsPath} (logPrompts=false).`,
|
|
5445
|
+
telemetry: safeConfig,
|
|
5446
|
+
ok: true
|
|
5447
|
+
};
|
|
5448
|
+
}
|
|
5449
|
+
const nextTelemetry = {
|
|
5450
|
+
...rawTelemetry,
|
|
5451
|
+
enabled: safeConfig.enabled,
|
|
5452
|
+
target: safeConfig.target,
|
|
5453
|
+
otlpEndpoint: safeConfig.otlpEndpoint,
|
|
5454
|
+
logPrompts: safeConfig.logPrompts,
|
|
5455
|
+
outfile: safeConfig.outfile
|
|
5456
|
+
};
|
|
5457
|
+
const changed = rawTelemetry["enabled"] !== safeConfig.enabled || rawTelemetry["target"] !== safeConfig.target || rawTelemetry["otlpEndpoint"] !== safeConfig.otlpEndpoint || rawTelemetry["logPrompts"] !== safeConfig.logPrompts || rawTelemetry["outfile"] !== safeConfig.outfile;
|
|
5458
|
+
if (!changed) {
|
|
5459
|
+
return {
|
|
5460
|
+
action: "enable",
|
|
5461
|
+
dry_run: dryRun,
|
|
5462
|
+
path: settingsPath,
|
|
5463
|
+
exists: loaded.exists,
|
|
5464
|
+
enabled: true,
|
|
5465
|
+
safe: true,
|
|
5466
|
+
log_prompts_safe: true,
|
|
5467
|
+
outfile: safeConfig.outfile,
|
|
5468
|
+
status: "unchanged",
|
|
5469
|
+
message: `Privacy-safe local telemetry is already configured in ${settingsPath}.`,
|
|
5470
|
+
telemetry: nextTelemetry,
|
|
5471
|
+
ok: true
|
|
5472
|
+
};
|
|
5473
|
+
}
|
|
5474
|
+
root["telemetry"] = nextTelemetry;
|
|
5475
|
+
if (!dryRun) {
|
|
5476
|
+
await writeSettingsJson2(settingsPath, root);
|
|
5477
|
+
}
|
|
5478
|
+
return {
|
|
5479
|
+
action: "enable",
|
|
5480
|
+
dry_run: dryRun,
|
|
5481
|
+
path: settingsPath,
|
|
5482
|
+
exists: loaded.exists,
|
|
5483
|
+
enabled: true,
|
|
5484
|
+
safe: true,
|
|
5485
|
+
log_prompts_safe: true,
|
|
5486
|
+
outfile: safeConfig.outfile,
|
|
5487
|
+
status: "updated",
|
|
5488
|
+
message: `Updated telemetry config in ${settingsPath} with privacy-safe defaults (logPrompts=false).`,
|
|
5489
|
+
telemetry: nextTelemetry,
|
|
5490
|
+
ok: true
|
|
5491
|
+
};
|
|
5492
|
+
}
|
|
5493
|
+
async function runTelemetryDisable(options) {
|
|
5494
|
+
const dryRun = Boolean(options?.dryRun);
|
|
5495
|
+
const settingsPath = resolveTelemetrySettingsPath({
|
|
5496
|
+
settingsPath: options?.settingsPath,
|
|
5497
|
+
homeDir: options?.homeDir
|
|
5498
|
+
});
|
|
5499
|
+
const loaded = await readSettingsJson2(settingsPath);
|
|
5500
|
+
if ("error" in loaded) {
|
|
5501
|
+
return {
|
|
5502
|
+
action: "disable",
|
|
5503
|
+
dry_run: dryRun,
|
|
5504
|
+
path: settingsPath,
|
|
5505
|
+
exists: loaded.exists,
|
|
5506
|
+
enabled: false,
|
|
5507
|
+
safe: false,
|
|
5508
|
+
log_prompts_safe: false,
|
|
5509
|
+
outfile: null,
|
|
5510
|
+
status: "error",
|
|
5511
|
+
message: loaded.error,
|
|
5512
|
+
error: loaded.error,
|
|
5513
|
+
ok: false
|
|
5514
|
+
};
|
|
5515
|
+
}
|
|
5516
|
+
if (!loaded.exists) {
|
|
5517
|
+
return {
|
|
5518
|
+
action: "disable",
|
|
5519
|
+
dry_run: dryRun,
|
|
5520
|
+
path: settingsPath,
|
|
5521
|
+
exists: false,
|
|
5522
|
+
enabled: false,
|
|
5523
|
+
safe: true,
|
|
5524
|
+
log_prompts_safe: true,
|
|
5525
|
+
outfile: null,
|
|
5526
|
+
status: "not_found",
|
|
5527
|
+
message: `Settings file not found (${settingsPath}); nothing to disable.`,
|
|
5528
|
+
telemetry: null,
|
|
5529
|
+
ok: true
|
|
5530
|
+
};
|
|
5531
|
+
}
|
|
5532
|
+
const root = structuredClone(loaded.data);
|
|
5533
|
+
const rawTelemetry = root["telemetry"];
|
|
5534
|
+
if (rawTelemetry === void 0) {
|
|
5535
|
+
return {
|
|
5536
|
+
action: "disable",
|
|
5537
|
+
dry_run: dryRun,
|
|
5538
|
+
path: settingsPath,
|
|
5539
|
+
exists: true,
|
|
5540
|
+
enabled: false,
|
|
5541
|
+
safe: true,
|
|
5542
|
+
log_prompts_safe: true,
|
|
5543
|
+
outfile: null,
|
|
5544
|
+
status: "already_disabled",
|
|
5545
|
+
message: `Telemetry is already absent/disabled in ${settingsPath}; no changes made.`,
|
|
5546
|
+
telemetry: null,
|
|
5547
|
+
ok: true
|
|
5548
|
+
};
|
|
5549
|
+
}
|
|
5550
|
+
if (!isPlainObject2(rawTelemetry)) {
|
|
5551
|
+
const errMsg = "`telemetry` field must be a JSON object.";
|
|
5552
|
+
return {
|
|
5553
|
+
action: "disable",
|
|
5554
|
+
dry_run: dryRun,
|
|
5555
|
+
path: settingsPath,
|
|
5556
|
+
exists: true,
|
|
5557
|
+
enabled: false,
|
|
5558
|
+
safe: false,
|
|
5559
|
+
log_prompts_safe: false,
|
|
5560
|
+
outfile: null,
|
|
5561
|
+
status: "error",
|
|
5562
|
+
message: errMsg,
|
|
5563
|
+
error: errMsg,
|
|
5564
|
+
ok: false
|
|
5565
|
+
};
|
|
5566
|
+
}
|
|
5567
|
+
delete root["telemetry"];
|
|
5568
|
+
if (!dryRun) {
|
|
5569
|
+
await writeSettingsJson2(settingsPath, root);
|
|
5570
|
+
}
|
|
5571
|
+
return {
|
|
5572
|
+
action: "disable",
|
|
5573
|
+
dry_run: dryRun,
|
|
5574
|
+
path: settingsPath,
|
|
5575
|
+
exists: true,
|
|
5576
|
+
enabled: false,
|
|
5577
|
+
safe: true,
|
|
5578
|
+
log_prompts_safe: true,
|
|
5579
|
+
outfile: null,
|
|
5580
|
+
status: "disabled",
|
|
5581
|
+
message: `Removed top-level \`telemetry\` field from ${settingsPath}; all other settings preserved.`,
|
|
5582
|
+
telemetry: null,
|
|
5583
|
+
ok: true
|
|
5584
|
+
};
|
|
5585
|
+
}
|
|
5586
|
+
async function runTelemetryStatus(options) {
|
|
5587
|
+
const settingsPath = resolveTelemetrySettingsPath({
|
|
5588
|
+
settingsPath: options?.settingsPath,
|
|
5589
|
+
homeDir: options?.homeDir
|
|
5590
|
+
});
|
|
5591
|
+
const loaded = await readSettingsJson2(settingsPath);
|
|
5592
|
+
if ("error" in loaded) {
|
|
5593
|
+
return {
|
|
5594
|
+
action: "status",
|
|
5595
|
+
dry_run: false,
|
|
5596
|
+
path: settingsPath,
|
|
5597
|
+
exists: loaded.exists,
|
|
5598
|
+
enabled: false,
|
|
5599
|
+
safe: false,
|
|
5600
|
+
log_prompts_safe: false,
|
|
5601
|
+
outfile: null,
|
|
5602
|
+
status: "error",
|
|
5603
|
+
message: loaded.error,
|
|
5604
|
+
error: loaded.error,
|
|
5605
|
+
ok: false
|
|
5606
|
+
};
|
|
5607
|
+
}
|
|
5608
|
+
if (!loaded.exists) {
|
|
5609
|
+
return {
|
|
5610
|
+
action: "status",
|
|
5611
|
+
dry_run: false,
|
|
5612
|
+
path: settingsPath,
|
|
5613
|
+
exists: false,
|
|
5614
|
+
enabled: false,
|
|
5615
|
+
safe: false,
|
|
5616
|
+
log_prompts_safe: true,
|
|
5617
|
+
outfile: null,
|
|
5618
|
+
status: "not_found",
|
|
5619
|
+
message: `Settings file not found (${settingsPath}).`,
|
|
5620
|
+
telemetry: null,
|
|
5621
|
+
ok: true
|
|
5622
|
+
};
|
|
5623
|
+
}
|
|
5624
|
+
const rawTelemetry = loaded.data["telemetry"];
|
|
5625
|
+
if (rawTelemetry === void 0) {
|
|
5626
|
+
return {
|
|
5627
|
+
action: "status",
|
|
5628
|
+
dry_run: false,
|
|
5629
|
+
path: settingsPath,
|
|
5630
|
+
exists: true,
|
|
5631
|
+
enabled: false,
|
|
5632
|
+
safe: true,
|
|
5633
|
+
log_prompts_safe: true,
|
|
5634
|
+
outfile: null,
|
|
5635
|
+
status: "inactive",
|
|
5636
|
+
message: `Telemetry is not configured in ${settingsPath}.`,
|
|
5637
|
+
telemetry: null,
|
|
5638
|
+
ok: true
|
|
5639
|
+
};
|
|
5640
|
+
}
|
|
5641
|
+
if (!isPlainObject2(rawTelemetry)) {
|
|
5642
|
+
const errMsg = "`telemetry` field must be a JSON object.";
|
|
5643
|
+
return {
|
|
5644
|
+
action: "status",
|
|
5645
|
+
dry_run: false,
|
|
5646
|
+
path: settingsPath,
|
|
5647
|
+
exists: true,
|
|
5648
|
+
enabled: false,
|
|
5649
|
+
safe: false,
|
|
5650
|
+
log_prompts_safe: false,
|
|
5651
|
+
outfile: null,
|
|
5652
|
+
status: "error",
|
|
5653
|
+
message: errMsg,
|
|
5654
|
+
error: errMsg,
|
|
5655
|
+
ok: false
|
|
5656
|
+
};
|
|
5657
|
+
}
|
|
5658
|
+
const enabled = rawTelemetry["enabled"] === true;
|
|
5659
|
+
const logPromptsSafe = rawTelemetry["logPrompts"] === false;
|
|
5660
|
+
const targetLocal = rawTelemetry["target"] === "local";
|
|
5661
|
+
const otlpEmpty = rawTelemetry["otlpEndpoint"] === "" || rawTelemetry["otlpEndpoint"] === void 0;
|
|
5662
|
+
const safe = logPromptsSafe && targetLocal && otlpEmpty;
|
|
5663
|
+
const outfile = typeof rawTelemetry["outfile"] === "string" && rawTelemetry["outfile"].trim().length > 0 ? rawTelemetry["outfile"].trim() : null;
|
|
5664
|
+
return {
|
|
5665
|
+
action: "status",
|
|
5666
|
+
dry_run: false,
|
|
5667
|
+
path: settingsPath,
|
|
5668
|
+
exists: true,
|
|
5669
|
+
enabled,
|
|
5670
|
+
safe,
|
|
5671
|
+
log_prompts_safe: logPromptsSafe,
|
|
5672
|
+
outfile,
|
|
5673
|
+
status: enabled ? "active" : "inactive",
|
|
5674
|
+
message: enabled ? `Telemetry is active in ${settingsPath} (logPrompts=${String(rawTelemetry["logPrompts"])}, outfile=${outfile ?? "unset"}).` : `Telemetry is inactive in ${settingsPath}.`,
|
|
5675
|
+
telemetry: rawTelemetry,
|
|
5676
|
+
ok: true
|
|
5677
|
+
};
|
|
5678
|
+
}
|
|
5679
|
+
function formatTelemetryManageResult(result) {
|
|
5680
|
+
const dryPrefix = result.dry_run ? "[dry-run] " : "";
|
|
5681
|
+
const lines = [`${dryPrefix}agycraft-mcp telemetry ${result.action}`];
|
|
5682
|
+
if (result.status === "error") {
|
|
5683
|
+
lines.push(` ERROR (${result.path}): ${result.error ?? result.message}`);
|
|
5684
|
+
return lines.join("\n");
|
|
5685
|
+
}
|
|
5686
|
+
lines.push(` status: ${result.status} (${result.path})`);
|
|
5687
|
+
if (result.action === "status" && result.exists) {
|
|
5688
|
+
lines.push(
|
|
5689
|
+
` enabled: ${result.enabled} | logPrompts===false: ${result.log_prompts_safe} | safe: ${result.safe} | outfile: ${result.outfile ?? "unset"}`
|
|
5690
|
+
);
|
|
5691
|
+
} else if (result.message) {
|
|
5692
|
+
lines.push(` ${result.message}`);
|
|
5693
|
+
}
|
|
5694
|
+
return lines.join("\n");
|
|
5695
|
+
}
|
|
5696
|
+
|
|
5697
|
+
// src/cli/setup.ts
|
|
5698
|
+
function buildSetupInstructions() {
|
|
5699
|
+
const usagePath = getUsageLogPath();
|
|
5700
|
+
return [
|
|
5701
|
+
"agycraft-mcp setup (non-destructive, opt-in instructions)",
|
|
5702
|
+
"================================================================",
|
|
3934
5703
|
"No files have been modified automatically. Copy and paste only what you want.",
|
|
3935
5704
|
"",
|
|
3936
5705
|
"1. Register agycraft MCP Server:",
|
|
@@ -4048,13 +5817,13 @@ function buildSetupInstructions() {
|
|
|
4048
5817
|
import { rm as rm2 } from "fs/promises";
|
|
4049
5818
|
|
|
4050
5819
|
// src/collectors/agy-hook.ts
|
|
4051
|
-
import { appendFile, mkdir as
|
|
4052
|
-
import { dirname as
|
|
5820
|
+
import { appendFile, mkdir as mkdir7, readFile as readFile11 } from "fs/promises";
|
|
5821
|
+
import { dirname as dirname7 } from "path";
|
|
4053
5822
|
async function appendUsageRecord(rawPayload, options) {
|
|
4054
5823
|
const logPath = options?.logPath ?? getUsageLogPath();
|
|
4055
5824
|
const salt = await getOrCreateLocalSalt(options?.saltPath);
|
|
4056
5825
|
const record = sanitizeUsagePayload(rawPayload, salt);
|
|
4057
|
-
await
|
|
5826
|
+
await mkdir7(dirname7(logPath), { recursive: true });
|
|
4058
5827
|
await appendFile(logPath, `${JSON.stringify(record)}
|
|
4059
5828
|
`, {
|
|
4060
5829
|
encoding: "utf8",
|
|
@@ -4066,7 +5835,7 @@ async function readUsageRecords(options) {
|
|
|
4066
5835
|
const logPath = options?.logPath ?? getUsageLogPath();
|
|
4067
5836
|
let content;
|
|
4068
5837
|
try {
|
|
4069
|
-
content = await
|
|
5838
|
+
content = await readFile11(logPath, "utf8");
|
|
4070
5839
|
} catch {
|
|
4071
5840
|
return [];
|
|
4072
5841
|
}
|
|
@@ -4121,19 +5890,19 @@ async function clearLocalData(options) {
|
|
|
4121
5890
|
|
|
4122
5891
|
// src/server.ts
|
|
4123
5892
|
import { access as access2 } from "fs/promises";
|
|
4124
|
-
import { join as
|
|
5893
|
+
import { join as join13 } from "path";
|
|
4125
5894
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4126
5895
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4127
5896
|
import { z } from "zod";
|
|
4128
5897
|
|
|
4129
5898
|
// src/collectors/gemini-otel.ts
|
|
4130
|
-
import { readFile as
|
|
5899
|
+
import { readFile as readFile12 } from "fs/promises";
|
|
4131
5900
|
async function readGeminiOtelRecords(options) {
|
|
4132
5901
|
const otelPath = options?.otelPath ?? getDefaultGeminiTelemetryPath();
|
|
4133
5902
|
const salt = options?.salt ?? await getOrCreateLocalSalt(options?.saltPath);
|
|
4134
5903
|
let content;
|
|
4135
5904
|
try {
|
|
4136
|
-
content = await
|
|
5905
|
+
content = await readFile12(otelPath, "utf8");
|
|
4137
5906
|
} catch {
|
|
4138
5907
|
return [];
|
|
4139
5908
|
}
|
|
@@ -4232,6 +6001,7 @@ function analyzeAntipatterns(records, options) {
|
|
|
4232
6001
|
const window = options?.window ?? "24h";
|
|
4233
6002
|
const scope = options?.scope ?? "global";
|
|
4234
6003
|
const nowMs = options?.nowMs ?? Date.now();
|
|
6004
|
+
const locale = options?.locale ?? "en";
|
|
4235
6005
|
const registry = options?.channels instanceof ChannelRegistry ? options.channels : options?.channels ? ChannelRegistry.fromSnapshot(options.channels) : loadBundledChannelRegistry();
|
|
4236
6006
|
const requestedAuthMode = options?.authMode;
|
|
4237
6007
|
const isSpecificAuthFilter = Boolean(
|
|
@@ -4265,23 +6035,91 @@ function analyzeAntipatterns(records, options) {
|
|
|
4265
6035
|
const longSessions = /* @__PURE__ */ new Map();
|
|
4266
6036
|
for (const r of filtered) {
|
|
4267
6037
|
const cur = longSessions.get(r.session_hash) ?? {
|
|
6038
|
+
sessionHash: r.session_hash,
|
|
4268
6039
|
maxTurn: 0,
|
|
4269
6040
|
maxCtxPct: null,
|
|
4270
6041
|
totalInput: 0,
|
|
6042
|
+
totalCacheRead: 0,
|
|
6043
|
+
peakReqInput: 0,
|
|
6044
|
+
latestReqInput: 0,
|
|
6045
|
+
latestTsMs: 0,
|
|
6046
|
+
maxIdleGapSec: 0,
|
|
6047
|
+
recent429Count: 0,
|
|
6048
|
+
recentWindows: [],
|
|
4271
6049
|
turns: 0
|
|
4272
6050
|
};
|
|
4273
6051
|
cur.maxTurn = Math.max(cur.maxTurn, r.turn_index);
|
|
4274
6052
|
if (typeof r.context_used_pct === "number") {
|
|
4275
6053
|
cur.maxCtxPct = cur.maxCtxPct === null ? r.context_used_pct : Math.max(cur.maxCtxPct, r.context_used_pct);
|
|
4276
6054
|
}
|
|
4277
|
-
|
|
6055
|
+
const cacheRead = r.cache_read_tokens ?? 0;
|
|
6056
|
+
const reqInput = r.input_tokens + cacheRead;
|
|
6057
|
+
cur.totalInput += reqInput;
|
|
6058
|
+
cur.totalCacheRead += cacheRead;
|
|
6059
|
+
if (reqInput > cur.peakReqInput) {
|
|
6060
|
+
cur.peakReqInput = reqInput;
|
|
6061
|
+
}
|
|
6062
|
+
const tsMs = Date.parse(r.ts);
|
|
6063
|
+
if (!Number.isNaN(tsMs)) {
|
|
6064
|
+
if (cur.latestTsMs > 0 && tsMs > cur.latestTsMs) {
|
|
6065
|
+
const gapSec = (tsMs - cur.latestTsMs) / 1e3;
|
|
6066
|
+
if (gapSec > cur.maxIdleGapSec) {
|
|
6067
|
+
cur.maxIdleGapSec = gapSec;
|
|
6068
|
+
}
|
|
6069
|
+
}
|
|
6070
|
+
if (tsMs >= cur.latestTsMs) {
|
|
6071
|
+
cur.latestTsMs = tsMs;
|
|
6072
|
+
cur.latestReqInput = reqInput;
|
|
6073
|
+
}
|
|
6074
|
+
} else {
|
|
6075
|
+
cur.latestReqInput = reqInput;
|
|
6076
|
+
}
|
|
6077
|
+
if (r.error_code && (r.error_code.includes("429") || r.error_code.includes("RESOURCE_EXHAUSTED"))) {
|
|
6078
|
+
cur.recent429Count += 1;
|
|
6079
|
+
}
|
|
6080
|
+
cur.recentWindows.push({ input: r.input_tokens, cacheRead });
|
|
6081
|
+
if (cur.recentWindows.length > 3) {
|
|
6082
|
+
cur.recentWindows.shift();
|
|
6083
|
+
}
|
|
4278
6084
|
cur.turns += 1;
|
|
4279
6085
|
longSessions.set(r.session_hash, cur);
|
|
4280
6086
|
}
|
|
4281
|
-
const snowballSessions = [...longSessions.values()].filter(
|
|
4282
|
-
|
|
6087
|
+
const snowballSessions = [...longSessions.values()].filter((s) => {
|
|
6088
|
+
const recentInputSum = s.recentWindows.reduce(
|
|
6089
|
+
(sum, w) => sum + w.input + w.cacheRead,
|
|
6090
|
+
0
|
|
6091
|
+
);
|
|
6092
|
+
const recentCacheSum = s.recentWindows.reduce((sum, w) => sum + w.cacheRead, 0);
|
|
6093
|
+
const recentHitPct = recentInputSum > 0 ? recentCacheSum / recentInputSum * 100 : 0;
|
|
6094
|
+
const sessionHitPct = s.totalInput > 0 ? s.totalCacheRead / s.totalInput * 100 : 0;
|
|
6095
|
+
const { decision } = evaluateSessionLifecycle(
|
|
6096
|
+
{
|
|
6097
|
+
session_hash: s.sessionHash,
|
|
6098
|
+
is_interactive: true,
|
|
6099
|
+
planner_turns_since_compact: Math.max(s.maxTurn, s.turns),
|
|
6100
|
+
current_input_tokens: Math.max(s.latestReqInput, s.peakReqInput),
|
|
6101
|
+
recent_cache_hit_pct: recentHitPct,
|
|
6102
|
+
idle_gap_sec: s.maxIdleGapSec,
|
|
6103
|
+
recent_429_count: s.recent429Count,
|
|
6104
|
+
recent_overflow_count: 0,
|
|
6105
|
+
model_context_limit: 512e3
|
|
6106
|
+
},
|
|
6107
|
+
void 0,
|
|
6108
|
+
{ nowMs, locale }
|
|
6109
|
+
);
|
|
6110
|
+
const highCtxUtilization = s.maxCtxPct !== null && s.maxCtxPct >= 70;
|
|
6111
|
+
const lifecycleFlagged = decision.action !== "HOLD_CACHE";
|
|
6112
|
+
const lowCacheMultiTurn = s.totalInput > 0 && sessionHitPct < 85 && (s.maxTurn >= 20 || s.turns >= 25);
|
|
6113
|
+
return highCtxUtilization || lifecycleFlagged || lowCacheMultiTurn;
|
|
6114
|
+
});
|
|
6115
|
+
const transcriptPeakInput = Math.max(
|
|
6116
|
+
options?.transcriptMeta?.peak_input_tokens ?? 0,
|
|
6117
|
+
options?.transcriptMeta?.latest_input_tokens ?? 0
|
|
6118
|
+
);
|
|
6119
|
+
const allFilteredHealthySmallWarm = filtered.length > 0 && snowballSessions.length === 0 && cacheHitRatePct >= 85 && [...longSessions.values()].every((s) => s.peakReqInput < 16e4);
|
|
6120
|
+
const transcriptUncompacted = Boolean(
|
|
6121
|
+
options?.transcriptMeta && options.transcriptMeta.steps_since_last_compact >= 30 && !allFilteredHealthySmallWarm && (transcriptPeakInput >= 16e4 || transcriptPeakInput === 0 && (snowballSessions.length > 0 || filtered.length === 0))
|
|
4283
6122
|
);
|
|
4284
|
-
const transcriptUncompacted = options?.transcriptMeta && options.transcriptMeta.steps_since_last_compact >= 30;
|
|
4285
6123
|
if (snowballSessions.length > 0 || transcriptUncompacted) {
|
|
4286
6124
|
const ctxValues = snowballSessions.map((s) => s.maxCtxPct).filter((v) => v !== null);
|
|
4287
6125
|
const peakCtx = ctxValues.length > 0 ? Math.max(...ctxValues) : null;
|
|
@@ -4330,7 +6168,7 @@ function analyzeAntipatterns(records, options) {
|
|
|
4330
6168
|
category: "thinking_downgrade",
|
|
4331
6169
|
title: "High Thinking/output token burn on flagship models",
|
|
4332
6170
|
evidence: `${totalHeavyOutput.toLocaleString()} output/thinking tokens on heavy models (${multiplierNote}).`,
|
|
4333
|
-
action: behaviors
|
|
6171
|
+
action: getLocalizedBehavior(behaviors, "thinking_guidance", locale) ?? "Lower Thinking level (e.g. Medium/Low) for boilerplate coding & log parsing, reserving High Thinking strictly for multi-file debugging or architecture.",
|
|
4334
6172
|
estimated_savings_pct: "25\u201345%"
|
|
4335
6173
|
});
|
|
4336
6174
|
}
|
|
@@ -4347,6 +6185,36 @@ function analyzeAntipatterns(records, options) {
|
|
|
4347
6185
|
estimated_savings_pct: "40\u201380% on runaway turns"
|
|
4348
6186
|
});
|
|
4349
6187
|
}
|
|
6188
|
+
if (options?.transcriptMeta) {
|
|
6189
|
+
const redundantReads = options.transcriptMeta.redundant_read_file_count ?? 0;
|
|
6190
|
+
const redundantReadPct = options.transcriptMeta.redundant_read_file_pct ?? 0;
|
|
6191
|
+
const pollingDups = options.transcriptMeta.polling_dup_count ?? 0;
|
|
6192
|
+
const pollingDupPct = options.transcriptMeta.polling_dup_rate_pct ?? 0;
|
|
6193
|
+
const hasRedundantReads = redundantReadPct >= 20 && redundantReads >= 5;
|
|
6194
|
+
const hasPollingDups = pollingDupPct >= 15 && pollingDups >= 5;
|
|
6195
|
+
if (hasRedundantReads || hasPollingDups) {
|
|
6196
|
+
const parts = [];
|
|
6197
|
+
if (hasRedundantReads) {
|
|
6198
|
+
parts.push(
|
|
6199
|
+
`${redundantReads} unedited file re-reads (${redundantReadPct}% of read_file calls)`
|
|
6200
|
+
);
|
|
6201
|
+
}
|
|
6202
|
+
if (hasPollingDups) {
|
|
6203
|
+
parts.push(
|
|
6204
|
+
`${pollingDups} exact-duplicate polling/tool calls (${pollingDupPct}% of all tool calls)`
|
|
6205
|
+
);
|
|
6206
|
+
}
|
|
6207
|
+
recs.push({
|
|
6208
|
+
id: "redundant_tool_calls",
|
|
6209
|
+
severity: redundantReadPct >= 35 || pollingDupPct >= 30 ? "high" : "medium",
|
|
6210
|
+
category: "redundant_tool_calls",
|
|
6211
|
+
title: "Redundant / polling tool calls inflating session context",
|
|
6212
|
+
evidence: `Transcript recorded ${parts.join(" and ")}.`,
|
|
6213
|
+
action: "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.",
|
|
6214
|
+
estimated_savings_pct: "15\u201335%"
|
|
6215
|
+
});
|
|
6216
|
+
}
|
|
6217
|
+
}
|
|
4350
6218
|
if (options?.hasGeminiIgnore === false) {
|
|
4351
6219
|
recs.push({
|
|
4352
6220
|
id: "missing_geminiignore",
|
|
@@ -4369,7 +6237,7 @@ function analyzeAntipatterns(records, options) {
|
|
|
4369
6237
|
category: "low_kv_cache_efficiency",
|
|
4370
6238
|
title: `Low KV cache hit efficiency${discountNote}`,
|
|
4371
6239
|
evidence: `KV cache hit rate is ${Math.round(cacheHitRatePct * 10) / 10}% (${totalCacheRead.toLocaleString()} cached / ${totalInputWithCache.toLocaleString()} total input tokens).`,
|
|
4372
|
-
action: behaviors
|
|
6240
|
+
action: getLocalizedBehavior(behaviors, "kv_cache_guidance", locale) ?? "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.",
|
|
4373
6241
|
estimated_savings_pct: "20\u201350% on input cost"
|
|
4374
6242
|
});
|
|
4375
6243
|
}
|
|
@@ -4427,7 +6295,7 @@ function analyzeAntipatterns(records, options) {
|
|
|
4427
6295
|
category: "peak_window_misalignment",
|
|
4428
6296
|
title: "Peak window concentration causing 429 rate limits",
|
|
4429
6297
|
evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s).`,
|
|
4430
|
-
action: behaviors
|
|
6298
|
+
action: getLocalizedBehavior(behaviors, "throttling_guidance", locale) ?? "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.",
|
|
4431
6299
|
estimated_savings_pct: "15\u201330% fewer 429 retries"
|
|
4432
6300
|
});
|
|
4433
6301
|
} else {
|
|
@@ -4437,7 +6305,7 @@ function analyzeAntipatterns(records, options) {
|
|
|
4437
6305
|
category: "burst_rpm_tpm_throttling",
|
|
4438
6306
|
title: `Burst RPM/TPM concentration causing 429 throttling (${activeChannelForPolicy.definition.display_name})`,
|
|
4439
6307
|
evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s) under ${policy.window_type}.`,
|
|
4440
|
-
action: behaviors
|
|
6308
|
+
action: getLocalizedBehavior(behaviors, "throttling_guidance", locale) ?? "Spread concurrent requests across regions or upgrade RPM/TPM quota.",
|
|
4441
6309
|
estimated_savings_pct: "15\u201330% fewer 429 retries"
|
|
4442
6310
|
});
|
|
4443
6311
|
}
|
|
@@ -4453,7 +6321,11 @@ function analyzeAntipatterns(records, options) {
|
|
|
4453
6321
|
category: "background_spend_warning",
|
|
4454
6322
|
title: `Background monitor / checkpoint calls billed on ${activeChannelForPolicy.definition.display_name}`,
|
|
4455
6323
|
evidence: `Detected ${bgRecords.length} estimated background CLI monitor call(s) (${bgTokens.toLocaleString()} tokens) on a pay-as-you-go/metered channel.`,
|
|
4456
|
-
action:
|
|
6324
|
+
action: getLocalizedBehavior(
|
|
6325
|
+
activeChannelForPolicy.definition.recommended_behaviors,
|
|
6326
|
+
"background_spend_guidance",
|
|
6327
|
+
locale
|
|
6328
|
+
) ?? "Background lightweight calls incur real metered usage on this channel; avoid idle polling loops.",
|
|
4457
6329
|
estimated_savings_pct: "10\u201325% background spend"
|
|
4458
6330
|
});
|
|
4459
6331
|
}
|
|
@@ -4803,18 +6675,20 @@ function buildIsolationCommands(channel) {
|
|
|
4803
6675
|
return cmds;
|
|
4804
6676
|
}
|
|
4805
6677
|
function applyChannelPrescription(params) {
|
|
4806
|
-
const { chosen, resolvedChannel, registry } = params;
|
|
6678
|
+
const { chosen, resolvedChannel, registry, locale = "en" } = params;
|
|
4807
6679
|
const variant = findChannelVariant(chosen, resolvedChannel, registry);
|
|
4808
6680
|
if (variant) {
|
|
6681
|
+
const localizedVariant = localizeDiagnosisEntry(variant, locale);
|
|
6682
|
+
const localizedChosen2 = localizeDiagnosisEntry(chosen, locale);
|
|
4809
6683
|
return {
|
|
4810
|
-
...
|
|
4811
|
-
title:
|
|
4812
|
-
root_cause:
|
|
4813
|
-
steps:
|
|
4814
|
-
commands:
|
|
4815
|
-
verify_command:
|
|
4816
|
-
dont_dos:
|
|
4817
|
-
deep_link:
|
|
6684
|
+
...localizedChosen2,
|
|
6685
|
+
title: localizedVariant.title ?? localizedChosen2.title,
|
|
6686
|
+
root_cause: localizedVariant.root_cause ?? localizedChosen2.root_cause,
|
|
6687
|
+
steps: localizedVariant.steps ?? localizedChosen2.steps,
|
|
6688
|
+
commands: localizedVariant.commands ?? localizedChosen2.commands,
|
|
6689
|
+
verify_command: localizedVariant.verify_command ?? localizedChosen2.verify_command,
|
|
6690
|
+
dont_dos: localizedVariant.dont_dos ?? localizedChosen2.dont_dos,
|
|
6691
|
+
deep_link: localizedVariant.deep_link ?? localizedChosen2.deep_link
|
|
4818
6692
|
};
|
|
4819
6693
|
}
|
|
4820
6694
|
const channel = resolvedChannel !== "unknown" && resolvedChannel !== "mixed_ambiguous" ? registry.getChannel(resolvedChannel) : void 0;
|
|
@@ -4825,57 +6699,66 @@ function applyChannelPrescription(params) {
|
|
|
4825
6699
|
if (!isGenericChannelSensitive) {
|
|
4826
6700
|
return chosen;
|
|
4827
6701
|
}
|
|
6702
|
+
const localizedChosen = localizeDiagnosisEntry(chosen, locale);
|
|
4828
6703
|
const behaviors = channel.definition.recommended_behaviors;
|
|
4829
6704
|
const policy = channel.definition.quota_reset_policy;
|
|
4830
6705
|
const isoCommands = buildIsolationCommands(channel);
|
|
4831
|
-
|
|
6706
|
+
const displayName = locale === "zh" && channel.definition.display_name_zh ? channel.definition.display_name_zh : channel.definition.display_name;
|
|
6707
|
+
const throttlingGuidance = getLocalizedBehavior(behaviors, "throttling_guidance", locale) ?? behaviors.throttling_guidance;
|
|
6708
|
+
const kvCacheGuidance = getLocalizedBehavior(behaviors, "kv_cache_guidance", locale) ?? behaviors.kv_cache_guidance;
|
|
6709
|
+
const backgroundSpendGuidance = getLocalizedBehavior(
|
|
6710
|
+
behaviors,
|
|
6711
|
+
"background_spend_guidance",
|
|
6712
|
+
locale
|
|
6713
|
+
);
|
|
6714
|
+
if (localizedChosen.domain === "quota") {
|
|
4832
6715
|
if (policy.window_type === "rolling_5h_7d") {
|
|
4833
|
-
const cleanSteps =
|
|
6716
|
+
const cleanSteps = localizedChosen.steps.filter(
|
|
4834
6717
|
(s) => !/gcloud|aiplatform|cloud\s*billing|aistudio\.google\.com/i.test(s)
|
|
4835
6718
|
);
|
|
4836
6719
|
return {
|
|
4837
|
-
...
|
|
4838
|
-
root_cause: `Shared ${policy.window_type} quota bucket exhausted or entitlement desync on ${
|
|
4839
|
-
steps: cleanSteps.length > 0 ? cleanSteps : [
|
|
6720
|
+
...localizedChosen,
|
|
6721
|
+
root_cause: locale === "zh" ? `${displayName} \u7684 ${policy.window_type} \u5171\u4EAB\u914D\u989D\u6876\u5DF2\u8017\u5C3D\u6216\u6743\u76CA\u5931\u6B65\u3002${throttlingGuidance}` : `Shared ${policy.window_type} quota bucket exhausted or entitlement desync on ${displayName}. ${throttlingGuidance}`,
|
|
6722
|
+
steps: cleanSteps.length > 0 ? cleanSteps : [throttlingGuidance, kvCacheGuidance],
|
|
4840
6723
|
commands: isoCommands,
|
|
4841
6724
|
verify_command: behaviors.verify_command
|
|
4842
6725
|
};
|
|
4843
6726
|
}
|
|
4844
6727
|
const steps = [
|
|
4845
|
-
|
|
4846
|
-
|
|
4847
|
-
...
|
|
6728
|
+
throttlingGuidance,
|
|
6729
|
+
kvCacheGuidance,
|
|
6730
|
+
...backgroundSpendGuidance ? [backgroundSpendGuidance] : []
|
|
4848
6731
|
];
|
|
4849
6732
|
return {
|
|
4850
|
-
...
|
|
4851
|
-
title: `429 Rate Limit / Quota Exhausted (${
|
|
4852
|
-
root_cause: `${
|
|
6733
|
+
...localizedChosen,
|
|
6734
|
+
title: locale === "zh" ? `429 \u9650\u6D41 / \u914D\u989D\u8017\u5C3D\uFF08${displayName}\uFF09` : `429 Rate Limit / Quota Exhausted (${displayName})`,
|
|
6735
|
+
root_cause: `${displayName} (${channel.definition.billing_model}, ${policy.window_type}): ${throttlingGuidance}`,
|
|
4853
6736
|
steps,
|
|
4854
6737
|
commands: isoCommands,
|
|
4855
6738
|
verify_command: behaviors.verify_command,
|
|
4856
6739
|
dont_dos: [
|
|
4857
|
-
"Do NOT apply consumer OAuth shared-bucket onboarding resets to this auth channel.",
|
|
4858
|
-
...
|
|
6740
|
+
locale === "zh" ? "\u4E0D\u8981\u5BF9\u8BE5\u8BA4\u8BC1\u901A\u9053\u6267\u884C\u4E2A\u4EBA OAuth \u5171\u4EAB\u914D\u989D\u6876\u7684 Reset Onboarding \u91CD\u7F6E\u64CD\u4F5C\u3002" : "Do NOT apply consumer OAuth shared-bucket onboarding resets to this auth channel.",
|
|
6741
|
+
...localizedChosen.dont_dos.filter(
|
|
4859
6742
|
(d) => !/reset\s*onboarding|5h\/7d/i.test(d)
|
|
4860
6743
|
)
|
|
4861
6744
|
]
|
|
4862
6745
|
};
|
|
4863
6746
|
}
|
|
4864
|
-
if (
|
|
6747
|
+
if (localizedChosen.domain === "auth") {
|
|
4865
6748
|
return {
|
|
4866
|
-
...
|
|
4867
|
-
title: `401/403 Auth & Entitlement Mismatch (${
|
|
4868
|
-
root_cause: `Authentication or entitlement mismatch on ${
|
|
6749
|
+
...localizedChosen,
|
|
6750
|
+
title: locale === "zh" ? `401/403 \u8BA4\u8BC1\u4E0E\u6743\u76CA\u4E0D\u5339\u914D\uFF08${displayName}\uFF09` : `401/403 Auth & Entitlement Mismatch (${displayName})`,
|
|
6751
|
+
root_cause: locale === "zh" ? `${displayName} \u5B58\u5728\u8BA4\u8BC1\u6216\u6743\u76CA\u4E0D\u5339\u914D\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u6E05\u7406\u5176\u4ED6\u901A\u9053\u7684\u51B2\u7A81\u73AF\u5883\u53D8\u91CF\u3002` : `Authentication or entitlement mismatch on ${displayName}. Ensure conflicting credentials from other channels are unset.`,
|
|
4869
6752
|
steps: [
|
|
4870
|
-
`Isolate environment variables for ${
|
|
4871
|
-
|
|
4872
|
-
`Verify connectivity with: ${behaviors.verify_command}`
|
|
6753
|
+
locale === "zh" ? `\u4E3A ${displayName} \u9694\u79BB\u51B2\u7A81\u73AF\u5883\u53D8\u91CF\u3002` : `Isolate environment variables for ${displayName}.`,
|
|
6754
|
+
throttlingGuidance,
|
|
6755
|
+
locale === "zh" ? `\u8FD0\u884C\u6821\u9A8C\u547D\u4EE4\u786E\u8BA4\u8FDE\u901A\u6027\uFF1A${behaviors.verify_command}` : `Verify connectivity with: ${behaviors.verify_command}`
|
|
4873
6756
|
],
|
|
4874
6757
|
commands: isoCommands,
|
|
4875
6758
|
verify_command: behaviors.verify_command
|
|
4876
6759
|
};
|
|
4877
6760
|
}
|
|
4878
|
-
return
|
|
6761
|
+
return localizedChosen;
|
|
4879
6762
|
}
|
|
4880
6763
|
|
|
4881
6764
|
// src/analyzers/error-diagnoser.ts
|
|
@@ -5332,6 +7215,7 @@ function extractSignals(errorText) {
|
|
|
5332
7215
|
};
|
|
5333
7216
|
}
|
|
5334
7217
|
function diagnoseError(options) {
|
|
7218
|
+
const locale = options.locale ?? "en";
|
|
5335
7219
|
const text = options.errorText;
|
|
5336
7220
|
const lowerText = text.toLowerCase();
|
|
5337
7221
|
const signals = extractSignals(text);
|
|
@@ -5422,7 +7306,8 @@ function diagnoseError(options) {
|
|
|
5422
7306
|
const chosen = rawChosen ? applyChannelPrescription({
|
|
5423
7307
|
chosen: rawChosen,
|
|
5424
7308
|
resolvedChannel,
|
|
5425
|
-
registry
|
|
7309
|
+
registry,
|
|
7310
|
+
locale
|
|
5426
7311
|
}) : null;
|
|
5427
7312
|
if (!chosen) {
|
|
5428
7313
|
return {
|
|
@@ -5471,7 +7356,13 @@ function diagnoseError(options) {
|
|
|
5471
7356
|
0
|
|
5472
7357
|
);
|
|
5473
7358
|
if (!isRollingBucketChannel && resolvedChannelDef) {
|
|
5474
|
-
|
|
7359
|
+
const displayName = locale === "zh" && resolvedChannelDef.definition.display_name_zh ? resolvedChannelDef.definition.display_name_zh : resolvedChannelDef.definition.display_name;
|
|
7360
|
+
const throttlingGuidance = getLocalizedBehavior(
|
|
7361
|
+
resolvedChannelDef.definition.recommended_behaviors,
|
|
7362
|
+
"throttling_guidance",
|
|
7363
|
+
locale
|
|
7364
|
+
) ?? resolvedChannelDef.definition.recommended_behaviors.throttling_guidance;
|
|
7365
|
+
attribution = hasActiveIncident ? `POSSIBLE UPSTREAM INCIDENT (${upstreamStatus}) on ${displayName}: ${throttlingGuidance}` : `${displayName} (${resolvedChannelDef.definition.billing_model}, ${recentRecords.length} recent channel turns / ${recentTokens.toLocaleString()} tokens): ${throttlingGuidance}`;
|
|
5475
7366
|
} else if (lowerText.includes("limit: 0") || recentRecords.length > 0 && recentTokens < 5e4) {
|
|
5476
7367
|
attribution = "LIKELY FALSE EXHAUSTION / ENTITLEMENT DESYNC: Local 5h usage is very low (<50k tokens) or `limit: 0` was returned. Check billing/account sync or Reset Onboarding before waiting.";
|
|
5477
7368
|
} else if (recentTokens >= 5e5) {
|
|
@@ -5484,24 +7375,27 @@ function diagnoseError(options) {
|
|
|
5484
7375
|
} else if (chosen.domain === "capacity") {
|
|
5485
7376
|
attribution = hasActiveIncident ? `UPSTREAM OUTAGE/DEGRADATION CONFIRMED (${upstreamStatus}): Not a local machine issue. Wait for recovery or temporarily switch to Flash/Hydrogen.` : "LOCAL CONTEXT OR TRANSIENT CAPACITY SPIKE: Upstream status appears operational; check for oversized context (>200k tokens) and add `.geminiignore`.";
|
|
5486
7377
|
}
|
|
5487
|
-
return
|
|
5488
|
-
|
|
5489
|
-
|
|
5490
|
-
|
|
5491
|
-
|
|
5492
|
-
|
|
5493
|
-
|
|
5494
|
-
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
|
|
5502
|
-
|
|
5503
|
-
|
|
5504
|
-
|
|
7378
|
+
return localizeDiagnosisEntry(
|
|
7379
|
+
{
|
|
7380
|
+
matched: true,
|
|
7381
|
+
domain: chosen.domain,
|
|
7382
|
+
diagnosis_id: chosen.id,
|
|
7383
|
+
title: chosen.title,
|
|
7384
|
+
confidence: "high",
|
|
7385
|
+
attribution,
|
|
7386
|
+
root_cause: chosen.root_cause,
|
|
7387
|
+
steps: chosen.steps,
|
|
7388
|
+
commands: chosen.commands,
|
|
7389
|
+
verify_command: chosen.verify_command,
|
|
7390
|
+
dont_dos: chosen.dont_dos,
|
|
7391
|
+
deep_link: chosen.deep_link.startsWith("/") ? `https://modelcraft.dev${chosen.deep_link}` : chosen.deep_link,
|
|
7392
|
+
official_source_url: chosen.official_source_url ?? null,
|
|
7393
|
+
upstream_status: upstreamStatus,
|
|
7394
|
+
extracted_signals: signals,
|
|
7395
|
+
auth_channel_analysis: authChannelAnalysis
|
|
7396
|
+
},
|
|
7397
|
+
locale
|
|
7398
|
+
);
|
|
5505
7399
|
}
|
|
5506
7400
|
|
|
5507
7401
|
// src/analyzers/countdown.ts
|
|
@@ -5647,8 +7541,8 @@ function computeResetCountdown(options) {
|
|
|
5647
7541
|
}
|
|
5648
7542
|
|
|
5649
7543
|
// src/remote/snapshot-client.ts
|
|
5650
|
-
import { mkdir as
|
|
5651
|
-
import { join as
|
|
7544
|
+
import { mkdir as mkdir8, readFile as readFile13, writeFile as writeFile7 } from "fs/promises";
|
|
7545
|
+
import { join as join12 } from "path";
|
|
5652
7546
|
var DEFAULT_DATA_URL2 = "https://modelcraft.dev/data/v1";
|
|
5653
7547
|
var TTL_MS = {
|
|
5654
7548
|
status: 5 * 60 * 1e3,
|
|
@@ -5736,8 +7630,8 @@ var SnapshotClient = class {
|
|
|
5736
7630
|
this.pkgVersion = options?.pkgVersion ?? getPackageVersion();
|
|
5737
7631
|
}
|
|
5738
7632
|
async get(name) {
|
|
5739
|
-
const cacheFile =
|
|
5740
|
-
const metaFile =
|
|
7633
|
+
const cacheFile = join12(this.cacheDir, `${name}.json`);
|
|
7634
|
+
const metaFile = join12(this.cacheDir, `${name}.meta.json`);
|
|
5741
7635
|
const ttl = TTL_MS[name];
|
|
5742
7636
|
const cached = await this.readCache(cacheFile, metaFile);
|
|
5743
7637
|
const versionMatches = cached?.meta.pkg_version === this.pkgVersion;
|
|
@@ -5766,8 +7660,8 @@ var SnapshotClient = class {
|
|
|
5766
7660
|
async readCache(cacheFile, metaFile) {
|
|
5767
7661
|
try {
|
|
5768
7662
|
const [rawJson, rawMeta] = await Promise.all([
|
|
5769
|
-
|
|
5770
|
-
|
|
7663
|
+
readFile13(cacheFile, "utf8"),
|
|
7664
|
+
readFile13(metaFile, "utf8")
|
|
5771
7665
|
]);
|
|
5772
7666
|
const data = JSON.parse(rawJson);
|
|
5773
7667
|
const meta = JSON.parse(rawMeta);
|
|
@@ -5778,15 +7672,15 @@ var SnapshotClient = class {
|
|
|
5778
7672
|
}
|
|
5779
7673
|
async writeCache(cacheFile, metaFile, data, etag) {
|
|
5780
7674
|
try {
|
|
5781
|
-
await
|
|
7675
|
+
await mkdir8(this.cacheDir, { recursive: true });
|
|
5782
7676
|
const meta = {
|
|
5783
7677
|
etag,
|
|
5784
7678
|
fetched_at_ms: Date.now(),
|
|
5785
7679
|
pkg_version: this.pkgVersion
|
|
5786
7680
|
};
|
|
5787
7681
|
await Promise.all([
|
|
5788
|
-
|
|
5789
|
-
|
|
7682
|
+
writeFile7(cacheFile, JSON.stringify(data), "utf8"),
|
|
7683
|
+
writeFile7(metaFile, JSON.stringify(meta), "utf8")
|
|
5790
7684
|
]);
|
|
5791
7685
|
} catch {
|
|
5792
7686
|
}
|
|
@@ -5836,8 +7730,8 @@ var SnapshotClient = class {
|
|
|
5836
7730
|
}
|
|
5837
7731
|
}
|
|
5838
7732
|
async readBundledFallback(name) {
|
|
5839
|
-
const filePath =
|
|
5840
|
-
const raw = await
|
|
7733
|
+
const filePath = join12(this.snapshotsDir, `${name}.json`);
|
|
7734
|
+
const raw = await readFile13(filePath, "utf8");
|
|
5841
7735
|
return JSON.parse(raw);
|
|
5842
7736
|
}
|
|
5843
7737
|
};
|
|
@@ -5949,7 +7843,7 @@ function createAgycraftServer(deps = {}) {
|
|
|
5949
7843
|
const client = deps.snapshotClient ?? new SnapshotClient();
|
|
5950
7844
|
const server = new McpServer({
|
|
5951
7845
|
name: "agycraft-mcp",
|
|
5952
|
-
version: "0.2.
|
|
7846
|
+
version: "0.2.3"
|
|
5953
7847
|
});
|
|
5954
7848
|
server.tool(
|
|
5955
7849
|
"analyze_token_usage",
|
|
@@ -5964,9 +7858,12 @@ function createAgycraftServer(deps = {}) {
|
|
|
5964
7858
|
workspace_dir: z.string().optional().describe(
|
|
5965
7859
|
"Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned)."
|
|
5966
7860
|
),
|
|
5967
|
-
auth_mode: z.string().default("all").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).")
|
|
7861
|
+
auth_mode: z.string().default("all").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)."),
|
|
7862
|
+
lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
|
|
5968
7863
|
},
|
|
5969
|
-
async ({ window, granularity, timezone, max_buckets, product, scope, workspace_dir, auth_mode }) => {
|
|
7864
|
+
async ({ window, granularity, timezone, max_buckets, product, scope, workspace_dir, auth_mode, lang }) => {
|
|
7865
|
+
const locale = resolveLocale(lang, process.env);
|
|
7866
|
+
const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : locale;
|
|
5970
7867
|
const [modelsSnap, channelsSnap, projectHash] = await Promise.all([
|
|
5971
7868
|
client.get("models"),
|
|
5972
7869
|
client.get("channels"),
|
|
@@ -6036,7 +7933,8 @@ function createAgycraftServer(deps = {}) {
|
|
|
6036
7933
|
time_series: rollupRes.time_series,
|
|
6037
7934
|
time_series_meta: rollupRes.time_series_meta,
|
|
6038
7935
|
models_snapshot_source: modelsSnap.source,
|
|
6039
|
-
|
|
7936
|
+
locale: effectiveLocale,
|
|
7937
|
+
privacy_note: effectiveLocale === "zh" ? "100% \u672C\u5730\u6570\u503C\u805A\u5408\uFF1B\u96F6\u7528\u6237\u6570\u636E\u4E0A\u4F20\u3002" : "100% local numeric aggregation; zero user data uploaded."
|
|
6040
7938
|
},
|
|
6041
7939
|
null,
|
|
6042
7940
|
2
|
|
@@ -6081,7 +7979,8 @@ function createAgycraftServer(deps = {}) {
|
|
|
6081
7979
|
session_count: effectiveSessionCount,
|
|
6082
7980
|
...transcriptFallback ? { transcript_activity_fallback: transcriptFallback } : {},
|
|
6083
7981
|
models_snapshot_source: modelsSnap.source,
|
|
6084
|
-
|
|
7982
|
+
locale: effectiveLocale,
|
|
7983
|
+
privacy_note: effectiveLocale === "zh" ? "100% \u672C\u5730\u6570\u503C\u805A\u5408\uFF1B\u96F6\u7528\u6237\u6570\u636E\u4E0A\u4F20\u3002" : "100% local numeric aggregation; zero user data uploaded."
|
|
6085
7984
|
},
|
|
6086
7985
|
null,
|
|
6087
7986
|
2
|
|
@@ -6101,15 +8000,17 @@ function createAgycraftServer(deps = {}) {
|
|
|
6101
8000
|
loopThreshold: z.number().int().positive().default(4).describe("Consecutive tool-failure streak threshold for infinite-loop detection (default: 4)."),
|
|
6102
8001
|
workspace_dir: z.string().optional().describe("Optional workspace directory path for .geminiignore check and project-scoped filtering."),
|
|
6103
8002
|
timezone: z.string().optional().describe("IANA timezone for peak_hours bucketing (default: UTC)."),
|
|
6104
|
-
auth_mode: z.string().default("auto").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).")
|
|
8003
|
+
auth_mode: z.string().default("auto").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)."),
|
|
8004
|
+
lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
|
|
6105
8005
|
},
|
|
6106
|
-
async ({ window, scope, transcript_path, loopThreshold, workspace_dir, timezone, auth_mode }) => {
|
|
8006
|
+
async ({ window, scope, transcript_path, loopThreshold, workspace_dir, timezone, auth_mode, lang }) => {
|
|
8007
|
+
const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : resolveLocale(lang, process.env);
|
|
6107
8008
|
const [modelsSnap, channelsSnap, projectHash, transcriptMeta, hasGeminiIgnore] = await Promise.all([
|
|
6108
8009
|
client.get("models"),
|
|
6109
8010
|
client.get("channels"),
|
|
6110
8011
|
resolveScopeProjectHash(scope, workspace_dir, deps),
|
|
6111
8012
|
transcript_path ? analyzeTranscriptStructure(transcript_path, loopThreshold) : Promise.resolve(null),
|
|
6112
|
-
workspace_dir ? access2(
|
|
8013
|
+
workspace_dir ? access2(join13(workspace_dir, ".geminiignore")).then(() => true).catch(() => false) : Promise.resolve(void 0)
|
|
6113
8014
|
]);
|
|
6114
8015
|
const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);
|
|
6115
8016
|
const authContext = deps.authContext ? deps.authContext : await detectAuthContext({ cliLogDir: deps.cliLogDir, registry });
|
|
@@ -6155,7 +8056,8 @@ function createAgycraftServer(deps = {}) {
|
|
|
6155
8056
|
has_mixed_auth: authContext.has_mixed_auth
|
|
6156
8057
|
},
|
|
6157
8058
|
authMode: auth_mode,
|
|
6158
|
-
channels: registry
|
|
8059
|
+
channels: registry,
|
|
8060
|
+
locale: effectiveLocale
|
|
6159
8061
|
});
|
|
6160
8062
|
return {
|
|
6161
8063
|
content: [
|
|
@@ -6164,6 +8066,7 @@ function createAgycraftServer(deps = {}) {
|
|
|
6164
8066
|
text: JSON.stringify(
|
|
6165
8067
|
{
|
|
6166
8068
|
...report,
|
|
8069
|
+
locale: effectiveLocale,
|
|
6167
8070
|
transcript_structure: transcriptMeta,
|
|
6168
8071
|
more_tips_url: "https://modelcraft.dev/quotas"
|
|
6169
8072
|
},
|
|
@@ -6182,9 +8085,11 @@ function createAgycraftServer(deps = {}) {
|
|
|
6182
8085
|
error_text: z.string().min(1).describe("Raw error message or JSON snippet."),
|
|
6183
8086
|
product: z.enum(["agy", "cli", "api", "web"]).optional(),
|
|
6184
8087
|
doctor_summary: z.string().optional(),
|
|
6185
|
-
auth_mode: z.string().default("auto").describe("Optional auth channel hint ('auto', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id).")
|
|
8088
|
+
auth_mode: z.string().default("auto").describe("Optional auth channel hint ('auto', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id)."),
|
|
8089
|
+
lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
|
|
6186
8090
|
},
|
|
6187
|
-
async ({ error_text, product, auth_mode }) => {
|
|
8091
|
+
async ({ error_text, product, auth_mode, lang }) => {
|
|
8092
|
+
const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : resolveLocale(lang, process.env);
|
|
6188
8093
|
const [records, statusSnap, diagnosisSnap, channelsSnap] = await Promise.all([
|
|
6189
8094
|
loadCombinedLocalRecords(deps),
|
|
6190
8095
|
client.get("status"),
|
|
@@ -6207,7 +8112,8 @@ function createAgycraftServer(deps = {}) {
|
|
|
6207
8112
|
authMode: auth_mode,
|
|
6208
8113
|
authContext,
|
|
6209
8114
|
cliChannel,
|
|
6210
|
-
channels: registry
|
|
8115
|
+
channels: registry,
|
|
8116
|
+
locale: effectiveLocale
|
|
6211
8117
|
});
|
|
6212
8118
|
return {
|
|
6213
8119
|
content: [
|
|
@@ -6216,6 +8122,7 @@ function createAgycraftServer(deps = {}) {
|
|
|
6216
8122
|
text: JSON.stringify(
|
|
6217
8123
|
{
|
|
6218
8124
|
...result,
|
|
8125
|
+
locale: effectiveLocale,
|
|
6219
8126
|
data_sources: {
|
|
6220
8127
|
status: statusSnap.source,
|
|
6221
8128
|
diagnosis: diagnosisSnap.source
|
|
@@ -6236,9 +8143,11 @@ function createAgycraftServer(deps = {}) {
|
|
|
6236
8143
|
task: z.string().optional().describe("Task description (e.g. 'architecture', 'multi-file refactor', 'quick qa', 'batch')."),
|
|
6237
8144
|
model_id: z.string().optional().describe("Specific model id, api_model_id, or codename (e.g. 'neon', 'hydrogen', 'argon', 'gemini-3.8-flash')."),
|
|
6238
8145
|
provider: z.enum(["google", "antigravity", "anthropic", "all"]).default("all"),
|
|
6239
|
-
include_history: z.boolean().default(false)
|
|
8146
|
+
include_history: z.boolean().default(false),
|
|
8147
|
+
lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
|
|
6240
8148
|
},
|
|
6241
|
-
async ({ task, model_id, provider, include_history }) => {
|
|
8149
|
+
async ({ task, model_id, provider, include_history, lang }) => {
|
|
8150
|
+
const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : resolveLocale(lang, process.env);
|
|
6242
8151
|
const [modelsSnap, chronicleSnap] = await Promise.all([
|
|
6243
8152
|
client.get("models"),
|
|
6244
8153
|
include_history ? client.get("chronicle") : Promise.resolve(null)
|
|
@@ -6301,10 +8210,14 @@ function createAgycraftServer(deps = {}) {
|
|
|
6301
8210
|
type: "text",
|
|
6302
8211
|
text: JSON.stringify(
|
|
6303
8212
|
{
|
|
6304
|
-
models: matched,
|
|
6305
|
-
orchestrator_recipes:
|
|
8213
|
+
models: matched.map((m) => localizeModelEntry(m, effectiveLocale)),
|
|
8214
|
+
orchestrator_recipes: localizeSnapshotText(
|
|
8215
|
+
modelsSnap.data.orchestrator_recipes,
|
|
8216
|
+
effectiveLocale
|
|
8217
|
+
),
|
|
6306
8218
|
deprecation_warnings: deprecationWarnings,
|
|
6307
|
-
chronicle_history: history,
|
|
8219
|
+
chronicle_history: history?.map((h) => localizeSnapshotText(h, effectiveLocale)),
|
|
8220
|
+
locale: effectiveLocale,
|
|
6308
8221
|
guide_url: "https://modelcraft.dev/models",
|
|
6309
8222
|
official_source_urls: [
|
|
6310
8223
|
...new Set(matched.flatMap((m) => m.official_source_urls ?? []))
|
|
@@ -6330,9 +8243,11 @@ function createAgycraftServer(deps = {}) {
|
|
|
6330
8243
|
workspace_dir: z.string().optional().describe(
|
|
6331
8244
|
"Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned)."
|
|
6332
8245
|
),
|
|
6333
|
-
auth_mode: z.string().default("all").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).")
|
|
8246
|
+
auth_mode: z.string().default("all").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)."),
|
|
8247
|
+
lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
|
|
6334
8248
|
},
|
|
6335
|
-
async ({ plan, product, timezone, scope, workspace_dir, auth_mode }) => {
|
|
8249
|
+
async ({ plan, product, timezone, scope, workspace_dir, auth_mode, lang }) => {
|
|
8250
|
+
const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : resolveLocale(lang, process.env);
|
|
6336
8251
|
const nowMs = Date.now();
|
|
6337
8252
|
const since7d = nowMs - 7 * 86400 * 1e3;
|
|
6338
8253
|
const [statusSnap, quotasSnap, updatesSnap, channelsSnap, projectHash] = await Promise.all([
|
|
@@ -6419,14 +8334,24 @@ function createAgycraftServer(deps = {}) {
|
|
|
6419
8334
|
...statusUsageNote ? { usage_note: statusUsageNote } : {},
|
|
6420
8335
|
session_count: isSpecificAuthEmpty ? 0 : effectiveRecords.length > 0 ? new Set(effectiveRecords.map((r) => r.session_hash)).size : transcriptFallback?.window_5h.session_count ?? 0,
|
|
6421
8336
|
overall_status: statusSnap.data.overall_status,
|
|
6422
|
-
surfaces: statusSnap.data.surfaces,
|
|
6423
|
-
active_incidents:
|
|
8337
|
+
surfaces: localizeSnapshotText(statusSnap.data.surfaces, effectiveLocale),
|
|
8338
|
+
active_incidents: localizeSnapshotText(
|
|
8339
|
+
statusSnap.data.active_incidents,
|
|
8340
|
+
effectiveLocale
|
|
8341
|
+
),
|
|
6424
8342
|
latest_versions: statusSnap.data.latest_versions,
|
|
6425
8343
|
countdown,
|
|
6426
8344
|
...transcriptFallback ? { transcript_activity_fallback: transcriptFallback } : {},
|
|
6427
|
-
quota_rules:
|
|
6428
|
-
|
|
6429
|
-
|
|
8345
|
+
quota_rules: localizeSnapshotText(
|
|
8346
|
+
{
|
|
8347
|
+
reset_rules: quotasSnap.data.reset_rules,
|
|
8348
|
+
...typeof quotasSnap.data.reset_rules_notes_zh === "string" ? { reset_rules_notes_zh: quotasSnap.data.reset_rules_notes_zh } : {}
|
|
8349
|
+
},
|
|
8350
|
+
effectiveLocale
|
|
8351
|
+
).reset_rules,
|
|
8352
|
+
plans: filteredPlans.map((p) => localizeSnapshotText(p, effectiveLocale)),
|
|
8353
|
+
recent_updates: filteredUpdates.slice(0, 8).map((u) => localizeSnapshotText(u, effectiveLocale)),
|
|
8354
|
+
locale: effectiveLocale,
|
|
6430
8355
|
dashboard_url: "https://modelcraft.dev",
|
|
6431
8356
|
official_source_urls: quotasSnap.data.official_source_urls ?? [],
|
|
6432
8357
|
snapshot_sources: {
|
|
@@ -6477,16 +8402,78 @@ function printPreflightHelp() {
|
|
|
6477
8402
|
].join("\n")
|
|
6478
8403
|
);
|
|
6479
8404
|
}
|
|
8405
|
+
function printIgnoreHelp() {
|
|
8406
|
+
console.log(
|
|
8407
|
+
[
|
|
8408
|
+
"agycraft-mcp ignore \u2014 Manage .geminiignore rules",
|
|
8409
|
+
"",
|
|
8410
|
+
"Usage:",
|
|
8411
|
+
" agycraft-mcp ignore init [--dir <path>] [--dry-run] [--json]",
|
|
8412
|
+
"",
|
|
8413
|
+
"Options:",
|
|
8414
|
+
" --dir <path> Target directory containing .geminiignore (default: cwd)",
|
|
8415
|
+
" --dry-run Preview changes without writing .geminiignore",
|
|
8416
|
+
" --json Output structured JSON"
|
|
8417
|
+
].join("\n")
|
|
8418
|
+
);
|
|
8419
|
+
}
|
|
8420
|
+
function printTelemetryHelp() {
|
|
8421
|
+
console.log(
|
|
8422
|
+
[
|
|
8423
|
+
"agycraft-mcp telemetry \u2014 Manage privacy-safe local Gemini CLI telemetry in settings.json",
|
|
8424
|
+
"",
|
|
8425
|
+
"Usage:",
|
|
8426
|
+
" agycraft-mcp telemetry enable [--settings <path>] [--dry-run] [--json]",
|
|
8427
|
+
" agycraft-mcp telemetry disable [--settings <path>] [--dry-run] [--json]",
|
|
8428
|
+
" agycraft-mcp telemetry status [--settings <path>] [--json]",
|
|
8429
|
+
"",
|
|
8430
|
+
"Options:",
|
|
8431
|
+
" --settings <path> Override target settings.json path (default: ~/.gemini/settings.json)",
|
|
8432
|
+
" --dry-run Preview changes without writing files",
|
|
8433
|
+
" --json Output structured JSON"
|
|
8434
|
+
].join("\n")
|
|
8435
|
+
);
|
|
8436
|
+
}
|
|
8437
|
+
function printHookHelp() {
|
|
8438
|
+
console.log(
|
|
8439
|
+
[
|
|
8440
|
+
"agycraft-mcp hook \u2014 Manage Stop / PostInvocation lifecycle hooks in settings.json / hooks.json",
|
|
8441
|
+
"",
|
|
8442
|
+
"Usage:",
|
|
8443
|
+
" agycraft-mcp hook enable [--kind stop|record] [--target agy|gemini|both] [--settings <path>] [--command <cmd>] [--local] [--lang en|zh|auto] [--dry-run] [--json]",
|
|
8444
|
+
" agycraft-mcp hook disable [--kind stop|record] [--target agy|gemini|both] [--settings <path>] [--dry-run] [--json]",
|
|
8445
|
+
" agycraft-mcp hook status [--kind stop|record] [--target agy|gemini|both] [--settings <path>] [--json]",
|
|
8446
|
+
"",
|
|
8447
|
+
"Options:",
|
|
8448
|
+
" --kind <name> Hook kind: stop (default, settings.json Stop) or record (~/.gemini/config/hooks.json PostInvocation)",
|
|
8449
|
+
" --target <name> Target settings.json: agy (default), gemini, or both (stop kind)",
|
|
8450
|
+
" --settings <path> Override target settings.json / hooks.json path directly",
|
|
8451
|
+
" --command <cmd> Custom hook command string (enable only)",
|
|
8452
|
+
" --local Use local dist/index.js path instead of npx (enable only)",
|
|
8453
|
+
" --lang <val> Append --lang en|zh|auto to generated hook-check command",
|
|
8454
|
+
" --dry-run Preview changes without writing files",
|
|
8455
|
+
" --json Output structured JSON"
|
|
8456
|
+
].join("\n")
|
|
8457
|
+
);
|
|
8458
|
+
}
|
|
6480
8459
|
function printHelp() {
|
|
6481
8460
|
console.log(
|
|
6482
8461
|
[
|
|
6483
8462
|
"agycraft-mcp \u2014 Privacy-first local MCP server & CLI doctor for Antigravity (AGY) & Gemini CLI",
|
|
6484
8463
|
"",
|
|
6485
8464
|
"Usage:",
|
|
6486
|
-
" agycraft-mcp
|
|
6487
|
-
" agycraft-mcp doctor [--cost] [--window 5h|24h|7d] [--json]",
|
|
8465
|
+
" agycraft-mcp [--lang en|zh|auto] Start Stdio MCP Server (default)",
|
|
8466
|
+
" agycraft-mcp doctor [--cost] [--window 5h|24h|7d] [--lang en|zh|auto] [--json]",
|
|
6488
8467
|
" Run offline preflight & hygiene check or readonly cost breakdown",
|
|
6489
8468
|
" agycraft-mcp preflight [--json] Check live ModelCraft status.json (exits 1 if degraded/429/503)",
|
|
8469
|
+
" agycraft-mcp ignore init [--dir <path>] [--dry-run] [--json]",
|
|
8470
|
+
" Initialize or append missing .geminiignore rules",
|
|
8471
|
+
" agycraft-mcp telemetry <enable|disable|status> [--settings <path>] [--dry-run] [--json]",
|
|
8472
|
+
" Manage privacy-safe local Gemini CLI telemetry",
|
|
8473
|
+
" agycraft-mcp hook <enable|disable|status> [--kind stop|record] [options]",
|
|
8474
|
+
" Manage Stop / PostInvocation record hook registration",
|
|
8475
|
+
" agycraft-mcp hook-check [--transcript <path>] [--state-file <path>] [--json] [--lang en|zh|auto]",
|
|
8476
|
+
" Lightweight O(1) Stop/PostToolUse lifecycle check (always exits 0)",
|
|
6490
8477
|
" agycraft-mcp setup Print non-destructive, opt-in AGY / Gemini CLI setup snippets",
|
|
6491
8478
|
" agycraft-mcp record Read hook JSON from stdin and append strictly whitelisted numeric metrics",
|
|
6492
8479
|
" agycraft-mcp clear-local-data Safely delete ~/.config/agycraft/usage.jsonl and cache",
|
|
@@ -6496,21 +8483,61 @@ function printHelp() {
|
|
|
6496
8483
|
].join("\n")
|
|
6497
8484
|
);
|
|
6498
8485
|
}
|
|
8486
|
+
function extractLangArg(argv) {
|
|
8487
|
+
const rest = [];
|
|
8488
|
+
let lang;
|
|
8489
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
8490
|
+
const arg = argv[i];
|
|
8491
|
+
if (arg === void 0) {
|
|
8492
|
+
continue;
|
|
8493
|
+
}
|
|
8494
|
+
if (arg === "--lang") {
|
|
8495
|
+
const next = argv[i + 1];
|
|
8496
|
+
if (next !== "en" && next !== "zh" && next !== "auto") {
|
|
8497
|
+
throw new Error(`Invalid --lang value "${next ?? ""}". Expected: en, zh, or auto.`);
|
|
8498
|
+
}
|
|
8499
|
+
lang = next;
|
|
8500
|
+
i += 1;
|
|
8501
|
+
continue;
|
|
8502
|
+
}
|
|
8503
|
+
if (arg.startsWith("--lang=")) {
|
|
8504
|
+
const val = arg.slice("--lang=".length);
|
|
8505
|
+
if (val !== "en" && val !== "zh" && val !== "auto") {
|
|
8506
|
+
throw new Error(`Invalid --lang value "${val}". Expected: en, zh, or auto.`);
|
|
8507
|
+
}
|
|
8508
|
+
lang = val;
|
|
8509
|
+
continue;
|
|
8510
|
+
}
|
|
8511
|
+
rest.push(arg);
|
|
8512
|
+
}
|
|
8513
|
+
return { lang, rest };
|
|
8514
|
+
}
|
|
6499
8515
|
async function main(argv = process.argv.slice(2)) {
|
|
6500
|
-
|
|
8516
|
+
let langArg;
|
|
8517
|
+
let restArgv;
|
|
8518
|
+
try {
|
|
8519
|
+
const parsed = extractLangArg(argv);
|
|
8520
|
+
langArg = parsed.lang;
|
|
8521
|
+
restArgv = parsed.rest;
|
|
8522
|
+
} catch (err) {
|
|
8523
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
8524
|
+
process.exitCode = 1;
|
|
8525
|
+
return;
|
|
8526
|
+
}
|
|
8527
|
+
const cmd = restArgv[0];
|
|
6501
8528
|
if (!cmd) {
|
|
6502
|
-
await startStdioServer();
|
|
8529
|
+
await startStdioServer({ defaultLang: langArg });
|
|
6503
8530
|
return;
|
|
6504
8531
|
}
|
|
6505
8532
|
switch (cmd) {
|
|
6506
8533
|
case "doctor": {
|
|
6507
|
-
const asJson =
|
|
6508
|
-
const withCost =
|
|
8534
|
+
const asJson = restArgv.includes("--json");
|
|
8535
|
+
const withCost = restArgv.includes("--cost");
|
|
6509
8536
|
if (withCost) {
|
|
6510
8537
|
let windowArg = "24h";
|
|
6511
|
-
const winIdx =
|
|
8538
|
+
const winIdx = restArgv.indexOf("--window");
|
|
6512
8539
|
if (winIdx !== -1) {
|
|
6513
|
-
const val =
|
|
8540
|
+
const val = restArgv[winIdx + 1];
|
|
6514
8541
|
if (val !== "5h" && val !== "24h" && val !== "7d") {
|
|
6515
8542
|
console.error(`Invalid --window value "${val ?? ""}". Expected: 5h, 24h, or 7d.`);
|
|
6516
8543
|
process.exitCode = 1;
|
|
@@ -6527,11 +8554,14 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
6527
8554
|
return;
|
|
6528
8555
|
}
|
|
6529
8556
|
let authModeArg;
|
|
6530
|
-
const authIdx =
|
|
6531
|
-
if (authIdx !== -1 &&
|
|
6532
|
-
authModeArg =
|
|
8557
|
+
const authIdx = restArgv.indexOf("--auth-mode");
|
|
8558
|
+
if (authIdx !== -1 && restArgv[authIdx + 1]) {
|
|
8559
|
+
authModeArg = restArgv[authIdx + 1];
|
|
6533
8560
|
}
|
|
6534
|
-
const report = await runDoctor(
|
|
8561
|
+
const report = await runDoctor({
|
|
8562
|
+
...authModeArg ? { authMode: authModeArg } : {},
|
|
8563
|
+
...langArg ? { lang: langArg } : {}
|
|
8564
|
+
});
|
|
6535
8565
|
if (asJson) {
|
|
6536
8566
|
console.log(JSON.stringify(report, null, 2));
|
|
6537
8567
|
} else {
|
|
@@ -6540,11 +8570,11 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
6540
8570
|
return;
|
|
6541
8571
|
}
|
|
6542
8572
|
case "preflight": {
|
|
6543
|
-
if (
|
|
8573
|
+
if (restArgv.includes("--help") || restArgv.includes("-h")) {
|
|
6544
8574
|
printPreflightHelp();
|
|
6545
8575
|
return;
|
|
6546
8576
|
}
|
|
6547
|
-
const asJson =
|
|
8577
|
+
const asJson = restArgv.includes("--json");
|
|
6548
8578
|
const result = await runPreflight();
|
|
6549
8579
|
if (asJson) {
|
|
6550
8580
|
console.log(JSON.stringify(result, null, 2));
|
|
@@ -6554,6 +8584,272 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
6554
8584
|
process.exitCode = result.exit_code;
|
|
6555
8585
|
return;
|
|
6556
8586
|
}
|
|
8587
|
+
case "ignore": {
|
|
8588
|
+
const sub = restArgv[1];
|
|
8589
|
+
if (!sub || sub === "--help" || sub === "-h" || sub === "help") {
|
|
8590
|
+
printIgnoreHelp();
|
|
8591
|
+
return;
|
|
8592
|
+
}
|
|
8593
|
+
if (sub !== "init") {
|
|
8594
|
+
console.error(`Unknown ignore subcommand: ${sub}`);
|
|
8595
|
+
printIgnoreHelp();
|
|
8596
|
+
process.exitCode = 1;
|
|
8597
|
+
return;
|
|
8598
|
+
}
|
|
8599
|
+
const subArgs = restArgv.slice(2);
|
|
8600
|
+
if (subArgs.includes("--help") || subArgs.includes("-h")) {
|
|
8601
|
+
printIgnoreHelp();
|
|
8602
|
+
return;
|
|
8603
|
+
}
|
|
8604
|
+
let dir;
|
|
8605
|
+
let dryRun = false;
|
|
8606
|
+
let asJson = false;
|
|
8607
|
+
try {
|
|
8608
|
+
for (let i = 0; i < subArgs.length; i += 1) {
|
|
8609
|
+
const arg = subArgs[i];
|
|
8610
|
+
if (arg === void 0) {
|
|
8611
|
+
continue;
|
|
8612
|
+
}
|
|
8613
|
+
if (arg === "--json") {
|
|
8614
|
+
asJson = true;
|
|
8615
|
+
continue;
|
|
8616
|
+
}
|
|
8617
|
+
if (arg === "--dry-run") {
|
|
8618
|
+
dryRun = true;
|
|
8619
|
+
continue;
|
|
8620
|
+
}
|
|
8621
|
+
if (arg === "--dir" || arg.startsWith("--dir=")) {
|
|
8622
|
+
const val = arg === "--dir" ? subArgs[++i] : arg.slice("--dir=".length);
|
|
8623
|
+
if (!val) {
|
|
8624
|
+
throw new Error("Missing value for --dir.");
|
|
8625
|
+
}
|
|
8626
|
+
dir = val;
|
|
8627
|
+
continue;
|
|
8628
|
+
}
|
|
8629
|
+
throw new Error(`Unknown option for ignore init: ${arg}`);
|
|
8630
|
+
}
|
|
8631
|
+
const result = await runIgnoreInit({
|
|
8632
|
+
...dir ? { dir } : {},
|
|
8633
|
+
...dryRun ? { dryRun: true } : {},
|
|
8634
|
+
...asJson ? { json: true } : {}
|
|
8635
|
+
});
|
|
8636
|
+
console.log(formatIgnoreInitResult(result, asJson));
|
|
8637
|
+
process.exitCode = result.ok ? 0 : 1;
|
|
8638
|
+
} catch (err) {
|
|
8639
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
8640
|
+
process.exitCode = 1;
|
|
8641
|
+
}
|
|
8642
|
+
return;
|
|
8643
|
+
}
|
|
8644
|
+
case "telemetry": {
|
|
8645
|
+
const sub = restArgv[1];
|
|
8646
|
+
if (!sub || sub === "--help" || sub === "-h" || sub === "help") {
|
|
8647
|
+
printTelemetryHelp();
|
|
8648
|
+
return;
|
|
8649
|
+
}
|
|
8650
|
+
if (sub !== "enable" && sub !== "disable" && sub !== "status") {
|
|
8651
|
+
console.error(`Unknown telemetry subcommand: ${sub}`);
|
|
8652
|
+
printTelemetryHelp();
|
|
8653
|
+
process.exitCode = 1;
|
|
8654
|
+
return;
|
|
8655
|
+
}
|
|
8656
|
+
const subArgs = restArgv.slice(2);
|
|
8657
|
+
if (subArgs.includes("--help") || subArgs.includes("-h")) {
|
|
8658
|
+
printTelemetryHelp();
|
|
8659
|
+
return;
|
|
8660
|
+
}
|
|
8661
|
+
let settingsPath;
|
|
8662
|
+
let dryRun = false;
|
|
8663
|
+
let asJson = false;
|
|
8664
|
+
try {
|
|
8665
|
+
for (let i = 0; i < subArgs.length; i += 1) {
|
|
8666
|
+
const arg = subArgs[i];
|
|
8667
|
+
if (arg === void 0) {
|
|
8668
|
+
continue;
|
|
8669
|
+
}
|
|
8670
|
+
if (arg === "--json") {
|
|
8671
|
+
asJson = true;
|
|
8672
|
+
continue;
|
|
8673
|
+
}
|
|
8674
|
+
if (arg === "--dry-run") {
|
|
8675
|
+
dryRun = true;
|
|
8676
|
+
continue;
|
|
8677
|
+
}
|
|
8678
|
+
if (arg === "--settings" || arg.startsWith("--settings=")) {
|
|
8679
|
+
const val = arg === "--settings" ? subArgs[++i] : arg.slice("--settings=".length);
|
|
8680
|
+
if (!val) {
|
|
8681
|
+
throw new Error("Missing value for --settings.");
|
|
8682
|
+
}
|
|
8683
|
+
settingsPath = val;
|
|
8684
|
+
continue;
|
|
8685
|
+
}
|
|
8686
|
+
throw new Error(`Unknown option for telemetry ${sub}: ${arg}`);
|
|
8687
|
+
}
|
|
8688
|
+
const result = sub === "enable" ? await runTelemetryEnable({
|
|
8689
|
+
...settingsPath ? { settingsPath } : {},
|
|
8690
|
+
...dryRun ? { dryRun: true } : {}
|
|
8691
|
+
}) : sub === "disable" ? await runTelemetryDisable({
|
|
8692
|
+
...settingsPath ? { settingsPath } : {},
|
|
8693
|
+
...dryRun ? { dryRun: true } : {}
|
|
8694
|
+
}) : await runTelemetryStatus({
|
|
8695
|
+
...settingsPath ? { settingsPath } : {}
|
|
8696
|
+
});
|
|
8697
|
+
if (asJson) {
|
|
8698
|
+
console.log(JSON.stringify(result, null, 2));
|
|
8699
|
+
} else {
|
|
8700
|
+
console.log(formatTelemetryManageResult(result));
|
|
8701
|
+
}
|
|
8702
|
+
process.exitCode = result.ok ? 0 : 1;
|
|
8703
|
+
} catch (err) {
|
|
8704
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
8705
|
+
process.exitCode = 1;
|
|
8706
|
+
}
|
|
8707
|
+
return;
|
|
8708
|
+
}
|
|
8709
|
+
case "hook": {
|
|
8710
|
+
const sub = restArgv[1];
|
|
8711
|
+
if (!sub || sub === "--help" || sub === "-h" || sub === "help") {
|
|
8712
|
+
printHookHelp();
|
|
8713
|
+
return;
|
|
8714
|
+
}
|
|
8715
|
+
if (sub !== "enable" && sub !== "disable" && sub !== "status") {
|
|
8716
|
+
console.error(`Unknown hook subcommand: ${sub}`);
|
|
8717
|
+
printHookHelp();
|
|
8718
|
+
process.exitCode = 1;
|
|
8719
|
+
return;
|
|
8720
|
+
}
|
|
8721
|
+
const subArgs = restArgv.slice(2);
|
|
8722
|
+
if (subArgs.includes("--help") || subArgs.includes("-h")) {
|
|
8723
|
+
printHookHelp();
|
|
8724
|
+
return;
|
|
8725
|
+
}
|
|
8726
|
+
let kind = "stop";
|
|
8727
|
+
let target = "agy";
|
|
8728
|
+
let settingsPath;
|
|
8729
|
+
let command;
|
|
8730
|
+
let local = false;
|
|
8731
|
+
let dryRun = false;
|
|
8732
|
+
let asJson = false;
|
|
8733
|
+
try {
|
|
8734
|
+
for (let i = 0; i < subArgs.length; i += 1) {
|
|
8735
|
+
const arg = subArgs[i];
|
|
8736
|
+
if (arg === void 0) {
|
|
8737
|
+
continue;
|
|
8738
|
+
}
|
|
8739
|
+
if (arg === "--json") {
|
|
8740
|
+
asJson = true;
|
|
8741
|
+
continue;
|
|
8742
|
+
}
|
|
8743
|
+
if (arg === "--dry-run") {
|
|
8744
|
+
dryRun = true;
|
|
8745
|
+
continue;
|
|
8746
|
+
}
|
|
8747
|
+
if (arg === "--local") {
|
|
8748
|
+
local = true;
|
|
8749
|
+
continue;
|
|
8750
|
+
}
|
|
8751
|
+
if (arg === "--kind" || arg.startsWith("--kind=")) {
|
|
8752
|
+
const val = arg === "--kind" ? subArgs[++i] : arg.slice("--kind=".length);
|
|
8753
|
+
if (val !== "stop" && val !== "record") {
|
|
8754
|
+
throw new Error(`Invalid --kind value "${val ?? ""}". Expected: stop or record.`);
|
|
8755
|
+
}
|
|
8756
|
+
kind = val;
|
|
8757
|
+
continue;
|
|
8758
|
+
}
|
|
8759
|
+
if (arg === "--target" || arg.startsWith("--target=")) {
|
|
8760
|
+
const val = arg === "--target" ? subArgs[++i] : arg.slice("--target=".length);
|
|
8761
|
+
if (val !== "agy" && val !== "gemini" && val !== "both") {
|
|
8762
|
+
throw new Error(`Invalid --target value "${val ?? ""}". Expected: agy, gemini, or both.`);
|
|
8763
|
+
}
|
|
8764
|
+
target = val;
|
|
8765
|
+
continue;
|
|
8766
|
+
}
|
|
8767
|
+
if (arg === "--settings" || arg.startsWith("--settings=")) {
|
|
8768
|
+
const val = arg === "--settings" ? subArgs[++i] : arg.slice("--settings=".length);
|
|
8769
|
+
if (!val) {
|
|
8770
|
+
throw new Error("Missing value for --settings.");
|
|
8771
|
+
}
|
|
8772
|
+
settingsPath = val;
|
|
8773
|
+
continue;
|
|
8774
|
+
}
|
|
8775
|
+
if (arg === "--command" || arg.startsWith("--command=")) {
|
|
8776
|
+
const val = arg === "--command" ? subArgs[++i] : arg.slice("--command=".length);
|
|
8777
|
+
if (val === void 0) {
|
|
8778
|
+
throw new Error("Missing value for --command.");
|
|
8779
|
+
}
|
|
8780
|
+
command = val;
|
|
8781
|
+
continue;
|
|
8782
|
+
}
|
|
8783
|
+
throw new Error(`Unknown option for hook ${sub}: ${arg}`);
|
|
8784
|
+
}
|
|
8785
|
+
const result = sub === "enable" ? await runHookEnable({
|
|
8786
|
+
kind,
|
|
8787
|
+
target,
|
|
8788
|
+
...settingsPath ? { settingsPath } : {},
|
|
8789
|
+
...command !== void 0 ? { command } : {},
|
|
8790
|
+
...local ? { local: true } : {},
|
|
8791
|
+
...langArg ? { lang: langArg } : {},
|
|
8792
|
+
...dryRun ? { dryRun: true } : {}
|
|
8793
|
+
}) : sub === "disable" ? await runHookDisable({
|
|
8794
|
+
kind,
|
|
8795
|
+
target,
|
|
8796
|
+
...settingsPath ? { settingsPath } : {},
|
|
8797
|
+
...dryRun ? { dryRun: true } : {}
|
|
8798
|
+
}) : await runHookStatus({
|
|
8799
|
+
kind,
|
|
8800
|
+
target,
|
|
8801
|
+
...settingsPath ? { settingsPath } : {}
|
|
8802
|
+
});
|
|
8803
|
+
if (asJson) {
|
|
8804
|
+
console.log(JSON.stringify(result, null, 2));
|
|
8805
|
+
} else {
|
|
8806
|
+
console.log(formatHookManageResult(result));
|
|
8807
|
+
}
|
|
8808
|
+
process.exitCode = result.ok ? 0 : 1;
|
|
8809
|
+
} catch (err) {
|
|
8810
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
8811
|
+
process.exitCode = 1;
|
|
8812
|
+
}
|
|
8813
|
+
return;
|
|
8814
|
+
}
|
|
8815
|
+
case "hook-check": {
|
|
8816
|
+
const asJson = restArgv.includes("--json");
|
|
8817
|
+
let transcriptPath;
|
|
8818
|
+
let stateFilePath;
|
|
8819
|
+
const tIdx = restArgv.indexOf("--transcript");
|
|
8820
|
+
if (tIdx !== -1 && restArgv[tIdx + 1]) {
|
|
8821
|
+
transcriptPath = restArgv[tIdx + 1];
|
|
8822
|
+
}
|
|
8823
|
+
const sIdx = restArgv.indexOf("--state-file");
|
|
8824
|
+
if (sIdx !== -1 && restArgv[sIdx + 1]) {
|
|
8825
|
+
stateFilePath = restArgv[sIdx + 1];
|
|
8826
|
+
}
|
|
8827
|
+
try {
|
|
8828
|
+
const result = await runHookCheck({
|
|
8829
|
+
...transcriptPath ? { transcriptPath } : {},
|
|
8830
|
+
...stateFilePath ? { stateFilePath } : {},
|
|
8831
|
+
...langArg ? { lang: langArg } : {}
|
|
8832
|
+
});
|
|
8833
|
+
if (asJson) {
|
|
8834
|
+
console.log(
|
|
8835
|
+
JSON.stringify({
|
|
8836
|
+
...result.decision,
|
|
8837
|
+
transcript_found: result.transcript_found,
|
|
8838
|
+
...result.metrics ? {
|
|
8839
|
+
session_hash: result.metrics.session_hash,
|
|
8840
|
+
current_input_tokens: result.metrics.current_input_tokens,
|
|
8841
|
+
recent_cache_hit_pct: result.metrics.recent_cache_hit_pct
|
|
8842
|
+
} : {}
|
|
8843
|
+
})
|
|
8844
|
+
);
|
|
8845
|
+
} else if (result.decision.should_notify && result.decision.message) {
|
|
8846
|
+
console.error(result.decision.message);
|
|
8847
|
+
}
|
|
8848
|
+
} catch {
|
|
8849
|
+
}
|
|
8850
|
+
process.exitCode = 0;
|
|
8851
|
+
return;
|
|
8852
|
+
}
|
|
6557
8853
|
case "setup": {
|
|
6558
8854
|
console.log(buildSetupInstructions());
|
|
6559
8855
|
return;
|