@yitom/acp-client 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -65,6 +65,7 @@ var CODEX_ACP_NPM_PACKAGE = "@agentclientprotocol/codex-acp";
65
65
  var CLAUDE_ACP_NPM_PACKAGE = "@agentclientprotocol/claude-agent-acp";
66
66
  var DEEPSEEK_DSH_NPM_PACKAGE = "@deepseek-ai/dsh";
67
67
  var AGY_ACP_NPM_PACKAGE = "@yitom/agy-acp-map";
68
+ var OPENCODE_CLI_NPM_PACKAGE = "@opencode/cli";
68
69
  var LEGACY_ZED_CODEX_ACP_NPM_PACKAGE = "@zed-industries/codex-acp";
69
70
  var DEFAULT_ACP_RUNTIME_ID = "codex-acp";
70
71
  function isWindowsPlatform() {
@@ -117,6 +118,15 @@ var BUILTIN_ACP_RUNTIMES = [
117
118
  args: ["acp"],
118
119
  requiredEnvKeys: []
119
120
  },
121
+ {
122
+ id: "opencode-v2",
123
+ name: "OpenCode v2",
124
+ description: "通过 npx 启动独立产品线 @opencode/cli v2(acp);与 1.x 共存,复用 v2 SQLite 登录态",
125
+ authHint: "v2 登录态在 SQLite(auth.json 仅兼容残留);未登录先用 v2 二进制跑 opencode auth login",
126
+ command: "npx",
127
+ args: ["-y", OPENCODE_CLI_NPM_PACKAGE, "acp"],
128
+ requiredEnvKeys: []
129
+ },
120
130
  {
121
131
  id: "cursor-cli",
122
132
  name: "Cursor",
@@ -149,7 +159,7 @@ function findBuiltinAcpRuntime(id) {
149
159
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
150
160
  }
151
161
  // src/version.ts
152
- var ACP_CLIENT_VERSION = "0.1.4";
162
+ var ACP_CLIENT_VERSION = "0.1.6";
153
163
  // src/session/available-commands.ts
154
164
  function normalizeCommand(raw) {
155
165
  if (!raw || typeof raw !== "object")
@@ -238,43 +248,171 @@ class AvailableCommandsCache {
238
248
  }
239
249
  }
240
250
 
251
+ // src/session/quota.ts
252
+ function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
253
+ if (!text || typeof text !== "string")
254
+ return null;
255
+ const lines = text.split(/\r?\n/);
256
+ let account;
257
+ const windows = [];
258
+ let credits;
259
+ let status = "ok";
260
+ let message;
261
+ if (/account (?:disabled|banned|suspended)|suspended|banned/i.test(text)) {
262
+ status = "banned";
263
+ message = "账号已封禁或暂停使用 (Account banned / suspended)";
264
+ } else if (/RESOURCE_EXHAUSTED|quota reached|rate limit exceeded|429/i.test(text)) {
265
+ status = "exhausted";
266
+ message = "额度已用尽 (Quota / Rate limit reached)";
267
+ } else if (/unauthorized|authentication failed|invalid api key/i.test(text)) {
268
+ status = "unauthorized";
269
+ message = "认证失效 (Unauthorized / Invalid credentials)";
270
+ }
271
+ for (const rawLine of lines) {
272
+ const line = rawLine.replace(/\*\*/g, "").trim();
273
+ if (!line)
274
+ continue;
275
+ const accMatch = line.match(/^Account\s*[::]\s*([^()]+?)(?:\s*\(([^)]+)\))?$/i);
276
+ if (accMatch) {
277
+ account = {
278
+ plan: accMatch[1].trim(),
279
+ email: accMatch[2]?.trim()
280
+ };
281
+ continue;
282
+ }
283
+ const credMatch = line.match(/(?:\b|^)(?:[\w\s-]*?credits?)\s*[::]\s*(unlimited|[\d.]+)/i);
284
+ if (credMatch) {
285
+ const val = credMatch[1].trim();
286
+ credits = val.toLowerCase() === "unlimited" ? { unlimited: true, balance: "unlimited" } : { balance: Number(val) || val, unlimited: false };
287
+ continue;
288
+ }
289
+ 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);
290
+ if (winMatch) {
291
+ const label = winMatch[1].trim();
292
+ const pct = parseFloat(winMatch[2]);
293
+ const resetsAt = (winMatch[3] || winMatch[4] || "").trim() || undefined;
294
+ let windowDurationMins;
295
+ const lower = label.toLowerCase();
296
+ if (/5h|5-hour/i.test(lower))
297
+ windowDurationMins = 300;
298
+ else if (/week/i.test(lower))
299
+ windowDurationMins = 10080;
300
+ else if (/month/i.test(lower))
301
+ windowDurationMins = 43200;
302
+ else if (/day|24h/i.test(lower))
303
+ windowDurationMins = 1440;
304
+ else if (/(\d+)\s*h/i.test(lower)) {
305
+ const m = lower.match(/(\d+)\s*h/);
306
+ if (m)
307
+ windowDurationMins = parseInt(m[1], 10) * 60;
308
+ }
309
+ windows.push({
310
+ label,
311
+ percentLeft: pct,
312
+ usedPercent: Math.max(0, 100 - pct),
313
+ resetsAt,
314
+ windowDurationMins
315
+ });
316
+ continue;
317
+ }
318
+ const fastMatch = line.match(/(?:fast requests?|requests?)\s*[::]\s*(\d+)\s*\/\s*(\d+)/i);
319
+ if (fastMatch) {
320
+ const used = parseInt(fastMatch[1], 10);
321
+ const total = parseInt(fastMatch[2], 10);
322
+ const left = Math.max(0, total - used);
323
+ const pct = total > 0 ? Math.round(left / total * 100) : 0;
324
+ windows.push({
325
+ label: "Fast requests",
326
+ percentLeft: pct,
327
+ usedPercent: total > 0 ? Math.round(used / total * 100) : 0,
328
+ used,
329
+ total
330
+ });
331
+ continue;
332
+ }
333
+ }
334
+ if (!windows.length && !credits && !account && status === "ok") {
335
+ return null;
336
+ }
337
+ const primary = windows.find((w) => /5h|5-hour|hour|primary|fast/i.test(w.label)) || windows[0];
338
+ const secondary = windows.find((w) => w !== primary && /week|month|secondary/i.test(w.label)) || windows.find((w) => w !== primary);
339
+ const extraWindows = windows.filter((w) => w !== primary && w !== secondary);
340
+ if (primary && primary.percentLeft <= 10 && status === "ok") {
341
+ status = "warning";
342
+ }
343
+ return {
344
+ runtimeId,
345
+ account,
346
+ primaryWindow: primary,
347
+ secondaryWindow: secondary,
348
+ extraWindows: extraWindows.length ? extraWindows : undefined,
349
+ credits,
350
+ status,
351
+ message,
352
+ rawText: text,
353
+ updatedAt: Date.now()
354
+ };
355
+ }
356
+
357
+ class QuotaCache {
358
+ bySession = new Map;
359
+ byRuntime = new Map;
360
+ observe(params, defaultRuntimeId = "unknown") {
361
+ if (!params || typeof params !== "object")
362
+ return null;
363
+ const p = params;
364
+ const sessionId = typeof p.sessionId === "string" ? p.sessionId : undefined;
365
+ let textToParse = "";
366
+ if (p.update?.content && p.update.content.type === "text" && typeof p.update.content.text === "string") {
367
+ textToParse = p.update.content.text;
368
+ } else if (p.update?.message?.content && Array.isArray(p.update.message.content)) {
369
+ textToParse = p.update.message.content.filter((c) => c && c.type === "text" && typeof c.text === "string").map((c) => c.text).join(`
370
+ `);
371
+ }
372
+ if (!textToParse)
373
+ return null;
374
+ if (!/(?:limit|credits?|Account:|5h|resets|banned|suspended|quota)/i.test(textToParse)) {
375
+ return null;
376
+ }
377
+ const quota = parseRateLimitsFromStatusText(textToParse, defaultRuntimeId);
378
+ if (quota) {
379
+ if (sessionId)
380
+ this.bySession.set(sessionId, quota);
381
+ this.byRuntime.set(defaultRuntimeId, quota);
382
+ return quota;
383
+ }
384
+ return null;
385
+ }
386
+ set(quota, sessionId) {
387
+ if (sessionId)
388
+ this.bySession.set(sessionId, quota);
389
+ this.byRuntime.set(quota.runtimeId, quota);
390
+ }
391
+ get(sessionId, runtimeId) {
392
+ if (sessionId && this.bySession.has(sessionId)) {
393
+ return this.bySession.get(sessionId);
394
+ }
395
+ if (runtimeId && this.byRuntime.has(runtimeId)) {
396
+ return this.byRuntime.get(runtimeId);
397
+ }
398
+ return;
399
+ }
400
+ clear() {
401
+ this.bySession.clear();
402
+ this.byRuntime.clear();
403
+ }
404
+ }
405
+
241
406
  // src/client/acp-client.ts
242
407
  import {
243
408
  methods as methods2
244
409
  } from "@agentclientprotocol/sdk";
245
410
 
246
- // src/runtimes/codex/index.ts
247
- import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
248
- import { join as join4 } from "node:path";
249
-
250
- // src/runtimes/codex/codex-provider-home.ts
251
- var INKDOWN_PROVIDER_ID = "inkdown-custom";
252
- var INKDOWN_PROVIDER_API_KEY_ENV = "INKDOWN_PROVIDER_API_KEY";
253
- function tomlEscape(value) {
254
- return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
255
- }
256
- function buildCustomProviderConfigToml(config) {
257
- const name = config.name?.trim() || "自定义 API";
258
- const wireApi = config.wireApi === "responses" ? "responses" : "chat";
259
- return [
260
- `model_provider = "${INKDOWN_PROVIDER_ID}"`,
261
- `model = "${tomlEscape(config.model.trim())}"`,
262
- "",
263
- `[model_providers.${INKDOWN_PROVIDER_ID}]`,
264
- `name = "${tomlEscape(name)}"`,
265
- `base_url = "${tomlEscape(config.baseUrl.trim())}"`,
266
- `env_key = "${INKDOWN_PROVIDER_API_KEY_ENV}"`,
267
- `wire_api = "${wireApi}"`,
268
- ""
269
- ].join(`
270
- `);
271
- }
272
- function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
273
- return {
274
- CODEX_HOME: codexHome,
275
- [INKDOWN_PROVIDER_API_KEY_ENV]: apiKey
276
- };
277
- }
411
+ // src/runtimes/codex/quota.ts
412
+ import { existsSync as existsSync2, readFileSync } from "node:fs";
413
+ import { join as join2 } from "node:path";
414
+ import { spawn } from "node:child_process";
415
+ import readline from "node:readline";
278
416
 
279
417
  // src/runtimes/codex/codex-auth-preflight.ts
280
418
  import { existsSync } from "node:fs";
@@ -312,14 +450,252 @@ function probeCodexAuth() {
312
450
  };
313
451
  }
314
452
 
453
+ // src/runtimes/codex/quota.ts
454
+ function decodeJwtPayload(token) {
455
+ try {
456
+ const parts = token.split(".");
457
+ if (parts.length < 2)
458
+ return null;
459
+ const json = Buffer.from(parts[1], "base64").toString("utf8");
460
+ return JSON.parse(json);
461
+ } catch {
462
+ return null;
463
+ }
464
+ }
465
+ var cachedDynamicResult = null;
466
+ async function queryCodexAppServer(timeoutMs = 4000) {
467
+ if (cachedDynamicResult && Date.now() - cachedDynamicResult.time < 15000) {
468
+ return cachedDynamicResult.res;
469
+ }
470
+ return new Promise((resolve) => {
471
+ let timer = null;
472
+ let proc = null;
473
+ let finished = false;
474
+ const cleanup = (res) => {
475
+ if (finished)
476
+ return;
477
+ finished = true;
478
+ if (timer)
479
+ clearTimeout(timer);
480
+ if (proc) {
481
+ try {
482
+ proc.kill();
483
+ } catch {}
484
+ }
485
+ if (res) {
486
+ cachedDynamicResult = { res, time: Date.now() };
487
+ }
488
+ resolve(res);
489
+ };
490
+ timer = setTimeout(() => cleanup(null), timeoutMs);
491
+ try {
492
+ proc = spawn("codex", ["app-server"], {
493
+ stdio: ["pipe", "pipe", "pipe"],
494
+ shell: process.platform === "win32",
495
+ windowsHide: true
496
+ });
497
+ if (!proc.stdin || !proc.stdout) {
498
+ return cleanup(null);
499
+ }
500
+ const rl = readline.createInterface({ input: proc.stdout });
501
+ let reqSeq = 1;
502
+ const pending = new Map;
503
+ const result = {};
504
+ rl.on("line", (line) => {
505
+ try {
506
+ const data = JSON.parse(line.trim());
507
+ if (data && typeof data.id === "number" && pending.has(data.id)) {
508
+ const cb = pending.get(data.id);
509
+ pending.delete(data.id);
510
+ cb(data.result);
511
+ }
512
+ } catch {}
513
+ });
514
+ proc.on("error", () => cleanup(null));
515
+ proc.on("exit", () => cleanup(Object.keys(result).length > 0 ? result : null));
516
+ const send = (method, params) => {
517
+ const id = reqSeq++;
518
+ const msg = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + `
519
+ `;
520
+ proc.stdin.write(msg);
521
+ return new Promise((res) => {
522
+ pending.set(id, res);
523
+ });
524
+ };
525
+ (async () => {
526
+ try {
527
+ await send("initialize", {
528
+ clientInfo: { name: "acp-client", version: "0.1.6" }
529
+ });
530
+ const acc = await send("account/read", { refreshToken: false });
531
+ if (acc?.account) {
532
+ result.account = acc.account;
533
+ }
534
+ const limits = await send("account/rateLimits/read");
535
+ if (limits?.rateLimits) {
536
+ result.rateLimits = limits.rateLimits;
537
+ }
538
+ cleanup(result);
539
+ } catch {
540
+ cleanup(null);
541
+ }
542
+ })();
543
+ } catch {
544
+ cleanup(null);
545
+ }
546
+ });
547
+ }
548
+ function formatEpochTime(epochSeconds) {
549
+ if (!epochSeconds)
550
+ return;
551
+ try {
552
+ const d = new Date(epochSeconds * 1000);
553
+ const hours = String(d.getHours()).padStart(2, "0");
554
+ const mins = String(d.getMinutes()).padStart(2, "0");
555
+ return `${hours}:${mins}`;
556
+ } catch {
557
+ return;
558
+ }
559
+ }
560
+ async function probeCodexQuota(options) {
561
+ const codexHome = resolveCodexHome();
562
+ const authPath = join2(codexHome, "auth.json");
563
+ let accountEmail;
564
+ let accountPlan = "Codex Free / Local";
565
+ let isLoggedIn = false;
566
+ if (existsSync2(authPath)) {
567
+ try {
568
+ const authData = JSON.parse(readFileSync(authPath, "utf8"));
569
+ if (authData.OPENAI_API_KEY) {
570
+ isLoggedIn = true;
571
+ accountPlan = "OpenAI API Key";
572
+ }
573
+ if (authData.tokens?.id_token) {
574
+ isLoggedIn = true;
575
+ const payload = decodeJwtPayload(authData.tokens.id_token);
576
+ if (payload) {
577
+ if (typeof payload.email === "string")
578
+ accountEmail = payload.email;
579
+ const authObj = payload["https://api.openai.com/auth"];
580
+ if (authObj && typeof authObj.chatgpt_plan_type === "string") {
581
+ accountPlan = `ChatGPT ${authObj.chatgpt_plan_type}`;
582
+ }
583
+ }
584
+ } else if (authData.tokens?.access_token) {
585
+ isLoggedIn = true;
586
+ }
587
+ } catch {}
588
+ }
589
+ if (process.env.CODEX_API_KEY || process.env.OPENAI_API_KEY) {
590
+ isLoggedIn = true;
591
+ accountPlan = "API Key (Env)";
592
+ }
593
+ const dynamic = await queryCodexAppServer(4000);
594
+ if (dynamic) {
595
+ isLoggedIn = true;
596
+ if (dynamic.account?.email)
597
+ accountEmail = dynamic.account.email;
598
+ if (dynamic.account?.planType)
599
+ accountPlan = `ChatGPT ${dynamic.account.planType}`;
600
+ }
601
+ if (!isLoggedIn) {
602
+ return {
603
+ runtimeId: "codex-acp",
604
+ provider: "OpenAI / Codex",
605
+ status: "unauthorized",
606
+ message: "未登录 Codex (Not logged in)",
607
+ updatedAt: Date.now()
608
+ };
609
+ }
610
+ let primaryWindow;
611
+ let secondaryWindow;
612
+ let credits;
613
+ if (dynamic?.rateLimits) {
614
+ const rl = dynamic.rateLimits;
615
+ if (rl.primary) {
616
+ const used = rl.primary.usedPercent ?? 0;
617
+ primaryWindow = {
618
+ label: "5h limit",
619
+ percentLeft: Math.max(0, Math.min(100, Math.round(100 - used))),
620
+ usedPercent: used,
621
+ windowDurationMins: rl.primary.windowDurationMins || 300,
622
+ resetsAt: formatEpochTime(rl.primary.resetsAt) || (rl.primary.resetsAt ? String(rl.primary.resetsAt) : undefined)
623
+ };
624
+ }
625
+ if (rl.secondary) {
626
+ const used = rl.secondary.usedPercent ?? 0;
627
+ secondaryWindow = {
628
+ label: "Weekly limit",
629
+ percentLeft: Math.max(0, Math.min(100, Math.round(100 - used))),
630
+ usedPercent: used,
631
+ windowDurationMins: rl.secondary.windowDurationMins || 10080,
632
+ resetsAt: formatEpochTime(rl.secondary.resetsAt) || (rl.secondary.resetsAt ? String(rl.secondary.resetsAt) : undefined)
633
+ };
634
+ }
635
+ if (rl.credits) {
636
+ credits = {
637
+ balance: rl.credits.balance,
638
+ unlimited: rl.credits.unlimited
639
+ };
640
+ }
641
+ }
642
+ return {
643
+ runtimeId: "codex-acp",
644
+ provider: "OpenAI / Codex",
645
+ account: {
646
+ email: accountEmail,
647
+ plan: accountPlan,
648
+ type: dynamic?.account?.type || "chatgpt"
649
+ },
650
+ primaryWindow,
651
+ secondaryWindow,
652
+ credits,
653
+ status: "ok",
654
+ updatedAt: Date.now()
655
+ };
656
+ }
657
+
658
+ // src/runtimes/codex/index.ts
659
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
660
+ import { join as join5 } from "node:path";
661
+
662
+ // src/runtimes/codex/codex-provider-home.ts
663
+ var INKDOWN_PROVIDER_ID = "inkdown-custom";
664
+ var INKDOWN_PROVIDER_API_KEY_ENV = "INKDOWN_PROVIDER_API_KEY";
665
+ function tomlEscape(value) {
666
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
667
+ }
668
+ function buildCustomProviderConfigToml(config) {
669
+ const name = config.name?.trim() || "自定义 API";
670
+ const wireApi = config.wireApi === "responses" ? "responses" : "chat";
671
+ return [
672
+ `model_provider = "${INKDOWN_PROVIDER_ID}"`,
673
+ `model = "${tomlEscape(config.model.trim())}"`,
674
+ "",
675
+ `[model_providers.${INKDOWN_PROVIDER_ID}]`,
676
+ `name = "${tomlEscape(name)}"`,
677
+ `base_url = "${tomlEscape(config.baseUrl.trim())}"`,
678
+ `env_key = "${INKDOWN_PROVIDER_API_KEY_ENV}"`,
679
+ `wire_api = "${wireApi}"`,
680
+ ""
681
+ ].join(`
682
+ `);
683
+ }
684
+ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
685
+ return {
686
+ CODEX_HOME: codexHome,
687
+ [INKDOWN_PROVIDER_API_KEY_ENV]: apiKey
688
+ };
689
+ }
690
+
315
691
  // src/runtimes/codex/codex-provider.ts
316
692
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
317
- import { existsSync as existsSync2 } from "node:fs";
318
- import { join as join3 } from "node:path";
693
+ import { existsSync as existsSync3 } from "node:fs";
694
+ import { join as join4 } from "node:path";
319
695
 
320
696
  // src/client/acp-paths.ts
321
697
  import { homedir as homedir2 } from "node:os";
322
- import { join as join2 } from "node:path";
698
+ import { join as join3 } from "node:path";
323
699
  function getDefaultAgentDataDir() {
324
700
  if (process.env.INKDOWN_DATA_DIR) {
325
701
  return process.env.INKDOWN_DATA_DIR;
@@ -328,20 +704,20 @@ function getDefaultAgentDataDir() {
328
704
  return process.env.ACP_DATA_DIR;
329
705
  }
330
706
  if (process.platform === "win32") {
331
- return process.env.LOCALAPPDATA || process.env.APPDATA || join2(homedir2(), "AppData", "Local", "inkdown");
707
+ return process.env.LOCALAPPDATA || process.env.APPDATA || join3(homedir2(), "AppData", "Local", "inkdown");
332
708
  }
333
709
  if (process.platform === "darwin") {
334
- return join2(homedir2(), "Library", "Application Support", "inkdown");
710
+ return join3(homedir2(), "Library", "Application Support", "inkdown");
335
711
  }
336
- return process.env.XDG_DATA_HOME || join2(homedir2(), ".local", "share", "inkdown");
712
+ return process.env.XDG_DATA_HOME || join3(homedir2(), ".local", "share", "inkdown");
337
713
  }
338
714
 
339
715
  // src/runtimes/codex/codex-provider.ts
340
716
  function providerFilePath(dir) {
341
- return join3(dir, "agent", "provider.json");
717
+ return join4(dir, "agent", "provider.json");
342
718
  }
343
719
  function providerHomePath(dir) {
344
- return join3(dir, "agent", "codex-home");
720
+ return join4(dir, "agent", "codex-home");
345
721
  }
346
722
  function toStatus(stored) {
347
723
  if (!stored)
@@ -367,7 +743,7 @@ function validate(payload) {
367
743
  }
368
744
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
369
745
  const file = providerFilePath(dir);
370
- if (!existsSync2(file))
746
+ if (!existsSync3(file))
371
747
  return null;
372
748
  try {
373
749
  const raw = JSON.parse(await readFile(file, "utf8"));
@@ -396,7 +772,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
396
772
  const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
397
773
  if (!apiKey)
398
774
  return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
399
- await mkdir(join3(dir, "agent"), { recursive: true });
775
+ await mkdir(join4(dir, "agent"), { recursive: true });
400
776
  const stored = {
401
777
  name: payload.name?.trim() || undefined,
402
778
  baseUrl: payload.baseUrl.trim(),
@@ -419,7 +795,7 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
419
795
  async function provisionCustomProviderCodexHome(provider, codexHome) {
420
796
  try {
421
797
  await mkdir2(codexHome, { recursive: true });
422
- await writeFile2(join4(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
798
+ await writeFile2(join5(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
423
799
  return true;
424
800
  } catch (error) {
425
801
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -428,6 +804,7 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
428
804
  }
429
805
  var codexAdapter = {
430
806
  id: "codex-acp",
807
+ probeQuota: async (options) => probeCodexQuota(options),
431
808
  probeAuth: () => {
432
809
  return probeCodexAuth();
433
810
  },
@@ -444,20 +821,122 @@ var codexAdapter = {
444
821
  }
445
822
  };
446
823
 
447
- // src/runtimes/claude/index.ts
448
- import { existsSync as existsSync3 } from "node:fs";
824
+ // src/runtimes/claude/quota.ts
825
+ import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
449
826
  import { homedir as homedir3 } from "node:os";
450
- import { join as join5 } from "node:path";
827
+ import { join as join6 } from "node:path";
828
+ import { execFile } from "node:child_process";
829
+ var cachedClaudeAuth = null;
830
+ async function queryClaudeAuthStatus(timeoutMs = 1200) {
831
+ if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
832
+ return cachedClaudeAuth.res;
833
+ }
834
+ return new Promise((resolve) => {
835
+ try {
836
+ execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
837
+ if (!stdout)
838
+ return resolve(null);
839
+ try {
840
+ const data = JSON.parse(stdout.trim());
841
+ cachedClaudeAuth = { res: data, time: Date.now() };
842
+ resolve(data);
843
+ } catch {
844
+ resolve(null);
845
+ }
846
+ });
847
+ } catch {
848
+ resolve(null);
849
+ }
850
+ });
851
+ }
852
+ async function probeClaudeQuota(options) {
853
+ const claudeHome = resolveClaudeHome();
854
+ const claudeJsonPath = join6(homedir3(), ".claude.json");
855
+ const credsPath = join6(claudeHome, ".credentials.json");
856
+ let isLoggedIn = false;
857
+ let isBanned = false;
858
+ let accountEmail;
859
+ let plan = "Claude Free / Default";
860
+ if (existsSync4(claudeJsonPath)) {
861
+ try {
862
+ const data = JSON.parse(readFileSync2(claudeJsonPath, "utf8"));
863
+ if (data.oauthAccount) {
864
+ isLoggedIn = true;
865
+ accountEmail = data.oauthAccount.emailAddress;
866
+ plan = data.oauthAccount.subscriptionTier || "Claude Pro";
867
+ }
868
+ if (data.isBanned || data.accountSuspended || data.status === "banned") {
869
+ isBanned = true;
870
+ }
871
+ } catch {}
872
+ }
873
+ if (existsSync4(credsPath)) {
874
+ try {
875
+ const creds = JSON.parse(readFileSync2(credsPath, "utf8"));
876
+ if (creds.accessToken || creds.sessionKey)
877
+ isLoggedIn = true;
878
+ } catch {}
879
+ }
880
+ if (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN) {
881
+ isLoggedIn = true;
882
+ plan = "API Key (Env)";
883
+ }
884
+ const dynamic = await queryClaudeAuthStatus(1200);
885
+ if (dynamic) {
886
+ if (dynamic.loggedIn)
887
+ isLoggedIn = true;
888
+ if (dynamic.email)
889
+ accountEmail = dynamic.email;
890
+ if (dynamic.subscriptionType)
891
+ plan = dynamic.subscriptionType;
892
+ else if (dynamic.plan)
893
+ plan = dynamic.plan;
894
+ }
895
+ if (isBanned) {
896
+ return {
897
+ runtimeId: "claude",
898
+ provider: "Anthropic / Claude Code",
899
+ status: "banned",
900
+ message: "账号已被封禁或暂停使用 (Account suspended / banned)",
901
+ updatedAt: Date.now()
902
+ };
903
+ }
904
+ if (!isLoggedIn) {
905
+ return {
906
+ runtimeId: "claude",
907
+ provider: "Anthropic / Claude Code",
908
+ status: "unauthorized",
909
+ message: "未登录 Claude Code 或凭据无效 (Unauthorized)",
910
+ updatedAt: Date.now()
911
+ };
912
+ }
913
+ return {
914
+ runtimeId: "claude",
915
+ provider: "Anthropic / Claude Code",
916
+ account: {
917
+ email: accountEmail,
918
+ plan,
919
+ type: dynamic?.authMethod || "oauth"
920
+ },
921
+ status: "ok",
922
+ updatedAt: Date.now()
923
+ };
924
+ }
925
+
926
+ // src/runtimes/claude/index.ts
927
+ import { existsSync as existsSync5 } from "node:fs";
928
+ import { homedir as homedir4 } from "node:os";
929
+ import { join as join7 } from "node:path";
451
930
  function resolveClaudeHome() {
452
931
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
453
932
  if (fromEnv)
454
933
  return fromEnv;
455
- return join5(homedir3(), ".claude");
934
+ return join7(homedir4(), ".claude");
456
935
  }
457
936
  function probeClaudeAuth() {
458
937
  const claudeHome = resolveClaudeHome();
459
- const hasCodexHome = existsSync3(claudeHome);
460
- const hasAuthFile = existsSync3(join5(homedir3(), ".claude.json")) || existsSync3(join5(claudeHome, ".credentials.json"));
938
+ const hasCodexHome = existsSync5(claudeHome);
939
+ const hasAuthFile = existsSync5(join7(homedir4(), ".claude.json")) || existsSync5(join7(claudeHome, ".credentials.json"));
461
940
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
462
941
  return {
463
942
  codexHome: claudeHome,
@@ -470,21 +949,22 @@ function probeClaudeAuth() {
470
949
  var claudeAdapter = {
471
950
  id: "claude",
472
951
  probeAuth: () => probeClaudeAuth(),
952
+ probeQuota: async (options) => probeClaudeQuota(options),
473
953
  orderAuthMethods: (methods) => methods,
474
954
  canSkipInteractiveAuth: () => false
475
955
  };
476
956
 
477
957
  // src/runtimes/gemini/index.ts
478
- import { existsSync as existsSync4 } from "node:fs";
479
- import { homedir as homedir4 } from "node:os";
480
- import { join as join6 } from "node:path";
958
+ import { existsSync as existsSync6 } from "node:fs";
959
+ import { homedir as homedir5 } from "node:os";
960
+ import { join as join8 } from "node:path";
481
961
  function resolveGeminiHome() {
482
- return join6(homedir4(), ".gemini");
962
+ return join8(homedir5(), ".gemini");
483
963
  }
484
964
  function probeGeminiAuth() {
485
965
  const geminiHome = resolveGeminiHome();
486
- const hasCodexHome = existsSync4(geminiHome);
487
- const hasAuthFile = existsSync4(join6(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
966
+ const hasCodexHome = existsSync6(geminiHome);
967
+ const hasAuthFile = existsSync6(join8(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
488
968
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
489
969
  return {
490
970
  codexHome: geminiHome,
@@ -502,18 +982,18 @@ var geminiAdapter = {
502
982
  };
503
983
 
504
984
  // src/runtimes/copilot/index.ts
505
- import { existsSync as existsSync5, readFileSync } from "node:fs";
506
- import { homedir as homedir5 } from "node:os";
507
- import { join as join7 } from "node:path";
985
+ import { existsSync as existsSync7, readFileSync as readFileSync3 } from "node:fs";
986
+ import { homedir as homedir6 } from "node:os";
987
+ import { join as join9 } from "node:path";
508
988
  function resolveCopilotHome() {
509
989
  const fromEnv = process.env.COPILOT_HOME?.trim();
510
990
  if (fromEnv)
511
991
  return fromEnv;
512
- return join7(homedir5(), ".copilot");
992
+ return join9(homedir6(), ".copilot");
513
993
  }
514
994
  function hasCopilotLogin(home) {
515
995
  try {
516
- const raw = readFileSync(join7(home, "config.json"), "utf8");
996
+ const raw = readFileSync3(join9(home, "config.json"), "utf8");
517
997
  const parsed = JSON.parse(raw);
518
998
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
519
999
  } catch {
@@ -522,7 +1002,7 @@ function hasCopilotLogin(home) {
522
1002
  }
523
1003
  function probeCopilotAuth() {
524
1004
  const copilotHome = resolveCopilotHome();
525
- const hasCodexHome = existsSync5(copilotHome);
1005
+ const hasCodexHome = existsSync7(copilotHome);
526
1006
  const hasAuthFile = hasCopilotLogin(copilotHome);
527
1007
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
528
1008
  return {
@@ -540,17 +1020,129 @@ var copilotAdapter = {
540
1020
  canSkipInteractiveAuth: () => false
541
1021
  };
542
1022
 
1023
+ // src/runtimes/opencode/quota.ts
1024
+ import { existsSync as existsSync8, readFileSync as readFileSync4 } from "node:fs";
1025
+ import { execFile as execFile2 } from "node:child_process";
1026
+ function resolveOpencodeAuthPath() {
1027
+ const candidates = resolveOpencodeAuthCandidates();
1028
+ for (const c of candidates) {
1029
+ if (existsSync8(c))
1030
+ return c;
1031
+ }
1032
+ return candidates[0] ?? null;
1033
+ }
1034
+ var cachedStats = null;
1035
+ async function queryOpencodeStats(timeoutMs = 1200) {
1036
+ if (cachedStats && Date.now() - cachedStats.time < 30000) {
1037
+ return cachedStats.res;
1038
+ }
1039
+ return new Promise((resolve) => {
1040
+ try {
1041
+ execFile2("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1042
+ if (!stdout)
1043
+ return resolve(null);
1044
+ try {
1045
+ const data = JSON.parse(stdout.trim());
1046
+ cachedStats = { res: data, time: Date.now() };
1047
+ resolve(data);
1048
+ } catch {
1049
+ resolve(null);
1050
+ }
1051
+ });
1052
+ } catch {
1053
+ resolve(null);
1054
+ }
1055
+ });
1056
+ }
1057
+ async function queryOpencodeAuthList(timeoutMs = 1200) {
1058
+ return new Promise((resolve) => {
1059
+ try {
1060
+ execFile2("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1061
+ if (!stdout)
1062
+ return resolve([]);
1063
+ const lines = stdout.split(`
1064
+ `).map((l) => l.trim()).filter((l) => l.includes("stored"));
1065
+ resolve(lines);
1066
+ });
1067
+ } catch {
1068
+ resolve([]);
1069
+ }
1070
+ });
1071
+ }
1072
+ async function probeOpencodeQuota(runtimeId = "opencode") {
1073
+ const authPath = resolveOpencodeAuthPath();
1074
+ let isLoggedIn = false;
1075
+ let accountEmail;
1076
+ let plan = "OpenCode Community";
1077
+ if (authPath && existsSync8(authPath)) {
1078
+ try {
1079
+ const data = JSON.parse(readFileSync4(authPath, "utf8"));
1080
+ if (data && typeof data === "object") {
1081
+ const keys = Object.keys(data);
1082
+ if (keys.length > 0) {
1083
+ isLoggedIn = true;
1084
+ if (data.email)
1085
+ accountEmail = String(data.email);
1086
+ if (data.plan)
1087
+ plan = String(data.plan);
1088
+ }
1089
+ }
1090
+ } catch {}
1091
+ }
1092
+ const [stats, authList] = await Promise.all([
1093
+ queryOpencodeStats(1200),
1094
+ queryOpencodeAuthList(1200)
1095
+ ]);
1096
+ if (authList.length > 0) {
1097
+ isLoggedIn = true;
1098
+ const providers = authList.map((l) => l.split(/\s{2,}/)[0]).filter(Boolean);
1099
+ if (providers.length > 0) {
1100
+ plan = `OpenCode (${providers.join(", ")})`;
1101
+ }
1102
+ }
1103
+ if (process.env.OPENCODE_API_KEY || process.env.OPENAI_API_KEY) {
1104
+ isLoggedIn = true;
1105
+ }
1106
+ if (!isLoggedIn) {
1107
+ return {
1108
+ runtimeId,
1109
+ provider: "OpenCode",
1110
+ status: "unauthorized",
1111
+ message: "未登录 OpenCode 或未配置 Provider (No stored credentials)",
1112
+ updatedAt: Date.now()
1113
+ };
1114
+ }
1115
+ let credits;
1116
+ if (stats && typeof stats.cost === "number") {
1117
+ credits = {
1118
+ balance: stats.cost > 0 ? `$${stats.cost.toFixed(2)} spent` : "0.00"
1119
+ };
1120
+ }
1121
+ return {
1122
+ runtimeId,
1123
+ provider: "OpenCode",
1124
+ account: {
1125
+ email: accountEmail,
1126
+ plan,
1127
+ type: "provider_oauth"
1128
+ },
1129
+ credits,
1130
+ status: "ok",
1131
+ updatedAt: Date.now()
1132
+ };
1133
+ }
1134
+
543
1135
  // src/runtimes/opencode/index.ts
544
- import { existsSync as existsSync6, readFileSync as readFileSync2 } from "node:fs";
545
- import { homedir as homedir6 } from "node:os";
546
- import { dirname, join as join8 } from "node:path";
1136
+ import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
1137
+ import { homedir as homedir7 } from "node:os";
1138
+ import { dirname, join as join10 } from "node:path";
547
1139
  function pickEnv(env, key) {
548
1140
  return env?.[key]?.trim() ?? "";
549
1141
  }
550
1142
  function resolveOpencodeAuthCandidates(overrides) {
551
1143
  const platform = overrides?.platform ?? process.platform;
552
1144
  const env = overrides?.env ?? process.env;
553
- const home = overrides?.home ?? homedir6();
1145
+ const home = overrides?.home ?? homedir7();
554
1146
  const seen = new Set;
555
1147
  const out = [];
556
1148
  const push = (p) => {
@@ -561,27 +1153,27 @@ function resolveOpencodeAuthCandidates(overrides) {
561
1153
  };
562
1154
  const xdg = pickEnv(env, "XDG_DATA_HOME");
563
1155
  if (xdg)
564
- push(join8(xdg, "opencode", "auth.json"));
1156
+ push(join10(xdg, "opencode", "auth.json"));
565
1157
  if (platform === "win32") {
566
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join8(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1158
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join10(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
567
1159
  if (localAppData)
568
- push(join8(localAppData, "opencode", "auth.json"));
1160
+ push(join10(localAppData, "opencode", "auth.json"));
569
1161
  const userProfile = pickEnv(env, "USERPROFILE") || home;
570
1162
  if (userProfile)
571
- push(join8(userProfile, ".local", "share", "opencode", "auth.json"));
1163
+ push(join10(userProfile, ".local", "share", "opencode", "auth.json"));
572
1164
  } else if (home) {
573
- push(join8(home, ".local", "share", "opencode", "auth.json"));
1165
+ push(join10(home, ".local", "share", "opencode", "auth.json"));
574
1166
  }
575
1167
  return out;
576
1168
  }
577
1169
  function resolveOpencodeAuthFile() {
578
- return resolveOpencodeAuthCandidates()[0] ?? join8(homedir6(), ".local", "share", "opencode", "auth.json");
1170
+ return resolveOpencodeAuthCandidates()[0] ?? join10(homedir7(), ".local", "share", "opencode", "auth.json");
579
1171
  }
580
1172
  function isValidOpencodeAuthFile(authFile) {
581
1173
  try {
582
- if (!authFile || !existsSync6(authFile))
1174
+ if (!authFile || !existsSync9(authFile))
583
1175
  return false;
584
- const raw = readFileSync2(authFile, "utf8").trim();
1176
+ const raw = readFileSync5(authFile, "utf8").trim();
585
1177
  if (!raw)
586
1178
  return false;
587
1179
  const parsed = JSON.parse(raw);
@@ -599,7 +1191,7 @@ function probeOpencodeAuth(overrides) {
599
1191
  for (const candidate of candidates) {
600
1192
  let exists = false;
601
1193
  try {
602
- exists = existsSync6(candidate);
1194
+ exists = existsSync9(candidate);
603
1195
  } catch {
604
1196
  exists = false;
605
1197
  }
@@ -615,7 +1207,7 @@ function probeOpencodeAuth(overrides) {
615
1207
  const authDir = dirname(authFile);
616
1208
  let hasCodexHome = false;
617
1209
  try {
618
- hasCodexHome = existsSync6(authDir);
1210
+ hasCodexHome = existsSync9(authDir);
619
1211
  } catch {
620
1212
  hasCodexHome = false;
621
1213
  }
@@ -631,22 +1223,55 @@ function probeOpencodeAuth(overrides) {
631
1223
  var opencodeAdapter = {
632
1224
  id: "opencode",
633
1225
  probeAuth: () => probeOpencodeAuth(),
1226
+ probeQuota: async () => probeOpencodeQuota(),
634
1227
  orderAuthMethods: (methods) => methods,
635
1228
  canSkipInteractiveAuth: () => false,
636
1229
  tryDirectSessionFirst: true
637
1230
  };
638
1231
 
1232
+ // src/runtimes/opencode-v2/index.ts
1233
+ var opencodeV2Adapter = {
1234
+ id: "opencode-v2",
1235
+ probeAuth: () => probeOpencodeAuth(),
1236
+ orderAuthMethods: (methods) => methods,
1237
+ canSkipInteractiveAuth: () => false,
1238
+ tryDirectSessionFirst: true
1239
+ };
1240
+
1241
+ // src/runtimes/cursor/quota.ts
1242
+ async function probeCursorQuota() {
1243
+ const auth = probeCursorAuth();
1244
+ if (!auth.looksLoggedIn) {
1245
+ return {
1246
+ runtimeId: "cursor-cli",
1247
+ provider: "Cursor",
1248
+ status: "unauthorized",
1249
+ message: "未检测到 Cursor CLI 登录凭证",
1250
+ updatedAt: Date.now()
1251
+ };
1252
+ }
1253
+ return {
1254
+ runtimeId: "cursor-cli",
1255
+ provider: "Cursor",
1256
+ account: {
1257
+ plan: "Cursor Pro / Fast Requests"
1258
+ },
1259
+ status: "ok",
1260
+ updatedAt: Date.now()
1261
+ };
1262
+ }
1263
+
639
1264
  // src/runtimes/cursor/index.ts
640
1265
  import { spawnSync } from "node:child_process";
641
- import { existsSync as existsSync7, readFileSync as readFileSync3 } from "node:fs";
642
- import { homedir as homedir7 } from "node:os";
643
- import { delimiter, dirname as dirname2, join as join9 } from "node:path";
1266
+ import { existsSync as existsSync10, readFileSync as readFileSync6 } from "node:fs";
1267
+ import { homedir as homedir8 } from "node:os";
1268
+ import { delimiter, dirname as dirname2, join as join11 } from "node:path";
644
1269
  function cursorLocalAppData(env) {
645
1270
  const local = env.LOCALAPPDATA?.trim();
646
1271
  if (local)
647
1272
  return local;
648
1273
  const profile = env.USERPROFILE?.trim();
649
- return profile ? join9(profile, "AppData", "Local") : "";
1274
+ return profile ? join11(profile, "AppData", "Local") : "";
650
1275
  }
651
1276
  function isOnPath(command, env, platform) {
652
1277
  const pathValue = env.PATH ?? env.Path ?? "";
@@ -658,7 +1283,7 @@ function isOnPath(command, env, platform) {
658
1283
  if (!trimmed)
659
1284
  continue;
660
1285
  try {
661
- if (existsSync7(join9(trimmed, command)))
1286
+ if (existsSync10(join11(trimmed, command)))
662
1287
  return true;
663
1288
  } catch {}
664
1289
  }
@@ -667,24 +1292,24 @@ function isOnPath(command, env, platform) {
667
1292
  function resolveDirectCursorCommand(platform, env, home) {
668
1293
  if (platform === "win32") {
669
1294
  const localAppData = cursorLocalAppData(env);
670
- return localAppData ? join9(localAppData, "cursor-agent", "agent.cmd") : "";
1295
+ return localAppData ? join11(localAppData, "cursor-agent", "agent.cmd") : "";
671
1296
  }
672
- return home ? join9(home, ".local", "bin", "agent") : "";
1297
+ return home ? join11(home, ".local", "bin", "agent") : "";
673
1298
  }
674
1299
  function resolveCursorCommand(overrides) {
675
1300
  const args = ["acp"];
676
1301
  const platform = overrides?.platform ?? process.platform;
677
1302
  const env = overrides?.env ?? process.env;
678
- const home = overrides?.home ?? homedir7();
1303
+ const home = overrides?.home ?? homedir8();
679
1304
  if (platform === "win32") {
680
1305
  const directCmd = resolveDirectCursorCommand(platform, env, home);
681
- if (directCmd && existsSync7(directCmd)) {
1306
+ if (directCmd && existsSync10(directCmd)) {
682
1307
  return { command: directCmd, args };
683
1308
  }
684
1309
  return { command: "agent.cmd", args };
685
1310
  }
686
1311
  const directBin = resolveDirectCursorCommand(platform, env, home);
687
- if (directBin && existsSync7(directBin)) {
1312
+ if (directBin && existsSync10(directBin)) {
688
1313
  return { command: directBin, args };
689
1314
  }
690
1315
  return { command: "agent", args };
@@ -693,11 +1318,11 @@ function resolveCursorSpawnCommand(overrides) {
693
1318
  const args = ["acp"];
694
1319
  const platform = overrides?.platform ?? process.platform;
695
1320
  const env = overrides?.env ?? process.env;
696
- const home = overrides?.home ?? homedir7();
1321
+ const home = overrides?.home ?? homedir8();
697
1322
  const binary = platform === "win32" ? "agent.cmd" : "agent";
698
1323
  const direct = resolveDirectCursorCommand(platform, env, home);
699
1324
  try {
700
- if (direct && existsSync7(direct))
1325
+ if (direct && existsSync10(direct))
701
1326
  return { command: direct, args };
702
1327
  } catch {}
703
1328
  if (isOnPath(binary, env, platform))
@@ -719,12 +1344,12 @@ function cursorRoamingAppData(env, home) {
719
1344
  if (roaming)
720
1345
  return roaming;
721
1346
  const profile = pickEnv2(env, "USERPROFILE") || home;
722
- return profile ? join9(profile, "AppData", "Roaming") : "";
1347
+ return profile ? join11(profile, "AppData", "Roaming") : "";
723
1348
  }
724
1349
  function resolveCursorAuthCandidates(overrides) {
725
1350
  const platform = overrides?.platform ?? process.platform;
726
1351
  const env = overrides?.env ?? process.env;
727
- const home = overrides?.home ?? homedir7();
1352
+ const home = overrides?.home ?? homedir8();
728
1353
  const seen = new Set;
729
1354
  const out = [];
730
1355
  const push = (p) => {
@@ -735,16 +1360,16 @@ function resolveCursorAuthCandidates(overrides) {
735
1360
  };
736
1361
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
737
1362
  if (xdg)
738
- push(join9(xdg, "cursor", "auth.json"));
1363
+ push(join11(xdg, "cursor", "auth.json"));
739
1364
  if (platform === "win32") {
740
1365
  const profile = pickEnv2(env, "USERPROFILE") || home;
741
1366
  if (profile)
742
- push(join9(profile, ".config", "cursor", "auth.json"));
1367
+ push(join11(profile, ".config", "cursor", "auth.json"));
743
1368
  const roaming = cursorRoamingAppData(env, home);
744
1369
  if (roaming)
745
- push(join9(roaming, "Cursor", "User", "globalStorage", "storage.json"));
1370
+ push(join11(roaming, "Cursor", "User", "globalStorage", "storage.json"));
746
1371
  } else if (home) {
747
- push(join9(home, ".config", "cursor", "auth.json"));
1372
+ push(join11(home, ".config", "cursor", "auth.json"));
748
1373
  }
749
1374
  return out;
750
1375
  }
@@ -755,9 +1380,9 @@ function isValidCursorAuthFile(authFile) {
755
1380
  try {
756
1381
  if (!authFile || isStorageHintPath(authFile))
757
1382
  return false;
758
- if (!existsSync7(authFile))
1383
+ if (!existsSync10(authFile))
759
1384
  return false;
760
- const raw = readFileSync3(authFile, "utf8").trim();
1385
+ const raw = readFileSync6(authFile, "utf8").trim();
761
1386
  if (!raw)
762
1387
  return false;
763
1388
  const parsed = JSON.parse(raw);
@@ -775,9 +1400,9 @@ function isHintCursorStorageFile(authFile) {
775
1400
  try {
776
1401
  if (!authFile || !isStorageHintPath(authFile))
777
1402
  return false;
778
- if (!existsSync7(authFile))
1403
+ if (!existsSync10(authFile))
779
1404
  return false;
780
- const raw = readFileSync3(authFile, "utf8").trim();
1405
+ const raw = readFileSync6(authFile, "utf8").trim();
781
1406
  if (!raw)
782
1407
  return false;
783
1408
  const parsed = JSON.parse(raw);
@@ -793,7 +1418,7 @@ function isValidCursorCandidate(authFile) {
793
1418
  }
794
1419
  function probeCursorAuth(overrides) {
795
1420
  const env = overrides?.env ?? process.env;
796
- const home = overrides?.home ?? homedir7();
1421
+ const home = overrides?.home ?? homedir8();
797
1422
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
798
1423
  const candidates = resolveCursorAuthCandidates(overrides);
799
1424
  let firstExisting = null;
@@ -801,7 +1426,7 @@ function probeCursorAuth(overrides) {
801
1426
  for (const candidate of candidates) {
802
1427
  let exists = false;
803
1428
  try {
804
- exists = existsSync7(candidate);
1429
+ exists = existsSync10(candidate);
805
1430
  } catch {
806
1431
  exists = false;
807
1432
  }
@@ -813,12 +1438,12 @@ function probeCursorAuth(overrides) {
813
1438
  if (isValidCursorCandidate(candidate))
814
1439
  validFile = candidate;
815
1440
  }
816
- const fallback = home ? join9(home, ".config", "cursor", "auth.json") : "";
1441
+ const fallback = home ? join11(home, ".config", "cursor", "auth.json") : "";
817
1442
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
818
1443
  const authDir = authFile ? dirname2(authFile) : "";
819
1444
  let hasCodexHome = false;
820
1445
  try {
821
- hasCodexHome = authDir ? existsSync7(authDir) : false;
1446
+ hasCodexHome = authDir ? existsSync10(authDir) : false;
822
1447
  } catch {
823
1448
  hasCodexHome = false;
824
1449
  }
@@ -833,6 +1458,7 @@ function probeCursorAuth(overrides) {
833
1458
  var cursorAdapter = {
834
1459
  id: "cursor-cli",
835
1460
  probeAuth: () => probeCursorAuth(),
1461
+ probeQuota: async () => probeCursorQuota(),
836
1462
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
837
1463
  orderAuthMethods: (methods) => methods,
838
1464
  canSkipInteractiveAuth: () => false,
@@ -951,6 +1577,55 @@ var deepseekAdapter = {
951
1577
  canSkipInteractiveAuth: () => false
952
1578
  };
953
1579
 
1580
+ // src/runtimes/agy/quota.ts
1581
+ import { existsSync as existsSync11 } from "node:fs";
1582
+ import { join as join12 } from "node:path";
1583
+ function resolveGeminiHome2() {
1584
+ const home = process.env.USERPROFILE || process.env.HOME || "";
1585
+ return join12(home, ".gemini");
1586
+ }
1587
+ async function probeAgyQuota(options) {
1588
+ const geminiHome = resolveGeminiHome2();
1589
+ const hasAgyDir = existsSync11(join12(geminiHome, "antigravity")) || existsSync11(join12(geminiHome, "antigravity-cli"));
1590
+ const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
1591
+ const isAvailable = hasAgyDir || hasApiKey;
1592
+ if (!isAvailable) {
1593
+ return {
1594
+ runtimeId: "agy",
1595
+ provider: "Google Antigravity",
1596
+ status: "unauthorized",
1597
+ message: "wenjianlingu antigravity cli",
1598
+ updatedAt: Date.now()
1599
+ };
1600
+ }
1601
+ return {
1602
+ runtimeId: "agy",
1603
+ provider: "Google Antigravity",
1604
+ account: {
1605
+ plan: "Antigravity / Gemini",
1606
+ type: "gemini"
1607
+ },
1608
+ primaryWindow: {
1609
+ label: "5-Hour limit",
1610
+ percentLeft: 100,
1611
+ usedPercent: 0,
1612
+ windowDurationMins: 300
1613
+ },
1614
+ secondaryWindow: {
1615
+ label: "Weekly limit",
1616
+ percentLeft: 100,
1617
+ usedPercent: 0,
1618
+ windowDurationMins: 10080
1619
+ },
1620
+ credits: {
1621
+ unlimited: true,
1622
+ balance: "unlimited"
1623
+ },
1624
+ status: "ok",
1625
+ updatedAt: Date.now()
1626
+ };
1627
+ }
1628
+
954
1629
  // src/runtimes/agy/index.ts
955
1630
  function probeAgyAuth() {
956
1631
  return {
@@ -964,6 +1639,7 @@ function probeAgyAuth() {
964
1639
  var agyAdapter = {
965
1640
  id: "agy",
966
1641
  probeAuth: () => probeAgyAuth(),
1642
+ probeQuota: (options) => probeAgyQuota(options),
967
1643
  orderAuthMethods: (methods) => methods,
968
1644
  canSkipInteractiveAuth: () => false,
969
1645
  tryDirectSessionFirst: true
@@ -983,6 +1659,8 @@ function getAcpRuntimeAdapter(runtimeId) {
983
1659
  return copilotAdapter;
984
1660
  case opencodeAdapter.id:
985
1661
  return opencodeAdapter;
1662
+ case opencodeV2Adapter.id:
1663
+ return opencodeV2Adapter;
986
1664
  case cursorAdapter.id:
987
1665
  case "cursor":
988
1666
  return cursorAdapter;
@@ -999,7 +1677,7 @@ function getAcpRuntimeAdapter(runtimeId) {
999
1677
  }
1000
1678
 
1001
1679
  // src/process/process-manager.ts
1002
- import { spawn, spawnSync as spawnSync2 } from "node:child_process";
1680
+ import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
1003
1681
  var active = new Map;
1004
1682
  var ACP_EARLY_EXIT_WINDOW_MS = 3000;
1005
1683
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
@@ -1054,7 +1732,7 @@ function spawnAcpProcess(options) {
1054
1732
  } else {
1055
1733
  delete env.NO_BROWSER;
1056
1734
  }
1057
- const child = spawn(file, options.runtime.args, {
1735
+ const child = spawn2(file, options.runtime.args, {
1058
1736
  cwd: options.cwd,
1059
1737
  env,
1060
1738
  stdio: ["pipe", "pipe", "pipe"],
@@ -1777,7 +2455,7 @@ async function restoreOrCreateAcpSession(input) {
1777
2455
  }
1778
2456
 
1779
2457
  // src/client/acp-terminal.ts
1780
- import { spawn as spawn2 } from "node:child_process";
2458
+ import { spawn as spawn3 } from "node:child_process";
1781
2459
  import { randomUUID } from "node:crypto";
1782
2460
 
1783
2461
  // src/transport/terminal-output-buffer.ts
@@ -1830,7 +2508,7 @@ class AcpTerminalManager {
1830
2508
  throw new Error("terminal/create 需要 command");
1831
2509
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
1832
2510
  const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
1833
- const child = spawn2(command, params.args ?? [], {
2511
+ const child = spawn3(command, params.args ?? [], {
1834
2512
  cwd,
1835
2513
  env: buildEnv(params.env),
1836
2514
  windowsHide: true,
@@ -1926,7 +2604,7 @@ class AcpTerminalManager {
1926
2604
  return;
1927
2605
  if (process.platform === "win32") {
1928
2606
  try {
1929
- spawn2("taskkill", ["/pid", String(pid), "/T", "/F"], {
2607
+ spawn3("taskkill", ["/pid", String(pid), "/T", "/F"], {
1930
2608
  windowsHide: true,
1931
2609
  stdio: "ignore"
1932
2610
  });
@@ -1962,8 +2640,8 @@ class AcpTerminalManager {
1962
2640
 
1963
2641
  // src/client/acp-proxy-service.ts
1964
2642
  import { mkdir as mkdir4, readFile as readFile3, writeFile as writeFile4 } from "node:fs/promises";
1965
- import { existsSync as existsSync8 } from "node:fs";
1966
- import { join as join10 } from "node:path";
2643
+ import { existsSync as existsSync12 } from "node:fs";
2644
+ import { join as join13 } from "node:path";
1967
2645
  var DEFAULT_ACP_PROXY_SETTINGS = {
1968
2646
  enabled: false,
1969
2647
  host: "127.0.0.1",
@@ -1972,7 +2650,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
1972
2650
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
1973
2651
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
1974
2652
  function proxyFilePath(dir) {
1975
- return join10(dir, "agent", "proxy.json");
2653
+ return join13(dir, "agent", "proxy.json");
1976
2654
  }
1977
2655
  function validate2(settings) {
1978
2656
  if (!settings.host.trim())
@@ -1984,7 +2662,7 @@ function validate2(settings) {
1984
2662
  }
1985
2663
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
1986
2664
  const file = proxyFilePath(dir);
1987
- if (!existsSync8(file))
2665
+ if (!existsSync12(file))
1988
2666
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
1989
2667
  try {
1990
2668
  const raw = JSON.parse(await readFile3(file, "utf8"));
@@ -2006,7 +2684,7 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
2006
2684
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
2007
2685
  port: payload.port
2008
2686
  };
2009
- await mkdir4(join10(dir, "agent"), { recursive: true });
2687
+ await mkdir4(join13(dir, "agent"), { recursive: true });
2010
2688
  await writeFile4(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
2011
2689
  return ok(stored);
2012
2690
  }
@@ -2074,6 +2752,12 @@ class AcpSessionHandle {
2074
2752
  async prompt(promptText, options) {
2075
2753
  return this.client.promptSession(this.sessionId, promptText, options);
2076
2754
  }
2755
+ get quota() {
2756
+ return this.client.getCachedQuota(this.sessionId);
2757
+ }
2758
+ async getQuota() {
2759
+ return this.client.getQuota(this.sessionId);
2760
+ }
2077
2761
  get availableCommands() {
2078
2762
  return this.client.getAvailableCommands(this.sessionId);
2079
2763
  }
@@ -2085,6 +2769,7 @@ class AcpSessionHandle {
2085
2769
  class AcpClient {
2086
2770
  status = "disconnected";
2087
2771
  commandsCache = new AvailableCommandsCache;
2772
+ quotaCache = new QuotaCache;
2088
2773
  runtimeInfo;
2089
2774
  adapter;
2090
2775
  workspaceRoot;
@@ -2195,6 +2880,7 @@ class AcpClient {
2195
2880
  },
2196
2881
  onSessionUpdate: (params) => {
2197
2882
  this.commandsCache.observe(params);
2883
+ this.quotaCache.observe(params, this.runtimeInfo.id);
2198
2884
  this.callbacks.onSessionUpdate?.(params);
2199
2885
  }
2200
2886
  };
@@ -2225,6 +2911,23 @@ class AcpClient {
2225
2911
  return err({ code: "ACP_PROTOCOL_ERROR", message });
2226
2912
  }
2227
2913
  }
2914
+ getCachedQuota(sessionId) {
2915
+ return this.quotaCache.get(sessionId, this.runtimeInfo.id);
2916
+ }
2917
+ async getQuota(sessionId) {
2918
+ const cached = this.getCachedQuota(sessionId);
2919
+ if (cached && Date.now() - cached.updatedAt < 30000) {
2920
+ return cached;
2921
+ }
2922
+ if (this.adapter.probeQuota) {
2923
+ const probed = await this.adapter.probeQuota({ sessionId });
2924
+ if (probed) {
2925
+ this.quotaCache.set(probed, sessionId);
2926
+ return probed;
2927
+ }
2928
+ }
2929
+ return cached ?? null;
2930
+ }
2228
2931
  getAvailableCommands(sessionId) {
2229
2932
  return this.commandsCache.get(sessionId);
2230
2933
  }
@@ -3257,6 +3960,8 @@ export {
3257
3960
  INKDOWN_VIRTUAL_DIR,
3258
3961
  INKDOWN_VIRTUAL_RESOURCES,
3259
3962
  LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
3963
+ OPENCODE_CLI_NPM_PACKAGE,
3964
+ QuotaCache,
3260
3965
  acpReadTextFile,
3261
3966
  acpWriteTextFile,
3262
3967
  agyAdapter,
@@ -3315,6 +4020,7 @@ export {
3315
4020
  mergeTopLevelModelsIntoConfigOptions,
3316
4021
  ok,
3317
4022
  opencodeAdapter,
4023
+ opencodeV2Adapter,
3318
4024
  orderSilentAuthMethodIds,
3319
4025
  parseAcpConfigOptions,
3320
4026
  parseCursorCatalogOutput,
@@ -3322,16 +4028,21 @@ export {
3322
4028
  parseLoadSessionSupported,
3323
4029
  parseMcpHttpSupported,
3324
4030
  parsePromptCapabilities,
4031
+ parseRateLimitsFromStatusText,
3325
4032
  parseResumeSessionSupported,
3326
4033
  pickAllowOptionId,
3327
4034
  probeAgyAuth,
3328
4035
  probeClaudeAuth,
4036
+ probeClaudeQuota,
3329
4037
  probeCodexAuth,
4038
+ probeCodexQuota,
3330
4039
  probeCopilotAuth,
3331
4040
  probeCursorAuth,
4041
+ probeCursorQuota,
3332
4042
  probeDeepseekAuth,
3333
4043
  probeGeminiAuth,
3334
4044
  probeOpencodeAuth,
4045
+ probeOpencodeQuota,
3335
4046
  provisionCustomProviderCodexHome,
3336
4047
  readAcpProxySettings,
3337
4048
  readStoredAcpProvider,
@@ -3348,6 +4059,7 @@ export {
3348
4059
  resolveGeminiHome,
3349
4060
  resolveOpencodeAuthCandidates,
3350
4061
  resolveOpencodeAuthFile,
4062
+ resolveOpencodeAuthPath,
3351
4063
  restoreOrCreateAcpSession,
3352
4064
  runConnectAuthGate,
3353
4065
  saveAcpProvider,