agycraft-mcp 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2220 -122
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
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() {
|
|
@@ -1522,25 +1522,82 @@ function getLocalizedBehavior(behaviors, key, locale) {
|
|
|
1522
1522
|
return typeof enVal === "string" ? enVal : void 0;
|
|
1523
1523
|
}
|
|
1524
1524
|
|
|
1525
|
-
// src/storage/rollups.ts
|
|
1526
|
-
import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
|
|
1527
|
-
import {
|
|
1528
|
-
mkdir as mkdir2,
|
|
1529
|
-
open,
|
|
1530
|
-
readdir as readdir3,
|
|
1531
|
-
readFile as readFile5,
|
|
1532
|
-
rename,
|
|
1533
|
-
rm,
|
|
1534
|
-
stat as stat2,
|
|
1535
|
-
unlink,
|
|
1536
|
-
writeFile as writeFile2
|
|
1537
|
-
} from "fs/promises";
|
|
1538
|
-
import { dirname as dirname2, join as join6 } from "path";
|
|
1539
|
-
|
|
1540
1525
|
// src/collectors/transcript-meta.ts
|
|
1526
|
+
import { createHash as createHash2 } from "crypto";
|
|
1541
1527
|
import { readdir as readdir2, readFile as readFile4 } from "fs/promises";
|
|
1542
1528
|
import { join as join5, resolve as resolve4 } from "path";
|
|
1543
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
|
+
}
|
|
1544
1601
|
function sanitizeToolCategory(raw) {
|
|
1545
1602
|
if (typeof raw !== "string") {
|
|
1546
1603
|
return "unknown_tool";
|
|
@@ -1572,6 +1629,45 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1572
1629
|
let currentStreakTool = null;
|
|
1573
1630
|
let maxConsecutiveFailures = 0;
|
|
1574
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
|
+
};
|
|
1575
1671
|
for (const line of lines) {
|
|
1576
1672
|
const trimmed = line.trim();
|
|
1577
1673
|
if (!trimmed) {
|
|
@@ -1591,8 +1687,27 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1591
1687
|
if (eventType === "compact" || eventType === "compaction") {
|
|
1592
1688
|
hasCompactEvent = true;
|
|
1593
1689
|
stepsSinceLastCompact = 0;
|
|
1690
|
+
seenReadFileHashes.clear();
|
|
1594
1691
|
continue;
|
|
1595
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
|
+
}
|
|
1596
1711
|
if (role === "user" || eventType === "user_message" || eventType === "user_input" || source === "USER_EXPLICIT") {
|
|
1597
1712
|
userTurns += 1;
|
|
1598
1713
|
currentStreak = 0;
|
|
@@ -1608,6 +1723,10 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1608
1723
|
}
|
|
1609
1724
|
const tcObj = tc;
|
|
1610
1725
|
const toolName = sanitizeToolCategory(tcObj.tool_name ?? tcObj.name);
|
|
1726
|
+
trackToolRedundancy(
|
|
1727
|
+
toolName,
|
|
1728
|
+
tcObj.arguments ?? tcObj.args ?? tcObj.input ?? tcObj.params
|
|
1729
|
+
);
|
|
1611
1730
|
const failed = tcObj.is_error === true || tcObj.status === "error" || tcObj.status === "failed" || typeof tcObj.exit_code === "number" && tcObj.exit_code !== 0;
|
|
1612
1731
|
if (failed) {
|
|
1613
1732
|
toolErrorCount += 1;
|
|
@@ -1633,6 +1752,10 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1633
1752
|
if (isToolEvent) {
|
|
1634
1753
|
toolCallCount += 1;
|
|
1635
1754
|
const toolName = sanitizeToolCategory(parsed.tool_name ?? parsed.name);
|
|
1755
|
+
trackToolRedundancy(
|
|
1756
|
+
toolName,
|
|
1757
|
+
parsed.arguments ?? parsed.args ?? parsed.input ?? parsed.params
|
|
1758
|
+
);
|
|
1636
1759
|
const failed = parsed.is_error === true || parsed.status === "error" || parsed.status === "failed" || typeof parsed.exit_code === "number" && parsed.exit_code !== 0;
|
|
1637
1760
|
if (failed) {
|
|
1638
1761
|
toolErrorCount += 1;
|
|
@@ -1662,7 +1785,13 @@ function parseTranscriptLines(lines, loopThreshold = 4) {
|
|
|
1662
1785
|
consecutive_failure_tool_type: maxFailureTool,
|
|
1663
1786
|
has_compact_event: hasCompactEvent,
|
|
1664
1787
|
steps_since_last_compact: stepsSinceLastCompact,
|
|
1665
|
-
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
|
|
1666
1795
|
};
|
|
1667
1796
|
}
|
|
1668
1797
|
function emptyTranscriptMeta() {
|
|
@@ -1676,7 +1805,13 @@ function emptyTranscriptMeta() {
|
|
|
1676
1805
|
consecutive_failure_tool_type: null,
|
|
1677
1806
|
has_compact_event: false,
|
|
1678
1807
|
steps_since_last_compact: 0,
|
|
1679
|
-
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
|
|
1680
1815
|
};
|
|
1681
1816
|
}
|
|
1682
1817
|
function extractStructuralTimestampMs(parsed) {
|
|
@@ -2023,11 +2158,437 @@ async function collectTranscriptUsageRecords(options) {
|
|
|
2023
2158
|
};
|
|
2024
2159
|
}
|
|
2025
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
|
+
|
|
2026
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";
|
|
2027
2588
|
var STALE_LOCK_MS = 1e4;
|
|
2028
2589
|
var DEFAULT_COLD_BRAIN_DAYS = 30;
|
|
2029
2590
|
function computeSaltFingerprint(salt) {
|
|
2030
|
-
return
|
|
2591
|
+
return createHash4("sha256").update(salt).digest("hex").slice(0, 12);
|
|
2031
2592
|
}
|
|
2032
2593
|
function computeModelsFingerprint(input) {
|
|
2033
2594
|
const models = Array.isArray(input.models) ? input.models : [];
|
|
@@ -2041,16 +2602,16 @@ function computeModelsFingerprint(input) {
|
|
|
2041
2602
|
pricing: m.pricing
|
|
2042
2603
|
})).sort((a, b) => a.id.localeCompare(b.id))
|
|
2043
2604
|
};
|
|
2044
|
-
return
|
|
2605
|
+
return createHash4("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 12);
|
|
2045
2606
|
}
|
|
2046
2607
|
async function cleanupRollupsDirKeepLock(rollupsDir) {
|
|
2047
2608
|
try {
|
|
2048
|
-
const entries = await
|
|
2609
|
+
const entries = await readdir4(rollupsDir, { withFileTypes: true });
|
|
2049
2610
|
for (const entry of entries) {
|
|
2050
2611
|
if (entry.name === ".rollup.lock") {
|
|
2051
2612
|
continue;
|
|
2052
2613
|
}
|
|
2053
|
-
await rm(
|
|
2614
|
+
await rm(join7(rollupsDir, entry.name), { recursive: true, force: true });
|
|
2054
2615
|
}
|
|
2055
2616
|
} catch {
|
|
2056
2617
|
}
|
|
@@ -2156,9 +2717,9 @@ function getUtcMonthKey(ms) {
|
|
|
2156
2717
|
return formatBucketKey(ms, "monthly", "UTC");
|
|
2157
2718
|
}
|
|
2158
2719
|
async function atomicWriteJson(targetPath, data) {
|
|
2159
|
-
await
|
|
2720
|
+
await mkdir3(dirname3(targetPath), { recursive: true });
|
|
2160
2721
|
const tmpPath = `${targetPath}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
|
|
2161
|
-
await
|
|
2722
|
+
await writeFile3(tmpPath, JSON.stringify(data, null, 2), {
|
|
2162
2723
|
encoding: "utf8",
|
|
2163
2724
|
mode: 384
|
|
2164
2725
|
});
|
|
@@ -2167,7 +2728,7 @@ async function atomicWriteJson(targetPath, data) {
|
|
|
2167
2728
|
async function safeReadJson(filePath) {
|
|
2168
2729
|
let raw;
|
|
2169
2730
|
try {
|
|
2170
|
-
raw = await
|
|
2731
|
+
raw = await readFile6(filePath, "utf8");
|
|
2171
2732
|
} catch (err) {
|
|
2172
2733
|
const code = err?.code;
|
|
2173
2734
|
if (code === "ENOENT") {
|
|
@@ -2186,12 +2747,12 @@ async function safeReadJson(filePath) {
|
|
|
2186
2747
|
}
|
|
2187
2748
|
}
|
|
2188
2749
|
async function acquireRollupLock(rollupsDir, timeoutMs = 150) {
|
|
2189
|
-
await
|
|
2190
|
-
const lockPath =
|
|
2750
|
+
await mkdir3(rollupsDir, { recursive: true });
|
|
2751
|
+
const lockPath = join7(rollupsDir, ".rollup.lock");
|
|
2191
2752
|
const deadline = Date.now() + timeoutMs;
|
|
2192
2753
|
while (true) {
|
|
2193
2754
|
try {
|
|
2194
|
-
const fh = await
|
|
2755
|
+
const fh = await open2(lockPath, "wx", 384);
|
|
2195
2756
|
await fh.writeFile(JSON.stringify({ pid: process.pid, ts: Date.now() }), "utf8");
|
|
2196
2757
|
await fh.close();
|
|
2197
2758
|
return lockPath;
|
|
@@ -2201,10 +2762,10 @@ async function acquireRollupLock(rollupsDir, timeoutMs = 150) {
|
|
|
2201
2762
|
return null;
|
|
2202
2763
|
}
|
|
2203
2764
|
try {
|
|
2204
|
-
const st = await
|
|
2765
|
+
const st = await stat3(lockPath);
|
|
2205
2766
|
let lockTs = st.mtimeMs;
|
|
2206
2767
|
try {
|
|
2207
|
-
const raw = await
|
|
2768
|
+
const raw = await readFile6(lockPath, "utf8");
|
|
2208
2769
|
const parsed = JSON.parse(raw);
|
|
2209
2770
|
if (typeof parsed.ts === "number") {
|
|
2210
2771
|
lockTs = parsed.ts;
|
|
@@ -2236,7 +2797,7 @@ async function releaseLock(lockPath) {
|
|
|
2236
2797
|
async function readFileIncrementalLines(filePath, watermark) {
|
|
2237
2798
|
let st;
|
|
2238
2799
|
try {
|
|
2239
|
-
st = await
|
|
2800
|
+
st = await stat3(filePath);
|
|
2240
2801
|
} catch {
|
|
2241
2802
|
return null;
|
|
2242
2803
|
}
|
|
@@ -2249,7 +2810,7 @@ async function readFileIncrementalLines(filePath, watermark) {
|
|
|
2249
2810
|
if (bytesToRead <= 0) {
|
|
2250
2811
|
return { lines: [], newOffset: st.size, mtimeMs: st.mtimeMs, resetRequired };
|
|
2251
2812
|
}
|
|
2252
|
-
const fh = await
|
|
2813
|
+
const fh = await open2(filePath, "r");
|
|
2253
2814
|
try {
|
|
2254
2815
|
const buf = Buffer.alloc(bytesToRead);
|
|
2255
2816
|
const { bytesRead } = await fh.read(buf, 0, bytesToRead, startOffset);
|
|
@@ -2458,8 +3019,8 @@ async function queryRollups(options) {
|
|
|
2458
3019
|
const nowMs = options.nowMs ?? Date.now();
|
|
2459
3020
|
const readonly = isReadonlyEnv(options.readonly);
|
|
2460
3021
|
const rollupsDir = options.rollupsDir ?? getRollupsDir();
|
|
2461
|
-
const hourlyDir =
|
|
2462
|
-
const watermarksPath =
|
|
3022
|
+
const hourlyDir = join7(rollupsDir, "hourly");
|
|
3023
|
+
const watermarksPath = join7(rollupsDir, "watermarks.json");
|
|
2463
3024
|
const catalog = options.models ?? [];
|
|
2464
3025
|
const rules = options.normalizationRules;
|
|
2465
3026
|
const tz = normalizeTimezone(options.timezone);
|
|
@@ -2496,14 +3057,14 @@ async function queryRollups(options) {
|
|
|
2496
3057
|
let corruptDetected = wmRes.status === "corrupt";
|
|
2497
3058
|
let existingHourlyFiles = [];
|
|
2498
3059
|
try {
|
|
2499
|
-
const files = await
|
|
3060
|
+
const files = await readdir4(hourlyDir);
|
|
2500
3061
|
existingHourlyFiles = files.filter((f) => /^\d{4}-\d{2}\.json$/.test(f)).sort();
|
|
2501
3062
|
} catch {
|
|
2502
3063
|
existingHourlyFiles = [];
|
|
2503
3064
|
}
|
|
2504
3065
|
let hasLegacyPeriodFiles = false;
|
|
2505
3066
|
try {
|
|
2506
|
-
const rootFiles = await
|
|
3067
|
+
const rootFiles = await readdir4(rollupsDir);
|
|
2507
3068
|
hasLegacyPeriodFiles = rootFiles.some(
|
|
2508
3069
|
(f) => f === "daily.json" || f === "weekly.json" || f === "monthly.json"
|
|
2509
3070
|
);
|
|
@@ -2513,7 +3074,7 @@ async function queryRollups(options) {
|
|
|
2513
3074
|
let legacySchemaDetected = false;
|
|
2514
3075
|
if (!corruptDetected) {
|
|
2515
3076
|
for (const f of existingHourlyFiles) {
|
|
2516
|
-
const hRes = await safeReadJson(
|
|
3077
|
+
const hRes = await safeReadJson(join7(hourlyDir, f));
|
|
2517
3078
|
if (hRes.status === "corrupt") {
|
|
2518
3079
|
corruptDetected = true;
|
|
2519
3080
|
break;
|
|
@@ -2555,7 +3116,7 @@ async function queryRollups(options) {
|
|
|
2555
3116
|
return cached;
|
|
2556
3117
|
}
|
|
2557
3118
|
if (useDiskRollups) {
|
|
2558
|
-
const filePath =
|
|
3119
|
+
const filePath = join7(hourlyDir, `${monthKey}.json`);
|
|
2559
3120
|
const res = await safeReadJson(filePath);
|
|
2560
3121
|
if (res.status === "ok" && res.data.buckets) {
|
|
2561
3122
|
for (const entries of Object.values(res.data.buckets)) {
|
|
@@ -2707,13 +3268,13 @@ async function queryRollups(options) {
|
|
|
2707
3268
|
const projectIndex = await buildConversationProjectIndex(historyPath, salt);
|
|
2708
3269
|
let sessionDirs = [];
|
|
2709
3270
|
try {
|
|
2710
|
-
const entries = await
|
|
3271
|
+
const entries = await readdir4(brainDir, { withFileTypes: true });
|
|
2711
3272
|
sessionDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
2712
3273
|
} catch {
|
|
2713
3274
|
sessionDirs = [];
|
|
2714
3275
|
}
|
|
2715
3276
|
for (const sessionId of sessionDirs) {
|
|
2716
|
-
const transcriptPath =
|
|
3277
|
+
const transcriptPath = join7(
|
|
2717
3278
|
brainDir,
|
|
2718
3279
|
sessionId,
|
|
2719
3280
|
".system_generated",
|
|
@@ -2722,7 +3283,7 @@ async function queryRollups(options) {
|
|
|
2722
3283
|
);
|
|
2723
3284
|
let st;
|
|
2724
3285
|
try {
|
|
2725
|
-
st = await
|
|
3286
|
+
st = await stat3(transcriptPath);
|
|
2726
3287
|
} catch {
|
|
2727
3288
|
continue;
|
|
2728
3289
|
}
|
|
@@ -2777,7 +3338,7 @@ async function queryRollups(options) {
|
|
|
2777
3338
|
}
|
|
2778
3339
|
if (lastSeenModel === null && dominantModel === null && prevWm && !inc.resetRequired && prevWm.byte_offset > 0) {
|
|
2779
3340
|
try {
|
|
2780
|
-
const headText = await
|
|
3341
|
+
const headText = await readFile6(transcriptPath, "utf8");
|
|
2781
3342
|
const headFreq = /* @__PURE__ */ new Map();
|
|
2782
3343
|
for (const rawLine of headText.split("\n")) {
|
|
2783
3344
|
const t = rawLine.trim();
|
|
@@ -2908,7 +3469,7 @@ async function queryRollups(options) {
|
|
|
2908
3469
|
for (const monthKey of dirtyHourlyMonths) {
|
|
2909
3470
|
const hf = hourlyCache.get(monthKey);
|
|
2910
3471
|
if (hf) {
|
|
2911
|
-
await atomicWriteJson(
|
|
3472
|
+
await atomicWriteJson(join7(hourlyDir, `${monthKey}.json`), hf);
|
|
2912
3473
|
}
|
|
2913
3474
|
}
|
|
2914
3475
|
await atomicWriteJson(watermarksPath, watermarks);
|
|
@@ -3192,12 +3753,12 @@ async function readSaltReadonly(rollupsDir, explicitSalt, explicitSaltPath) {
|
|
|
3192
3753
|
}
|
|
3193
3754
|
const candidates = [
|
|
3194
3755
|
...explicitSaltPath ? [explicitSaltPath] : [],
|
|
3195
|
-
|
|
3756
|
+
join7(dirname3(rollupsDir), ".salt"),
|
|
3196
3757
|
...rollupsDir === getRollupsDir() ? [getSaltFilePath()] : []
|
|
3197
3758
|
];
|
|
3198
3759
|
for (const candidate of candidates) {
|
|
3199
3760
|
try {
|
|
3200
|
-
const content = (await
|
|
3761
|
+
const content = (await readFile6(candidate, "utf8")).trim();
|
|
3201
3762
|
if (content.length > 0) {
|
|
3202
3763
|
return content;
|
|
3203
3764
|
}
|
|
@@ -3209,8 +3770,8 @@ async function readSaltReadonly(rollupsDir, explicitSalt, explicitSaltPath) {
|
|
|
3209
3770
|
async function readRollupCostSummary(options) {
|
|
3210
3771
|
const nowMs = options?.nowMs ?? Date.now();
|
|
3211
3772
|
const rollupsDir = options?.rollupsDir ?? getRollupsDir();
|
|
3212
|
-
const hourlyDir =
|
|
3213
|
-
const watermarksPath =
|
|
3773
|
+
const hourlyDir = join7(rollupsDir, "hourly");
|
|
3774
|
+
const watermarksPath = join7(rollupsDir, "watermarks.json");
|
|
3214
3775
|
const catalog = options?.models ?? [];
|
|
3215
3776
|
const rules = options?.normalizationRules;
|
|
3216
3777
|
const pkgVersion = options?.pkgVersion ?? getPackageVersion();
|
|
@@ -3233,7 +3794,7 @@ async function readRollupCostSummary(options) {
|
|
|
3233
3794
|
if (fingerprintValid) {
|
|
3234
3795
|
const monthKeys = [.../* @__PURE__ */ new Set([getUtcMonthKey(nowMs), getUtcMonthKey(nowMs - WINDOW_MS["7d"])])];
|
|
3235
3796
|
for (const mk of monthKeys) {
|
|
3236
|
-
const res = await safeReadJson(
|
|
3797
|
+
const res = await safeReadJson(join7(hourlyDir, `${mk}.json`));
|
|
3237
3798
|
if (res.status === "ok" && res.data.v === 2 && res.data.buckets) {
|
|
3238
3799
|
hourlyFiles.push(res.data);
|
|
3239
3800
|
}
|
|
@@ -3293,7 +3854,7 @@ tmp/
|
|
|
3293
3854
|
async function loadOfflineModelsSnapshot(snapshotsDir) {
|
|
3294
3855
|
const dir = snapshotsDir ?? getSnapshotsDir();
|
|
3295
3856
|
try {
|
|
3296
|
-
const raw = await
|
|
3857
|
+
const raw = await readFile7(join8(dir, "models.json"), "utf8");
|
|
3297
3858
|
const parsed = JSON.parse(raw);
|
|
3298
3859
|
return {
|
|
3299
3860
|
models: Array.isArray(parsed.models) ? parsed.models : [],
|
|
@@ -3342,7 +3903,7 @@ async function inspectJsonConfig(filePath, kind) {
|
|
|
3342
3903
|
}
|
|
3343
3904
|
let parsed;
|
|
3344
3905
|
try {
|
|
3345
|
-
const raw = await
|
|
3906
|
+
const raw = await readFile7(filePath, "utf8");
|
|
3346
3907
|
parsed = JSON.parse(raw);
|
|
3347
3908
|
} catch (err) {
|
|
3348
3909
|
const msg = err instanceof Error ? err.message : "Invalid JSON syntax";
|
|
@@ -3496,12 +4057,12 @@ async function runDoctor(options) {
|
|
|
3496
4057
|
});
|
|
3497
4058
|
}
|
|
3498
4059
|
const mcpPaths = options?.mcpConfigPaths ?? [
|
|
3499
|
-
|
|
3500
|
-
|
|
4060
|
+
join8(home, ".gemini", "antigravity", "mcp_config.json"),
|
|
4061
|
+
join8(cwd, "mcp_config.json")
|
|
3501
4062
|
];
|
|
3502
4063
|
const settingsPaths = options?.settingsJsonPaths ?? [
|
|
3503
|
-
|
|
3504
|
-
|
|
4064
|
+
join8(home, ".gemini", "settings.json"),
|
|
4065
|
+
join8(cwd, ".gemini", "settings.json")
|
|
3505
4066
|
];
|
|
3506
4067
|
let foundAnyConfig = false;
|
|
3507
4068
|
for (const p of mcpPaths) {
|
|
@@ -3628,7 +4189,7 @@ async function runDoctor(options) {
|
|
|
3628
4189
|
detail: "Direct HTTPS connection environment."
|
|
3629
4190
|
});
|
|
3630
4191
|
}
|
|
3631
|
-
const hasGeminiIgnore = await fileExists(
|
|
4192
|
+
const hasGeminiIgnore = await fileExists(join8(cwd, ".geminiignore"));
|
|
3632
4193
|
checks.push({
|
|
3633
4194
|
id: "geminiignore_check",
|
|
3634
4195
|
category: "context_hygiene",
|
|
@@ -3638,15 +4199,15 @@ async function runDoctor(options) {
|
|
|
3638
4199
|
fix_hint: hasGeminiIgnore ? void 0 : "Create a `.geminiignore` file using the recommended template below."
|
|
3639
4200
|
});
|
|
3640
4201
|
const ruleCandidates = [
|
|
3641
|
-
{ label: "~/.gemini/GEMINI.md", path:
|
|
3642
|
-
{ label: "./GEMINI.md", path:
|
|
3643
|
-
{ 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") }
|
|
3644
4205
|
];
|
|
3645
4206
|
let totalRuleBytes = 0;
|
|
3646
4207
|
let foundRuleFiles = 0;
|
|
3647
4208
|
for (const candidate of ruleCandidates) {
|
|
3648
4209
|
try {
|
|
3649
|
-
const s = await
|
|
4210
|
+
const s = await stat4(candidate.path);
|
|
3650
4211
|
if (s.isFile()) {
|
|
3651
4212
|
totalRuleBytes += s.size;
|
|
3652
4213
|
foundRuleFiles += 1;
|
|
@@ -3720,6 +4281,70 @@ async function runDoctor(options) {
|
|
|
3720
4281
|
});
|
|
3721
4282
|
}
|
|
3722
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
|
+
}
|
|
3723
4348
|
checks.push({
|
|
3724
4349
|
id: "git_safety_guardrail",
|
|
3725
4350
|
category: "safety_guardrail",
|
|
@@ -4022,44 +4647,1091 @@ function formatPreflightReport(result) {
|
|
|
4022
4647
|
return lines.join("\n");
|
|
4023
4648
|
}
|
|
4024
4649
|
|
|
4025
|
-
// src/cli/
|
|
4026
|
-
|
|
4027
|
-
|
|
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
|
+
}
|
|
4028
4696
|
return [
|
|
4029
|
-
|
|
4030
|
-
"
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
|
|
4037
|
-
|
|
4038
|
-
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
|
|
4043
|
-
|
|
4044
|
-
|
|
4045
|
-
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
4051
|
-
|
|
4052
|
-
|
|
4053
|
-
|
|
4054
|
-
|
|
4055
|
-
|
|
4056
|
-
|
|
4057
|
-
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
|
|
4062
|
-
|
|
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
|
+
"================================================================",
|
|
5703
|
+
"No files have been modified automatically. Copy and paste only what you want.",
|
|
5704
|
+
"",
|
|
5705
|
+
"1. Register agycraft MCP Server:",
|
|
5706
|
+
"",
|
|
5707
|
+
" Option A \u2014 Antigravity CLI (`agy`) one-liner:",
|
|
5708
|
+
" agy mcp add agycraft npx -y agycraft-mcp",
|
|
5709
|
+
"",
|
|
5710
|
+
" (Local dev testing against a local ModelCraft server):",
|
|
5711
|
+
" agy mcp add --env MODELCRAFT_DATA_URL=http://127.0.0.1:4321/data/v1 agycraft agycraft-mcp",
|
|
5712
|
+
"",
|
|
5713
|
+
" Option B \u2014 Antigravity IDE (~/.gemini/antigravity/mcp_config.json)",
|
|
5714
|
+
" or Gemini CLI (~/.gemini/settings.json):",
|
|
5715
|
+
"",
|
|
5716
|
+
JSON.stringify(
|
|
5717
|
+
{
|
|
5718
|
+
mcpServers: {
|
|
5719
|
+
agycraft: {
|
|
5720
|
+
command: "npx",
|
|
5721
|
+
args: ["-y", "agycraft-mcp"]
|
|
5722
|
+
}
|
|
5723
|
+
}
|
|
5724
|
+
},
|
|
5725
|
+
null,
|
|
5726
|
+
2
|
|
5727
|
+
),
|
|
5728
|
+
"",
|
|
5729
|
+
"2. (Optional) Enable Privacy-Safe Gemini CLI OpenTelemetry outfile (exact token & model metrics)",
|
|
5730
|
+
" Add to ~/.gemini/settings.json (logPrompts MUST remain false):",
|
|
5731
|
+
"",
|
|
5732
|
+
JSON.stringify(
|
|
5733
|
+
{
|
|
5734
|
+
telemetry: {
|
|
4063
5735
|
enabled: true,
|
|
4064
5736
|
target: "local",
|
|
4065
5737
|
otlpEndpoint: "",
|
|
@@ -4145,13 +5817,13 @@ function buildSetupInstructions() {
|
|
|
4145
5817
|
import { rm as rm2 } from "fs/promises";
|
|
4146
5818
|
|
|
4147
5819
|
// src/collectors/agy-hook.ts
|
|
4148
|
-
import { appendFile, mkdir as
|
|
4149
|
-
import { dirname as
|
|
5820
|
+
import { appendFile, mkdir as mkdir7, readFile as readFile11 } from "fs/promises";
|
|
5821
|
+
import { dirname as dirname7 } from "path";
|
|
4150
5822
|
async function appendUsageRecord(rawPayload, options) {
|
|
4151
5823
|
const logPath = options?.logPath ?? getUsageLogPath();
|
|
4152
5824
|
const salt = await getOrCreateLocalSalt(options?.saltPath);
|
|
4153
5825
|
const record = sanitizeUsagePayload(rawPayload, salt);
|
|
4154
|
-
await
|
|
5826
|
+
await mkdir7(dirname7(logPath), { recursive: true });
|
|
4155
5827
|
await appendFile(logPath, `${JSON.stringify(record)}
|
|
4156
5828
|
`, {
|
|
4157
5829
|
encoding: "utf8",
|
|
@@ -4163,7 +5835,7 @@ async function readUsageRecords(options) {
|
|
|
4163
5835
|
const logPath = options?.logPath ?? getUsageLogPath();
|
|
4164
5836
|
let content;
|
|
4165
5837
|
try {
|
|
4166
|
-
content = await
|
|
5838
|
+
content = await readFile11(logPath, "utf8");
|
|
4167
5839
|
} catch {
|
|
4168
5840
|
return [];
|
|
4169
5841
|
}
|
|
@@ -4218,19 +5890,19 @@ async function clearLocalData(options) {
|
|
|
4218
5890
|
|
|
4219
5891
|
// src/server.ts
|
|
4220
5892
|
import { access as access2 } from "fs/promises";
|
|
4221
|
-
import { join as
|
|
5893
|
+
import { join as join13 } from "path";
|
|
4222
5894
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4223
5895
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4224
5896
|
import { z } from "zod";
|
|
4225
5897
|
|
|
4226
5898
|
// src/collectors/gemini-otel.ts
|
|
4227
|
-
import { readFile as
|
|
5899
|
+
import { readFile as readFile12 } from "fs/promises";
|
|
4228
5900
|
async function readGeminiOtelRecords(options) {
|
|
4229
5901
|
const otelPath = options?.otelPath ?? getDefaultGeminiTelemetryPath();
|
|
4230
5902
|
const salt = options?.salt ?? await getOrCreateLocalSalt(options?.saltPath);
|
|
4231
5903
|
let content;
|
|
4232
5904
|
try {
|
|
4233
|
-
content = await
|
|
5905
|
+
content = await readFile12(otelPath, "utf8");
|
|
4234
5906
|
} catch {
|
|
4235
5907
|
return [];
|
|
4236
5908
|
}
|
|
@@ -4363,23 +6035,91 @@ function analyzeAntipatterns(records, options) {
|
|
|
4363
6035
|
const longSessions = /* @__PURE__ */ new Map();
|
|
4364
6036
|
for (const r of filtered) {
|
|
4365
6037
|
const cur = longSessions.get(r.session_hash) ?? {
|
|
6038
|
+
sessionHash: r.session_hash,
|
|
4366
6039
|
maxTurn: 0,
|
|
4367
6040
|
maxCtxPct: null,
|
|
4368
6041
|
totalInput: 0,
|
|
6042
|
+
totalCacheRead: 0,
|
|
6043
|
+
peakReqInput: 0,
|
|
6044
|
+
latestReqInput: 0,
|
|
6045
|
+
latestTsMs: 0,
|
|
6046
|
+
maxIdleGapSec: 0,
|
|
6047
|
+
recent429Count: 0,
|
|
6048
|
+
recentWindows: [],
|
|
4369
6049
|
turns: 0
|
|
4370
6050
|
};
|
|
4371
6051
|
cur.maxTurn = Math.max(cur.maxTurn, r.turn_index);
|
|
4372
6052
|
if (typeof r.context_used_pct === "number") {
|
|
4373
6053
|
cur.maxCtxPct = cur.maxCtxPct === null ? r.context_used_pct : Math.max(cur.maxCtxPct, r.context_used_pct);
|
|
4374
6054
|
}
|
|
4375
|
-
|
|
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
|
+
}
|
|
4376
6084
|
cur.turns += 1;
|
|
4377
6085
|
longSessions.set(r.session_hash, cur);
|
|
4378
6086
|
}
|
|
4379
|
-
const snowballSessions = [...longSessions.values()].filter(
|
|
4380
|
-
|
|
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))
|
|
4381
6122
|
);
|
|
4382
|
-
const transcriptUncompacted = options?.transcriptMeta && options.transcriptMeta.steps_since_last_compact >= 30;
|
|
4383
6123
|
if (snowballSessions.length > 0 || transcriptUncompacted) {
|
|
4384
6124
|
const ctxValues = snowballSessions.map((s) => s.maxCtxPct).filter((v) => v !== null);
|
|
4385
6125
|
const peakCtx = ctxValues.length > 0 ? Math.max(...ctxValues) : null;
|
|
@@ -4445,6 +6185,36 @@ function analyzeAntipatterns(records, options) {
|
|
|
4445
6185
|
estimated_savings_pct: "40\u201380% on runaway turns"
|
|
4446
6186
|
});
|
|
4447
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
|
+
}
|
|
4448
6218
|
if (options?.hasGeminiIgnore === false) {
|
|
4449
6219
|
recs.push({
|
|
4450
6220
|
id: "missing_geminiignore",
|
|
@@ -5771,8 +7541,8 @@ function computeResetCountdown(options) {
|
|
|
5771
7541
|
}
|
|
5772
7542
|
|
|
5773
7543
|
// src/remote/snapshot-client.ts
|
|
5774
|
-
import { mkdir as
|
|
5775
|
-
import { join as
|
|
7544
|
+
import { mkdir as mkdir8, readFile as readFile13, writeFile as writeFile7 } from "fs/promises";
|
|
7545
|
+
import { join as join12 } from "path";
|
|
5776
7546
|
var DEFAULT_DATA_URL2 = "https://modelcraft.dev/data/v1";
|
|
5777
7547
|
var TTL_MS = {
|
|
5778
7548
|
status: 5 * 60 * 1e3,
|
|
@@ -5860,8 +7630,8 @@ var SnapshotClient = class {
|
|
|
5860
7630
|
this.pkgVersion = options?.pkgVersion ?? getPackageVersion();
|
|
5861
7631
|
}
|
|
5862
7632
|
async get(name) {
|
|
5863
|
-
const cacheFile =
|
|
5864
|
-
const metaFile =
|
|
7633
|
+
const cacheFile = join12(this.cacheDir, `${name}.json`);
|
|
7634
|
+
const metaFile = join12(this.cacheDir, `${name}.meta.json`);
|
|
5865
7635
|
const ttl = TTL_MS[name];
|
|
5866
7636
|
const cached = await this.readCache(cacheFile, metaFile);
|
|
5867
7637
|
const versionMatches = cached?.meta.pkg_version === this.pkgVersion;
|
|
@@ -5890,8 +7660,8 @@ var SnapshotClient = class {
|
|
|
5890
7660
|
async readCache(cacheFile, metaFile) {
|
|
5891
7661
|
try {
|
|
5892
7662
|
const [rawJson, rawMeta] = await Promise.all([
|
|
5893
|
-
|
|
5894
|
-
|
|
7663
|
+
readFile13(cacheFile, "utf8"),
|
|
7664
|
+
readFile13(metaFile, "utf8")
|
|
5895
7665
|
]);
|
|
5896
7666
|
const data = JSON.parse(rawJson);
|
|
5897
7667
|
const meta = JSON.parse(rawMeta);
|
|
@@ -5902,15 +7672,15 @@ var SnapshotClient = class {
|
|
|
5902
7672
|
}
|
|
5903
7673
|
async writeCache(cacheFile, metaFile, data, etag) {
|
|
5904
7674
|
try {
|
|
5905
|
-
await
|
|
7675
|
+
await mkdir8(this.cacheDir, { recursive: true });
|
|
5906
7676
|
const meta = {
|
|
5907
7677
|
etag,
|
|
5908
7678
|
fetched_at_ms: Date.now(),
|
|
5909
7679
|
pkg_version: this.pkgVersion
|
|
5910
7680
|
};
|
|
5911
7681
|
await Promise.all([
|
|
5912
|
-
|
|
5913
|
-
|
|
7682
|
+
writeFile7(cacheFile, JSON.stringify(data), "utf8"),
|
|
7683
|
+
writeFile7(metaFile, JSON.stringify(meta), "utf8")
|
|
5914
7684
|
]);
|
|
5915
7685
|
} catch {
|
|
5916
7686
|
}
|
|
@@ -5960,8 +7730,8 @@ var SnapshotClient = class {
|
|
|
5960
7730
|
}
|
|
5961
7731
|
}
|
|
5962
7732
|
async readBundledFallback(name) {
|
|
5963
|
-
const filePath =
|
|
5964
|
-
const raw = await
|
|
7733
|
+
const filePath = join12(this.snapshotsDir, `${name}.json`);
|
|
7734
|
+
const raw = await readFile13(filePath, "utf8");
|
|
5965
7735
|
return JSON.parse(raw);
|
|
5966
7736
|
}
|
|
5967
7737
|
};
|
|
@@ -6073,7 +7843,7 @@ function createAgycraftServer(deps = {}) {
|
|
|
6073
7843
|
const client = deps.snapshotClient ?? new SnapshotClient();
|
|
6074
7844
|
const server = new McpServer({
|
|
6075
7845
|
name: "agycraft-mcp",
|
|
6076
|
-
version: "0.2.
|
|
7846
|
+
version: "0.2.3"
|
|
6077
7847
|
});
|
|
6078
7848
|
server.tool(
|
|
6079
7849
|
"analyze_token_usage",
|
|
@@ -6240,7 +8010,7 @@ function createAgycraftServer(deps = {}) {
|
|
|
6240
8010
|
client.get("channels"),
|
|
6241
8011
|
resolveScopeProjectHash(scope, workspace_dir, deps),
|
|
6242
8012
|
transcript_path ? analyzeTranscriptStructure(transcript_path, loopThreshold) : Promise.resolve(null),
|
|
6243
|
-
workspace_dir ? access2(
|
|
8013
|
+
workspace_dir ? access2(join13(workspace_dir, ".geminiignore")).then(() => true).catch(() => false) : Promise.resolve(void 0)
|
|
6244
8014
|
]);
|
|
6245
8015
|
const registry = ChannelRegistry.fromSnapshot(channelsSnap.data);
|
|
6246
8016
|
const authContext = deps.authContext ? deps.authContext : await detectAuthContext({ cliLogDir: deps.cliLogDir, registry });
|
|
@@ -6632,6 +8402,60 @@ function printPreflightHelp() {
|
|
|
6632
8402
|
].join("\n")
|
|
6633
8403
|
);
|
|
6634
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
|
+
}
|
|
6635
8459
|
function printHelp() {
|
|
6636
8460
|
console.log(
|
|
6637
8461
|
[
|
|
@@ -6642,6 +8466,14 @@ function printHelp() {
|
|
|
6642
8466
|
" agycraft-mcp doctor [--cost] [--window 5h|24h|7d] [--lang en|zh|auto] [--json]",
|
|
6643
8467
|
" Run offline preflight & hygiene check or readonly cost breakdown",
|
|
6644
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)",
|
|
6645
8477
|
" agycraft-mcp setup Print non-destructive, opt-in AGY / Gemini CLI setup snippets",
|
|
6646
8478
|
" agycraft-mcp record Read hook JSON from stdin and append strictly whitelisted numeric metrics",
|
|
6647
8479
|
" agycraft-mcp clear-local-data Safely delete ~/.config/agycraft/usage.jsonl and cache",
|
|
@@ -6752,6 +8584,272 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
6752
8584
|
process.exitCode = result.exit_code;
|
|
6753
8585
|
return;
|
|
6754
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
|
+
}
|
|
6755
8853
|
case "setup": {
|
|
6756
8854
|
console.log(buildSetupInstructions());
|
|
6757
8855
|
return;
|