@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/sidecar.cjs CHANGED
@@ -33,11 +33,10 @@ var __toESM = (mod, isNodeMode, target) => {
33
33
  };
34
34
 
35
35
  // src/sidecar/main.ts
36
- var readline = __toESM(require("node:readline"), 1);
36
+ var readline2 = __toESM(require("node:readline"), 1);
37
37
 
38
38
  // src/version.ts
39
- var ACP_CLIENT_VERSION = "0.1.4";
40
-
39
+ var ACP_CLIENT_VERSION = "0.1.6";
41
40
  // src/contracts/index.ts
42
41
  function ok(value) {
43
42
  return { ok: true, value };
@@ -84,6 +83,7 @@ var CODEX_ACP_NPM_PACKAGE = "@agentclientprotocol/codex-acp";
84
83
  var CLAUDE_ACP_NPM_PACKAGE = "@agentclientprotocol/claude-agent-acp";
85
84
  var DEEPSEEK_DSH_NPM_PACKAGE = "@deepseek-ai/dsh";
86
85
  var AGY_ACP_NPM_PACKAGE = "@yitom/agy-acp-map";
86
+ var OPENCODE_CLI_NPM_PACKAGE = "@opencode/cli";
87
87
  var DEFAULT_ACP_RUNTIME_ID = "codex-acp";
88
88
  function isWindowsPlatform() {
89
89
  const proc = globalThis.process;
@@ -135,6 +135,15 @@ var BUILTIN_ACP_RUNTIMES = [
135
135
  args: ["acp"],
136
136
  requiredEnvKeys: []
137
137
  },
138
+ {
139
+ id: "opencode-v2",
140
+ name: "OpenCode v2",
141
+ description: "通过 npx 启动独立产品线 @opencode/cli v2(acp);与 1.x 共存,复用 v2 SQLite 登录态",
142
+ authHint: "v2 登录态在 SQLite(auth.json 仅兼容残留);未登录先用 v2 二进制跑 opencode auth login",
143
+ command: "npx",
144
+ args: ["-y", OPENCODE_CLI_NPM_PACKAGE, "acp"],
145
+ requiredEnvKeys: []
146
+ },
138
147
  {
139
148
  id: "cursor-cli",
140
149
  name: "Cursor",
@@ -248,6 +257,161 @@ class AvailableCommandsCache {
248
257
  }
249
258
  }
250
259
 
260
+ // src/session/quota.ts
261
+ function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
262
+ if (!text || typeof text !== "string")
263
+ return null;
264
+ const lines = text.split(/\r?\n/);
265
+ let account;
266
+ const windows = [];
267
+ let credits;
268
+ let status = "ok";
269
+ let message;
270
+ if (/account (?:disabled|banned|suspended)|suspended|banned/i.test(text)) {
271
+ status = "banned";
272
+ message = "账号已封禁或暂停使用 (Account banned / suspended)";
273
+ } else if (/RESOURCE_EXHAUSTED|quota reached|rate limit exceeded|429/i.test(text)) {
274
+ status = "exhausted";
275
+ message = "额度已用尽 (Quota / Rate limit reached)";
276
+ } else if (/unauthorized|authentication failed|invalid api key/i.test(text)) {
277
+ status = "unauthorized";
278
+ message = "认证失效 (Unauthorized / Invalid credentials)";
279
+ }
280
+ for (const rawLine of lines) {
281
+ const line = rawLine.replace(/\*\*/g, "").trim();
282
+ if (!line)
283
+ continue;
284
+ const accMatch = line.match(/^Account\s*[::]\s*([^()]+?)(?:\s*\(([^)]+)\))?$/i);
285
+ if (accMatch) {
286
+ account = {
287
+ plan: accMatch[1].trim(),
288
+ email: accMatch[2]?.trim()
289
+ };
290
+ continue;
291
+ }
292
+ const credMatch = line.match(/(?:\b|^)(?:[\w\s-]*?credits?)\s*[::]\s*(unlimited|[\d.]+)/i);
293
+ if (credMatch) {
294
+ const val = credMatch[1].trim();
295
+ credits = val.toLowerCase() === "unlimited" ? { unlimited: true, balance: "unlimited" } : { balance: Number(val) || val, unlimited: false };
296
+ continue;
297
+ }
298
+ 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);
299
+ if (winMatch) {
300
+ const label = winMatch[1].trim();
301
+ const pct = parseFloat(winMatch[2]);
302
+ const resetsAt = (winMatch[3] || winMatch[4] || "").trim() || undefined;
303
+ let windowDurationMins;
304
+ const lower = label.toLowerCase();
305
+ if (/5h|5-hour/i.test(lower))
306
+ windowDurationMins = 300;
307
+ else if (/week/i.test(lower))
308
+ windowDurationMins = 10080;
309
+ else if (/month/i.test(lower))
310
+ windowDurationMins = 43200;
311
+ else if (/day|24h/i.test(lower))
312
+ windowDurationMins = 1440;
313
+ else if (/(\d+)\s*h/i.test(lower)) {
314
+ const m = lower.match(/(\d+)\s*h/);
315
+ if (m)
316
+ windowDurationMins = parseInt(m[1], 10) * 60;
317
+ }
318
+ windows.push({
319
+ label,
320
+ percentLeft: pct,
321
+ usedPercent: Math.max(0, 100 - pct),
322
+ resetsAt,
323
+ windowDurationMins
324
+ });
325
+ continue;
326
+ }
327
+ const fastMatch = line.match(/(?:fast requests?|requests?)\s*[::]\s*(\d+)\s*\/\s*(\d+)/i);
328
+ if (fastMatch) {
329
+ const used = parseInt(fastMatch[1], 10);
330
+ const total = parseInt(fastMatch[2], 10);
331
+ const left = Math.max(0, total - used);
332
+ const pct = total > 0 ? Math.round(left / total * 100) : 0;
333
+ windows.push({
334
+ label: "Fast requests",
335
+ percentLeft: pct,
336
+ usedPercent: total > 0 ? Math.round(used / total * 100) : 0,
337
+ used,
338
+ total
339
+ });
340
+ continue;
341
+ }
342
+ }
343
+ if (!windows.length && !credits && !account && status === "ok") {
344
+ return null;
345
+ }
346
+ const primary = windows.find((w) => /5h|5-hour|hour|primary|fast/i.test(w.label)) || windows[0];
347
+ const secondary = windows.find((w) => w !== primary && /week|month|secondary/i.test(w.label)) || windows.find((w) => w !== primary);
348
+ const extraWindows = windows.filter((w) => w !== primary && w !== secondary);
349
+ if (primary && primary.percentLeft <= 10 && status === "ok") {
350
+ status = "warning";
351
+ }
352
+ return {
353
+ runtimeId,
354
+ account,
355
+ primaryWindow: primary,
356
+ secondaryWindow: secondary,
357
+ extraWindows: extraWindows.length ? extraWindows : undefined,
358
+ credits,
359
+ status,
360
+ message,
361
+ rawText: text,
362
+ updatedAt: Date.now()
363
+ };
364
+ }
365
+
366
+ class QuotaCache {
367
+ bySession = new Map;
368
+ byRuntime = new Map;
369
+ observe(params, defaultRuntimeId = "unknown") {
370
+ if (!params || typeof params !== "object")
371
+ return null;
372
+ const p = params;
373
+ const sessionId = typeof p.sessionId === "string" ? p.sessionId : undefined;
374
+ let textToParse = "";
375
+ if (p.update?.content && p.update.content.type === "text" && typeof p.update.content.text === "string") {
376
+ textToParse = p.update.content.text;
377
+ } else if (p.update?.message?.content && Array.isArray(p.update.message.content)) {
378
+ textToParse = p.update.message.content.filter((c) => c && c.type === "text" && typeof c.text === "string").map((c) => c.text).join(`
379
+ `);
380
+ }
381
+ if (!textToParse)
382
+ return null;
383
+ if (!/(?:limit|credits?|Account:|5h|resets|banned|suspended|quota)/i.test(textToParse)) {
384
+ return null;
385
+ }
386
+ const quota = parseRateLimitsFromStatusText(textToParse, defaultRuntimeId);
387
+ if (quota) {
388
+ if (sessionId)
389
+ this.bySession.set(sessionId, quota);
390
+ this.byRuntime.set(defaultRuntimeId, quota);
391
+ return quota;
392
+ }
393
+ return null;
394
+ }
395
+ set(quota, sessionId) {
396
+ if (sessionId)
397
+ this.bySession.set(sessionId, quota);
398
+ this.byRuntime.set(quota.runtimeId, quota);
399
+ }
400
+ get(sessionId, runtimeId) {
401
+ if (sessionId && this.bySession.has(sessionId)) {
402
+ return this.bySession.get(sessionId);
403
+ }
404
+ if (runtimeId && this.byRuntime.has(runtimeId)) {
405
+ return this.byRuntime.get(runtimeId);
406
+ }
407
+ return;
408
+ }
409
+ clear() {
410
+ this.bySession.clear();
411
+ this.byRuntime.clear();
412
+ }
413
+ }
414
+
251
415
  // node_modules/@agentclientprotocol/sdk/dist/schema/index.js
252
416
  var AGENT_METHODS = {
253
417
  initialize: "initialize",
@@ -10133,38 +10297,11 @@ var legacyClientNotificationMethods = new Set([
10133
10297
  CLIENT_METHODS.elicitation_complete
10134
10298
  ]);
10135
10299
 
10136
- // src/runtimes/codex/index.ts
10137
- var import_promises2 = require("node:fs/promises");
10138
- var import_node_path4 = require("node:path");
10139
-
10140
- // src/runtimes/codex/codex-provider-home.ts
10141
- var INKDOWN_PROVIDER_ID = "inkdown-custom";
10142
- var INKDOWN_PROVIDER_API_KEY_ENV = "INKDOWN_PROVIDER_API_KEY";
10143
- function tomlEscape(value) {
10144
- return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
10145
- }
10146
- function buildCustomProviderConfigToml(config) {
10147
- const name = config.name?.trim() || "自定义 API";
10148
- const wireApi = config.wireApi === "responses" ? "responses" : "chat";
10149
- return [
10150
- `model_provider = "${INKDOWN_PROVIDER_ID}"`,
10151
- `model = "${tomlEscape(config.model.trim())}"`,
10152
- "",
10153
- `[model_providers.${INKDOWN_PROVIDER_ID}]`,
10154
- `name = "${tomlEscape(name)}"`,
10155
- `base_url = "${tomlEscape(config.baseUrl.trim())}"`,
10156
- `env_key = "${INKDOWN_PROVIDER_API_KEY_ENV}"`,
10157
- `wire_api = "${wireApi}"`,
10158
- ""
10159
- ].join(`
10160
- `);
10161
- }
10162
- function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
10163
- return {
10164
- CODEX_HOME: codexHome,
10165
- [INKDOWN_PROVIDER_API_KEY_ENV]: apiKey
10166
- };
10167
- }
10300
+ // src/runtimes/codex/quota.ts
10301
+ var import_node_fs2 = require("node:fs");
10302
+ var import_node_path2 = require("node:path");
10303
+ var import_node_child_process = require("node:child_process");
10304
+ var import_node_readline = __toESM(require("node:readline"), 1);
10168
10305
 
10169
10306
  // src/runtimes/codex/codex-auth-preflight.ts
10170
10307
  var import_node_fs = require("node:fs");
@@ -10199,14 +10336,252 @@ function probeCodexAuth() {
10199
10336
  };
10200
10337
  }
10201
10338
 
10339
+ // src/runtimes/codex/quota.ts
10340
+ function decodeJwtPayload(token) {
10341
+ try {
10342
+ const parts = token.split(".");
10343
+ if (parts.length < 2)
10344
+ return null;
10345
+ const json = Buffer.from(parts[1], "base64").toString("utf8");
10346
+ return JSON.parse(json);
10347
+ } catch {
10348
+ return null;
10349
+ }
10350
+ }
10351
+ var cachedDynamicResult = null;
10352
+ async function queryCodexAppServer(timeoutMs = 4000) {
10353
+ if (cachedDynamicResult && Date.now() - cachedDynamicResult.time < 15000) {
10354
+ return cachedDynamicResult.res;
10355
+ }
10356
+ return new Promise((resolve) => {
10357
+ let timer = null;
10358
+ let proc = null;
10359
+ let finished = false;
10360
+ const cleanup = (res) => {
10361
+ if (finished)
10362
+ return;
10363
+ finished = true;
10364
+ if (timer)
10365
+ clearTimeout(timer);
10366
+ if (proc) {
10367
+ try {
10368
+ proc.kill();
10369
+ } catch {}
10370
+ }
10371
+ if (res) {
10372
+ cachedDynamicResult = { res, time: Date.now() };
10373
+ }
10374
+ resolve(res);
10375
+ };
10376
+ timer = setTimeout(() => cleanup(null), timeoutMs);
10377
+ try {
10378
+ proc = import_node_child_process.spawn("codex", ["app-server"], {
10379
+ stdio: ["pipe", "pipe", "pipe"],
10380
+ shell: process.platform === "win32",
10381
+ windowsHide: true
10382
+ });
10383
+ if (!proc.stdin || !proc.stdout) {
10384
+ return cleanup(null);
10385
+ }
10386
+ const rl = import_node_readline.default.createInterface({ input: proc.stdout });
10387
+ let reqSeq = 1;
10388
+ const pending = new Map;
10389
+ const result = {};
10390
+ rl.on("line", (line) => {
10391
+ try {
10392
+ const data = JSON.parse(line.trim());
10393
+ if (data && typeof data.id === "number" && pending.has(data.id)) {
10394
+ const cb = pending.get(data.id);
10395
+ pending.delete(data.id);
10396
+ cb(data.result);
10397
+ }
10398
+ } catch {}
10399
+ });
10400
+ proc.on("error", () => cleanup(null));
10401
+ proc.on("exit", () => cleanup(Object.keys(result).length > 0 ? result : null));
10402
+ const send = (method, params) => {
10403
+ const id = reqSeq++;
10404
+ const msg = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + `
10405
+ `;
10406
+ proc.stdin.write(msg);
10407
+ return new Promise((res) => {
10408
+ pending.set(id, res);
10409
+ });
10410
+ };
10411
+ (async () => {
10412
+ try {
10413
+ await send("initialize", {
10414
+ clientInfo: { name: "acp-client", version: "0.1.6" }
10415
+ });
10416
+ const acc = await send("account/read", { refreshToken: false });
10417
+ if (acc?.account) {
10418
+ result.account = acc.account;
10419
+ }
10420
+ const limits = await send("account/rateLimits/read");
10421
+ if (limits?.rateLimits) {
10422
+ result.rateLimits = limits.rateLimits;
10423
+ }
10424
+ cleanup(result);
10425
+ } catch {
10426
+ cleanup(null);
10427
+ }
10428
+ })();
10429
+ } catch {
10430
+ cleanup(null);
10431
+ }
10432
+ });
10433
+ }
10434
+ function formatEpochTime(epochSeconds) {
10435
+ if (!epochSeconds)
10436
+ return;
10437
+ try {
10438
+ const d = new Date(epochSeconds * 1000);
10439
+ const hours = String(d.getHours()).padStart(2, "0");
10440
+ const mins = String(d.getMinutes()).padStart(2, "0");
10441
+ return `${hours}:${mins}`;
10442
+ } catch {
10443
+ return;
10444
+ }
10445
+ }
10446
+ async function probeCodexQuota(options) {
10447
+ const codexHome = resolveCodexHome();
10448
+ const authPath = import_node_path2.join(codexHome, "auth.json");
10449
+ let accountEmail;
10450
+ let accountPlan = "Codex Free / Local";
10451
+ let isLoggedIn = false;
10452
+ if (import_node_fs2.existsSync(authPath)) {
10453
+ try {
10454
+ const authData = JSON.parse(import_node_fs2.readFileSync(authPath, "utf8"));
10455
+ if (authData.OPENAI_API_KEY) {
10456
+ isLoggedIn = true;
10457
+ accountPlan = "OpenAI API Key";
10458
+ }
10459
+ if (authData.tokens?.id_token) {
10460
+ isLoggedIn = true;
10461
+ const payload = decodeJwtPayload(authData.tokens.id_token);
10462
+ if (payload) {
10463
+ if (typeof payload.email === "string")
10464
+ accountEmail = payload.email;
10465
+ const authObj = payload["https://api.openai.com/auth"];
10466
+ if (authObj && typeof authObj.chatgpt_plan_type === "string") {
10467
+ accountPlan = `ChatGPT ${authObj.chatgpt_plan_type}`;
10468
+ }
10469
+ }
10470
+ } else if (authData.tokens?.access_token) {
10471
+ isLoggedIn = true;
10472
+ }
10473
+ } catch {}
10474
+ }
10475
+ if (process.env.CODEX_API_KEY || process.env.OPENAI_API_KEY) {
10476
+ isLoggedIn = true;
10477
+ accountPlan = "API Key (Env)";
10478
+ }
10479
+ const dynamic = await queryCodexAppServer(4000);
10480
+ if (dynamic) {
10481
+ isLoggedIn = true;
10482
+ if (dynamic.account?.email)
10483
+ accountEmail = dynamic.account.email;
10484
+ if (dynamic.account?.planType)
10485
+ accountPlan = `ChatGPT ${dynamic.account.planType}`;
10486
+ }
10487
+ if (!isLoggedIn) {
10488
+ return {
10489
+ runtimeId: "codex-acp",
10490
+ provider: "OpenAI / Codex",
10491
+ status: "unauthorized",
10492
+ message: "未登录 Codex (Not logged in)",
10493
+ updatedAt: Date.now()
10494
+ };
10495
+ }
10496
+ let primaryWindow;
10497
+ let secondaryWindow;
10498
+ let credits;
10499
+ if (dynamic?.rateLimits) {
10500
+ const rl = dynamic.rateLimits;
10501
+ if (rl.primary) {
10502
+ const used = rl.primary.usedPercent ?? 0;
10503
+ primaryWindow = {
10504
+ label: "5h limit",
10505
+ percentLeft: Math.max(0, Math.min(100, Math.round(100 - used))),
10506
+ usedPercent: used,
10507
+ windowDurationMins: rl.primary.windowDurationMins || 300,
10508
+ resetsAt: formatEpochTime(rl.primary.resetsAt) || (rl.primary.resetsAt ? String(rl.primary.resetsAt) : undefined)
10509
+ };
10510
+ }
10511
+ if (rl.secondary) {
10512
+ const used = rl.secondary.usedPercent ?? 0;
10513
+ secondaryWindow = {
10514
+ label: "Weekly limit",
10515
+ percentLeft: Math.max(0, Math.min(100, Math.round(100 - used))),
10516
+ usedPercent: used,
10517
+ windowDurationMins: rl.secondary.windowDurationMins || 10080,
10518
+ resetsAt: formatEpochTime(rl.secondary.resetsAt) || (rl.secondary.resetsAt ? String(rl.secondary.resetsAt) : undefined)
10519
+ };
10520
+ }
10521
+ if (rl.credits) {
10522
+ credits = {
10523
+ balance: rl.credits.balance,
10524
+ unlimited: rl.credits.unlimited
10525
+ };
10526
+ }
10527
+ }
10528
+ return {
10529
+ runtimeId: "codex-acp",
10530
+ provider: "OpenAI / Codex",
10531
+ account: {
10532
+ email: accountEmail,
10533
+ plan: accountPlan,
10534
+ type: dynamic?.account?.type || "chatgpt"
10535
+ },
10536
+ primaryWindow,
10537
+ secondaryWindow,
10538
+ credits,
10539
+ status: "ok",
10540
+ updatedAt: Date.now()
10541
+ };
10542
+ }
10543
+
10544
+ // src/runtimes/codex/index.ts
10545
+ var import_promises2 = require("node:fs/promises");
10546
+ var import_node_path5 = require("node:path");
10547
+
10548
+ // src/runtimes/codex/codex-provider-home.ts
10549
+ var INKDOWN_PROVIDER_ID = "inkdown-custom";
10550
+ var INKDOWN_PROVIDER_API_KEY_ENV = "INKDOWN_PROVIDER_API_KEY";
10551
+ function tomlEscape(value) {
10552
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
10553
+ }
10554
+ function buildCustomProviderConfigToml(config) {
10555
+ const name = config.name?.trim() || "自定义 API";
10556
+ const wireApi = config.wireApi === "responses" ? "responses" : "chat";
10557
+ return [
10558
+ `model_provider = "${INKDOWN_PROVIDER_ID}"`,
10559
+ `model = "${tomlEscape(config.model.trim())}"`,
10560
+ "",
10561
+ `[model_providers.${INKDOWN_PROVIDER_ID}]`,
10562
+ `name = "${tomlEscape(name)}"`,
10563
+ `base_url = "${tomlEscape(config.baseUrl.trim())}"`,
10564
+ `env_key = "${INKDOWN_PROVIDER_API_KEY_ENV}"`,
10565
+ `wire_api = "${wireApi}"`,
10566
+ ""
10567
+ ].join(`
10568
+ `);
10569
+ }
10570
+ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
10571
+ return {
10572
+ CODEX_HOME: codexHome,
10573
+ [INKDOWN_PROVIDER_API_KEY_ENV]: apiKey
10574
+ };
10575
+ }
10576
+
10202
10577
  // src/runtimes/codex/codex-provider.ts
10203
10578
  var import_promises = require("node:fs/promises");
10204
- var import_node_fs2 = require("node:fs");
10205
- var import_node_path3 = require("node:path");
10579
+ var import_node_fs3 = require("node:fs");
10580
+ var import_node_path4 = require("node:path");
10206
10581
 
10207
10582
  // src/client/acp-paths.ts
10208
10583
  var import_node_os2 = require("node:os");
10209
- var import_node_path2 = require("node:path");
10584
+ var import_node_path3 = require("node:path");
10210
10585
  function getDefaultAgentDataDir() {
10211
10586
  if (process.env.INKDOWN_DATA_DIR) {
10212
10587
  return process.env.INKDOWN_DATA_DIR;
@@ -10215,24 +10590,24 @@ function getDefaultAgentDataDir() {
10215
10590
  return process.env.ACP_DATA_DIR;
10216
10591
  }
10217
10592
  if (process.platform === "win32") {
10218
- return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path2.join(import_node_os2.homedir(), "AppData", "Local", "inkdown");
10593
+ return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path3.join(import_node_os2.homedir(), "AppData", "Local", "inkdown");
10219
10594
  }
10220
10595
  if (process.platform === "darwin") {
10221
- return import_node_path2.join(import_node_os2.homedir(), "Library", "Application Support", "inkdown");
10596
+ return import_node_path3.join(import_node_os2.homedir(), "Library", "Application Support", "inkdown");
10222
10597
  }
10223
- return process.env.XDG_DATA_HOME || import_node_path2.join(import_node_os2.homedir(), ".local", "share", "inkdown");
10598
+ return process.env.XDG_DATA_HOME || import_node_path3.join(import_node_os2.homedir(), ".local", "share", "inkdown");
10224
10599
  }
10225
10600
 
10226
10601
  // src/runtimes/codex/codex-provider.ts
10227
10602
  function providerFilePath(dir) {
10228
- return import_node_path3.join(dir, "agent", "provider.json");
10603
+ return import_node_path4.join(dir, "agent", "provider.json");
10229
10604
  }
10230
10605
  function providerHomePath(dir) {
10231
- return import_node_path3.join(dir, "agent", "codex-home");
10606
+ return import_node_path4.join(dir, "agent", "codex-home");
10232
10607
  }
10233
10608
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
10234
10609
  const file = providerFilePath(dir);
10235
- if (!import_node_fs2.existsSync(file))
10610
+ if (!import_node_fs3.existsSync(file))
10236
10611
  return null;
10237
10612
  try {
10238
10613
  const raw = JSON.parse(await import_promises.readFile(file, "utf8"));
@@ -10258,7 +10633,7 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
10258
10633
  async function provisionCustomProviderCodexHome(provider, codexHome) {
10259
10634
  try {
10260
10635
  await import_promises2.mkdir(codexHome, { recursive: true });
10261
- await import_promises2.writeFile(import_node_path4.join(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
10636
+ await import_promises2.writeFile(import_node_path5.join(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
10262
10637
  return true;
10263
10638
  } catch (error) {
10264
10639
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -10267,6 +10642,7 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
10267
10642
  }
10268
10643
  var codexAdapter = {
10269
10644
  id: "codex-acp",
10645
+ probeQuota: async (options) => probeCodexQuota(options),
10270
10646
  probeAuth: () => {
10271
10647
  return probeCodexAuth();
10272
10648
  },
@@ -10283,20 +10659,122 @@ var codexAdapter = {
10283
10659
  }
10284
10660
  };
10285
10661
 
10286
- // src/runtimes/claude/index.ts
10287
- var import_node_fs3 = require("node:fs");
10662
+ // src/runtimes/claude/quota.ts
10663
+ var import_node_fs4 = require("node:fs");
10288
10664
  var import_node_os3 = require("node:os");
10289
- var import_node_path5 = require("node:path");
10665
+ var import_node_path6 = require("node:path");
10666
+ var import_node_child_process2 = require("node:child_process");
10667
+ var cachedClaudeAuth = null;
10668
+ async function queryClaudeAuthStatus(timeoutMs = 1200) {
10669
+ if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
10670
+ return cachedClaudeAuth.res;
10671
+ }
10672
+ return new Promise((resolve) => {
10673
+ try {
10674
+ import_node_child_process2.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
10675
+ if (!stdout)
10676
+ return resolve(null);
10677
+ try {
10678
+ const data = JSON.parse(stdout.trim());
10679
+ cachedClaudeAuth = { res: data, time: Date.now() };
10680
+ resolve(data);
10681
+ } catch {
10682
+ resolve(null);
10683
+ }
10684
+ });
10685
+ } catch {
10686
+ resolve(null);
10687
+ }
10688
+ });
10689
+ }
10690
+ async function probeClaudeQuota(options) {
10691
+ const claudeHome = resolveClaudeHome();
10692
+ const claudeJsonPath = import_node_path6.join(import_node_os3.homedir(), ".claude.json");
10693
+ const credsPath = import_node_path6.join(claudeHome, ".credentials.json");
10694
+ let isLoggedIn = false;
10695
+ let isBanned = false;
10696
+ let accountEmail;
10697
+ let plan = "Claude Free / Default";
10698
+ if (import_node_fs4.existsSync(claudeJsonPath)) {
10699
+ try {
10700
+ const data = JSON.parse(import_node_fs4.readFileSync(claudeJsonPath, "utf8"));
10701
+ if (data.oauthAccount) {
10702
+ isLoggedIn = true;
10703
+ accountEmail = data.oauthAccount.emailAddress;
10704
+ plan = data.oauthAccount.subscriptionTier || "Claude Pro";
10705
+ }
10706
+ if (data.isBanned || data.accountSuspended || data.status === "banned") {
10707
+ isBanned = true;
10708
+ }
10709
+ } catch {}
10710
+ }
10711
+ if (import_node_fs4.existsSync(credsPath)) {
10712
+ try {
10713
+ const creds = JSON.parse(import_node_fs4.readFileSync(credsPath, "utf8"));
10714
+ if (creds.accessToken || creds.sessionKey)
10715
+ isLoggedIn = true;
10716
+ } catch {}
10717
+ }
10718
+ if (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN) {
10719
+ isLoggedIn = true;
10720
+ plan = "API Key (Env)";
10721
+ }
10722
+ const dynamic = await queryClaudeAuthStatus(1200);
10723
+ if (dynamic) {
10724
+ if (dynamic.loggedIn)
10725
+ isLoggedIn = true;
10726
+ if (dynamic.email)
10727
+ accountEmail = dynamic.email;
10728
+ if (dynamic.subscriptionType)
10729
+ plan = dynamic.subscriptionType;
10730
+ else if (dynamic.plan)
10731
+ plan = dynamic.plan;
10732
+ }
10733
+ if (isBanned) {
10734
+ return {
10735
+ runtimeId: "claude",
10736
+ provider: "Anthropic / Claude Code",
10737
+ status: "banned",
10738
+ message: "账号已被封禁或暂停使用 (Account suspended / banned)",
10739
+ updatedAt: Date.now()
10740
+ };
10741
+ }
10742
+ if (!isLoggedIn) {
10743
+ return {
10744
+ runtimeId: "claude",
10745
+ provider: "Anthropic / Claude Code",
10746
+ status: "unauthorized",
10747
+ message: "未登录 Claude Code 或凭据无效 (Unauthorized)",
10748
+ updatedAt: Date.now()
10749
+ };
10750
+ }
10751
+ return {
10752
+ runtimeId: "claude",
10753
+ provider: "Anthropic / Claude Code",
10754
+ account: {
10755
+ email: accountEmail,
10756
+ plan,
10757
+ type: dynamic?.authMethod || "oauth"
10758
+ },
10759
+ status: "ok",
10760
+ updatedAt: Date.now()
10761
+ };
10762
+ }
10763
+
10764
+ // src/runtimes/claude/index.ts
10765
+ var import_node_fs5 = require("node:fs");
10766
+ var import_node_os4 = require("node:os");
10767
+ var import_node_path7 = require("node:path");
10290
10768
  function resolveClaudeHome() {
10291
10769
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
10292
10770
  if (fromEnv)
10293
10771
  return fromEnv;
10294
- return import_node_path5.join(import_node_os3.homedir(), ".claude");
10772
+ return import_node_path7.join(import_node_os4.homedir(), ".claude");
10295
10773
  }
10296
10774
  function probeClaudeAuth() {
10297
10775
  const claudeHome = resolveClaudeHome();
10298
- const hasCodexHome = import_node_fs3.existsSync(claudeHome);
10299
- 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"));
10776
+ const hasCodexHome = import_node_fs5.existsSync(claudeHome);
10777
+ 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"));
10300
10778
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
10301
10779
  return {
10302
10780
  codexHome: claudeHome,
@@ -10309,21 +10787,22 @@ function probeClaudeAuth() {
10309
10787
  var claudeAdapter = {
10310
10788
  id: "claude",
10311
10789
  probeAuth: () => probeClaudeAuth(),
10790
+ probeQuota: async (options) => probeClaudeQuota(options),
10312
10791
  orderAuthMethods: (methods) => methods,
10313
10792
  canSkipInteractiveAuth: () => false
10314
10793
  };
10315
10794
 
10316
10795
  // src/runtimes/gemini/index.ts
10317
- var import_node_fs4 = require("node:fs");
10318
- var import_node_os4 = require("node:os");
10319
- var import_node_path6 = require("node:path");
10796
+ var import_node_fs6 = require("node:fs");
10797
+ var import_node_os5 = require("node:os");
10798
+ var import_node_path8 = require("node:path");
10320
10799
  function resolveGeminiHome() {
10321
- return import_node_path6.join(import_node_os4.homedir(), ".gemini");
10800
+ return import_node_path8.join(import_node_os5.homedir(), ".gemini");
10322
10801
  }
10323
10802
  function probeGeminiAuth() {
10324
10803
  const geminiHome = resolveGeminiHome();
10325
- const hasCodexHome = import_node_fs4.existsSync(geminiHome);
10326
- const hasAuthFile = import_node_fs4.existsSync(import_node_path6.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
10804
+ const hasCodexHome = import_node_fs6.existsSync(geminiHome);
10805
+ const hasAuthFile = import_node_fs6.existsSync(import_node_path8.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
10327
10806
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
10328
10807
  return {
10329
10808
  codexHome: geminiHome,
@@ -10341,18 +10820,18 @@ var geminiAdapter = {
10341
10820
  };
10342
10821
 
10343
10822
  // src/runtimes/copilot/index.ts
10344
- var import_node_fs5 = require("node:fs");
10345
- var import_node_os5 = require("node:os");
10346
- var import_node_path7 = require("node:path");
10823
+ var import_node_fs7 = require("node:fs");
10824
+ var import_node_os6 = require("node:os");
10825
+ var import_node_path9 = require("node:path");
10347
10826
  function resolveCopilotHome() {
10348
10827
  const fromEnv = process.env.COPILOT_HOME?.trim();
10349
10828
  if (fromEnv)
10350
10829
  return fromEnv;
10351
- return import_node_path7.join(import_node_os5.homedir(), ".copilot");
10830
+ return import_node_path9.join(import_node_os6.homedir(), ".copilot");
10352
10831
  }
10353
10832
  function hasCopilotLogin(home) {
10354
10833
  try {
10355
- const raw = import_node_fs5.readFileSync(import_node_path7.join(home, "config.json"), "utf8");
10834
+ const raw = import_node_fs7.readFileSync(import_node_path9.join(home, "config.json"), "utf8");
10356
10835
  const parsed = JSON.parse(raw);
10357
10836
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
10358
10837
  } catch {
@@ -10361,7 +10840,7 @@ function hasCopilotLogin(home) {
10361
10840
  }
10362
10841
  function probeCopilotAuth() {
10363
10842
  const copilotHome = resolveCopilotHome();
10364
- const hasCodexHome = import_node_fs5.existsSync(copilotHome);
10843
+ const hasCodexHome = import_node_fs7.existsSync(copilotHome);
10365
10844
  const hasAuthFile = hasCopilotLogin(copilotHome);
10366
10845
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
10367
10846
  return {
@@ -10379,17 +10858,129 @@ var copilotAdapter = {
10379
10858
  canSkipInteractiveAuth: () => false
10380
10859
  };
10381
10860
 
10861
+ // src/runtimes/opencode/quota.ts
10862
+ var import_node_fs8 = require("node:fs");
10863
+ var import_node_child_process3 = require("node:child_process");
10864
+ function resolveOpencodeAuthPath() {
10865
+ const candidates = resolveOpencodeAuthCandidates();
10866
+ for (const c of candidates) {
10867
+ if (import_node_fs8.existsSync(c))
10868
+ return c;
10869
+ }
10870
+ return candidates[0] ?? null;
10871
+ }
10872
+ var cachedStats = null;
10873
+ async function queryOpencodeStats(timeoutMs = 1200) {
10874
+ if (cachedStats && Date.now() - cachedStats.time < 30000) {
10875
+ return cachedStats.res;
10876
+ }
10877
+ return new Promise((resolve) => {
10878
+ try {
10879
+ import_node_child_process3.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
10880
+ if (!stdout)
10881
+ return resolve(null);
10882
+ try {
10883
+ const data = JSON.parse(stdout.trim());
10884
+ cachedStats = { res: data, time: Date.now() };
10885
+ resolve(data);
10886
+ } catch {
10887
+ resolve(null);
10888
+ }
10889
+ });
10890
+ } catch {
10891
+ resolve(null);
10892
+ }
10893
+ });
10894
+ }
10895
+ async function queryOpencodeAuthList(timeoutMs = 1200) {
10896
+ return new Promise((resolve) => {
10897
+ try {
10898
+ import_node_child_process3.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
10899
+ if (!stdout)
10900
+ return resolve([]);
10901
+ const lines = stdout.split(`
10902
+ `).map((l) => l.trim()).filter((l) => l.includes("stored"));
10903
+ resolve(lines);
10904
+ });
10905
+ } catch {
10906
+ resolve([]);
10907
+ }
10908
+ });
10909
+ }
10910
+ async function probeOpencodeQuota(runtimeId = "opencode") {
10911
+ const authPath = resolveOpencodeAuthPath();
10912
+ let isLoggedIn = false;
10913
+ let accountEmail;
10914
+ let plan = "OpenCode Community";
10915
+ if (authPath && import_node_fs8.existsSync(authPath)) {
10916
+ try {
10917
+ const data = JSON.parse(import_node_fs8.readFileSync(authPath, "utf8"));
10918
+ if (data && typeof data === "object") {
10919
+ const keys = Object.keys(data);
10920
+ if (keys.length > 0) {
10921
+ isLoggedIn = true;
10922
+ if (data.email)
10923
+ accountEmail = String(data.email);
10924
+ if (data.plan)
10925
+ plan = String(data.plan);
10926
+ }
10927
+ }
10928
+ } catch {}
10929
+ }
10930
+ const [stats, authList] = await Promise.all([
10931
+ queryOpencodeStats(1200),
10932
+ queryOpencodeAuthList(1200)
10933
+ ]);
10934
+ if (authList.length > 0) {
10935
+ isLoggedIn = true;
10936
+ const providers = authList.map((l) => l.split(/\s{2,}/)[0]).filter(Boolean);
10937
+ if (providers.length > 0) {
10938
+ plan = `OpenCode (${providers.join(", ")})`;
10939
+ }
10940
+ }
10941
+ if (process.env.OPENCODE_API_KEY || process.env.OPENAI_API_KEY) {
10942
+ isLoggedIn = true;
10943
+ }
10944
+ if (!isLoggedIn) {
10945
+ return {
10946
+ runtimeId,
10947
+ provider: "OpenCode",
10948
+ status: "unauthorized",
10949
+ message: "未登录 OpenCode 或未配置 Provider (No stored credentials)",
10950
+ updatedAt: Date.now()
10951
+ };
10952
+ }
10953
+ let credits;
10954
+ if (stats && typeof stats.cost === "number") {
10955
+ credits = {
10956
+ balance: stats.cost > 0 ? `$${stats.cost.toFixed(2)} spent` : "0.00"
10957
+ };
10958
+ }
10959
+ return {
10960
+ runtimeId,
10961
+ provider: "OpenCode",
10962
+ account: {
10963
+ email: accountEmail,
10964
+ plan,
10965
+ type: "provider_oauth"
10966
+ },
10967
+ credits,
10968
+ status: "ok",
10969
+ updatedAt: Date.now()
10970
+ };
10971
+ }
10972
+
10382
10973
  // src/runtimes/opencode/index.ts
10383
- var import_node_fs6 = require("node:fs");
10384
- var import_node_os6 = require("node:os");
10385
- var import_node_path8 = require("node:path");
10974
+ var import_node_fs9 = require("node:fs");
10975
+ var import_node_os7 = require("node:os");
10976
+ var import_node_path10 = require("node:path");
10386
10977
  function pickEnv(env, key) {
10387
10978
  return env?.[key]?.trim() ?? "";
10388
10979
  }
10389
10980
  function resolveOpencodeAuthCandidates(overrides) {
10390
10981
  const platform = overrides?.platform ?? process.platform;
10391
10982
  const env = overrides?.env ?? process.env;
10392
- const home = overrides?.home ?? import_node_os6.homedir();
10983
+ const home = overrides?.home ?? import_node_os7.homedir();
10393
10984
  const seen = new Set;
10394
10985
  const out = [];
10395
10986
  const push = (p) => {
@@ -10400,27 +10991,27 @@ function resolveOpencodeAuthCandidates(overrides) {
10400
10991
  };
10401
10992
  const xdg = pickEnv(env, "XDG_DATA_HOME");
10402
10993
  if (xdg)
10403
- push(import_node_path8.join(xdg, "opencode", "auth.json"));
10994
+ push(import_node_path10.join(xdg, "opencode", "auth.json"));
10404
10995
  if (platform === "win32") {
10405
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path8.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
10996
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path10.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
10406
10997
  if (localAppData)
10407
- push(import_node_path8.join(localAppData, "opencode", "auth.json"));
10998
+ push(import_node_path10.join(localAppData, "opencode", "auth.json"));
10408
10999
  const userProfile = pickEnv(env, "USERPROFILE") || home;
10409
11000
  if (userProfile)
10410
- push(import_node_path8.join(userProfile, ".local", "share", "opencode", "auth.json"));
11001
+ push(import_node_path10.join(userProfile, ".local", "share", "opencode", "auth.json"));
10411
11002
  } else if (home) {
10412
- push(import_node_path8.join(home, ".local", "share", "opencode", "auth.json"));
11003
+ push(import_node_path10.join(home, ".local", "share", "opencode", "auth.json"));
10413
11004
  }
10414
11005
  return out;
10415
11006
  }
10416
11007
  function resolveOpencodeAuthFile() {
10417
- return resolveOpencodeAuthCandidates()[0] ?? import_node_path8.join(import_node_os6.homedir(), ".local", "share", "opencode", "auth.json");
11008
+ return resolveOpencodeAuthCandidates()[0] ?? import_node_path10.join(import_node_os7.homedir(), ".local", "share", "opencode", "auth.json");
10418
11009
  }
10419
11010
  function isValidOpencodeAuthFile(authFile) {
10420
11011
  try {
10421
- if (!authFile || !import_node_fs6.existsSync(authFile))
11012
+ if (!authFile || !import_node_fs9.existsSync(authFile))
10422
11013
  return false;
10423
- const raw = import_node_fs6.readFileSync(authFile, "utf8").trim();
11014
+ const raw = import_node_fs9.readFileSync(authFile, "utf8").trim();
10424
11015
  if (!raw)
10425
11016
  return false;
10426
11017
  const parsed = JSON.parse(raw);
@@ -10438,7 +11029,7 @@ function probeOpencodeAuth(overrides) {
10438
11029
  for (const candidate of candidates) {
10439
11030
  let exists = false;
10440
11031
  try {
10441
- exists = import_node_fs6.existsSync(candidate);
11032
+ exists = import_node_fs9.existsSync(candidate);
10442
11033
  } catch {
10443
11034
  exists = false;
10444
11035
  }
@@ -10451,10 +11042,10 @@ function probeOpencodeAuth(overrides) {
10451
11042
  validFile = candidate;
10452
11043
  }
10453
11044
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
10454
- const authDir = import_node_path8.dirname(authFile);
11045
+ const authDir = import_node_path10.dirname(authFile);
10455
11046
  let hasCodexHome = false;
10456
11047
  try {
10457
- hasCodexHome = import_node_fs6.existsSync(authDir);
11048
+ hasCodexHome = import_node_fs9.existsSync(authDir);
10458
11049
  } catch {
10459
11050
  hasCodexHome = false;
10460
11051
  }
@@ -10470,33 +11061,65 @@ function probeOpencodeAuth(overrides) {
10470
11061
  var opencodeAdapter = {
10471
11062
  id: "opencode",
10472
11063
  probeAuth: () => probeOpencodeAuth(),
11064
+ probeQuota: async () => probeOpencodeQuota(),
11065
+ orderAuthMethods: (methods) => methods,
11066
+ canSkipInteractiveAuth: () => false,
11067
+ tryDirectSessionFirst: true
11068
+ };
11069
+
11070
+ // src/runtimes/opencode-v2/index.ts
11071
+ var opencodeV2Adapter = {
11072
+ id: "opencode-v2",
11073
+ probeAuth: () => probeOpencodeAuth(),
10473
11074
  orderAuthMethods: (methods) => methods,
10474
11075
  canSkipInteractiveAuth: () => false,
10475
11076
  tryDirectSessionFirst: true
10476
11077
  };
10477
11078
 
11079
+ // src/runtimes/cursor/quota.ts
11080
+ async function probeCursorQuota() {
11081
+ const auth = probeCursorAuth();
11082
+ if (!auth.looksLoggedIn) {
11083
+ return {
11084
+ runtimeId: "cursor-cli",
11085
+ provider: "Cursor",
11086
+ status: "unauthorized",
11087
+ message: "未检测到 Cursor CLI 登录凭证",
11088
+ updatedAt: Date.now()
11089
+ };
11090
+ }
11091
+ return {
11092
+ runtimeId: "cursor-cli",
11093
+ provider: "Cursor",
11094
+ account: {
11095
+ plan: "Cursor Pro / Fast Requests"
11096
+ },
11097
+ status: "ok",
11098
+ updatedAt: Date.now()
11099
+ };
11100
+ }
10478
11101
  // src/runtimes/cursor/index.ts
10479
- var import_node_fs7 = require("node:fs");
10480
- var import_node_os7 = require("node:os");
10481
- var import_node_path9 = require("node:path");
11102
+ var import_node_fs10 = require("node:fs");
11103
+ var import_node_os8 = require("node:os");
11104
+ var import_node_path11 = require("node:path");
10482
11105
  function cursorLocalAppData(env) {
10483
11106
  const local = env.LOCALAPPDATA?.trim();
10484
11107
  if (local)
10485
11108
  return local;
10486
11109
  const profile = env.USERPROFILE?.trim();
10487
- return profile ? import_node_path9.join(profile, "AppData", "Local") : "";
11110
+ return profile ? import_node_path11.join(profile, "AppData", "Local") : "";
10488
11111
  }
10489
11112
  function isOnPath(command, env, platform) {
10490
11113
  const pathValue = env.PATH ?? env.Path ?? "";
10491
11114
  if (!pathValue.trim())
10492
11115
  return false;
10493
- const sep = platform === "win32" ? ";" : import_node_path9.delimiter;
11116
+ const sep = platform === "win32" ? ";" : import_node_path11.delimiter;
10494
11117
  for (const dir of pathValue.split(sep)) {
10495
11118
  const trimmed = dir.trim().replace(/^"|"$/g, "");
10496
11119
  if (!trimmed)
10497
11120
  continue;
10498
11121
  try {
10499
- if (import_node_fs7.existsSync(import_node_path9.join(trimmed, command)))
11122
+ if (import_node_fs10.existsSync(import_node_path11.join(trimmed, command)))
10500
11123
  return true;
10501
11124
  } catch {}
10502
11125
  }
@@ -10505,19 +11128,19 @@ function isOnPath(command, env, platform) {
10505
11128
  function resolveDirectCursorCommand(platform, env, home) {
10506
11129
  if (platform === "win32") {
10507
11130
  const localAppData = cursorLocalAppData(env);
10508
- return localAppData ? import_node_path9.join(localAppData, "cursor-agent", "agent.cmd") : "";
11131
+ return localAppData ? import_node_path11.join(localAppData, "cursor-agent", "agent.cmd") : "";
10509
11132
  }
10510
- return home ? import_node_path9.join(home, ".local", "bin", "agent") : "";
11133
+ return home ? import_node_path11.join(home, ".local", "bin", "agent") : "";
10511
11134
  }
10512
11135
  function resolveCursorSpawnCommand(overrides) {
10513
11136
  const args = ["acp"];
10514
11137
  const platform = overrides?.platform ?? process.platform;
10515
11138
  const env = overrides?.env ?? process.env;
10516
- const home = overrides?.home ?? import_node_os7.homedir();
11139
+ const home = overrides?.home ?? import_node_os8.homedir();
10517
11140
  const binary = platform === "win32" ? "agent.cmd" : "agent";
10518
11141
  const direct = resolveDirectCursorCommand(platform, env, home);
10519
11142
  try {
10520
- if (direct && import_node_fs7.existsSync(direct))
11143
+ if (direct && import_node_fs10.existsSync(direct))
10521
11144
  return { command: direct, args };
10522
11145
  } catch {}
10523
11146
  if (isOnPath(binary, env, platform))
@@ -10532,12 +11155,12 @@ function cursorRoamingAppData(env, home) {
10532
11155
  if (roaming)
10533
11156
  return roaming;
10534
11157
  const profile = pickEnv2(env, "USERPROFILE") || home;
10535
- return profile ? import_node_path9.join(profile, "AppData", "Roaming") : "";
11158
+ return profile ? import_node_path11.join(profile, "AppData", "Roaming") : "";
10536
11159
  }
10537
11160
  function resolveCursorAuthCandidates(overrides) {
10538
11161
  const platform = overrides?.platform ?? process.platform;
10539
11162
  const env = overrides?.env ?? process.env;
10540
- const home = overrides?.home ?? import_node_os7.homedir();
11163
+ const home = overrides?.home ?? import_node_os8.homedir();
10541
11164
  const seen = new Set;
10542
11165
  const out = [];
10543
11166
  const push = (p) => {
@@ -10548,16 +11171,16 @@ function resolveCursorAuthCandidates(overrides) {
10548
11171
  };
10549
11172
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
10550
11173
  if (xdg)
10551
- push(import_node_path9.join(xdg, "cursor", "auth.json"));
11174
+ push(import_node_path11.join(xdg, "cursor", "auth.json"));
10552
11175
  if (platform === "win32") {
10553
11176
  const profile = pickEnv2(env, "USERPROFILE") || home;
10554
11177
  if (profile)
10555
- push(import_node_path9.join(profile, ".config", "cursor", "auth.json"));
11178
+ push(import_node_path11.join(profile, ".config", "cursor", "auth.json"));
10556
11179
  const roaming = cursorRoamingAppData(env, home);
10557
11180
  if (roaming)
10558
- push(import_node_path9.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
11181
+ push(import_node_path11.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
10559
11182
  } else if (home) {
10560
- push(import_node_path9.join(home, ".config", "cursor", "auth.json"));
11183
+ push(import_node_path11.join(home, ".config", "cursor", "auth.json"));
10561
11184
  }
10562
11185
  return out;
10563
11186
  }
@@ -10568,9 +11191,9 @@ function isValidCursorAuthFile(authFile) {
10568
11191
  try {
10569
11192
  if (!authFile || isStorageHintPath(authFile))
10570
11193
  return false;
10571
- if (!import_node_fs7.existsSync(authFile))
11194
+ if (!import_node_fs10.existsSync(authFile))
10572
11195
  return false;
10573
- const raw = import_node_fs7.readFileSync(authFile, "utf8").trim();
11196
+ const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
10574
11197
  if (!raw)
10575
11198
  return false;
10576
11199
  const parsed = JSON.parse(raw);
@@ -10588,9 +11211,9 @@ function isHintCursorStorageFile(authFile) {
10588
11211
  try {
10589
11212
  if (!authFile || !isStorageHintPath(authFile))
10590
11213
  return false;
10591
- if (!import_node_fs7.existsSync(authFile))
11214
+ if (!import_node_fs10.existsSync(authFile))
10592
11215
  return false;
10593
- const raw = import_node_fs7.readFileSync(authFile, "utf8").trim();
11216
+ const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
10594
11217
  if (!raw)
10595
11218
  return false;
10596
11219
  const parsed = JSON.parse(raw);
@@ -10606,7 +11229,7 @@ function isValidCursorCandidate(authFile) {
10606
11229
  }
10607
11230
  function probeCursorAuth(overrides) {
10608
11231
  const env = overrides?.env ?? process.env;
10609
- const home = overrides?.home ?? import_node_os7.homedir();
11232
+ const home = overrides?.home ?? import_node_os8.homedir();
10610
11233
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
10611
11234
  const candidates = resolveCursorAuthCandidates(overrides);
10612
11235
  let firstExisting = null;
@@ -10614,7 +11237,7 @@ function probeCursorAuth(overrides) {
10614
11237
  for (const candidate of candidates) {
10615
11238
  let exists = false;
10616
11239
  try {
10617
- exists = import_node_fs7.existsSync(candidate);
11240
+ exists = import_node_fs10.existsSync(candidate);
10618
11241
  } catch {
10619
11242
  exists = false;
10620
11243
  }
@@ -10626,12 +11249,12 @@ function probeCursorAuth(overrides) {
10626
11249
  if (isValidCursorCandidate(candidate))
10627
11250
  validFile = candidate;
10628
11251
  }
10629
- const fallback = home ? import_node_path9.join(home, ".config", "cursor", "auth.json") : "";
11252
+ const fallback = home ? import_node_path11.join(home, ".config", "cursor", "auth.json") : "";
10630
11253
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
10631
- const authDir = authFile ? import_node_path9.dirname(authFile) : "";
11254
+ const authDir = authFile ? import_node_path11.dirname(authFile) : "";
10632
11255
  let hasCodexHome = false;
10633
11256
  try {
10634
- hasCodexHome = authDir ? import_node_fs7.existsSync(authDir) : false;
11257
+ hasCodexHome = authDir ? import_node_fs10.existsSync(authDir) : false;
10635
11258
  } catch {
10636
11259
  hasCodexHome = false;
10637
11260
  }
@@ -10646,6 +11269,7 @@ function probeCursorAuth(overrides) {
10646
11269
  var cursorAdapter = {
10647
11270
  id: "cursor-cli",
10648
11271
  probeAuth: () => probeCursorAuth(),
11272
+ probeQuota: async () => probeCursorQuota(),
10649
11273
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
10650
11274
  orderAuthMethods: (methods) => methods,
10651
11275
  canSkipInteractiveAuth: () => false,
@@ -10699,6 +11323,55 @@ var deepseekAdapter = {
10699
11323
  canSkipInteractiveAuth: () => false
10700
11324
  };
10701
11325
 
11326
+ // src/runtimes/agy/quota.ts
11327
+ var import_node_fs11 = require("node:fs");
11328
+ var import_node_path12 = require("node:path");
11329
+ function resolveGeminiHome2() {
11330
+ const home = process.env.USERPROFILE || process.env.HOME || "";
11331
+ return import_node_path12.join(home, ".gemini");
11332
+ }
11333
+ async function probeAgyQuota(options) {
11334
+ const geminiHome = resolveGeminiHome2();
11335
+ const hasAgyDir = import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity")) || import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity-cli"));
11336
+ const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
11337
+ const isAvailable = hasAgyDir || hasApiKey;
11338
+ if (!isAvailable) {
11339
+ return {
11340
+ runtimeId: "agy",
11341
+ provider: "Google Antigravity",
11342
+ status: "unauthorized",
11343
+ message: "wenjianlingu antigravity cli",
11344
+ updatedAt: Date.now()
11345
+ };
11346
+ }
11347
+ return {
11348
+ runtimeId: "agy",
11349
+ provider: "Google Antigravity",
11350
+ account: {
11351
+ plan: "Antigravity / Gemini",
11352
+ type: "gemini"
11353
+ },
11354
+ primaryWindow: {
11355
+ label: "5-Hour limit",
11356
+ percentLeft: 100,
11357
+ usedPercent: 0,
11358
+ windowDurationMins: 300
11359
+ },
11360
+ secondaryWindow: {
11361
+ label: "Weekly limit",
11362
+ percentLeft: 100,
11363
+ usedPercent: 0,
11364
+ windowDurationMins: 10080
11365
+ },
11366
+ credits: {
11367
+ unlimited: true,
11368
+ balance: "unlimited"
11369
+ },
11370
+ status: "ok",
11371
+ updatedAt: Date.now()
11372
+ };
11373
+ }
11374
+
10702
11375
  // src/runtimes/agy/index.ts
10703
11376
  function probeAgyAuth() {
10704
11377
  return {
@@ -10712,6 +11385,7 @@ function probeAgyAuth() {
10712
11385
  var agyAdapter = {
10713
11386
  id: "agy",
10714
11387
  probeAuth: () => probeAgyAuth(),
11388
+ probeQuota: (options) => probeAgyQuota(options),
10715
11389
  orderAuthMethods: (methods) => methods,
10716
11390
  canSkipInteractiveAuth: () => false,
10717
11391
  tryDirectSessionFirst: true
@@ -10731,6 +11405,8 @@ function getAcpRuntimeAdapter(runtimeId) {
10731
11405
  return copilotAdapter;
10732
11406
  case opencodeAdapter.id:
10733
11407
  return opencodeAdapter;
11408
+ case opencodeV2Adapter.id:
11409
+ return opencodeV2Adapter;
10734
11410
  case cursorAdapter.id:
10735
11411
  case "cursor":
10736
11412
  return cursorAdapter;
@@ -10747,7 +11423,7 @@ function getAcpRuntimeAdapter(runtimeId) {
10747
11423
  }
10748
11424
 
10749
11425
  // src/process/process-manager.ts
10750
- var import_node_child_process = require("node:child_process");
11426
+ var import_node_child_process4 = require("node:child_process");
10751
11427
  var active = new Map;
10752
11428
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
10753
11429
  function isSpawnedAcpProcessAlive(handle) {
@@ -10758,7 +11434,7 @@ function killProcessTree(pid) {
10758
11434
  if (process.platform !== "win32")
10759
11435
  return;
10760
11436
  try {
10761
- import_node_child_process.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
11437
+ import_node_child_process4.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
10762
11438
  windowsHide: true,
10763
11439
  timeout: 8000
10764
11440
  });
@@ -10801,7 +11477,7 @@ function spawnAcpProcess(options) {
10801
11477
  } else {
10802
11478
  delete env.NO_BROWSER;
10803
11479
  }
10804
- const child = import_node_child_process.spawn(file, options.runtime.args, {
11480
+ const child = import_node_child_process4.spawn(file, options.runtime.args, {
10805
11481
  cwd: options.cwd,
10806
11482
  env,
10807
11483
  stdio: ["pipe", "pipe", "pipe"],
@@ -10937,17 +11613,17 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
10937
11613
 
10938
11614
  // src/client/acp-fs.ts
10939
11615
  var import_promises3 = require("node:fs/promises");
10940
- var import_node_path10 = require("node:path");
11616
+ var import_node_path13 = require("node:path");
10941
11617
  var import_promises4 = require("node:fs/promises");
10942
11618
  var MAX_READ_BYTES = 2 * 1024 * 1024;
10943
11619
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
10944
11620
  function isBinaryDocumentPath(filePath) {
10945
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path10.extname(filePath).toLowerCase());
11621
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path13.extname(filePath).toLowerCase());
10946
11622
  }
10947
11623
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
10948
- const root = import_node_path10.resolve(workspaceRoot);
10949
- const target = import_node_path10.resolve(filePath);
10950
- const rootWithSep = root.endsWith(import_node_path10.sep) ? root : root + import_node_path10.sep;
11624
+ const root = import_node_path13.resolve(workspaceRoot);
11625
+ const target = import_node_path13.resolve(filePath);
11626
+ const rootWithSep = root.endsWith(import_node_path13.sep) ? root : root + import_node_path13.sep;
10951
11627
  if (target !== root && !target.startsWith(rootWithSep)) {
10952
11628
  throw new Error(`路径不在工作区内: ${filePath}`);
10953
11629
  }
@@ -10978,7 +11654,7 @@ async function acpReadTextFile(params) {
10978
11654
  }
10979
11655
  async function acpWriteTextFile(params) {
10980
11656
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
10981
- await import_promises4.mkdir(import_node_path10.dirname(abs), { recursive: true });
11657
+ await import_promises4.mkdir(import_node_path13.dirname(abs), { recursive: true });
10982
11658
  await import_promises3.writeFile(abs, params.content, "utf-8");
10983
11659
  return {};
10984
11660
  }
@@ -11438,7 +12114,7 @@ async function restoreOrCreateAcpSession(input) {
11438
12114
  }
11439
12115
 
11440
12116
  // src/client/acp-terminal.ts
11441
- var import_node_child_process2 = require("node:child_process");
12117
+ var import_node_child_process5 = require("node:child_process");
11442
12118
  var import_node_crypto = require("node:crypto");
11443
12119
 
11444
12120
  // src/transport/terminal-output-buffer.ts
@@ -11491,7 +12167,7 @@ class AcpTerminalManager {
11491
12167
  throw new Error("terminal/create 需要 command");
11492
12168
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
11493
12169
  const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
11494
- const child = import_node_child_process2.spawn(command, params.args ?? [], {
12170
+ const child = import_node_child_process5.spawn(command, params.args ?? [], {
11495
12171
  cwd,
11496
12172
  env: buildEnv(params.env),
11497
12173
  windowsHide: true,
@@ -11587,7 +12263,7 @@ class AcpTerminalManager {
11587
12263
  return;
11588
12264
  if (process.platform === "win32") {
11589
12265
  try {
11590
- import_node_child_process2.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
12266
+ import_node_child_process5.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
11591
12267
  windowsHide: true,
11592
12268
  stdio: "ignore"
11593
12269
  });
@@ -11623,8 +12299,8 @@ class AcpTerminalManager {
11623
12299
 
11624
12300
  // src/client/acp-proxy-service.ts
11625
12301
  var import_promises5 = require("node:fs/promises");
11626
- var import_node_fs8 = require("node:fs");
11627
- var import_node_path11 = require("node:path");
12302
+ var import_node_fs12 = require("node:fs");
12303
+ var import_node_path14 = require("node:path");
11628
12304
  var DEFAULT_ACP_PROXY_SETTINGS = {
11629
12305
  enabled: false,
11630
12306
  host: "127.0.0.1",
@@ -11633,11 +12309,11 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
11633
12309
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
11634
12310
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
11635
12311
  function proxyFilePath(dir) {
11636
- return import_node_path11.join(dir, "agent", "proxy.json");
12312
+ return import_node_path14.join(dir, "agent", "proxy.json");
11637
12313
  }
11638
12314
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
11639
12315
  const file = proxyFilePath(dir);
11640
- if (!import_node_fs8.existsSync(file))
12316
+ if (!import_node_fs12.existsSync(file))
11641
12317
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
11642
12318
  try {
11643
12319
  const raw = JSON.parse(await import_promises5.readFile(file, "utf8"));
@@ -11700,6 +12376,12 @@ class AcpSessionHandle {
11700
12376
  async prompt(promptText, options) {
11701
12377
  return this.client.promptSession(this.sessionId, promptText, options);
11702
12378
  }
12379
+ get quota() {
12380
+ return this.client.getCachedQuota(this.sessionId);
12381
+ }
12382
+ async getQuota() {
12383
+ return this.client.getQuota(this.sessionId);
12384
+ }
11703
12385
  get availableCommands() {
11704
12386
  return this.client.getAvailableCommands(this.sessionId);
11705
12387
  }
@@ -11711,6 +12393,7 @@ class AcpSessionHandle {
11711
12393
  class AcpClient {
11712
12394
  status = "disconnected";
11713
12395
  commandsCache = new AvailableCommandsCache;
12396
+ quotaCache = new QuotaCache;
11714
12397
  runtimeInfo;
11715
12398
  adapter;
11716
12399
  workspaceRoot;
@@ -11821,6 +12504,7 @@ class AcpClient {
11821
12504
  },
11822
12505
  onSessionUpdate: (params) => {
11823
12506
  this.commandsCache.observe(params);
12507
+ this.quotaCache.observe(params, this.runtimeInfo.id);
11824
12508
  this.callbacks.onSessionUpdate?.(params);
11825
12509
  }
11826
12510
  };
@@ -11851,6 +12535,23 @@ class AcpClient {
11851
12535
  return err({ code: "ACP_PROTOCOL_ERROR", message });
11852
12536
  }
11853
12537
  }
12538
+ getCachedQuota(sessionId) {
12539
+ return this.quotaCache.get(sessionId, this.runtimeInfo.id);
12540
+ }
12541
+ async getQuota(sessionId) {
12542
+ const cached = this.getCachedQuota(sessionId);
12543
+ if (cached && Date.now() - cached.updatedAt < 30000) {
12544
+ return cached;
12545
+ }
12546
+ if (this.adapter.probeQuota) {
12547
+ const probed = await this.adapter.probeQuota({ sessionId });
12548
+ if (probed) {
12549
+ this.quotaCache.set(probed, sessionId);
12550
+ return probed;
12551
+ }
12552
+ }
12553
+ return cached ?? null;
12554
+ }
11854
12555
  getAvailableCommands(sessionId) {
11855
12556
  return this.commandsCache.get(sessionId);
11856
12557
  }
@@ -12678,6 +13379,20 @@ async function handleRpcRequest(id, method, params) {
12678
13379
  }
12679
13380
  break;
12680
13381
  }
13382
+ case "session/quota": {
13383
+ const { sessionId } = params ?? {};
13384
+ if (!client2) {
13385
+ sendError(id, -32002, "Client not connected");
13386
+ return;
13387
+ }
13388
+ try {
13389
+ const quota = await client2.getQuota(sessionId ? String(sessionId) : undefined);
13390
+ sendResponse(id, { sessionId, quota });
13391
+ } catch (err) {
13392
+ sendError(id, -32000, err instanceof Error ? err.message : String(err));
13393
+ }
13394
+ break;
13395
+ }
12681
13396
  case "session/commands": {
12682
13397
  const { sessionId } = params ?? {};
12683
13398
  if (!client2) {
@@ -12734,7 +13449,7 @@ async function handleRpcRequest(id, method, params) {
12734
13449
  }
12735
13450
  }
12736
13451
  function startSidecar() {
12737
- const rl = readline.createInterface({
13452
+ const rl = readline2.createInterface({
12738
13453
  input: process.stdin,
12739
13454
  terminal: false
12740
13455
  });