@yitom/acp-client 0.1.4 → 0.1.5

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.cjs CHANGED
@@ -62,6 +62,8 @@ __export(exports_src, {
62
62
  INKDOWN_VIRTUAL_DIR: () => INKDOWN_VIRTUAL_DIR,
63
63
  INKDOWN_VIRTUAL_RESOURCES: () => INKDOWN_VIRTUAL_RESOURCES,
64
64
  LEGACY_ZED_CODEX_ACP_NPM_PACKAGE: () => LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
65
+ OPENCODE_CLI_NPM_PACKAGE: () => OPENCODE_CLI_NPM_PACKAGE,
66
+ QuotaCache: () => QuotaCache,
65
67
  acpReadTextFile: () => acpReadTextFile,
66
68
  acpWriteTextFile: () => acpWriteTextFile,
67
69
  agyAdapter: () => agyAdapter,
@@ -120,6 +122,7 @@ __export(exports_src, {
120
122
  mergeTopLevelModelsIntoConfigOptions: () => mergeTopLevelModelsIntoConfigOptions,
121
123
  ok: () => ok,
122
124
  opencodeAdapter: () => opencodeAdapter,
125
+ opencodeV2Adapter: () => opencodeV2Adapter,
123
126
  orderSilentAuthMethodIds: () => orderSilentAuthMethodIds,
124
127
  parseAcpConfigOptions: () => parseAcpConfigOptions,
125
128
  parseCursorCatalogOutput: () => parseCursorCatalogOutput,
@@ -127,16 +130,21 @@ __export(exports_src, {
127
130
  parseLoadSessionSupported: () => parseLoadSessionSupported,
128
131
  parseMcpHttpSupported: () => parseMcpHttpSupported,
129
132
  parsePromptCapabilities: () => parsePromptCapabilities,
133
+ parseRateLimitsFromStatusText: () => parseRateLimitsFromStatusText,
130
134
  parseResumeSessionSupported: () => parseResumeSessionSupported,
131
135
  pickAllowOptionId: () => pickAllowOptionId,
132
136
  probeAgyAuth: () => probeAgyAuth,
133
137
  probeClaudeAuth: () => probeClaudeAuth,
138
+ probeClaudeQuota: () => probeClaudeQuota,
134
139
  probeCodexAuth: () => probeCodexAuth,
140
+ probeCodexQuota: () => probeCodexQuota,
135
141
  probeCopilotAuth: () => probeCopilotAuth,
136
142
  probeCursorAuth: () => probeCursorAuth,
143
+ probeCursorQuota: () => probeCursorQuota,
137
144
  probeDeepseekAuth: () => probeDeepseekAuth,
138
145
  probeGeminiAuth: () => probeGeminiAuth,
139
146
  probeOpencodeAuth: () => probeOpencodeAuth,
147
+ probeOpencodeQuota: () => probeOpencodeQuota,
140
148
  provisionCustomProviderCodexHome: () => provisionCustomProviderCodexHome,
141
149
  readAcpProxySettings: () => readAcpProxySettings,
142
150
  readStoredAcpProvider: () => readStoredAcpProvider,
@@ -153,6 +161,7 @@ __export(exports_src, {
153
161
  resolveGeminiHome: () => resolveGeminiHome,
154
162
  resolveOpencodeAuthCandidates: () => resolveOpencodeAuthCandidates,
155
163
  resolveOpencodeAuthFile: () => resolveOpencodeAuthFile,
164
+ resolveOpencodeAuthPath: () => resolveOpencodeAuthPath,
156
165
  restoreOrCreateAcpSession: () => restoreOrCreateAcpSession,
157
166
  runConnectAuthGate: () => runConnectAuthGate,
158
167
  saveAcpProvider: () => saveAcpProvider,
@@ -234,6 +243,7 @@ var CODEX_ACP_NPM_PACKAGE = "@agentclientprotocol/codex-acp";
234
243
  var CLAUDE_ACP_NPM_PACKAGE = "@agentclientprotocol/claude-agent-acp";
235
244
  var DEEPSEEK_DSH_NPM_PACKAGE = "@deepseek-ai/dsh";
236
245
  var AGY_ACP_NPM_PACKAGE = "@yitom/agy-acp-map";
246
+ var OPENCODE_CLI_NPM_PACKAGE = "@opencode/cli";
237
247
  var LEGACY_ZED_CODEX_ACP_NPM_PACKAGE = "@zed-industries/codex-acp";
238
248
  var DEFAULT_ACP_RUNTIME_ID = "codex-acp";
239
249
  function isWindowsPlatform() {
@@ -286,6 +296,15 @@ var BUILTIN_ACP_RUNTIMES = [
286
296
  args: ["acp"],
287
297
  requiredEnvKeys: []
288
298
  },
299
+ {
300
+ id: "opencode-v2",
301
+ name: "OpenCode v2",
302
+ description: "通过 npx 启动独立产品线 @opencode/cli v2(acp);与 1.x 共存,复用 v2 SQLite 登录态",
303
+ authHint: "v2 登录态在 SQLite(auth.json 仅兼容残留);未登录先用 v2 二进制跑 opencode auth login",
304
+ command: "npx",
305
+ args: ["-y", OPENCODE_CLI_NPM_PACKAGE, "acp"],
306
+ requiredEnvKeys: []
307
+ },
289
308
  {
290
309
  id: "cursor-cli",
291
310
  name: "Cursor",
@@ -318,7 +337,7 @@ function findBuiltinAcpRuntime(id) {
318
337
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
319
338
  }
320
339
  // src/version.ts
321
- var ACP_CLIENT_VERSION = "0.1.4";
340
+ var ACP_CLIENT_VERSION = "0.1.5";
322
341
  // src/session/available-commands.ts
323
342
  function normalizeCommand(raw) {
324
343
  if (!raw || typeof raw !== "object")
@@ -407,42 +426,168 @@ class AvailableCommandsCache {
407
426
  }
408
427
  }
409
428
 
410
- // src/client/acp-client.ts
411
- var import_sdk4 = require("@agentclientprotocol/sdk");
412
-
413
- // src/runtimes/codex/index.ts
414
- var import_promises2 = require("node:fs/promises");
415
- var import_node_path4 = require("node:path");
416
-
417
- // src/runtimes/codex/codex-provider-home.ts
418
- var INKDOWN_PROVIDER_ID = "inkdown-custom";
419
- var INKDOWN_PROVIDER_API_KEY_ENV = "INKDOWN_PROVIDER_API_KEY";
420
- function tomlEscape(value) {
421
- return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
422
- }
423
- function buildCustomProviderConfigToml(config) {
424
- const name = config.name?.trim() || "自定义 API";
425
- const wireApi = config.wireApi === "responses" ? "responses" : "chat";
426
- return [
427
- `model_provider = "${INKDOWN_PROVIDER_ID}"`,
428
- `model = "${tomlEscape(config.model.trim())}"`,
429
- "",
430
- `[model_providers.${INKDOWN_PROVIDER_ID}]`,
431
- `name = "${tomlEscape(name)}"`,
432
- `base_url = "${tomlEscape(config.baseUrl.trim())}"`,
433
- `env_key = "${INKDOWN_PROVIDER_API_KEY_ENV}"`,
434
- `wire_api = "${wireApi}"`,
435
- ""
436
- ].join(`
437
- `);
438
- }
439
- function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
429
+ // src/session/quota.ts
430
+ function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
431
+ if (!text || typeof text !== "string")
432
+ return null;
433
+ const lines = text.split(/\r?\n/);
434
+ let account;
435
+ const windows = [];
436
+ let credits;
437
+ let status = "ok";
438
+ let message;
439
+ if (/account (?:disabled|banned|suspended)|suspended|banned/i.test(text)) {
440
+ status = "banned";
441
+ message = "账号已封禁或暂停使用 (Account banned / suspended)";
442
+ } else if (/RESOURCE_EXHAUSTED|quota reached|rate limit exceeded|429/i.test(text)) {
443
+ status = "exhausted";
444
+ message = "额度已用尽 (Quota / Rate limit reached)";
445
+ } else if (/unauthorized|authentication failed|invalid api key/i.test(text)) {
446
+ status = "unauthorized";
447
+ message = "认证失效 (Unauthorized / Invalid credentials)";
448
+ }
449
+ for (const rawLine of lines) {
450
+ const line = rawLine.replace(/\*\*/g, "").trim();
451
+ if (!line)
452
+ continue;
453
+ const accMatch = line.match(/^Account\s*[::]\s*([^()]+?)(?:\s*\(([^)]+)\))?$/i);
454
+ if (accMatch) {
455
+ account = {
456
+ plan: accMatch[1].trim(),
457
+ email: accMatch[2]?.trim()
458
+ };
459
+ continue;
460
+ }
461
+ const credMatch = line.match(/(?:\b|^)(?:[\w\s-]*?credits?)\s*[::]\s*(unlimited|[\d.]+)/i);
462
+ if (credMatch) {
463
+ const val = credMatch[1].trim();
464
+ credits = val.toLowerCase() === "unlimited" ? { unlimited: true, balance: "unlimited" } : { balance: Number(val) || val, unlimited: false };
465
+ continue;
466
+ }
467
+ const winMatch = line.match(/(?:(?:[\w-]+\s+)?([\w\s-]+?(?:limit|spend limit|window)))\s*[::]\s*(\d+(?:\.\d+)?)%\s*(?:left|remaining)(?:\s*\((?:resets\s*(?:at\s*)?([^)]+)|([^)]+))\))?/i);
468
+ if (winMatch) {
469
+ const label = winMatch[1].trim();
470
+ const pct = parseFloat(winMatch[2]);
471
+ const resetsAt = (winMatch[3] || winMatch[4] || "").trim() || undefined;
472
+ let windowDurationMins;
473
+ const lower = label.toLowerCase();
474
+ if (/5h|5-hour/i.test(lower))
475
+ windowDurationMins = 300;
476
+ else if (/week/i.test(lower))
477
+ windowDurationMins = 10080;
478
+ else if (/month/i.test(lower))
479
+ windowDurationMins = 43200;
480
+ else if (/day|24h/i.test(lower))
481
+ windowDurationMins = 1440;
482
+ else if (/(\d+)\s*h/i.test(lower)) {
483
+ const m = lower.match(/(\d+)\s*h/);
484
+ if (m)
485
+ windowDurationMins = parseInt(m[1], 10) * 60;
486
+ }
487
+ windows.push({
488
+ label,
489
+ percentLeft: pct,
490
+ usedPercent: Math.max(0, 100 - pct),
491
+ resetsAt,
492
+ windowDurationMins
493
+ });
494
+ continue;
495
+ }
496
+ const fastMatch = line.match(/(?:fast requests?|requests?)\s*[::]\s*(\d+)\s*\/\s*(\d+)/i);
497
+ if (fastMatch) {
498
+ const used = parseInt(fastMatch[1], 10);
499
+ const total = parseInt(fastMatch[2], 10);
500
+ const left = Math.max(0, total - used);
501
+ const pct = total > 0 ? Math.round(left / total * 100) : 0;
502
+ windows.push({
503
+ label: "Fast requests",
504
+ percentLeft: pct,
505
+ usedPercent: total > 0 ? Math.round(used / total * 100) : 0,
506
+ used,
507
+ total
508
+ });
509
+ continue;
510
+ }
511
+ }
512
+ if (!windows.length && !credits && !account && status === "ok") {
513
+ return null;
514
+ }
515
+ const primary = windows.find((w) => /5h|5-hour|hour|primary|fast/i.test(w.label)) || windows[0];
516
+ const secondary = windows.find((w) => w !== primary && /week|month|secondary/i.test(w.label)) || windows.find((w) => w !== primary);
517
+ const extraWindows = windows.filter((w) => w !== primary && w !== secondary);
518
+ if (primary && primary.percentLeft <= 10 && status === "ok") {
519
+ status = "warning";
520
+ }
440
521
  return {
441
- CODEX_HOME: codexHome,
442
- [INKDOWN_PROVIDER_API_KEY_ENV]: apiKey
522
+ runtimeId,
523
+ account,
524
+ primaryWindow: primary,
525
+ secondaryWindow: secondary,
526
+ extraWindows: extraWindows.length ? extraWindows : undefined,
527
+ credits,
528
+ status,
529
+ message,
530
+ rawText: text,
531
+ updatedAt: Date.now()
443
532
  };
444
533
  }
445
534
 
535
+ class QuotaCache {
536
+ bySession = new Map;
537
+ byRuntime = new Map;
538
+ observe(params, defaultRuntimeId = "unknown") {
539
+ if (!params || typeof params !== "object")
540
+ return null;
541
+ const p = params;
542
+ const sessionId = typeof p.sessionId === "string" ? p.sessionId : undefined;
543
+ let textToParse = "";
544
+ if (p.update?.content && p.update.content.type === "text" && typeof p.update.content.text === "string") {
545
+ textToParse = p.update.content.text;
546
+ } else if (p.update?.message?.content && Array.isArray(p.update.message.content)) {
547
+ textToParse = p.update.message.content.filter((c) => c && c.type === "text" && typeof c.text === "string").map((c) => c.text).join(`
548
+ `);
549
+ }
550
+ if (!textToParse)
551
+ return null;
552
+ if (!/(?:limit|credits?|Account:|5h|resets|banned|suspended|quota)/i.test(textToParse)) {
553
+ return null;
554
+ }
555
+ const quota = parseRateLimitsFromStatusText(textToParse, defaultRuntimeId);
556
+ if (quota) {
557
+ if (sessionId)
558
+ this.bySession.set(sessionId, quota);
559
+ this.byRuntime.set(defaultRuntimeId, quota);
560
+ return quota;
561
+ }
562
+ return null;
563
+ }
564
+ set(quota, sessionId) {
565
+ if (sessionId)
566
+ this.bySession.set(sessionId, quota);
567
+ this.byRuntime.set(quota.runtimeId, quota);
568
+ }
569
+ get(sessionId, runtimeId) {
570
+ if (sessionId && this.bySession.has(sessionId)) {
571
+ return this.bySession.get(sessionId);
572
+ }
573
+ if (runtimeId && this.byRuntime.has(runtimeId)) {
574
+ return this.byRuntime.get(runtimeId);
575
+ }
576
+ return;
577
+ }
578
+ clear() {
579
+ this.bySession.clear();
580
+ this.byRuntime.clear();
581
+ }
582
+ }
583
+
584
+ // src/client/acp-client.ts
585
+ var import_sdk4 = require("@agentclientprotocol/sdk");
586
+
587
+ // src/runtimes/codex/quota.ts
588
+ var import_node_fs2 = require("node:fs");
589
+ var import_node_path2 = require("node:path");
590
+
446
591
  // src/runtimes/codex/codex-auth-preflight.ts
447
592
  var import_node_fs = require("node:fs");
448
593
  var import_node_os = require("node:os");
@@ -479,14 +624,114 @@ function probeCodexAuth() {
479
624
  };
480
625
  }
481
626
 
627
+ // src/runtimes/codex/quota.ts
628
+ function decodeJwtPayload(token) {
629
+ try {
630
+ const parts = token.split(".");
631
+ if (parts.length < 2)
632
+ return null;
633
+ const json = Buffer.from(parts[1], "base64").toString("utf8");
634
+ return JSON.parse(json);
635
+ } catch {
636
+ return null;
637
+ }
638
+ }
639
+ async function probeCodexQuota(options) {
640
+ const codexHome = resolveCodexHome();
641
+ const authPath = import_node_path2.join(codexHome, "auth.json");
642
+ let accountEmail;
643
+ let accountPlan = "Codex Free / Local";
644
+ let isLoggedIn = false;
645
+ if (import_node_fs2.existsSync(authPath)) {
646
+ try {
647
+ const authData = JSON.parse(import_node_fs2.readFileSync(authPath, "utf8"));
648
+ if (authData.OPENAI_API_KEY) {
649
+ isLoggedIn = true;
650
+ accountPlan = "OpenAI API Key";
651
+ }
652
+ if (authData.tokens?.id_token) {
653
+ isLoggedIn = true;
654
+ const payload = decodeJwtPayload(authData.tokens.id_token);
655
+ if (payload) {
656
+ if (typeof payload.email === "string")
657
+ accountEmail = payload.email;
658
+ const authObj = payload["https://api.openai.com/auth"];
659
+ if (authObj && typeof authObj.chatgpt_plan_type === "string") {
660
+ accountPlan = `ChatGPT ${authObj.chatgpt_plan_type}`;
661
+ }
662
+ }
663
+ } else if (authData.tokens?.access_token) {
664
+ isLoggedIn = true;
665
+ }
666
+ } catch {}
667
+ }
668
+ if (process.env.CODEX_API_KEY || process.env.OPENAI_API_KEY) {
669
+ isLoggedIn = true;
670
+ accountPlan = "API Key (Env)";
671
+ }
672
+ if (!isLoggedIn) {
673
+ return {
674
+ runtimeId: "codex-acp",
675
+ provider: "OpenAI / Codex",
676
+ status: "unauthorized",
677
+ message: "未登录 Codex (Not logged in)",
678
+ updatedAt: Date.now()
679
+ };
680
+ }
681
+ return {
682
+ runtimeId: "codex-acp",
683
+ provider: "OpenAI / Codex",
684
+ account: {
685
+ email: accountEmail,
686
+ plan: accountPlan,
687
+ type: "chatgpt"
688
+ },
689
+ status: "ok",
690
+ updatedAt: Date.now()
691
+ };
692
+ }
693
+
694
+ // src/runtimes/codex/index.ts
695
+ var import_promises2 = require("node:fs/promises");
696
+ var import_node_path5 = require("node:path");
697
+
698
+ // src/runtimes/codex/codex-provider-home.ts
699
+ var INKDOWN_PROVIDER_ID = "inkdown-custom";
700
+ var INKDOWN_PROVIDER_API_KEY_ENV = "INKDOWN_PROVIDER_API_KEY";
701
+ function tomlEscape(value) {
702
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
703
+ }
704
+ function buildCustomProviderConfigToml(config) {
705
+ const name = config.name?.trim() || "自定义 API";
706
+ const wireApi = config.wireApi === "responses" ? "responses" : "chat";
707
+ return [
708
+ `model_provider = "${INKDOWN_PROVIDER_ID}"`,
709
+ `model = "${tomlEscape(config.model.trim())}"`,
710
+ "",
711
+ `[model_providers.${INKDOWN_PROVIDER_ID}]`,
712
+ `name = "${tomlEscape(name)}"`,
713
+ `base_url = "${tomlEscape(config.baseUrl.trim())}"`,
714
+ `env_key = "${INKDOWN_PROVIDER_API_KEY_ENV}"`,
715
+ `wire_api = "${wireApi}"`,
716
+ ""
717
+ ].join(`
718
+ `);
719
+ }
720
+ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
721
+ return {
722
+ CODEX_HOME: codexHome,
723
+ [INKDOWN_PROVIDER_API_KEY_ENV]: apiKey
724
+ };
725
+ }
726
+
482
727
  // src/runtimes/codex/codex-provider.ts
483
728
  var import_promises = require("node:fs/promises");
484
- var import_node_fs2 = require("node:fs");
485
- var import_node_path3 = require("node:path");
729
+ var import_node_fs3 = require("node:fs");
730
+ var import_node_path4 = require("node:path");
486
731
 
487
732
  // src/client/acp-paths.ts
488
733
  var import_node_os2 = require("node:os");
489
- var import_node_path2 = require("node:path");
734
+ var import_node_path3 = require("node:path");
490
735
  function getDefaultAgentDataDir() {
491
736
  if (process.env.INKDOWN_DATA_DIR) {
492
737
  return process.env.INKDOWN_DATA_DIR;
@@ -495,20 +740,20 @@ function getDefaultAgentDataDir() {
495
740
  return process.env.ACP_DATA_DIR;
496
741
  }
497
742
  if (process.platform === "win32") {
498
- return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path2.join(import_node_os2.homedir(), "AppData", "Local", "inkdown");
743
+ return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path3.join(import_node_os2.homedir(), "AppData", "Local", "inkdown");
499
744
  }
500
745
  if (process.platform === "darwin") {
501
- return import_node_path2.join(import_node_os2.homedir(), "Library", "Application Support", "inkdown");
746
+ return import_node_path3.join(import_node_os2.homedir(), "Library", "Application Support", "inkdown");
502
747
  }
503
- return process.env.XDG_DATA_HOME || import_node_path2.join(import_node_os2.homedir(), ".local", "share", "inkdown");
748
+ return process.env.XDG_DATA_HOME || import_node_path3.join(import_node_os2.homedir(), ".local", "share", "inkdown");
504
749
  }
505
750
 
506
751
  // src/runtimes/codex/codex-provider.ts
507
752
  function providerFilePath(dir) {
508
- return import_node_path3.join(dir, "agent", "provider.json");
753
+ return import_node_path4.join(dir, "agent", "provider.json");
509
754
  }
510
755
  function providerHomePath(dir) {
511
- return import_node_path3.join(dir, "agent", "codex-home");
756
+ return import_node_path4.join(dir, "agent", "codex-home");
512
757
  }
513
758
  function toStatus(stored) {
514
759
  if (!stored)
@@ -534,7 +779,7 @@ function validate(payload) {
534
779
  }
535
780
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
536
781
  const file = providerFilePath(dir);
537
- if (!import_node_fs2.existsSync(file))
782
+ if (!import_node_fs3.existsSync(file))
538
783
  return null;
539
784
  try {
540
785
  const raw = JSON.parse(await import_promises.readFile(file, "utf8"));
@@ -563,7 +808,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
563
808
  const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
564
809
  if (!apiKey)
565
810
  return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
566
- await import_promises.mkdir(import_node_path3.join(dir, "agent"), { recursive: true });
811
+ await import_promises.mkdir(import_node_path4.join(dir, "agent"), { recursive: true });
567
812
  const stored = {
568
813
  name: payload.name?.trim() || undefined,
569
814
  baseUrl: payload.baseUrl.trim(),
@@ -586,7 +831,7 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
586
831
  async function provisionCustomProviderCodexHome(provider, codexHome) {
587
832
  try {
588
833
  await import_promises2.mkdir(codexHome, { recursive: true });
589
- await import_promises2.writeFile(import_node_path4.join(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
834
+ await import_promises2.writeFile(import_node_path5.join(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
590
835
  return true;
591
836
  } catch (error) {
592
837
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -595,6 +840,7 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
595
840
  }
596
841
  var codexAdapter = {
597
842
  id: "codex-acp",
843
+ probeQuota: async (options) => probeCodexQuota(options),
598
844
  probeAuth: () => {
599
845
  return probeCodexAuth();
600
846
  },
@@ -611,20 +857,86 @@ var codexAdapter = {
611
857
  }
612
858
  };
613
859
 
614
- // src/runtimes/claude/index.ts
615
- var import_node_fs3 = require("node:fs");
860
+ // src/runtimes/claude/quota.ts
861
+ var import_node_fs4 = require("node:fs");
616
862
  var import_node_os3 = require("node:os");
617
- var import_node_path5 = require("node:path");
863
+ var import_node_path6 = require("node:path");
864
+ async function probeClaudeQuota(options) {
865
+ const claudeHome = resolveClaudeHome();
866
+ const claudeJsonPath = import_node_path6.join(import_node_os3.homedir(), ".claude.json");
867
+ const credsPath = import_node_path6.join(claudeHome, ".credentials.json");
868
+ let isLoggedIn = false;
869
+ let isBanned = false;
870
+ let accountEmail;
871
+ let plan = "Claude Free / Default";
872
+ if (import_node_fs4.existsSync(claudeJsonPath)) {
873
+ try {
874
+ const data = JSON.parse(import_node_fs4.readFileSync(claudeJsonPath, "utf8"));
875
+ if (data.oauthAccount) {
876
+ isLoggedIn = true;
877
+ accountEmail = data.oauthAccount.emailAddress;
878
+ plan = data.oauthAccount.subscriptionTier || "Claude Pro";
879
+ }
880
+ if (data.isBanned || data.accountSuspended || data.status === "banned") {
881
+ isBanned = true;
882
+ }
883
+ } catch {}
884
+ }
885
+ if (import_node_fs4.existsSync(credsPath)) {
886
+ try {
887
+ const creds = JSON.parse(import_node_fs4.readFileSync(credsPath, "utf8"));
888
+ if (creds.accessToken || creds.sessionKey)
889
+ isLoggedIn = true;
890
+ } catch {}
891
+ }
892
+ if (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN) {
893
+ isLoggedIn = true;
894
+ plan = "API Key (Env)";
895
+ }
896
+ if (isBanned) {
897
+ return {
898
+ runtimeId: "claude",
899
+ provider: "Anthropic / Claude Code",
900
+ status: "banned",
901
+ message: "账号已被封禁或暂停使用 (Account suspended / banned)",
902
+ updatedAt: Date.now()
903
+ };
904
+ }
905
+ if (!isLoggedIn) {
906
+ return {
907
+ runtimeId: "claude",
908
+ provider: "Anthropic / Claude Code",
909
+ status: "unauthorized",
910
+ message: "未登录 Claude Code 或凭据无效 (Unauthorized)",
911
+ updatedAt: Date.now()
912
+ };
913
+ }
914
+ return {
915
+ runtimeId: "claude",
916
+ provider: "Anthropic / Claude Code",
917
+ account: {
918
+ email: accountEmail,
919
+ plan
920
+ },
921
+ status: "ok",
922
+ updatedAt: Date.now()
923
+ };
924
+ }
925
+
926
+ // src/runtimes/claude/index.ts
927
+ var import_node_fs5 = require("node:fs");
928
+ var import_node_os4 = require("node:os");
929
+ var import_node_path7 = require("node:path");
618
930
  function resolveClaudeHome() {
619
931
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
620
932
  if (fromEnv)
621
933
  return fromEnv;
622
- return import_node_path5.join(import_node_os3.homedir(), ".claude");
934
+ return import_node_path7.join(import_node_os4.homedir(), ".claude");
623
935
  }
624
936
  function probeClaudeAuth() {
625
937
  const claudeHome = resolveClaudeHome();
626
- const hasCodexHome = import_node_fs3.existsSync(claudeHome);
627
- const hasAuthFile = import_node_fs3.existsSync(import_node_path5.join(import_node_os3.homedir(), ".claude.json")) || import_node_fs3.existsSync(import_node_path5.join(claudeHome, ".credentials.json"));
938
+ const hasCodexHome = import_node_fs5.existsSync(claudeHome);
939
+ const hasAuthFile = import_node_fs5.existsSync(import_node_path7.join(import_node_os4.homedir(), ".claude.json")) || import_node_fs5.existsSync(import_node_path7.join(claudeHome, ".credentials.json"));
628
940
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
629
941
  return {
630
942
  codexHome: claudeHome,
@@ -637,21 +949,22 @@ function probeClaudeAuth() {
637
949
  var claudeAdapter = {
638
950
  id: "claude",
639
951
  probeAuth: () => probeClaudeAuth(),
952
+ probeQuota: async (options) => probeClaudeQuota(options),
640
953
  orderAuthMethods: (methods) => methods,
641
954
  canSkipInteractiveAuth: () => false
642
955
  };
643
956
 
644
957
  // src/runtimes/gemini/index.ts
645
- var import_node_fs4 = require("node:fs");
646
- var import_node_os4 = require("node:os");
647
- var import_node_path6 = require("node:path");
958
+ var import_node_fs6 = require("node:fs");
959
+ var import_node_os5 = require("node:os");
960
+ var import_node_path8 = require("node:path");
648
961
  function resolveGeminiHome() {
649
- return import_node_path6.join(import_node_os4.homedir(), ".gemini");
962
+ return import_node_path8.join(import_node_os5.homedir(), ".gemini");
650
963
  }
651
964
  function probeGeminiAuth() {
652
965
  const geminiHome = resolveGeminiHome();
653
- const hasCodexHome = import_node_fs4.existsSync(geminiHome);
654
- const hasAuthFile = import_node_fs4.existsSync(import_node_path6.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
966
+ const hasCodexHome = import_node_fs6.existsSync(geminiHome);
967
+ const hasAuthFile = import_node_fs6.existsSync(import_node_path8.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
655
968
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
656
969
  return {
657
970
  codexHome: geminiHome,
@@ -669,18 +982,18 @@ var geminiAdapter = {
669
982
  };
670
983
 
671
984
  // src/runtimes/copilot/index.ts
672
- var import_node_fs5 = require("node:fs");
673
- var import_node_os5 = require("node:os");
674
- var import_node_path7 = require("node:path");
985
+ var import_node_fs7 = require("node:fs");
986
+ var import_node_os6 = require("node:os");
987
+ var import_node_path9 = require("node:path");
675
988
  function resolveCopilotHome() {
676
989
  const fromEnv = process.env.COPILOT_HOME?.trim();
677
990
  if (fromEnv)
678
991
  return fromEnv;
679
- return import_node_path7.join(import_node_os5.homedir(), ".copilot");
992
+ return import_node_path9.join(import_node_os6.homedir(), ".copilot");
680
993
  }
681
994
  function hasCopilotLogin(home) {
682
995
  try {
683
- const raw = import_node_fs5.readFileSync(import_node_path7.join(home, "config.json"), "utf8");
996
+ const raw = import_node_fs7.readFileSync(import_node_path9.join(home, "config.json"), "utf8");
684
997
  const parsed = JSON.parse(raw);
685
998
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
686
999
  } catch {
@@ -689,7 +1002,7 @@ function hasCopilotLogin(home) {
689
1002
  }
690
1003
  function probeCopilotAuth() {
691
1004
  const copilotHome = resolveCopilotHome();
692
- const hasCodexHome = import_node_fs5.existsSync(copilotHome);
1005
+ const hasCodexHome = import_node_fs7.existsSync(copilotHome);
693
1006
  const hasAuthFile = hasCopilotLogin(copilotHome);
694
1007
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
695
1008
  return {
@@ -707,17 +1020,68 @@ var copilotAdapter = {
707
1020
  canSkipInteractiveAuth: () => false
708
1021
  };
709
1022
 
1023
+ // src/runtimes/opencode/quota.ts
1024
+ var import_node_fs8 = require("node:fs");
1025
+ function resolveOpencodeAuthPath() {
1026
+ const candidates = resolveOpencodeAuthCandidates();
1027
+ for (const c of candidates) {
1028
+ if (import_node_fs8.existsSync(c))
1029
+ return c;
1030
+ }
1031
+ return candidates[0] ?? null;
1032
+ }
1033
+ async function probeOpencodeQuota(runtimeId = "opencode") {
1034
+ const authPath = resolveOpencodeAuthPath();
1035
+ let isLoggedIn = false;
1036
+ let accountEmail;
1037
+ let plan = "OpenCode Community";
1038
+ if (authPath && import_node_fs8.existsSync(authPath)) {
1039
+ try {
1040
+ const data = JSON.parse(import_node_fs8.readFileSync(authPath, "utf8"));
1041
+ if (data && typeof data === "object") {
1042
+ const keys = Object.keys(data);
1043
+ if (keys.length > 0) {
1044
+ isLoggedIn = true;
1045
+ if (data.email)
1046
+ accountEmail = String(data.email);
1047
+ if (data.plan)
1048
+ plan = String(data.plan);
1049
+ }
1050
+ }
1051
+ } catch {}
1052
+ }
1053
+ if (!isLoggedIn) {
1054
+ return {
1055
+ runtimeId,
1056
+ provider: "OpenCode",
1057
+ status: "unauthorized",
1058
+ message: "未检测到 OpenCode 登录凭证 (auth.json / SQLite)",
1059
+ updatedAt: Date.now()
1060
+ };
1061
+ }
1062
+ return {
1063
+ runtimeId,
1064
+ provider: "OpenCode",
1065
+ account: {
1066
+ email: accountEmail,
1067
+ plan
1068
+ },
1069
+ status: "ok",
1070
+ updatedAt: Date.now()
1071
+ };
1072
+ }
1073
+
710
1074
  // src/runtimes/opencode/index.ts
711
- var import_node_fs6 = require("node:fs");
712
- var import_node_os6 = require("node:os");
713
- var import_node_path8 = require("node:path");
1075
+ var import_node_fs9 = require("node:fs");
1076
+ var import_node_os7 = require("node:os");
1077
+ var import_node_path10 = require("node:path");
714
1078
  function pickEnv(env, key) {
715
1079
  return env?.[key]?.trim() ?? "";
716
1080
  }
717
1081
  function resolveOpencodeAuthCandidates(overrides) {
718
1082
  const platform = overrides?.platform ?? process.platform;
719
1083
  const env = overrides?.env ?? process.env;
720
- const home = overrides?.home ?? import_node_os6.homedir();
1084
+ const home = overrides?.home ?? import_node_os7.homedir();
721
1085
  const seen = new Set;
722
1086
  const out = [];
723
1087
  const push = (p) => {
@@ -728,27 +1092,27 @@ function resolveOpencodeAuthCandidates(overrides) {
728
1092
  };
729
1093
  const xdg = pickEnv(env, "XDG_DATA_HOME");
730
1094
  if (xdg)
731
- push(import_node_path8.join(xdg, "opencode", "auth.json"));
1095
+ push(import_node_path10.join(xdg, "opencode", "auth.json"));
732
1096
  if (platform === "win32") {
733
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path8.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1097
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path10.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
734
1098
  if (localAppData)
735
- push(import_node_path8.join(localAppData, "opencode", "auth.json"));
1099
+ push(import_node_path10.join(localAppData, "opencode", "auth.json"));
736
1100
  const userProfile = pickEnv(env, "USERPROFILE") || home;
737
1101
  if (userProfile)
738
- push(import_node_path8.join(userProfile, ".local", "share", "opencode", "auth.json"));
1102
+ push(import_node_path10.join(userProfile, ".local", "share", "opencode", "auth.json"));
739
1103
  } else if (home) {
740
- push(import_node_path8.join(home, ".local", "share", "opencode", "auth.json"));
1104
+ push(import_node_path10.join(home, ".local", "share", "opencode", "auth.json"));
741
1105
  }
742
1106
  return out;
743
1107
  }
744
1108
  function resolveOpencodeAuthFile() {
745
- return resolveOpencodeAuthCandidates()[0] ?? import_node_path8.join(import_node_os6.homedir(), ".local", "share", "opencode", "auth.json");
1109
+ return resolveOpencodeAuthCandidates()[0] ?? import_node_path10.join(import_node_os7.homedir(), ".local", "share", "opencode", "auth.json");
746
1110
  }
747
1111
  function isValidOpencodeAuthFile(authFile) {
748
1112
  try {
749
- if (!authFile || !import_node_fs6.existsSync(authFile))
1113
+ if (!authFile || !import_node_fs9.existsSync(authFile))
750
1114
  return false;
751
- const raw = import_node_fs6.readFileSync(authFile, "utf8").trim();
1115
+ const raw = import_node_fs9.readFileSync(authFile, "utf8").trim();
752
1116
  if (!raw)
753
1117
  return false;
754
1118
  const parsed = JSON.parse(raw);
@@ -766,7 +1130,7 @@ function probeOpencodeAuth(overrides) {
766
1130
  for (const candidate of candidates) {
767
1131
  let exists = false;
768
1132
  try {
769
- exists = import_node_fs6.existsSync(candidate);
1133
+ exists = import_node_fs9.existsSync(candidate);
770
1134
  } catch {
771
1135
  exists = false;
772
1136
  }
@@ -779,10 +1143,10 @@ function probeOpencodeAuth(overrides) {
779
1143
  validFile = candidate;
780
1144
  }
781
1145
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
782
- const authDir = import_node_path8.dirname(authFile);
1146
+ const authDir = import_node_path10.dirname(authFile);
783
1147
  let hasCodexHome = false;
784
1148
  try {
785
- hasCodexHome = import_node_fs6.existsSync(authDir);
1149
+ hasCodexHome = import_node_fs9.existsSync(authDir);
786
1150
  } catch {
787
1151
  hasCodexHome = false;
788
1152
  }
@@ -798,34 +1162,67 @@ function probeOpencodeAuth(overrides) {
798
1162
  var opencodeAdapter = {
799
1163
  id: "opencode",
800
1164
  probeAuth: () => probeOpencodeAuth(),
1165
+ probeQuota: async () => probeOpencodeQuota(),
1166
+ orderAuthMethods: (methods) => methods,
1167
+ canSkipInteractiveAuth: () => false,
1168
+ tryDirectSessionFirst: true
1169
+ };
1170
+
1171
+ // src/runtimes/opencode-v2/index.ts
1172
+ var opencodeV2Adapter = {
1173
+ id: "opencode-v2",
1174
+ probeAuth: () => probeOpencodeAuth(),
801
1175
  orderAuthMethods: (methods) => methods,
802
1176
  canSkipInteractiveAuth: () => false,
803
1177
  tryDirectSessionFirst: true
804
1178
  };
805
1179
 
1180
+ // src/runtimes/cursor/quota.ts
1181
+ async function probeCursorQuota() {
1182
+ const auth = probeCursorAuth();
1183
+ if (!auth.looksLoggedIn) {
1184
+ return {
1185
+ runtimeId: "cursor-cli",
1186
+ provider: "Cursor",
1187
+ status: "unauthorized",
1188
+ message: "未检测到 Cursor CLI 登录凭证",
1189
+ updatedAt: Date.now()
1190
+ };
1191
+ }
1192
+ return {
1193
+ runtimeId: "cursor-cli",
1194
+ provider: "Cursor",
1195
+ account: {
1196
+ plan: "Cursor Pro / Fast Requests"
1197
+ },
1198
+ status: "ok",
1199
+ updatedAt: Date.now()
1200
+ };
1201
+ }
1202
+
806
1203
  // src/runtimes/cursor/index.ts
807
1204
  var import_node_child_process = require("node:child_process");
808
- var import_node_fs7 = require("node:fs");
809
- var import_node_os7 = require("node:os");
810
- var import_node_path9 = require("node:path");
1205
+ var import_node_fs10 = require("node:fs");
1206
+ var import_node_os8 = require("node:os");
1207
+ var import_node_path11 = require("node:path");
811
1208
  function cursorLocalAppData(env) {
812
1209
  const local = env.LOCALAPPDATA?.trim();
813
1210
  if (local)
814
1211
  return local;
815
1212
  const profile = env.USERPROFILE?.trim();
816
- return profile ? import_node_path9.join(profile, "AppData", "Local") : "";
1213
+ return profile ? import_node_path11.join(profile, "AppData", "Local") : "";
817
1214
  }
818
1215
  function isOnPath(command, env, platform) {
819
1216
  const pathValue = env.PATH ?? env.Path ?? "";
820
1217
  if (!pathValue.trim())
821
1218
  return false;
822
- const sep = platform === "win32" ? ";" : import_node_path9.delimiter;
1219
+ const sep = platform === "win32" ? ";" : import_node_path11.delimiter;
823
1220
  for (const dir of pathValue.split(sep)) {
824
1221
  const trimmed = dir.trim().replace(/^"|"$/g, "");
825
1222
  if (!trimmed)
826
1223
  continue;
827
1224
  try {
828
- if (import_node_fs7.existsSync(import_node_path9.join(trimmed, command)))
1225
+ if (import_node_fs10.existsSync(import_node_path11.join(trimmed, command)))
829
1226
  return true;
830
1227
  } catch {}
831
1228
  }
@@ -834,24 +1231,24 @@ function isOnPath(command, env, platform) {
834
1231
  function resolveDirectCursorCommand(platform, env, home) {
835
1232
  if (platform === "win32") {
836
1233
  const localAppData = cursorLocalAppData(env);
837
- return localAppData ? import_node_path9.join(localAppData, "cursor-agent", "agent.cmd") : "";
1234
+ return localAppData ? import_node_path11.join(localAppData, "cursor-agent", "agent.cmd") : "";
838
1235
  }
839
- return home ? import_node_path9.join(home, ".local", "bin", "agent") : "";
1236
+ return home ? import_node_path11.join(home, ".local", "bin", "agent") : "";
840
1237
  }
841
1238
  function resolveCursorCommand(overrides) {
842
1239
  const args = ["acp"];
843
1240
  const platform = overrides?.platform ?? process.platform;
844
1241
  const env = overrides?.env ?? process.env;
845
- const home = overrides?.home ?? import_node_os7.homedir();
1242
+ const home = overrides?.home ?? import_node_os8.homedir();
846
1243
  if (platform === "win32") {
847
1244
  const directCmd = resolveDirectCursorCommand(platform, env, home);
848
- if (directCmd && import_node_fs7.existsSync(directCmd)) {
1245
+ if (directCmd && import_node_fs10.existsSync(directCmd)) {
849
1246
  return { command: directCmd, args };
850
1247
  }
851
1248
  return { command: "agent.cmd", args };
852
1249
  }
853
1250
  const directBin = resolveDirectCursorCommand(platform, env, home);
854
- if (directBin && import_node_fs7.existsSync(directBin)) {
1251
+ if (directBin && import_node_fs10.existsSync(directBin)) {
855
1252
  return { command: directBin, args };
856
1253
  }
857
1254
  return { command: "agent", args };
@@ -860,11 +1257,11 @@ function resolveCursorSpawnCommand(overrides) {
860
1257
  const args = ["acp"];
861
1258
  const platform = overrides?.platform ?? process.platform;
862
1259
  const env = overrides?.env ?? process.env;
863
- const home = overrides?.home ?? import_node_os7.homedir();
1260
+ const home = overrides?.home ?? import_node_os8.homedir();
864
1261
  const binary = platform === "win32" ? "agent.cmd" : "agent";
865
1262
  const direct = resolveDirectCursorCommand(platform, env, home);
866
1263
  try {
867
- if (direct && import_node_fs7.existsSync(direct))
1264
+ if (direct && import_node_fs10.existsSync(direct))
868
1265
  return { command: direct, args };
869
1266
  } catch {}
870
1267
  if (isOnPath(binary, env, platform))
@@ -886,12 +1283,12 @@ function cursorRoamingAppData(env, home) {
886
1283
  if (roaming)
887
1284
  return roaming;
888
1285
  const profile = pickEnv2(env, "USERPROFILE") || home;
889
- return profile ? import_node_path9.join(profile, "AppData", "Roaming") : "";
1286
+ return profile ? import_node_path11.join(profile, "AppData", "Roaming") : "";
890
1287
  }
891
1288
  function resolveCursorAuthCandidates(overrides) {
892
1289
  const platform = overrides?.platform ?? process.platform;
893
1290
  const env = overrides?.env ?? process.env;
894
- const home = overrides?.home ?? import_node_os7.homedir();
1291
+ const home = overrides?.home ?? import_node_os8.homedir();
895
1292
  const seen = new Set;
896
1293
  const out = [];
897
1294
  const push = (p) => {
@@ -902,16 +1299,16 @@ function resolveCursorAuthCandidates(overrides) {
902
1299
  };
903
1300
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
904
1301
  if (xdg)
905
- push(import_node_path9.join(xdg, "cursor", "auth.json"));
1302
+ push(import_node_path11.join(xdg, "cursor", "auth.json"));
906
1303
  if (platform === "win32") {
907
1304
  const profile = pickEnv2(env, "USERPROFILE") || home;
908
1305
  if (profile)
909
- push(import_node_path9.join(profile, ".config", "cursor", "auth.json"));
1306
+ push(import_node_path11.join(profile, ".config", "cursor", "auth.json"));
910
1307
  const roaming = cursorRoamingAppData(env, home);
911
1308
  if (roaming)
912
- push(import_node_path9.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
1309
+ push(import_node_path11.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
913
1310
  } else if (home) {
914
- push(import_node_path9.join(home, ".config", "cursor", "auth.json"));
1311
+ push(import_node_path11.join(home, ".config", "cursor", "auth.json"));
915
1312
  }
916
1313
  return out;
917
1314
  }
@@ -922,9 +1319,9 @@ function isValidCursorAuthFile(authFile) {
922
1319
  try {
923
1320
  if (!authFile || isStorageHintPath(authFile))
924
1321
  return false;
925
- if (!import_node_fs7.existsSync(authFile))
1322
+ if (!import_node_fs10.existsSync(authFile))
926
1323
  return false;
927
- const raw = import_node_fs7.readFileSync(authFile, "utf8").trim();
1324
+ const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
928
1325
  if (!raw)
929
1326
  return false;
930
1327
  const parsed = JSON.parse(raw);
@@ -942,9 +1339,9 @@ function isHintCursorStorageFile(authFile) {
942
1339
  try {
943
1340
  if (!authFile || !isStorageHintPath(authFile))
944
1341
  return false;
945
- if (!import_node_fs7.existsSync(authFile))
1342
+ if (!import_node_fs10.existsSync(authFile))
946
1343
  return false;
947
- const raw = import_node_fs7.readFileSync(authFile, "utf8").trim();
1344
+ const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
948
1345
  if (!raw)
949
1346
  return false;
950
1347
  const parsed = JSON.parse(raw);
@@ -960,7 +1357,7 @@ function isValidCursorCandidate(authFile) {
960
1357
  }
961
1358
  function probeCursorAuth(overrides) {
962
1359
  const env = overrides?.env ?? process.env;
963
- const home = overrides?.home ?? import_node_os7.homedir();
1360
+ const home = overrides?.home ?? import_node_os8.homedir();
964
1361
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
965
1362
  const candidates = resolveCursorAuthCandidates(overrides);
966
1363
  let firstExisting = null;
@@ -968,7 +1365,7 @@ function probeCursorAuth(overrides) {
968
1365
  for (const candidate of candidates) {
969
1366
  let exists = false;
970
1367
  try {
971
- exists = import_node_fs7.existsSync(candidate);
1368
+ exists = import_node_fs10.existsSync(candidate);
972
1369
  } catch {
973
1370
  exists = false;
974
1371
  }
@@ -980,12 +1377,12 @@ function probeCursorAuth(overrides) {
980
1377
  if (isValidCursorCandidate(candidate))
981
1378
  validFile = candidate;
982
1379
  }
983
- const fallback = home ? import_node_path9.join(home, ".config", "cursor", "auth.json") : "";
1380
+ const fallback = home ? import_node_path11.join(home, ".config", "cursor", "auth.json") : "";
984
1381
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
985
- const authDir = authFile ? import_node_path9.dirname(authFile) : "";
1382
+ const authDir = authFile ? import_node_path11.dirname(authFile) : "";
986
1383
  let hasCodexHome = false;
987
1384
  try {
988
- hasCodexHome = authDir ? import_node_fs7.existsSync(authDir) : false;
1385
+ hasCodexHome = authDir ? import_node_fs10.existsSync(authDir) : false;
989
1386
  } catch {
990
1387
  hasCodexHome = false;
991
1388
  }
@@ -1000,6 +1397,7 @@ function probeCursorAuth(overrides) {
1000
1397
  var cursorAdapter = {
1001
1398
  id: "cursor-cli",
1002
1399
  probeAuth: () => probeCursorAuth(),
1400
+ probeQuota: async () => probeCursorQuota(),
1003
1401
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
1004
1402
  orderAuthMethods: (methods) => methods,
1005
1403
  canSkipInteractiveAuth: () => false,
@@ -1118,6 +1516,55 @@ var deepseekAdapter = {
1118
1516
  canSkipInteractiveAuth: () => false
1119
1517
  };
1120
1518
 
1519
+ // src/runtimes/agy/quota.ts
1520
+ var import_node_fs11 = require("node:fs");
1521
+ var import_node_path12 = require("node:path");
1522
+ function resolveGeminiHome2() {
1523
+ const home = process.env.USERPROFILE || process.env.HOME || "";
1524
+ return import_node_path12.join(home, ".gemini");
1525
+ }
1526
+ async function probeAgyQuota(options) {
1527
+ const geminiHome = resolveGeminiHome2();
1528
+ const hasAgyDir = import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity")) || import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity-cli"));
1529
+ const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
1530
+ const isAvailable = hasAgyDir || hasApiKey;
1531
+ if (!isAvailable) {
1532
+ return {
1533
+ runtimeId: "agy",
1534
+ provider: "Google Antigravity",
1535
+ status: "unauthorized",
1536
+ message: "wenjianlingu antigravity cli",
1537
+ updatedAt: Date.now()
1538
+ };
1539
+ }
1540
+ return {
1541
+ runtimeId: "agy",
1542
+ provider: "Google Antigravity",
1543
+ account: {
1544
+ plan: "Antigravity / Gemini",
1545
+ type: "gemini"
1546
+ },
1547
+ primaryWindow: {
1548
+ label: "5-Hour limit",
1549
+ percentLeft: 100,
1550
+ usedPercent: 0,
1551
+ windowDurationMins: 300
1552
+ },
1553
+ secondaryWindow: {
1554
+ label: "Weekly limit",
1555
+ percentLeft: 100,
1556
+ usedPercent: 0,
1557
+ windowDurationMins: 10080
1558
+ },
1559
+ credits: {
1560
+ unlimited: true,
1561
+ balance: "unlimited"
1562
+ },
1563
+ status: "ok",
1564
+ updatedAt: Date.now()
1565
+ };
1566
+ }
1567
+
1121
1568
  // src/runtimes/agy/index.ts
1122
1569
  function probeAgyAuth() {
1123
1570
  return {
@@ -1131,6 +1578,7 @@ function probeAgyAuth() {
1131
1578
  var agyAdapter = {
1132
1579
  id: "agy",
1133
1580
  probeAuth: () => probeAgyAuth(),
1581
+ probeQuota: (options) => probeAgyQuota(options),
1134
1582
  orderAuthMethods: (methods) => methods,
1135
1583
  canSkipInteractiveAuth: () => false,
1136
1584
  tryDirectSessionFirst: true
@@ -1150,6 +1598,8 @@ function getAcpRuntimeAdapter(runtimeId) {
1150
1598
  return copilotAdapter;
1151
1599
  case opencodeAdapter.id:
1152
1600
  return opencodeAdapter;
1601
+ case opencodeV2Adapter.id:
1602
+ return opencodeV2Adapter;
1153
1603
  case cursorAdapter.id:
1154
1604
  case "cursor":
1155
1605
  return cursorAdapter;
@@ -1407,17 +1857,17 @@ var import_sdk2 = require("@agentclientprotocol/sdk");
1407
1857
 
1408
1858
  // src/client/acp-fs.ts
1409
1859
  var import_promises3 = require("node:fs/promises");
1410
- var import_node_path10 = require("node:path");
1860
+ var import_node_path13 = require("node:path");
1411
1861
  var import_promises4 = require("node:fs/promises");
1412
1862
  var MAX_READ_BYTES = 2 * 1024 * 1024;
1413
1863
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
1414
1864
  function isBinaryDocumentPath(filePath) {
1415
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path10.extname(filePath).toLowerCase());
1865
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path13.extname(filePath).toLowerCase());
1416
1866
  }
1417
1867
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
1418
- const root = import_node_path10.resolve(workspaceRoot);
1419
- const target = import_node_path10.resolve(filePath);
1420
- const rootWithSep = root.endsWith(import_node_path10.sep) ? root : root + import_node_path10.sep;
1868
+ const root = import_node_path13.resolve(workspaceRoot);
1869
+ const target = import_node_path13.resolve(filePath);
1870
+ const rootWithSep = root.endsWith(import_node_path13.sep) ? root : root + import_node_path13.sep;
1421
1871
  if (target !== root && !target.startsWith(rootWithSep)) {
1422
1872
  throw new Error(`路径不在工作区内: ${filePath}`);
1423
1873
  }
@@ -1448,7 +1898,7 @@ async function acpReadTextFile(params) {
1448
1898
  }
1449
1899
  async function acpWriteTextFile(params) {
1450
1900
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
1451
- await import_promises4.mkdir(import_node_path10.dirname(abs), { recursive: true });
1901
+ await import_promises4.mkdir(import_node_path13.dirname(abs), { recursive: true });
1452
1902
  await import_promises3.writeFile(abs, params.content, "utf-8");
1453
1903
  return {};
1454
1904
  }
@@ -2126,8 +2576,8 @@ class AcpTerminalManager {
2126
2576
 
2127
2577
  // src/client/acp-proxy-service.ts
2128
2578
  var import_promises5 = require("node:fs/promises");
2129
- var import_node_fs8 = require("node:fs");
2130
- var import_node_path11 = require("node:path");
2579
+ var import_node_fs12 = require("node:fs");
2580
+ var import_node_path14 = require("node:path");
2131
2581
  var DEFAULT_ACP_PROXY_SETTINGS = {
2132
2582
  enabled: false,
2133
2583
  host: "127.0.0.1",
@@ -2136,7 +2586,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
2136
2586
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
2137
2587
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
2138
2588
  function proxyFilePath(dir) {
2139
- return import_node_path11.join(dir, "agent", "proxy.json");
2589
+ return import_node_path14.join(dir, "agent", "proxy.json");
2140
2590
  }
2141
2591
  function validate2(settings) {
2142
2592
  if (!settings.host.trim())
@@ -2148,7 +2598,7 @@ function validate2(settings) {
2148
2598
  }
2149
2599
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
2150
2600
  const file = proxyFilePath(dir);
2151
- if (!import_node_fs8.existsSync(file))
2601
+ if (!import_node_fs12.existsSync(file))
2152
2602
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
2153
2603
  try {
2154
2604
  const raw = JSON.parse(await import_promises5.readFile(file, "utf8"));
@@ -2170,7 +2620,7 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
2170
2620
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
2171
2621
  port: payload.port
2172
2622
  };
2173
- await import_promises5.mkdir(import_node_path11.join(dir, "agent"), { recursive: true });
2623
+ await import_promises5.mkdir(import_node_path14.join(dir, "agent"), { recursive: true });
2174
2624
  await import_promises5.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
2175
2625
  return ok(stored);
2176
2626
  }
@@ -2238,6 +2688,12 @@ class AcpSessionHandle {
2238
2688
  async prompt(promptText, options) {
2239
2689
  return this.client.promptSession(this.sessionId, promptText, options);
2240
2690
  }
2691
+ get quota() {
2692
+ return this.client.getCachedQuota(this.sessionId);
2693
+ }
2694
+ async getQuota() {
2695
+ return this.client.getQuota(this.sessionId);
2696
+ }
2241
2697
  get availableCommands() {
2242
2698
  return this.client.getAvailableCommands(this.sessionId);
2243
2699
  }
@@ -2249,6 +2705,7 @@ class AcpSessionHandle {
2249
2705
  class AcpClient {
2250
2706
  status = "disconnected";
2251
2707
  commandsCache = new AvailableCommandsCache;
2708
+ quotaCache = new QuotaCache;
2252
2709
  runtimeInfo;
2253
2710
  adapter;
2254
2711
  workspaceRoot;
@@ -2359,6 +2816,7 @@ class AcpClient {
2359
2816
  },
2360
2817
  onSessionUpdate: (params) => {
2361
2818
  this.commandsCache.observe(params);
2819
+ this.quotaCache.observe(params, this.runtimeInfo.id);
2362
2820
  this.callbacks.onSessionUpdate?.(params);
2363
2821
  }
2364
2822
  };
@@ -2389,6 +2847,23 @@ class AcpClient {
2389
2847
  return err({ code: "ACP_PROTOCOL_ERROR", message });
2390
2848
  }
2391
2849
  }
2850
+ getCachedQuota(sessionId) {
2851
+ return this.quotaCache.get(sessionId, this.runtimeInfo.id);
2852
+ }
2853
+ async getQuota(sessionId) {
2854
+ const cached = this.getCachedQuota(sessionId);
2855
+ if (cached && Date.now() - cached.updatedAt < 30000) {
2856
+ return cached;
2857
+ }
2858
+ if (this.adapter.probeQuota) {
2859
+ const probed = await this.adapter.probeQuota({ sessionId });
2860
+ if (probed) {
2861
+ this.quotaCache.set(probed, sessionId);
2862
+ return probed;
2863
+ }
2864
+ }
2865
+ return cached ?? null;
2866
+ }
2392
2867
  getAvailableCommands(sessionId) {
2393
2868
  return this.commandsCache.get(sessionId);
2394
2869
  }