agycraft-mcp 0.2.1 → 0.2.2

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 CHANGED
@@ -37,7 +37,7 @@ function getPackageVersion() {
37
37
  }
38
38
  } catch {
39
39
  }
40
- cachedPkgVersion = "0.2.1";
40
+ cachedPkgVersion = "0.2.2";
41
41
  return cachedPkgVersion;
42
42
  }
43
43
  function getConfigDir() {
@@ -1426,6 +1426,102 @@ async function detectAuthContext(options) {
1426
1426
  };
1427
1427
  }
1428
1428
 
1429
+ // src/i18n.ts
1430
+ function normalizeExplicitLang(raw) {
1431
+ if (typeof raw !== "string") {
1432
+ return void 0;
1433
+ }
1434
+ const normalized = raw.trim().toLowerCase();
1435
+ if (!normalized || normalized === "auto") {
1436
+ return void 0;
1437
+ }
1438
+ if (normalized === "zh" || normalized.startsWith("zh-") || normalized.startsWith("zh_")) {
1439
+ return "zh";
1440
+ }
1441
+ if (normalized === "en" || normalized.startsWith("en-") || normalized.startsWith("en_")) {
1442
+ return "en";
1443
+ }
1444
+ return void 0;
1445
+ }
1446
+ function resolveLocale(explicitLang, env = process.env) {
1447
+ const fromArg = normalizeExplicitLang(explicitLang);
1448
+ if (fromArg) {
1449
+ return fromArg;
1450
+ }
1451
+ const fromEnv = normalizeExplicitLang(env.AGYCRAFT_LANG);
1452
+ if (fromEnv) {
1453
+ return fromEnv;
1454
+ }
1455
+ const sysLocale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || "").trim().toLowerCase();
1456
+ if (sysLocale.includes("zh")) {
1457
+ return "zh";
1458
+ }
1459
+ return "en";
1460
+ }
1461
+ function hasNonEmptyValue(val) {
1462
+ if (typeof val === "string") {
1463
+ return val.trim().length > 0;
1464
+ }
1465
+ if (Array.isArray(val)) {
1466
+ return val.length > 0;
1467
+ }
1468
+ return val !== void 0 && val !== null;
1469
+ }
1470
+ function localizeSnapshotText(value, locale) {
1471
+ if (value === null || value === void 0 || typeof value !== "object") {
1472
+ return value;
1473
+ }
1474
+ if (Array.isArray(value)) {
1475
+ return value.map((item) => localizeSnapshotText(item, locale));
1476
+ }
1477
+ const record = value;
1478
+ const out = {};
1479
+ for (const [key, val] of Object.entries(record)) {
1480
+ if (key.endsWith("_zh")) {
1481
+ continue;
1482
+ }
1483
+ out[key] = localizeSnapshotText(val, locale);
1484
+ }
1485
+ if (locale === "zh") {
1486
+ for (const [key, val] of Object.entries(record)) {
1487
+ if (!key.endsWith("_zh") || !hasNonEmptyValue(val)) {
1488
+ continue;
1489
+ }
1490
+ if (key === "reset_rules_notes_zh" && out.reset_rules && typeof out.reset_rules === "object") {
1491
+ out.reset_rules.notes = val;
1492
+ continue;
1493
+ }
1494
+ const baseKey = key.slice(0, -3);
1495
+ if (baseKey === "fix_steps" && !("fix_steps" in out) && "steps" in out) {
1496
+ out.steps = localizeSnapshotText(val, locale);
1497
+ } else {
1498
+ out[baseKey] = localizeSnapshotText(val, locale);
1499
+ }
1500
+ }
1501
+ }
1502
+ return out;
1503
+ }
1504
+ function localizeDiagnosisEntry(entry, locale) {
1505
+ return localizeSnapshotText(entry, locale);
1506
+ }
1507
+ function localizeModelEntry(entry, locale) {
1508
+ return localizeSnapshotText(entry, locale);
1509
+ }
1510
+ function getLocalizedBehavior(behaviors, key, locale) {
1511
+ if (!behaviors) {
1512
+ return void 0;
1513
+ }
1514
+ if (locale === "zh") {
1515
+ const zhKey = `${key}_zh`;
1516
+ const zhVal = behaviors[zhKey];
1517
+ if (typeof zhVal === "string" && zhVal.trim().length > 0) {
1518
+ return zhVal;
1519
+ }
1520
+ }
1521
+ const enVal = behaviors[key];
1522
+ return typeof enVal === "string" ? enVal : void 0;
1523
+ }
1524
+
1429
1525
  // src/storage/rollups.ts
1430
1526
  import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
1431
1527
  import {
@@ -3358,6 +3454,7 @@ async function runDoctor(options) {
3358
3454
  const cwd = options?.cwd ?? process.cwd();
3359
3455
  const home = options?.homeDir ?? homedir3();
3360
3456
  const env = options?.env ?? process.env;
3457
+ const locale = resolveLocale(options?.lang, env);
3361
3458
  const registry = options?.channels instanceof ChannelRegistry ? options.channels : options?.channels ? ChannelRegistry.fromSnapshot(options.channels) : loadBundledChannelRegistry(options?.snapshotsDir);
3362
3459
  const authContext = await detectAuthContext({
3363
3460
  homeDir: home,
@@ -3559,7 +3656,7 @@ async function runDoctor(options) {
3559
3656
  }
3560
3657
  const estimatedRuleTokens = Math.ceil(totalRuleBytes / 4);
3561
3658
  if (estimatedRuleTokens > 3e3) {
3562
- const channelHint = activeChannel ? ` Active channel (${activeChannel.channelId}): ${activeChannel.definition.recommended_behaviors.kv_cache_guidance}` : "";
3659
+ const channelHint = activeChannel ? ` Active channel (${activeChannel.channelId}): ${getLocalizedBehavior(activeChannel.definition.recommended_behaviors, "kv_cache_guidance", locale) ?? activeChannel.definition.recommended_behaviors.kv_cache_guidance}` : "";
3563
3660
  checks.push({
3564
3661
  id: "global_rules_bloat",
3565
3662
  category: "context_hygiene",
@@ -3603,7 +3700,7 @@ async function runDoctor(options) {
3603
3700
  title: has429 ? `Cost summary (5h: ${w5h.total_requests} reqs, ${w5h.rate_limit_429_count} x 429; 24h: ${w24h.total_requests} reqs)` : `Cost summary (5h: ${w5h.total_requests} reqs | 24h: ${w24h.total_requests} reqs)`,
3604
3701
  detail: `5h -> ${formatChannelSummaryText(w5h)} || 24h -> ${formatChannelSummaryText(w24h)}`,
3605
3702
  ...has429 ? {
3606
- fix_hint: activeChannel ? `429 rate limits detected in last 5h (${activeChannel.channelId}): ${activeChannel.definition.recommended_behaviors.throttling_guidance}` : "429 rate limits detected in last 5h. Run `npx agycraft-mcp preflight` to inspect live upstream status.json."
3703
+ fix_hint: activeChannel ? `429 rate limits detected in last 5h (${activeChannel.channelId}): ${getLocalizedBehavior(activeChannel.definition.recommended_behaviors, "throttling_guidance", locale) ?? activeChannel.definition.recommended_behaviors.throttling_guidance}` : "429 rate limits detected in last 5h. Run `npx agycraft-mcp preflight` to inspect live upstream status.json."
3607
3704
  } : {}
3608
3705
  });
3609
3706
  if (w24h.deprecated_models_in_use.length > 0) {
@@ -4232,6 +4329,7 @@ function analyzeAntipatterns(records, options) {
4232
4329
  const window = options?.window ?? "24h";
4233
4330
  const scope = options?.scope ?? "global";
4234
4331
  const nowMs = options?.nowMs ?? Date.now();
4332
+ const locale = options?.locale ?? "en";
4235
4333
  const registry = options?.channels instanceof ChannelRegistry ? options.channels : options?.channels ? ChannelRegistry.fromSnapshot(options.channels) : loadBundledChannelRegistry();
4236
4334
  const requestedAuthMode = options?.authMode;
4237
4335
  const isSpecificAuthFilter = Boolean(
@@ -4330,7 +4428,7 @@ function analyzeAntipatterns(records, options) {
4330
4428
  category: "thinking_downgrade",
4331
4429
  title: "High Thinking/output token burn on flagship models",
4332
4430
  evidence: `${totalHeavyOutput.toLocaleString()} output/thinking tokens on heavy models (${multiplierNote}).`,
4333
- action: behaviors?.thinking_guidance ?? "Lower Thinking level (e.g. Medium/Low) for boilerplate coding & log parsing, reserving High Thinking strictly for multi-file debugging or architecture.",
4431
+ action: getLocalizedBehavior(behaviors, "thinking_guidance", locale) ?? "Lower Thinking level (e.g. Medium/Low) for boilerplate coding & log parsing, reserving High Thinking strictly for multi-file debugging or architecture.",
4334
4432
  estimated_savings_pct: "25\u201345%"
4335
4433
  });
4336
4434
  }
@@ -4369,7 +4467,7 @@ function analyzeAntipatterns(records, options) {
4369
4467
  category: "low_kv_cache_efficiency",
4370
4468
  title: `Low KV cache hit efficiency${discountNote}`,
4371
4469
  evidence: `KV cache hit rate is ${Math.round(cacheHitRatePct * 10) / 10}% (${totalCacheRead.toLocaleString()} cached / ${totalInputWithCache.toLocaleString()} total input tokens).`,
4372
- action: behaviors?.kv_cache_guidance ?? "Keep system instructions, tool schemas, and file prefixes stable across turns to maximize implicit KV cache hits instead of re-paying full uncached input rates.",
4470
+ action: getLocalizedBehavior(behaviors, "kv_cache_guidance", locale) ?? "Keep system instructions, tool schemas, and file prefixes stable across turns to maximize implicit KV cache hits instead of re-paying full uncached input rates.",
4373
4471
  estimated_savings_pct: "20\u201350% on input cost"
4374
4472
  });
4375
4473
  }
@@ -4427,7 +4525,7 @@ function analyzeAntipatterns(records, options) {
4427
4525
  category: "peak_window_misalignment",
4428
4526
  title: "Peak window concentration causing 429 rate limits",
4429
4527
  evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s).`,
4430
- action: behaviors?.throttling_guidance ?? "Stagger heavy batch runs across 5h rolling windows and align daily quota resets with PT midnight (America/Los_Angeles 00:00) to avoid burst exhaustion.",
4528
+ action: getLocalizedBehavior(behaviors, "throttling_guidance", locale) ?? "Stagger heavy batch runs across 5h rolling windows and align daily quota resets with PT midnight (America/Los_Angeles 00:00) to avoid burst exhaustion.",
4431
4529
  estimated_savings_pct: "15\u201330% fewer 429 retries"
4432
4530
  });
4433
4531
  } else {
@@ -4437,7 +4535,7 @@ function analyzeAntipatterns(records, options) {
4437
4535
  category: "burst_rpm_tpm_throttling",
4438
4536
  title: `Burst RPM/TPM concentration causing 429 throttling (${activeChannelForPolicy.definition.display_name})`,
4439
4537
  evidence: `${top3SharePct}% of token volume was concentrated into 3 peak hours, triggering ${total429} 429/RESOURCE_EXHAUSTED error(s) under ${policy.window_type}.`,
4440
- action: behaviors?.throttling_guidance ?? "Spread concurrent requests across regions or upgrade RPM/TPM quota.",
4538
+ action: getLocalizedBehavior(behaviors, "throttling_guidance", locale) ?? "Spread concurrent requests across regions or upgrade RPM/TPM quota.",
4441
4539
  estimated_savings_pct: "15\u201330% fewer 429 retries"
4442
4540
  });
4443
4541
  }
@@ -4453,7 +4551,11 @@ function analyzeAntipatterns(records, options) {
4453
4551
  category: "background_spend_warning",
4454
4552
  title: `Background monitor / checkpoint calls billed on ${activeChannelForPolicy.definition.display_name}`,
4455
4553
  evidence: `Detected ${bgRecords.length} estimated background CLI monitor call(s) (${bgTokens.toLocaleString()} tokens) on a pay-as-you-go/metered channel.`,
4456
- action: activeChannelForPolicy.definition.recommended_behaviors.background_spend_guidance ?? "Background lightweight calls incur real metered usage on this channel; avoid idle polling loops.",
4554
+ action: getLocalizedBehavior(
4555
+ activeChannelForPolicy.definition.recommended_behaviors,
4556
+ "background_spend_guidance",
4557
+ locale
4558
+ ) ?? "Background lightweight calls incur real metered usage on this channel; avoid idle polling loops.",
4457
4559
  estimated_savings_pct: "10\u201325% background spend"
4458
4560
  });
4459
4561
  }
@@ -4803,18 +4905,20 @@ function buildIsolationCommands(channel) {
4803
4905
  return cmds;
4804
4906
  }
4805
4907
  function applyChannelPrescription(params) {
4806
- const { chosen, resolvedChannel, registry } = params;
4908
+ const { chosen, resolvedChannel, registry, locale = "en" } = params;
4807
4909
  const variant = findChannelVariant(chosen, resolvedChannel, registry);
4808
4910
  if (variant) {
4911
+ const localizedVariant = localizeDiagnosisEntry(variant, locale);
4912
+ const localizedChosen2 = localizeDiagnosisEntry(chosen, locale);
4809
4913
  return {
4810
- ...chosen,
4811
- title: variant.title ?? chosen.title,
4812
- root_cause: variant.root_cause ?? chosen.root_cause,
4813
- steps: variant.steps ?? chosen.steps,
4814
- commands: variant.commands ?? chosen.commands,
4815
- verify_command: variant.verify_command ?? chosen.verify_command,
4816
- dont_dos: variant.dont_dos ?? chosen.dont_dos,
4817
- deep_link: variant.deep_link ?? chosen.deep_link
4914
+ ...localizedChosen2,
4915
+ title: localizedVariant.title ?? localizedChosen2.title,
4916
+ root_cause: localizedVariant.root_cause ?? localizedChosen2.root_cause,
4917
+ steps: localizedVariant.steps ?? localizedChosen2.steps,
4918
+ commands: localizedVariant.commands ?? localizedChosen2.commands,
4919
+ verify_command: localizedVariant.verify_command ?? localizedChosen2.verify_command,
4920
+ dont_dos: localizedVariant.dont_dos ?? localizedChosen2.dont_dos,
4921
+ deep_link: localizedVariant.deep_link ?? localizedChosen2.deep_link
4818
4922
  };
4819
4923
  }
4820
4924
  const channel = resolvedChannel !== "unknown" && resolvedChannel !== "mixed_ambiguous" ? registry.getChannel(resolvedChannel) : void 0;
@@ -4825,57 +4929,66 @@ function applyChannelPrescription(params) {
4825
4929
  if (!isGenericChannelSensitive) {
4826
4930
  return chosen;
4827
4931
  }
4932
+ const localizedChosen = localizeDiagnosisEntry(chosen, locale);
4828
4933
  const behaviors = channel.definition.recommended_behaviors;
4829
4934
  const policy = channel.definition.quota_reset_policy;
4830
4935
  const isoCommands = buildIsolationCommands(channel);
4831
- if (chosen.domain === "quota") {
4936
+ const displayName = locale === "zh" && channel.definition.display_name_zh ? channel.definition.display_name_zh : channel.definition.display_name;
4937
+ const throttlingGuidance = getLocalizedBehavior(behaviors, "throttling_guidance", locale) ?? behaviors.throttling_guidance;
4938
+ const kvCacheGuidance = getLocalizedBehavior(behaviors, "kv_cache_guidance", locale) ?? behaviors.kv_cache_guidance;
4939
+ const backgroundSpendGuidance = getLocalizedBehavior(
4940
+ behaviors,
4941
+ "background_spend_guidance",
4942
+ locale
4943
+ );
4944
+ if (localizedChosen.domain === "quota") {
4832
4945
  if (policy.window_type === "rolling_5h_7d") {
4833
- const cleanSteps = chosen.steps.filter(
4946
+ const cleanSteps = localizedChosen.steps.filter(
4834
4947
  (s) => !/gcloud|aiplatform|cloud\s*billing|aistudio\.google\.com/i.test(s)
4835
4948
  );
4836
4949
  return {
4837
- ...chosen,
4838
- root_cause: `Shared ${policy.window_type} quota bucket exhausted or entitlement desync on ${channel.definition.display_name}. ${behaviors.throttling_guidance}`,
4839
- steps: cleanSteps.length > 0 ? cleanSteps : [behaviors.throttling_guidance, behaviors.kv_cache_guidance],
4950
+ ...localizedChosen,
4951
+ root_cause: locale === "zh" ? `${displayName} \u7684 ${policy.window_type} \u5171\u4EAB\u914D\u989D\u6876\u5DF2\u8017\u5C3D\u6216\u6743\u76CA\u5931\u6B65\u3002${throttlingGuidance}` : `Shared ${policy.window_type} quota bucket exhausted or entitlement desync on ${displayName}. ${throttlingGuidance}`,
4952
+ steps: cleanSteps.length > 0 ? cleanSteps : [throttlingGuidance, kvCacheGuidance],
4840
4953
  commands: isoCommands,
4841
4954
  verify_command: behaviors.verify_command
4842
4955
  };
4843
4956
  }
4844
4957
  const steps = [
4845
- behaviors.throttling_guidance,
4846
- behaviors.kv_cache_guidance,
4847
- ...behaviors.background_spend_guidance ? [behaviors.background_spend_guidance] : []
4958
+ throttlingGuidance,
4959
+ kvCacheGuidance,
4960
+ ...backgroundSpendGuidance ? [backgroundSpendGuidance] : []
4848
4961
  ];
4849
4962
  return {
4850
- ...chosen,
4851
- title: `429 Rate Limit / Quota Exhausted (${channel.definition.display_name})`,
4852
- root_cause: `${channel.definition.display_name} (${channel.definition.billing_model}, window: ${policy.window_type}): ${behaviors.throttling_guidance}`,
4963
+ ...localizedChosen,
4964
+ title: locale === "zh" ? `429 \u9650\u6D41 / \u914D\u989D\u8017\u5C3D\uFF08${displayName}\uFF09` : `429 Rate Limit / Quota Exhausted (${displayName})`,
4965
+ root_cause: `${displayName} (${channel.definition.billing_model}, ${policy.window_type}): ${throttlingGuidance}`,
4853
4966
  steps,
4854
4967
  commands: isoCommands,
4855
4968
  verify_command: behaviors.verify_command,
4856
4969
  dont_dos: [
4857
- "Do NOT apply consumer OAuth shared-bucket onboarding resets to this auth channel.",
4858
- ...chosen.dont_dos.filter(
4970
+ locale === "zh" ? "\u4E0D\u8981\u5BF9\u8BE5\u8BA4\u8BC1\u901A\u9053\u6267\u884C\u4E2A\u4EBA OAuth \u5171\u4EAB\u914D\u989D\u6876\u7684 Reset Onboarding \u91CD\u7F6E\u64CD\u4F5C\u3002" : "Do NOT apply consumer OAuth shared-bucket onboarding resets to this auth channel.",
4971
+ ...localizedChosen.dont_dos.filter(
4859
4972
  (d) => !/reset\s*onboarding|5h\/7d/i.test(d)
4860
4973
  )
4861
4974
  ]
4862
4975
  };
4863
4976
  }
4864
- if (chosen.domain === "auth") {
4977
+ if (localizedChosen.domain === "auth") {
4865
4978
  return {
4866
- ...chosen,
4867
- title: `401/403 Auth & Entitlement Mismatch (${channel.definition.display_name})`,
4868
- root_cause: `Authentication or entitlement mismatch on ${channel.definition.display_name}. Ensure conflicting credentials from other channels are unset.`,
4979
+ ...localizedChosen,
4980
+ title: locale === "zh" ? `401/403 \u8BA4\u8BC1\u4E0E\u6743\u76CA\u4E0D\u5339\u914D\uFF08${displayName}\uFF09` : `401/403 Auth & Entitlement Mismatch (${displayName})`,
4981
+ root_cause: locale === "zh" ? `${displayName} \u5B58\u5728\u8BA4\u8BC1\u6216\u6743\u76CA\u4E0D\u5339\u914D\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u6E05\u7406\u5176\u4ED6\u901A\u9053\u7684\u51B2\u7A81\u73AF\u5883\u53D8\u91CF\u3002` : `Authentication or entitlement mismatch on ${displayName}. Ensure conflicting credentials from other channels are unset.`,
4869
4982
  steps: [
4870
- `Isolate environment variables for ${channel.definition.display_name}.`,
4871
- behaviors.throttling_guidance,
4872
- `Verify connectivity with: ${behaviors.verify_command}`
4983
+ locale === "zh" ? `\u4E3A ${displayName} \u9694\u79BB\u51B2\u7A81\u73AF\u5883\u53D8\u91CF\u3002` : `Isolate environment variables for ${displayName}.`,
4984
+ throttlingGuidance,
4985
+ locale === "zh" ? `\u8FD0\u884C\u6821\u9A8C\u547D\u4EE4\u786E\u8BA4\u8FDE\u901A\u6027\uFF1A${behaviors.verify_command}` : `Verify connectivity with: ${behaviors.verify_command}`
4873
4986
  ],
4874
4987
  commands: isoCommands,
4875
4988
  verify_command: behaviors.verify_command
4876
4989
  };
4877
4990
  }
4878
- return chosen;
4991
+ return localizedChosen;
4879
4992
  }
4880
4993
 
4881
4994
  // src/analyzers/error-diagnoser.ts
@@ -5332,6 +5445,7 @@ function extractSignals(errorText) {
5332
5445
  };
5333
5446
  }
5334
5447
  function diagnoseError(options) {
5448
+ const locale = options.locale ?? "en";
5335
5449
  const text = options.errorText;
5336
5450
  const lowerText = text.toLowerCase();
5337
5451
  const signals = extractSignals(text);
@@ -5422,7 +5536,8 @@ function diagnoseError(options) {
5422
5536
  const chosen = rawChosen ? applyChannelPrescription({
5423
5537
  chosen: rawChosen,
5424
5538
  resolvedChannel,
5425
- registry
5539
+ registry,
5540
+ locale
5426
5541
  }) : null;
5427
5542
  if (!chosen) {
5428
5543
  return {
@@ -5471,7 +5586,13 @@ function diagnoseError(options) {
5471
5586
  0
5472
5587
  );
5473
5588
  if (!isRollingBucketChannel && resolvedChannelDef) {
5474
- attribution = hasActiveIncident ? `POSSIBLE UPSTREAM INCIDENT (${upstreamStatus}) on ${resolvedChannelDef.definition.display_name}: ${resolvedChannelDef.definition.recommended_behaviors.throttling_guidance}` : `${resolvedChannelDef.definition.display_name} (${resolvedChannelDef.definition.billing_model}, ${recentRecords.length} recent channel turns / ${recentTokens.toLocaleString()} tokens): ${resolvedChannelDef.definition.recommended_behaviors.throttling_guidance}`;
5589
+ const displayName = locale === "zh" && resolvedChannelDef.definition.display_name_zh ? resolvedChannelDef.definition.display_name_zh : resolvedChannelDef.definition.display_name;
5590
+ const throttlingGuidance = getLocalizedBehavior(
5591
+ resolvedChannelDef.definition.recommended_behaviors,
5592
+ "throttling_guidance",
5593
+ locale
5594
+ ) ?? resolvedChannelDef.definition.recommended_behaviors.throttling_guidance;
5595
+ attribution = hasActiveIncident ? `POSSIBLE UPSTREAM INCIDENT (${upstreamStatus}) on ${displayName}: ${throttlingGuidance}` : `${displayName} (${resolvedChannelDef.definition.billing_model}, ${recentRecords.length} recent channel turns / ${recentTokens.toLocaleString()} tokens): ${throttlingGuidance}`;
5475
5596
  } else if (lowerText.includes("limit: 0") || recentRecords.length > 0 && recentTokens < 5e4) {
5476
5597
  attribution = "LIKELY FALSE EXHAUSTION / ENTITLEMENT DESYNC: Local 5h usage is very low (<50k tokens) or `limit: 0` was returned. Check billing/account sync or Reset Onboarding before waiting.";
5477
5598
  } else if (recentTokens >= 5e5) {
@@ -5484,24 +5605,27 @@ function diagnoseError(options) {
5484
5605
  } else if (chosen.domain === "capacity") {
5485
5606
  attribution = hasActiveIncident ? `UPSTREAM OUTAGE/DEGRADATION CONFIRMED (${upstreamStatus}): Not a local machine issue. Wait for recovery or temporarily switch to Flash/Hydrogen.` : "LOCAL CONTEXT OR TRANSIENT CAPACITY SPIKE: Upstream status appears operational; check for oversized context (>200k tokens) and add `.geminiignore`.";
5486
5607
  }
5487
- return {
5488
- matched: true,
5489
- domain: chosen.domain,
5490
- diagnosis_id: chosen.id,
5491
- title: chosen.title,
5492
- confidence: "high",
5493
- attribution,
5494
- root_cause: chosen.root_cause,
5495
- steps: chosen.steps,
5496
- commands: chosen.commands,
5497
- verify_command: chosen.verify_command,
5498
- dont_dos: chosen.dont_dos,
5499
- deep_link: chosen.deep_link.startsWith("/") ? `https://modelcraft.dev${chosen.deep_link}` : chosen.deep_link,
5500
- official_source_url: chosen.official_source_url ?? null,
5501
- upstream_status: upstreamStatus,
5502
- extracted_signals: signals,
5503
- auth_channel_analysis: authChannelAnalysis
5504
- };
5608
+ return localizeDiagnosisEntry(
5609
+ {
5610
+ matched: true,
5611
+ domain: chosen.domain,
5612
+ diagnosis_id: chosen.id,
5613
+ title: chosen.title,
5614
+ confidence: "high",
5615
+ attribution,
5616
+ root_cause: chosen.root_cause,
5617
+ steps: chosen.steps,
5618
+ commands: chosen.commands,
5619
+ verify_command: chosen.verify_command,
5620
+ dont_dos: chosen.dont_dos,
5621
+ deep_link: chosen.deep_link.startsWith("/") ? `https://modelcraft.dev${chosen.deep_link}` : chosen.deep_link,
5622
+ official_source_url: chosen.official_source_url ?? null,
5623
+ upstream_status: upstreamStatus,
5624
+ extracted_signals: signals,
5625
+ auth_channel_analysis: authChannelAnalysis
5626
+ },
5627
+ locale
5628
+ );
5505
5629
  }
5506
5630
 
5507
5631
  // src/analyzers/countdown.ts
@@ -5949,7 +6073,7 @@ function createAgycraftServer(deps = {}) {
5949
6073
  const client = deps.snapshotClient ?? new SnapshotClient();
5950
6074
  const server = new McpServer({
5951
6075
  name: "agycraft-mcp",
5952
- version: "0.2.1"
6076
+ version: "0.2.2"
5953
6077
  });
5954
6078
  server.tool(
5955
6079
  "analyze_token_usage",
@@ -5964,9 +6088,12 @@ function createAgycraftServer(deps = {}) {
5964
6088
  workspace_dir: z.string().optional().describe(
5965
6089
  "Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned)."
5966
6090
  ),
5967
- auth_mode: z.string().default("all").describe("Optional auth channel filter ('all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', 'unknown', or any registered channel_id).")
6091
+ auth_mode: z.string().default("all").describe("Optional auth channel filter ('all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', 'unknown', or any registered channel_id)."),
6092
+ lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
5968
6093
  },
5969
- async ({ window, granularity, timezone, max_buckets, product, scope, workspace_dir, auth_mode }) => {
6094
+ async ({ window, granularity, timezone, max_buckets, product, scope, workspace_dir, auth_mode, lang }) => {
6095
+ const locale = resolveLocale(lang, process.env);
6096
+ const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : locale;
5970
6097
  const [modelsSnap, channelsSnap, projectHash] = await Promise.all([
5971
6098
  client.get("models"),
5972
6099
  client.get("channels"),
@@ -6036,7 +6163,8 @@ function createAgycraftServer(deps = {}) {
6036
6163
  time_series: rollupRes.time_series,
6037
6164
  time_series_meta: rollupRes.time_series_meta,
6038
6165
  models_snapshot_source: modelsSnap.source,
6039
- privacy_note: "100% local numeric aggregation; zero user data uploaded."
6166
+ locale: effectiveLocale,
6167
+ privacy_note: effectiveLocale === "zh" ? "100% \u672C\u5730\u6570\u503C\u805A\u5408\uFF1B\u96F6\u7528\u6237\u6570\u636E\u4E0A\u4F20\u3002" : "100% local numeric aggregation; zero user data uploaded."
6040
6168
  },
6041
6169
  null,
6042
6170
  2
@@ -6081,7 +6209,8 @@ function createAgycraftServer(deps = {}) {
6081
6209
  session_count: effectiveSessionCount,
6082
6210
  ...transcriptFallback ? { transcript_activity_fallback: transcriptFallback } : {},
6083
6211
  models_snapshot_source: modelsSnap.source,
6084
- privacy_note: "100% local numeric aggregation; zero user data uploaded."
6212
+ locale: effectiveLocale,
6213
+ privacy_note: effectiveLocale === "zh" ? "100% \u672C\u5730\u6570\u503C\u805A\u5408\uFF1B\u96F6\u7528\u6237\u6570\u636E\u4E0A\u4F20\u3002" : "100% local numeric aggregation; zero user data uploaded."
6085
6214
  },
6086
6215
  null,
6087
6216
  2
@@ -6101,9 +6230,11 @@ function createAgycraftServer(deps = {}) {
6101
6230
  loopThreshold: z.number().int().positive().default(4).describe("Consecutive tool-failure streak threshold for infinite-loop detection (default: 4)."),
6102
6231
  workspace_dir: z.string().optional().describe("Optional workspace directory path for .geminiignore check and project-scoped filtering."),
6103
6232
  timezone: z.string().optional().describe("IANA timezone for peak_hours bucketing (default: UTC)."),
6104
- auth_mode: z.string().default("auto").describe("Optional auth channel filter ('auto', 'all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id).")
6233
+ auth_mode: z.string().default("auto").describe("Optional auth channel filter ('auto', 'all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id)."),
6234
+ lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
6105
6235
  },
6106
- async ({ window, scope, transcript_path, loopThreshold, workspace_dir, timezone, auth_mode }) => {
6236
+ async ({ window, scope, transcript_path, loopThreshold, workspace_dir, timezone, auth_mode, lang }) => {
6237
+ const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : resolveLocale(lang, process.env);
6107
6238
  const [modelsSnap, channelsSnap, projectHash, transcriptMeta, hasGeminiIgnore] = await Promise.all([
6108
6239
  client.get("models"),
6109
6240
  client.get("channels"),
@@ -6155,7 +6286,8 @@ function createAgycraftServer(deps = {}) {
6155
6286
  has_mixed_auth: authContext.has_mixed_auth
6156
6287
  },
6157
6288
  authMode: auth_mode,
6158
- channels: registry
6289
+ channels: registry,
6290
+ locale: effectiveLocale
6159
6291
  });
6160
6292
  return {
6161
6293
  content: [
@@ -6164,6 +6296,7 @@ function createAgycraftServer(deps = {}) {
6164
6296
  text: JSON.stringify(
6165
6297
  {
6166
6298
  ...report,
6299
+ locale: effectiveLocale,
6167
6300
  transcript_structure: transcriptMeta,
6168
6301
  more_tips_url: "https://modelcraft.dev/quotas"
6169
6302
  },
@@ -6182,9 +6315,11 @@ function createAgycraftServer(deps = {}) {
6182
6315
  error_text: z.string().min(1).describe("Raw error message or JSON snippet."),
6183
6316
  product: z.enum(["agy", "cli", "api", "web"]).optional(),
6184
6317
  doctor_summary: z.string().optional(),
6185
- auth_mode: z.string().default("auto").describe("Optional auth channel hint ('auto', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id).")
6318
+ auth_mode: z.string().default("auto").describe("Optional auth channel hint ('auto', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', or any registered channel_id)."),
6319
+ lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
6186
6320
  },
6187
- async ({ error_text, product, auth_mode }) => {
6321
+ async ({ error_text, product, auth_mode, lang }) => {
6322
+ const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : resolveLocale(lang, process.env);
6188
6323
  const [records, statusSnap, diagnosisSnap, channelsSnap] = await Promise.all([
6189
6324
  loadCombinedLocalRecords(deps),
6190
6325
  client.get("status"),
@@ -6207,7 +6342,8 @@ function createAgycraftServer(deps = {}) {
6207
6342
  authMode: auth_mode,
6208
6343
  authContext,
6209
6344
  cliChannel,
6210
- channels: registry
6345
+ channels: registry,
6346
+ locale: effectiveLocale
6211
6347
  });
6212
6348
  return {
6213
6349
  content: [
@@ -6216,6 +6352,7 @@ function createAgycraftServer(deps = {}) {
6216
6352
  text: JSON.stringify(
6217
6353
  {
6218
6354
  ...result,
6355
+ locale: effectiveLocale,
6219
6356
  data_sources: {
6220
6357
  status: statusSnap.source,
6221
6358
  diagnosis: diagnosisSnap.source
@@ -6236,9 +6373,11 @@ function createAgycraftServer(deps = {}) {
6236
6373
  task: z.string().optional().describe("Task description (e.g. 'architecture', 'multi-file refactor', 'quick qa', 'batch')."),
6237
6374
  model_id: z.string().optional().describe("Specific model id, api_model_id, or codename (e.g. 'neon', 'hydrogen', 'argon', 'gemini-3.8-flash')."),
6238
6375
  provider: z.enum(["google", "antigravity", "anthropic", "all"]).default("all"),
6239
- include_history: z.boolean().default(false)
6376
+ include_history: z.boolean().default(false),
6377
+ lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
6240
6378
  },
6241
- async ({ task, model_id, provider, include_history }) => {
6379
+ async ({ task, model_id, provider, include_history, lang }) => {
6380
+ const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : resolveLocale(lang, process.env);
6242
6381
  const [modelsSnap, chronicleSnap] = await Promise.all([
6243
6382
  client.get("models"),
6244
6383
  include_history ? client.get("chronicle") : Promise.resolve(null)
@@ -6301,10 +6440,14 @@ function createAgycraftServer(deps = {}) {
6301
6440
  type: "text",
6302
6441
  text: JSON.stringify(
6303
6442
  {
6304
- models: matched,
6305
- orchestrator_recipes: modelsSnap.data.orchestrator_recipes,
6443
+ models: matched.map((m) => localizeModelEntry(m, effectiveLocale)),
6444
+ orchestrator_recipes: localizeSnapshotText(
6445
+ modelsSnap.data.orchestrator_recipes,
6446
+ effectiveLocale
6447
+ ),
6306
6448
  deprecation_warnings: deprecationWarnings,
6307
- chronicle_history: history,
6449
+ chronicle_history: history?.map((h) => localizeSnapshotText(h, effectiveLocale)),
6450
+ locale: effectiveLocale,
6308
6451
  guide_url: "https://modelcraft.dev/models",
6309
6452
  official_source_urls: [
6310
6453
  ...new Set(matched.flatMap((m) => m.official_source_urls ?? []))
@@ -6330,9 +6473,11 @@ function createAgycraftServer(deps = {}) {
6330
6473
  workspace_dir: z.string().optional().describe(
6331
6474
  "Workspace directory for project-scoped filtering (defaults to process.cwd() when scope='project'; hashed locally and never returned)."
6332
6475
  ),
6333
- auth_mode: z.string().default("all").describe("Optional auth channel filter ('all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', 'unknown', or any registered channel_id).")
6476
+ auth_mode: z.string().default("all").describe("Optional auth channel filter ('all', 'google_oauth', 'gcp_vertex_adc', 'gcp_adc', 'gemini_api_key', 'vertex_express_key', 'unknown', or any registered channel_id)."),
6477
+ lang: z.enum(["en", "zh", "auto"]).default("auto").describe("Output language ('en', 'zh', or 'auto' from AGYCRAFT_LANG / system locale).")
6334
6478
  },
6335
- async ({ plan, product, timezone, scope, workspace_dir, auth_mode }) => {
6479
+ async ({ plan, product, timezone, scope, workspace_dir, auth_mode, lang }) => {
6480
+ const effectiveLocale = lang === "auto" && deps.defaultLang ? resolveLocale(deps.defaultLang, process.env) : resolveLocale(lang, process.env);
6336
6481
  const nowMs = Date.now();
6337
6482
  const since7d = nowMs - 7 * 86400 * 1e3;
6338
6483
  const [statusSnap, quotasSnap, updatesSnap, channelsSnap, projectHash] = await Promise.all([
@@ -6419,14 +6564,24 @@ function createAgycraftServer(deps = {}) {
6419
6564
  ...statusUsageNote ? { usage_note: statusUsageNote } : {},
6420
6565
  session_count: isSpecificAuthEmpty ? 0 : effectiveRecords.length > 0 ? new Set(effectiveRecords.map((r) => r.session_hash)).size : transcriptFallback?.window_5h.session_count ?? 0,
6421
6566
  overall_status: statusSnap.data.overall_status,
6422
- surfaces: statusSnap.data.surfaces,
6423
- active_incidents: statusSnap.data.active_incidents,
6567
+ surfaces: localizeSnapshotText(statusSnap.data.surfaces, effectiveLocale),
6568
+ active_incidents: localizeSnapshotText(
6569
+ statusSnap.data.active_incidents,
6570
+ effectiveLocale
6571
+ ),
6424
6572
  latest_versions: statusSnap.data.latest_versions,
6425
6573
  countdown,
6426
6574
  ...transcriptFallback ? { transcript_activity_fallback: transcriptFallback } : {},
6427
- quota_rules: quotasSnap.data.reset_rules,
6428
- plans: filteredPlans,
6429
- recent_updates: filteredUpdates.slice(0, 8),
6575
+ quota_rules: localizeSnapshotText(
6576
+ {
6577
+ reset_rules: quotasSnap.data.reset_rules,
6578
+ ...typeof quotasSnap.data.reset_rules_notes_zh === "string" ? { reset_rules_notes_zh: quotasSnap.data.reset_rules_notes_zh } : {}
6579
+ },
6580
+ effectiveLocale
6581
+ ).reset_rules,
6582
+ plans: filteredPlans.map((p) => localizeSnapshotText(p, effectiveLocale)),
6583
+ recent_updates: filteredUpdates.slice(0, 8).map((u) => localizeSnapshotText(u, effectiveLocale)),
6584
+ locale: effectiveLocale,
6430
6585
  dashboard_url: "https://modelcraft.dev",
6431
6586
  official_source_urls: quotasSnap.data.official_source_urls ?? [],
6432
6587
  snapshot_sources: {
@@ -6483,8 +6638,8 @@ function printHelp() {
6483
6638
  "agycraft-mcp \u2014 Privacy-first local MCP server & CLI doctor for Antigravity (AGY) & Gemini CLI",
6484
6639
  "",
6485
6640
  "Usage:",
6486
- " agycraft-mcp Start Stdio MCP Server (default)",
6487
- " agycraft-mcp doctor [--cost] [--window 5h|24h|7d] [--json]",
6641
+ " agycraft-mcp [--lang en|zh|auto] Start Stdio MCP Server (default)",
6642
+ " agycraft-mcp doctor [--cost] [--window 5h|24h|7d] [--lang en|zh|auto] [--json]",
6488
6643
  " Run offline preflight & hygiene check or readonly cost breakdown",
6489
6644
  " agycraft-mcp preflight [--json] Check live ModelCraft status.json (exits 1 if degraded/429/503)",
6490
6645
  " agycraft-mcp setup Print non-destructive, opt-in AGY / Gemini CLI setup snippets",
@@ -6496,21 +6651,61 @@ function printHelp() {
6496
6651
  ].join("\n")
6497
6652
  );
6498
6653
  }
6654
+ function extractLangArg(argv) {
6655
+ const rest = [];
6656
+ let lang;
6657
+ for (let i = 0; i < argv.length; i += 1) {
6658
+ const arg = argv[i];
6659
+ if (arg === void 0) {
6660
+ continue;
6661
+ }
6662
+ if (arg === "--lang") {
6663
+ const next = argv[i + 1];
6664
+ if (next !== "en" && next !== "zh" && next !== "auto") {
6665
+ throw new Error(`Invalid --lang value "${next ?? ""}". Expected: en, zh, or auto.`);
6666
+ }
6667
+ lang = next;
6668
+ i += 1;
6669
+ continue;
6670
+ }
6671
+ if (arg.startsWith("--lang=")) {
6672
+ const val = arg.slice("--lang=".length);
6673
+ if (val !== "en" && val !== "zh" && val !== "auto") {
6674
+ throw new Error(`Invalid --lang value "${val}". Expected: en, zh, or auto.`);
6675
+ }
6676
+ lang = val;
6677
+ continue;
6678
+ }
6679
+ rest.push(arg);
6680
+ }
6681
+ return { lang, rest };
6682
+ }
6499
6683
  async function main(argv = process.argv.slice(2)) {
6500
- const cmd = argv[0];
6684
+ let langArg;
6685
+ let restArgv;
6686
+ try {
6687
+ const parsed = extractLangArg(argv);
6688
+ langArg = parsed.lang;
6689
+ restArgv = parsed.rest;
6690
+ } catch (err) {
6691
+ console.error(err instanceof Error ? err.message : String(err));
6692
+ process.exitCode = 1;
6693
+ return;
6694
+ }
6695
+ const cmd = restArgv[0];
6501
6696
  if (!cmd) {
6502
- await startStdioServer();
6697
+ await startStdioServer({ defaultLang: langArg });
6503
6698
  return;
6504
6699
  }
6505
6700
  switch (cmd) {
6506
6701
  case "doctor": {
6507
- const asJson = argv.includes("--json");
6508
- const withCost = argv.includes("--cost");
6702
+ const asJson = restArgv.includes("--json");
6703
+ const withCost = restArgv.includes("--cost");
6509
6704
  if (withCost) {
6510
6705
  let windowArg = "24h";
6511
- const winIdx = argv.indexOf("--window");
6706
+ const winIdx = restArgv.indexOf("--window");
6512
6707
  if (winIdx !== -1) {
6513
- const val = argv[winIdx + 1];
6708
+ const val = restArgv[winIdx + 1];
6514
6709
  if (val !== "5h" && val !== "24h" && val !== "7d") {
6515
6710
  console.error(`Invalid --window value "${val ?? ""}". Expected: 5h, 24h, or 7d.`);
6516
6711
  process.exitCode = 1;
@@ -6527,11 +6722,14 @@ async function main(argv = process.argv.slice(2)) {
6527
6722
  return;
6528
6723
  }
6529
6724
  let authModeArg;
6530
- const authIdx = argv.indexOf("--auth-mode");
6531
- if (authIdx !== -1 && argv[authIdx + 1]) {
6532
- authModeArg = argv[authIdx + 1];
6725
+ const authIdx = restArgv.indexOf("--auth-mode");
6726
+ if (authIdx !== -1 && restArgv[authIdx + 1]) {
6727
+ authModeArg = restArgv[authIdx + 1];
6533
6728
  }
6534
- const report = await runDoctor(authModeArg ? { authMode: authModeArg } : void 0);
6729
+ const report = await runDoctor({
6730
+ ...authModeArg ? { authMode: authModeArg } : {},
6731
+ ...langArg ? { lang: langArg } : {}
6732
+ });
6535
6733
  if (asJson) {
6536
6734
  console.log(JSON.stringify(report, null, 2));
6537
6735
  } else {
@@ -6540,11 +6738,11 @@ async function main(argv = process.argv.slice(2)) {
6540
6738
  return;
6541
6739
  }
6542
6740
  case "preflight": {
6543
- if (argv.includes("--help") || argv.includes("-h")) {
6741
+ if (restArgv.includes("--help") || restArgv.includes("-h")) {
6544
6742
  printPreflightHelp();
6545
6743
  return;
6546
6744
  }
6547
- const asJson = argv.includes("--json");
6745
+ const asJson = restArgv.includes("--json");
6548
6746
  const result = await runPreflight();
6549
6747
  if (asJson) {
6550
6748
  console.log(JSON.stringify(result, null, 2));