@yitom/acp-client 0.1.3 → 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
@@ -39,6 +39,7 @@ var __export = (target, all) => {
39
39
  // src/index.ts
40
40
  var exports_src = {};
41
41
  __export(exports_src, {
42
+ ACP_CLIENT_VERSION: () => ACP_CLIENT_VERSION,
42
43
  ACP_EARLY_EXIT_STDERR_TAIL_LINES: () => ACP_EARLY_EXIT_STDERR_TAIL_LINES,
43
44
  ACP_EARLY_EXIT_WINDOW_MS: () => ACP_EARLY_EXIT_WINDOW_MS,
44
45
  ACP_SDK_REQUEST_TIMEOUT_MS: () => ACP_SDK_REQUEST_TIMEOUT_MS,
@@ -61,6 +62,8 @@ __export(exports_src, {
61
62
  INKDOWN_VIRTUAL_DIR: () => INKDOWN_VIRTUAL_DIR,
62
63
  INKDOWN_VIRTUAL_RESOURCES: () => INKDOWN_VIRTUAL_RESOURCES,
63
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,
64
67
  acpReadTextFile: () => acpReadTextFile,
65
68
  acpWriteTextFile: () => acpWriteTextFile,
66
69
  agyAdapter: () => agyAdapter,
@@ -119,6 +122,7 @@ __export(exports_src, {
119
122
  mergeTopLevelModelsIntoConfigOptions: () => mergeTopLevelModelsIntoConfigOptions,
120
123
  ok: () => ok,
121
124
  opencodeAdapter: () => opencodeAdapter,
125
+ opencodeV2Adapter: () => opencodeV2Adapter,
122
126
  orderSilentAuthMethodIds: () => orderSilentAuthMethodIds,
123
127
  parseAcpConfigOptions: () => parseAcpConfigOptions,
124
128
  parseCursorCatalogOutput: () => parseCursorCatalogOutput,
@@ -126,16 +130,21 @@ __export(exports_src, {
126
130
  parseLoadSessionSupported: () => parseLoadSessionSupported,
127
131
  parseMcpHttpSupported: () => parseMcpHttpSupported,
128
132
  parsePromptCapabilities: () => parsePromptCapabilities,
133
+ parseRateLimitsFromStatusText: () => parseRateLimitsFromStatusText,
129
134
  parseResumeSessionSupported: () => parseResumeSessionSupported,
130
135
  pickAllowOptionId: () => pickAllowOptionId,
131
136
  probeAgyAuth: () => probeAgyAuth,
132
137
  probeClaudeAuth: () => probeClaudeAuth,
138
+ probeClaudeQuota: () => probeClaudeQuota,
133
139
  probeCodexAuth: () => probeCodexAuth,
140
+ probeCodexQuota: () => probeCodexQuota,
134
141
  probeCopilotAuth: () => probeCopilotAuth,
135
142
  probeCursorAuth: () => probeCursorAuth,
143
+ probeCursorQuota: () => probeCursorQuota,
136
144
  probeDeepseekAuth: () => probeDeepseekAuth,
137
145
  probeGeminiAuth: () => probeGeminiAuth,
138
146
  probeOpencodeAuth: () => probeOpencodeAuth,
147
+ probeOpencodeQuota: () => probeOpencodeQuota,
139
148
  provisionCustomProviderCodexHome: () => provisionCustomProviderCodexHome,
140
149
  readAcpProxySettings: () => readAcpProxySettings,
141
150
  readStoredAcpProvider: () => readStoredAcpProvider,
@@ -152,6 +161,7 @@ __export(exports_src, {
152
161
  resolveGeminiHome: () => resolveGeminiHome,
153
162
  resolveOpencodeAuthCandidates: () => resolveOpencodeAuthCandidates,
154
163
  resolveOpencodeAuthFile: () => resolveOpencodeAuthFile,
164
+ resolveOpencodeAuthPath: () => resolveOpencodeAuthPath,
155
165
  restoreOrCreateAcpSession: () => restoreOrCreateAcpSession,
156
166
  runConnectAuthGate: () => runConnectAuthGate,
157
167
  saveAcpProvider: () => saveAcpProvider,
@@ -233,6 +243,7 @@ var CODEX_ACP_NPM_PACKAGE = "@agentclientprotocol/codex-acp";
233
243
  var CLAUDE_ACP_NPM_PACKAGE = "@agentclientprotocol/claude-agent-acp";
234
244
  var DEEPSEEK_DSH_NPM_PACKAGE = "@deepseek-ai/dsh";
235
245
  var AGY_ACP_NPM_PACKAGE = "@yitom/agy-acp-map";
246
+ var OPENCODE_CLI_NPM_PACKAGE = "@opencode/cli";
236
247
  var LEGACY_ZED_CODEX_ACP_NPM_PACKAGE = "@zed-industries/codex-acp";
237
248
  var DEFAULT_ACP_RUNTIME_ID = "codex-acp";
238
249
  function isWindowsPlatform() {
@@ -285,6 +296,15 @@ var BUILTIN_ACP_RUNTIMES = [
285
296
  args: ["acp"],
286
297
  requiredEnvKeys: []
287
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
+ },
288
308
  {
289
309
  id: "cursor-cli",
290
310
  name: "Cursor",
@@ -316,6 +336,8 @@ var BUILTIN_ACP_RUNTIMES = [
316
336
  function findBuiltinAcpRuntime(id) {
317
337
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
318
338
  }
339
+ // src/version.ts
340
+ var ACP_CLIENT_VERSION = "0.1.5";
319
341
  // src/session/available-commands.ts
320
342
  function normalizeCommand(raw) {
321
343
  if (!raw || typeof raw !== "object")
@@ -404,42 +426,168 @@ class AvailableCommandsCache {
404
426
  }
405
427
  }
406
428
 
407
- // src/client/acp-client.ts
408
- var import_sdk4 = require("@agentclientprotocol/sdk");
409
-
410
- // src/runtimes/codex/index.ts
411
- var import_promises2 = require("node:fs/promises");
412
- var import_node_path4 = require("node:path");
413
-
414
- // src/runtimes/codex/codex-provider-home.ts
415
- var INKDOWN_PROVIDER_ID = "inkdown-custom";
416
- var INKDOWN_PROVIDER_API_KEY_ENV = "INKDOWN_PROVIDER_API_KEY";
417
- function tomlEscape(value) {
418
- return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
419
- }
420
- function buildCustomProviderConfigToml(config) {
421
- const name = config.name?.trim() || "自定义 API";
422
- const wireApi = config.wireApi === "responses" ? "responses" : "chat";
423
- return [
424
- `model_provider = "${INKDOWN_PROVIDER_ID}"`,
425
- `model = "${tomlEscape(config.model.trim())}"`,
426
- "",
427
- `[model_providers.${INKDOWN_PROVIDER_ID}]`,
428
- `name = "${tomlEscape(name)}"`,
429
- `base_url = "${tomlEscape(config.baseUrl.trim())}"`,
430
- `env_key = "${INKDOWN_PROVIDER_API_KEY_ENV}"`,
431
- `wire_api = "${wireApi}"`,
432
- ""
433
- ].join(`
434
- `);
435
- }
436
- 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
+ }
437
521
  return {
438
- CODEX_HOME: codexHome,
439
- [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()
440
532
  };
441
533
  }
442
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
+
443
591
  // src/runtimes/codex/codex-auth-preflight.ts
444
592
  var import_node_fs = require("node:fs");
445
593
  var import_node_os = require("node:os");
@@ -476,14 +624,114 @@ function probeCodexAuth() {
476
624
  };
477
625
  }
478
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
+
479
727
  // src/runtimes/codex/codex-provider.ts
480
728
  var import_promises = require("node:fs/promises");
481
- var import_node_fs2 = require("node:fs");
482
- var import_node_path3 = require("node:path");
729
+ var import_node_fs3 = require("node:fs");
730
+ var import_node_path4 = require("node:path");
483
731
 
484
732
  // src/client/acp-paths.ts
485
733
  var import_node_os2 = require("node:os");
486
- var import_node_path2 = require("node:path");
734
+ var import_node_path3 = require("node:path");
487
735
  function getDefaultAgentDataDir() {
488
736
  if (process.env.INKDOWN_DATA_DIR) {
489
737
  return process.env.INKDOWN_DATA_DIR;
@@ -492,20 +740,20 @@ function getDefaultAgentDataDir() {
492
740
  return process.env.ACP_DATA_DIR;
493
741
  }
494
742
  if (process.platform === "win32") {
495
- 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");
496
744
  }
497
745
  if (process.platform === "darwin") {
498
- 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");
499
747
  }
500
- 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");
501
749
  }
502
750
 
503
751
  // src/runtimes/codex/codex-provider.ts
504
752
  function providerFilePath(dir) {
505
- return import_node_path3.join(dir, "agent", "provider.json");
753
+ return import_node_path4.join(dir, "agent", "provider.json");
506
754
  }
507
755
  function providerHomePath(dir) {
508
- return import_node_path3.join(dir, "agent", "codex-home");
756
+ return import_node_path4.join(dir, "agent", "codex-home");
509
757
  }
510
758
  function toStatus(stored) {
511
759
  if (!stored)
@@ -531,7 +779,7 @@ function validate(payload) {
531
779
  }
532
780
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
533
781
  const file = providerFilePath(dir);
534
- if (!import_node_fs2.existsSync(file))
782
+ if (!import_node_fs3.existsSync(file))
535
783
  return null;
536
784
  try {
537
785
  const raw = JSON.parse(await import_promises.readFile(file, "utf8"));
@@ -560,7 +808,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
560
808
  const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
561
809
  if (!apiKey)
562
810
  return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
563
- 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 });
564
812
  const stored = {
565
813
  name: payload.name?.trim() || undefined,
566
814
  baseUrl: payload.baseUrl.trim(),
@@ -583,7 +831,7 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
583
831
  async function provisionCustomProviderCodexHome(provider, codexHome) {
584
832
  try {
585
833
  await import_promises2.mkdir(codexHome, { recursive: true });
586
- 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");
587
835
  return true;
588
836
  } catch (error) {
589
837
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -592,6 +840,7 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
592
840
  }
593
841
  var codexAdapter = {
594
842
  id: "codex-acp",
843
+ probeQuota: async (options) => probeCodexQuota(options),
595
844
  probeAuth: () => {
596
845
  return probeCodexAuth();
597
846
  },
@@ -608,20 +857,86 @@ var codexAdapter = {
608
857
  }
609
858
  };
610
859
 
611
- // src/runtimes/claude/index.ts
612
- var import_node_fs3 = require("node:fs");
860
+ // src/runtimes/claude/quota.ts
861
+ var import_node_fs4 = require("node:fs");
613
862
  var import_node_os3 = require("node:os");
614
- 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");
615
930
  function resolveClaudeHome() {
616
931
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
617
932
  if (fromEnv)
618
933
  return fromEnv;
619
- return import_node_path5.join(import_node_os3.homedir(), ".claude");
934
+ return import_node_path7.join(import_node_os4.homedir(), ".claude");
620
935
  }
621
936
  function probeClaudeAuth() {
622
937
  const claudeHome = resolveClaudeHome();
623
- const hasCodexHome = import_node_fs3.existsSync(claudeHome);
624
- 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"));
625
940
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
626
941
  return {
627
942
  codexHome: claudeHome,
@@ -634,21 +949,22 @@ function probeClaudeAuth() {
634
949
  var claudeAdapter = {
635
950
  id: "claude",
636
951
  probeAuth: () => probeClaudeAuth(),
952
+ probeQuota: async (options) => probeClaudeQuota(options),
637
953
  orderAuthMethods: (methods) => methods,
638
954
  canSkipInteractiveAuth: () => false
639
955
  };
640
956
 
641
957
  // src/runtimes/gemini/index.ts
642
- var import_node_fs4 = require("node:fs");
643
- var import_node_os4 = require("node:os");
644
- 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");
645
961
  function resolveGeminiHome() {
646
- return import_node_path6.join(import_node_os4.homedir(), ".gemini");
962
+ return import_node_path8.join(import_node_os5.homedir(), ".gemini");
647
963
  }
648
964
  function probeGeminiAuth() {
649
965
  const geminiHome = resolveGeminiHome();
650
- const hasCodexHome = import_node_fs4.existsSync(geminiHome);
651
- 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());
652
968
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
653
969
  return {
654
970
  codexHome: geminiHome,
@@ -666,18 +982,18 @@ var geminiAdapter = {
666
982
  };
667
983
 
668
984
  // src/runtimes/copilot/index.ts
669
- var import_node_fs5 = require("node:fs");
670
- var import_node_os5 = require("node:os");
671
- 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");
672
988
  function resolveCopilotHome() {
673
989
  const fromEnv = process.env.COPILOT_HOME?.trim();
674
990
  if (fromEnv)
675
991
  return fromEnv;
676
- return import_node_path7.join(import_node_os5.homedir(), ".copilot");
992
+ return import_node_path9.join(import_node_os6.homedir(), ".copilot");
677
993
  }
678
994
  function hasCopilotLogin(home) {
679
995
  try {
680
- 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");
681
997
  const parsed = JSON.parse(raw);
682
998
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
683
999
  } catch {
@@ -686,7 +1002,7 @@ function hasCopilotLogin(home) {
686
1002
  }
687
1003
  function probeCopilotAuth() {
688
1004
  const copilotHome = resolveCopilotHome();
689
- const hasCodexHome = import_node_fs5.existsSync(copilotHome);
1005
+ const hasCodexHome = import_node_fs7.existsSync(copilotHome);
690
1006
  const hasAuthFile = hasCopilotLogin(copilotHome);
691
1007
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
692
1008
  return {
@@ -704,17 +1020,68 @@ var copilotAdapter = {
704
1020
  canSkipInteractiveAuth: () => false
705
1021
  };
706
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
+
707
1074
  // src/runtimes/opencode/index.ts
708
- var import_node_fs6 = require("node:fs");
709
- var import_node_os6 = require("node:os");
710
- 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");
711
1078
  function pickEnv(env, key) {
712
1079
  return env?.[key]?.trim() ?? "";
713
1080
  }
714
1081
  function resolveOpencodeAuthCandidates(overrides) {
715
1082
  const platform = overrides?.platform ?? process.platform;
716
1083
  const env = overrides?.env ?? process.env;
717
- const home = overrides?.home ?? import_node_os6.homedir();
1084
+ const home = overrides?.home ?? import_node_os7.homedir();
718
1085
  const seen = new Set;
719
1086
  const out = [];
720
1087
  const push = (p) => {
@@ -725,27 +1092,27 @@ function resolveOpencodeAuthCandidates(overrides) {
725
1092
  };
726
1093
  const xdg = pickEnv(env, "XDG_DATA_HOME");
727
1094
  if (xdg)
728
- push(import_node_path8.join(xdg, "opencode", "auth.json"));
1095
+ push(import_node_path10.join(xdg, "opencode", "auth.json"));
729
1096
  if (platform === "win32") {
730
- 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") : "");
731
1098
  if (localAppData)
732
- push(import_node_path8.join(localAppData, "opencode", "auth.json"));
1099
+ push(import_node_path10.join(localAppData, "opencode", "auth.json"));
733
1100
  const userProfile = pickEnv(env, "USERPROFILE") || home;
734
1101
  if (userProfile)
735
- push(import_node_path8.join(userProfile, ".local", "share", "opencode", "auth.json"));
1102
+ push(import_node_path10.join(userProfile, ".local", "share", "opencode", "auth.json"));
736
1103
  } else if (home) {
737
- push(import_node_path8.join(home, ".local", "share", "opencode", "auth.json"));
1104
+ push(import_node_path10.join(home, ".local", "share", "opencode", "auth.json"));
738
1105
  }
739
1106
  return out;
740
1107
  }
741
1108
  function resolveOpencodeAuthFile() {
742
- 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");
743
1110
  }
744
1111
  function isValidOpencodeAuthFile(authFile) {
745
1112
  try {
746
- if (!authFile || !import_node_fs6.existsSync(authFile))
1113
+ if (!authFile || !import_node_fs9.existsSync(authFile))
747
1114
  return false;
748
- const raw = import_node_fs6.readFileSync(authFile, "utf8").trim();
1115
+ const raw = import_node_fs9.readFileSync(authFile, "utf8").trim();
749
1116
  if (!raw)
750
1117
  return false;
751
1118
  const parsed = JSON.parse(raw);
@@ -763,7 +1130,7 @@ function probeOpencodeAuth(overrides) {
763
1130
  for (const candidate of candidates) {
764
1131
  let exists = false;
765
1132
  try {
766
- exists = import_node_fs6.existsSync(candidate);
1133
+ exists = import_node_fs9.existsSync(candidate);
767
1134
  } catch {
768
1135
  exists = false;
769
1136
  }
@@ -776,10 +1143,10 @@ function probeOpencodeAuth(overrides) {
776
1143
  validFile = candidate;
777
1144
  }
778
1145
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
779
- const authDir = import_node_path8.dirname(authFile);
1146
+ const authDir = import_node_path10.dirname(authFile);
780
1147
  let hasCodexHome = false;
781
1148
  try {
782
- hasCodexHome = import_node_fs6.existsSync(authDir);
1149
+ hasCodexHome = import_node_fs9.existsSync(authDir);
783
1150
  } catch {
784
1151
  hasCodexHome = false;
785
1152
  }
@@ -795,34 +1162,67 @@ function probeOpencodeAuth(overrides) {
795
1162
  var opencodeAdapter = {
796
1163
  id: "opencode",
797
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(),
798
1175
  orderAuthMethods: (methods) => methods,
799
1176
  canSkipInteractiveAuth: () => false,
800
1177
  tryDirectSessionFirst: true
801
1178
  };
802
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
+
803
1203
  // src/runtimes/cursor/index.ts
804
1204
  var import_node_child_process = require("node:child_process");
805
- var import_node_fs7 = require("node:fs");
806
- var import_node_os7 = require("node:os");
807
- 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");
808
1208
  function cursorLocalAppData(env) {
809
1209
  const local = env.LOCALAPPDATA?.trim();
810
1210
  if (local)
811
1211
  return local;
812
1212
  const profile = env.USERPROFILE?.trim();
813
- return profile ? import_node_path9.join(profile, "AppData", "Local") : "";
1213
+ return profile ? import_node_path11.join(profile, "AppData", "Local") : "";
814
1214
  }
815
1215
  function isOnPath(command, env, platform) {
816
1216
  const pathValue = env.PATH ?? env.Path ?? "";
817
1217
  if (!pathValue.trim())
818
1218
  return false;
819
- const sep = platform === "win32" ? ";" : import_node_path9.delimiter;
1219
+ const sep = platform === "win32" ? ";" : import_node_path11.delimiter;
820
1220
  for (const dir of pathValue.split(sep)) {
821
1221
  const trimmed = dir.trim().replace(/^"|"$/g, "");
822
1222
  if (!trimmed)
823
1223
  continue;
824
1224
  try {
825
- if (import_node_fs7.existsSync(import_node_path9.join(trimmed, command)))
1225
+ if (import_node_fs10.existsSync(import_node_path11.join(trimmed, command)))
826
1226
  return true;
827
1227
  } catch {}
828
1228
  }
@@ -831,24 +1231,24 @@ function isOnPath(command, env, platform) {
831
1231
  function resolveDirectCursorCommand(platform, env, home) {
832
1232
  if (platform === "win32") {
833
1233
  const localAppData = cursorLocalAppData(env);
834
- return localAppData ? import_node_path9.join(localAppData, "cursor-agent", "agent.cmd") : "";
1234
+ return localAppData ? import_node_path11.join(localAppData, "cursor-agent", "agent.cmd") : "";
835
1235
  }
836
- return home ? import_node_path9.join(home, ".local", "bin", "agent") : "";
1236
+ return home ? import_node_path11.join(home, ".local", "bin", "agent") : "";
837
1237
  }
838
1238
  function resolveCursorCommand(overrides) {
839
1239
  const args = ["acp"];
840
1240
  const platform = overrides?.platform ?? process.platform;
841
1241
  const env = overrides?.env ?? process.env;
842
- const home = overrides?.home ?? import_node_os7.homedir();
1242
+ const home = overrides?.home ?? import_node_os8.homedir();
843
1243
  if (platform === "win32") {
844
1244
  const directCmd = resolveDirectCursorCommand(platform, env, home);
845
- if (directCmd && import_node_fs7.existsSync(directCmd)) {
1245
+ if (directCmd && import_node_fs10.existsSync(directCmd)) {
846
1246
  return { command: directCmd, args };
847
1247
  }
848
1248
  return { command: "agent.cmd", args };
849
1249
  }
850
1250
  const directBin = resolveDirectCursorCommand(platform, env, home);
851
- if (directBin && import_node_fs7.existsSync(directBin)) {
1251
+ if (directBin && import_node_fs10.existsSync(directBin)) {
852
1252
  return { command: directBin, args };
853
1253
  }
854
1254
  return { command: "agent", args };
@@ -857,11 +1257,11 @@ function resolveCursorSpawnCommand(overrides) {
857
1257
  const args = ["acp"];
858
1258
  const platform = overrides?.platform ?? process.platform;
859
1259
  const env = overrides?.env ?? process.env;
860
- const home = overrides?.home ?? import_node_os7.homedir();
1260
+ const home = overrides?.home ?? import_node_os8.homedir();
861
1261
  const binary = platform === "win32" ? "agent.cmd" : "agent";
862
1262
  const direct = resolveDirectCursorCommand(platform, env, home);
863
1263
  try {
864
- if (direct && import_node_fs7.existsSync(direct))
1264
+ if (direct && import_node_fs10.existsSync(direct))
865
1265
  return { command: direct, args };
866
1266
  } catch {}
867
1267
  if (isOnPath(binary, env, platform))
@@ -883,12 +1283,12 @@ function cursorRoamingAppData(env, home) {
883
1283
  if (roaming)
884
1284
  return roaming;
885
1285
  const profile = pickEnv2(env, "USERPROFILE") || home;
886
- return profile ? import_node_path9.join(profile, "AppData", "Roaming") : "";
1286
+ return profile ? import_node_path11.join(profile, "AppData", "Roaming") : "";
887
1287
  }
888
1288
  function resolveCursorAuthCandidates(overrides) {
889
1289
  const platform = overrides?.platform ?? process.platform;
890
1290
  const env = overrides?.env ?? process.env;
891
- const home = overrides?.home ?? import_node_os7.homedir();
1291
+ const home = overrides?.home ?? import_node_os8.homedir();
892
1292
  const seen = new Set;
893
1293
  const out = [];
894
1294
  const push = (p) => {
@@ -899,16 +1299,16 @@ function resolveCursorAuthCandidates(overrides) {
899
1299
  };
900
1300
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
901
1301
  if (xdg)
902
- push(import_node_path9.join(xdg, "cursor", "auth.json"));
1302
+ push(import_node_path11.join(xdg, "cursor", "auth.json"));
903
1303
  if (platform === "win32") {
904
1304
  const profile = pickEnv2(env, "USERPROFILE") || home;
905
1305
  if (profile)
906
- push(import_node_path9.join(profile, ".config", "cursor", "auth.json"));
1306
+ push(import_node_path11.join(profile, ".config", "cursor", "auth.json"));
907
1307
  const roaming = cursorRoamingAppData(env, home);
908
1308
  if (roaming)
909
- push(import_node_path9.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
1309
+ push(import_node_path11.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
910
1310
  } else if (home) {
911
- push(import_node_path9.join(home, ".config", "cursor", "auth.json"));
1311
+ push(import_node_path11.join(home, ".config", "cursor", "auth.json"));
912
1312
  }
913
1313
  return out;
914
1314
  }
@@ -919,9 +1319,9 @@ function isValidCursorAuthFile(authFile) {
919
1319
  try {
920
1320
  if (!authFile || isStorageHintPath(authFile))
921
1321
  return false;
922
- if (!import_node_fs7.existsSync(authFile))
1322
+ if (!import_node_fs10.existsSync(authFile))
923
1323
  return false;
924
- const raw = import_node_fs7.readFileSync(authFile, "utf8").trim();
1324
+ const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
925
1325
  if (!raw)
926
1326
  return false;
927
1327
  const parsed = JSON.parse(raw);
@@ -939,9 +1339,9 @@ function isHintCursorStorageFile(authFile) {
939
1339
  try {
940
1340
  if (!authFile || !isStorageHintPath(authFile))
941
1341
  return false;
942
- if (!import_node_fs7.existsSync(authFile))
1342
+ if (!import_node_fs10.existsSync(authFile))
943
1343
  return false;
944
- const raw = import_node_fs7.readFileSync(authFile, "utf8").trim();
1344
+ const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
945
1345
  if (!raw)
946
1346
  return false;
947
1347
  const parsed = JSON.parse(raw);
@@ -957,7 +1357,7 @@ function isValidCursorCandidate(authFile) {
957
1357
  }
958
1358
  function probeCursorAuth(overrides) {
959
1359
  const env = overrides?.env ?? process.env;
960
- const home = overrides?.home ?? import_node_os7.homedir();
1360
+ const home = overrides?.home ?? import_node_os8.homedir();
961
1361
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
962
1362
  const candidates = resolveCursorAuthCandidates(overrides);
963
1363
  let firstExisting = null;
@@ -965,7 +1365,7 @@ function probeCursorAuth(overrides) {
965
1365
  for (const candidate of candidates) {
966
1366
  let exists = false;
967
1367
  try {
968
- exists = import_node_fs7.existsSync(candidate);
1368
+ exists = import_node_fs10.existsSync(candidate);
969
1369
  } catch {
970
1370
  exists = false;
971
1371
  }
@@ -977,12 +1377,12 @@ function probeCursorAuth(overrides) {
977
1377
  if (isValidCursorCandidate(candidate))
978
1378
  validFile = candidate;
979
1379
  }
980
- 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") : "";
981
1381
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
982
- const authDir = authFile ? import_node_path9.dirname(authFile) : "";
1382
+ const authDir = authFile ? import_node_path11.dirname(authFile) : "";
983
1383
  let hasCodexHome = false;
984
1384
  try {
985
- hasCodexHome = authDir ? import_node_fs7.existsSync(authDir) : false;
1385
+ hasCodexHome = authDir ? import_node_fs10.existsSync(authDir) : false;
986
1386
  } catch {
987
1387
  hasCodexHome = false;
988
1388
  }
@@ -997,6 +1397,7 @@ function probeCursorAuth(overrides) {
997
1397
  var cursorAdapter = {
998
1398
  id: "cursor-cli",
999
1399
  probeAuth: () => probeCursorAuth(),
1400
+ probeQuota: async () => probeCursorQuota(),
1000
1401
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
1001
1402
  orderAuthMethods: (methods) => methods,
1002
1403
  canSkipInteractiveAuth: () => false,
@@ -1115,6 +1516,55 @@ var deepseekAdapter = {
1115
1516
  canSkipInteractiveAuth: () => false
1116
1517
  };
1117
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
+
1118
1568
  // src/runtimes/agy/index.ts
1119
1569
  function probeAgyAuth() {
1120
1570
  return {
@@ -1128,6 +1578,7 @@ function probeAgyAuth() {
1128
1578
  var agyAdapter = {
1129
1579
  id: "agy",
1130
1580
  probeAuth: () => probeAgyAuth(),
1581
+ probeQuota: (options) => probeAgyQuota(options),
1131
1582
  orderAuthMethods: (methods) => methods,
1132
1583
  canSkipInteractiveAuth: () => false,
1133
1584
  tryDirectSessionFirst: true
@@ -1147,6 +1598,8 @@ function getAcpRuntimeAdapter(runtimeId) {
1147
1598
  return copilotAdapter;
1148
1599
  case opencodeAdapter.id:
1149
1600
  return opencodeAdapter;
1601
+ case opencodeV2Adapter.id:
1602
+ return opencodeV2Adapter;
1150
1603
  case cursorAdapter.id:
1151
1604
  case "cursor":
1152
1605
  return cursorAdapter;
@@ -1404,17 +1857,17 @@ var import_sdk2 = require("@agentclientprotocol/sdk");
1404
1857
 
1405
1858
  // src/client/acp-fs.ts
1406
1859
  var import_promises3 = require("node:fs/promises");
1407
- var import_node_path10 = require("node:path");
1860
+ var import_node_path13 = require("node:path");
1408
1861
  var import_promises4 = require("node:fs/promises");
1409
1862
  var MAX_READ_BYTES = 2 * 1024 * 1024;
1410
1863
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
1411
1864
  function isBinaryDocumentPath(filePath) {
1412
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path10.extname(filePath).toLowerCase());
1865
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path13.extname(filePath).toLowerCase());
1413
1866
  }
1414
1867
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
1415
- const root = import_node_path10.resolve(workspaceRoot);
1416
- const target = import_node_path10.resolve(filePath);
1417
- 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;
1418
1871
  if (target !== root && !target.startsWith(rootWithSep)) {
1419
1872
  throw new Error(`路径不在工作区内: ${filePath}`);
1420
1873
  }
@@ -1445,7 +1898,7 @@ async function acpReadTextFile(params) {
1445
1898
  }
1446
1899
  async function acpWriteTextFile(params) {
1447
1900
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
1448
- await import_promises4.mkdir(import_node_path10.dirname(abs), { recursive: true });
1901
+ await import_promises4.mkdir(import_node_path13.dirname(abs), { recursive: true });
1449
1902
  await import_promises3.writeFile(abs, params.content, "utf-8");
1450
1903
  return {};
1451
1904
  }
@@ -2123,8 +2576,8 @@ class AcpTerminalManager {
2123
2576
 
2124
2577
  // src/client/acp-proxy-service.ts
2125
2578
  var import_promises5 = require("node:fs/promises");
2126
- var import_node_fs8 = require("node:fs");
2127
- var import_node_path11 = require("node:path");
2579
+ var import_node_fs12 = require("node:fs");
2580
+ var import_node_path14 = require("node:path");
2128
2581
  var DEFAULT_ACP_PROXY_SETTINGS = {
2129
2582
  enabled: false,
2130
2583
  host: "127.0.0.1",
@@ -2133,7 +2586,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
2133
2586
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
2134
2587
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
2135
2588
  function proxyFilePath(dir) {
2136
- return import_node_path11.join(dir, "agent", "proxy.json");
2589
+ return import_node_path14.join(dir, "agent", "proxy.json");
2137
2590
  }
2138
2591
  function validate2(settings) {
2139
2592
  if (!settings.host.trim())
@@ -2145,7 +2598,7 @@ function validate2(settings) {
2145
2598
  }
2146
2599
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
2147
2600
  const file = proxyFilePath(dir);
2148
- if (!import_node_fs8.existsSync(file))
2601
+ if (!import_node_fs12.existsSync(file))
2149
2602
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
2150
2603
  try {
2151
2604
  const raw = JSON.parse(await import_promises5.readFile(file, "utf8"));
@@ -2167,7 +2620,7 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
2167
2620
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
2168
2621
  port: payload.port
2169
2622
  };
2170
- 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 });
2171
2624
  await import_promises5.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
2172
2625
  return ok(stored);
2173
2626
  }
@@ -2235,6 +2688,12 @@ class AcpSessionHandle {
2235
2688
  async prompt(promptText, options) {
2236
2689
  return this.client.promptSession(this.sessionId, promptText, options);
2237
2690
  }
2691
+ get quota() {
2692
+ return this.client.getCachedQuota(this.sessionId);
2693
+ }
2694
+ async getQuota() {
2695
+ return this.client.getQuota(this.sessionId);
2696
+ }
2238
2697
  get availableCommands() {
2239
2698
  return this.client.getAvailableCommands(this.sessionId);
2240
2699
  }
@@ -2246,6 +2705,7 @@ class AcpSessionHandle {
2246
2705
  class AcpClient {
2247
2706
  status = "disconnected";
2248
2707
  commandsCache = new AvailableCommandsCache;
2708
+ quotaCache = new QuotaCache;
2249
2709
  runtimeInfo;
2250
2710
  adapter;
2251
2711
  workspaceRoot;
@@ -2356,6 +2816,7 @@ class AcpClient {
2356
2816
  },
2357
2817
  onSessionUpdate: (params) => {
2358
2818
  this.commandsCache.observe(params);
2819
+ this.quotaCache.observe(params, this.runtimeInfo.id);
2359
2820
  this.callbacks.onSessionUpdate?.(params);
2360
2821
  }
2361
2822
  };
@@ -2386,6 +2847,23 @@ class AcpClient {
2386
2847
  return err({ code: "ACP_PROTOCOL_ERROR", message });
2387
2848
  }
2388
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
+ }
2389
2867
  getAvailableCommands(sessionId) {
2390
2868
  return this.commandsCache.get(sessionId);
2391
2869
  }