@yitom/acp-client 0.1.12 → 0.1.13

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
@@ -36,7 +36,7 @@ var __toESM = (mod, isNodeMode, target) => {
36
36
  var readline2 = __toESM(require("node:readline"), 1);
37
37
 
38
38
  // src/version.ts
39
- var ACP_CLIENT_VERSION = "0.1.12";
39
+ var ACP_CLIENT_VERSION = "0.1.13";
40
40
  // src/contracts/index.ts
41
41
  function ok(value) {
42
42
  return { ok: true, value };
@@ -156,8 +156,8 @@ var BUILTIN_ACP_RUNTIMES = [
156
156
  {
157
157
  id: "deepseek",
158
158
  name: "DeepSeek",
159
- description: "通过 bunx 启动 @deepseek-ai/dsh(--profile acp);无 ACP 登录,靠 harness 自身凭证(DEEPSEEK_API_KEY / harness 配置);模型经 session 到达,无需额外动作",
160
- authHint: "无 ACP 登录,靠 harness 自身凭证(DEEPSEEK_API_KEY / harness 配置);未配置先导出 DEEPSEEK_API_KEY;模型经 session 到达,无需额外动作;若官方最新 dsh 存在坏依赖(如 rc.3 缺失),可设 DSH_PACKAGE pin 旧版",
159
+ description: "通过 dsh 启动 @deepseek-ai/dsh(--profile acp);无 ACP 登录,靠 harness 自身凭证(DEEPSEEK_API_KEY 或 $DSH_HOME/.credentials.yaml);模型经 session 到达(V4.1-Flash 的 id 是 deepseek-flash)",
160
+ authHint: "无 ACP 登录,靠 harness 自身凭证;先导出 DEEPSEEK_API_KEY 或在 dsh 里完成登录;稳定安装可设 DSH_BIN 指向 dsh 入口(bunx 临时目录被清理会让 profile 断链);pin 包版本用 DSH_PACKAGE(如 @deepseek-ai/dsh@0.2.1-rc.2)",
161
161
  command: "bunx",
162
162
  args: ["-y", `${DEEPSEEK_DSH_NPM_PACKAGE}@latest`, "--profile", "acp"],
163
163
  requiredEnvKeys: ["DEEPSEEK_API_KEY"]
@@ -10317,11 +10317,24 @@ function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
10317
10317
  class QuotaCache {
10318
10318
  bySession = new Map;
10319
10319
  byRuntime = new Map;
10320
+ usageBySession = new Map;
10321
+ usageByRuntime = new Map;
10320
10322
  observe(params, defaultRuntimeId = "unknown") {
10321
10323
  if (!params || typeof params !== "object")
10322
10324
  return null;
10323
10325
  const p = params;
10324
10326
  const sessionId = typeof p.sessionId === "string" ? p.sessionId : undefined;
10327
+ if (p.update?.sessionUpdate === "usage_update") {
10328
+ const used = Number(p.update.used);
10329
+ const size = Number(p.update.size);
10330
+ if (Number.isFinite(used) && Number.isFinite(size) && size > 0) {
10331
+ const usage = { used, size, updatedAt: Date.now() };
10332
+ if (sessionId)
10333
+ this.usageBySession.set(sessionId, usage);
10334
+ this.usageByRuntime.set(defaultRuntimeId, usage);
10335
+ }
10336
+ return null;
10337
+ }
10325
10338
  let textToParse = "";
10326
10339
  if (p.update?.content && p.update.content.type === "text" && typeof p.update.content.text === "string") {
10327
10340
  textToParse = p.update.content.text;
@@ -10357,9 +10370,29 @@ class QuotaCache {
10357
10370
  }
10358
10371
  return;
10359
10372
  }
10373
+ applyContextUsage(quota, sessionId, runtimeId = "unknown") {
10374
+ const usage = (sessionId ? this.usageBySession.get(sessionId) : undefined) ?? this.usageByRuntime.get(runtimeId);
10375
+ if (!usage)
10376
+ return quota ?? null;
10377
+ const usedPercent = usage.size > 0 ? Math.min(100, Math.round(usage.used / usage.size * 100)) : 0;
10378
+ const window = {
10379
+ label: "Context",
10380
+ used: usage.used,
10381
+ total: usage.size,
10382
+ usedPercent,
10383
+ percentLeft: Math.max(0, 100 - usedPercent)
10384
+ };
10385
+ if (!quota) {
10386
+ return { runtimeId, primaryWindow: window, status: "ok", updatedAt: usage.updatedAt };
10387
+ }
10388
+ const rest = (quota.extraWindows ?? []).filter((item) => item.label !== "Context");
10389
+ return { ...quota, extraWindows: [window, ...rest] };
10390
+ }
10360
10391
  clear() {
10361
10392
  this.bySession.clear();
10362
10393
  this.byRuntime.clear();
10394
+ this.usageBySession.clear();
10395
+ this.usageByRuntime.clear();
10363
10396
  }
10364
10397
  }
10365
10398
 
@@ -11774,14 +11807,326 @@ var cursorAdapter = {
11774
11807
  tryDirectSessionFirst: true
11775
11808
  };
11776
11809
 
11810
+ // src/runtimes/deepseek/index.ts
11811
+ var import_node_fs16 = require("node:fs");
11812
+
11813
+ // src/runtimes/deepseek/deepseek-provider.ts
11814
+ var import_node_fs14 = require("node:fs");
11815
+ var import_node_os11 = require("node:os");
11816
+ var import_node_path15 = require("node:path");
11817
+ var DEEPSEEK_OFFICIAL_BASE_URL = "https://api.deepseek.com/anthropic";
11818
+ function resolveDshHome(env = process.env) {
11819
+ const override = env.DSH_HOME?.trim();
11820
+ return override || import_node_path15.join(import_node_os11.homedir(), ".dsh");
11821
+ }
11822
+ function resolveDshCredentialsFile(env = process.env) {
11823
+ return import_node_path15.join(resolveDshHome(env), ".credentials.yaml");
11824
+ }
11825
+ function escapeRegExp(value) {
11826
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11827
+ }
11828
+ function readHarnessCredential(name, env = process.env) {
11829
+ try {
11830
+ const text = import_node_fs14.readFileSync(resolveDshCredentialsFile(env), "utf8");
11831
+ const pattern = new RegExp(`^\\s+${escapeRegExp(name)}\\s*:\\s*(.+)$`);
11832
+ let inRefs = false;
11833
+ for (const line of text.split(/\r?\n/)) {
11834
+ if (/^refs\s*:/.test(line)) {
11835
+ inRefs = true;
11836
+ continue;
11837
+ }
11838
+ if (!inRefs)
11839
+ continue;
11840
+ if (/^\S/.test(line))
11841
+ break;
11842
+ const match = pattern.exec(line);
11843
+ if (match) {
11844
+ const value = match[1].trim().replace(/^['"]|['"]$/g, "");
11845
+ return value || null;
11846
+ }
11847
+ }
11848
+ return null;
11849
+ } catch {
11850
+ return null;
11851
+ }
11852
+ }
11853
+ function normalizeDeepseekBaseUrl(raw) {
11854
+ const trimmed = (raw ?? "").trim();
11855
+ if (!trimmed)
11856
+ return DEEPSEEK_OFFICIAL_BASE_URL;
11857
+ const withoutSlash = trimmed.replace(/\/+$/, "");
11858
+ try {
11859
+ const url = new URL(withoutSlash);
11860
+ if (url.host.toLowerCase() === "api.deepseek.com" && (url.pathname === "" || url.pathname === "/")) {
11861
+ return DEEPSEEK_OFFICIAL_BASE_URL;
11862
+ }
11863
+ return withoutSlash;
11864
+ } catch {
11865
+ return withoutSlash;
11866
+ }
11867
+ }
11868
+ function providerFilePath2(dir) {
11869
+ return import_node_path15.join(dir, "agent", "deepseek-provider.json");
11870
+ }
11871
+ function readStoredDeepseekProvider(dir = getDefaultAgentDataDir()) {
11872
+ const file = providerFilePath2(dir);
11873
+ if (!import_node_fs14.existsSync(file))
11874
+ return null;
11875
+ try {
11876
+ const raw = JSON.parse(import_node_fs14.readFileSync(file, "utf8"));
11877
+ if (typeof raw.baseUrl !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
11878
+ return null;
11879
+ }
11880
+ return { baseUrl: normalizeDeepseekBaseUrl(raw.baseUrl), apiKey: raw.apiKey };
11881
+ } catch {
11882
+ return null;
11883
+ }
11884
+ }
11885
+ function buildDeepseekProviderEnv(stored, currentEnv = process.env) {
11886
+ if (!stored)
11887
+ return {};
11888
+ const env = {};
11889
+ if (!currentEnv.DEEPSEEK_BASE_URL?.trim())
11890
+ env.DEEPSEEK_BASE_URL = stored.baseUrl;
11891
+ if (!currentEnv.DEEPSEEK_API_KEY?.trim())
11892
+ env.DEEPSEEK_API_KEY = stored.apiKey;
11893
+ return env;
11894
+ }
11895
+
11896
+ // src/runtimes/deepseek/dsh-acp-bootstrap.ts
11897
+ var import_node_fs15 = require("node:fs");
11898
+ var import_node_os12 = require("node:os");
11899
+ var import_node_path16 = require("node:path");
11900
+ var DSH_ACP_PINNED_VERSION = "0.2.1-rc.2";
11901
+ var DSH_ACP_DEFAULT_MODEL = "deepseek-flash";
11902
+ var DSH_ACP_DEFAULT_PROVIDER = "deepseek-official";
11903
+ function resolveDshRuntimeRoot(env = process.env) {
11904
+ const override = env.DSH_RUNTIME_DIR?.trim();
11905
+ if (override)
11906
+ return override;
11907
+ if (process.platform === "win32") {
11908
+ const localAppData = env.LOCALAPPDATA?.trim() || import_node_path16.join(import_node_os12.homedir(), "AppData", "Local");
11909
+ return import_node_path16.join(localAppData, "acp-dsh");
11910
+ }
11911
+ if (process.platform === "darwin") {
11912
+ return import_node_path16.join(import_node_os12.homedir(), "Library", "Application Support", "acp-dsh");
11913
+ }
11914
+ const dataHome = env.XDG_DATA_HOME?.trim() || import_node_path16.join(import_node_os12.homedir(), ".local", "share");
11915
+ return import_node_path16.join(dataHome, "acp-dsh");
11916
+ }
11917
+ function resolveManagedDshEntry(env = process.env, version = resolveManagedDshVersion(env)) {
11918
+ return import_node_path16.join(resolveDshRuntimeRoot(env), version, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js");
11919
+ }
11920
+ function parseVersion(value) {
11921
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(value);
11922
+ if (!match)
11923
+ return null;
11924
+ return {
11925
+ nums: [Number(match[1]), Number(match[2]), Number(match[3])],
11926
+ pre: match[4] ? match[4].split(".") : []
11927
+ };
11928
+ }
11929
+ function compareDshVersions(a, b) {
11930
+ const left = parseVersion(a);
11931
+ const right = parseVersion(b);
11932
+ if (!left || !right)
11933
+ return a.localeCompare(b);
11934
+ for (let i = 0;i < 3; i += 1) {
11935
+ if (left.nums[i] !== right.nums[i])
11936
+ return left.nums[i] - right.nums[i];
11937
+ }
11938
+ if (left.pre.length === 0 && right.pre.length > 0)
11939
+ return 1;
11940
+ if (left.pre.length > 0 && right.pre.length === 0)
11941
+ return -1;
11942
+ for (let i = 0;i < Math.max(left.pre.length, right.pre.length); i += 1) {
11943
+ const x = left.pre[i];
11944
+ const y = right.pre[i];
11945
+ if (x === undefined)
11946
+ return -1;
11947
+ if (y === undefined)
11948
+ return 1;
11949
+ const nx = Number(x);
11950
+ const ny = Number(y);
11951
+ if (!Number.isNaN(nx) && !Number.isNaN(ny) && nx !== ny)
11952
+ return nx - ny;
11953
+ if (x !== y)
11954
+ return x < y ? -1 : 1;
11955
+ }
11956
+ return 0;
11957
+ }
11958
+ function hasManagedEntry(root, version) {
11959
+ return import_node_fs15.existsSync(import_node_path16.join(root, version, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"));
11960
+ }
11961
+ function resolveManagedDshVersion(env = process.env) {
11962
+ const explicit = env.DSH_RUNTIME_VERSION?.trim();
11963
+ if (explicit)
11964
+ return explicit;
11965
+ const root = resolveDshRuntimeRoot(env);
11966
+ let best = null;
11967
+ try {
11968
+ for (const name of import_node_fs15.readdirSync(root)) {
11969
+ if (!parseVersion(name))
11970
+ continue;
11971
+ if (!hasManagedEntry(root, name))
11972
+ continue;
11973
+ if (best === null || compareDshVersions(name, best) > 0)
11974
+ best = name;
11975
+ }
11976
+ } catch {}
11977
+ return best ?? DSH_ACP_PINNED_VERSION;
11978
+ }
11979
+ function hasManagedDshRuntime(env = process.env) {
11980
+ return import_node_fs15.existsSync(resolveManagedDshEntry(env));
11981
+ }
11982
+ function safeId(raw, fallback) {
11983
+ const value = raw?.trim();
11984
+ return value && /^[A-Za-z0-9._-]+$/.test(value) ? value : fallback;
11985
+ }
11986
+ function resolveAcpModelOverride(env = process.env) {
11987
+ const flag = env.DSH_ACP_MODEL_PATCH?.trim().toLowerCase();
11988
+ if (flag === "off" || flag === "0" || flag === "false" || flag === "none")
11989
+ return null;
11990
+ return {
11991
+ provider: safeId(env.DSH_PROVIDER, DSH_ACP_DEFAULT_PROVIDER),
11992
+ model: safeId(env.DSH_MODEL, DSH_ACP_DEFAULT_MODEL)
11993
+ };
11994
+ }
11995
+ function buildAcpModelPatch(override) {
11996
+ return [
11997
+ "# 由 @yitom/acp-client 生成:修正 ACP 会话默认模型。",
11998
+ "# dsh-acp-app 自带补丁把 model 写死为 deepseek-v4-flash,该 id 不在 provider catalog 中;",
11999
+ "# V4.1-Flash 的 catalog id 是 deepseek-flash(桌面端 1017 只是 UI 徽标)。",
12000
+ "- id: acp",
12001
+ " name: '@deepseek-ai/dsh-acp'",
12002
+ " config:",
12003
+ ` provider: ${override.provider}`,
12004
+ ` model: ${override.model}`,
12005
+ ""
12006
+ ].join(`
12007
+ `);
12008
+ }
12009
+ var patchFileCache = new Map;
12010
+ function ensureAcpModelPatchFile(env = process.env) {
12011
+ const override = resolveAcpModelOverride(env);
12012
+ if (!override)
12013
+ return null;
12014
+ const key = `${override.provider}/${override.model}`;
12015
+ const cached = patchFileCache.get(key);
12016
+ if (cached !== undefined)
12017
+ return cached;
12018
+ try {
12019
+ const dir = import_node_path16.join(import_node_os12.tmpdir(), "acp-dsh-runtime");
12020
+ import_node_fs15.mkdirSync(dir, { recursive: true });
12021
+ const file = import_node_path16.join(dir, `acp-model-${override.provider}--${override.model}.patch.yml`);
12022
+ const body = buildAcpModelPatch(override);
12023
+ if (!import_node_fs15.existsSync(file) || import_node_fs15.readFileSync(file, "utf8") !== body) {
12024
+ import_node_fs15.writeFileSync(file, body, "utf8");
12025
+ }
12026
+ patchFileCache.set(key, file);
12027
+ return file;
12028
+ } catch {
12029
+ patchFileCache.set(key, null);
12030
+ return null;
12031
+ }
12032
+ }
12033
+
12034
+ // src/runtimes/deepseek/quota.ts
12035
+ var DEFAULT_TIMEOUT_MS = 4000;
12036
+ function resolveDeepseekQuotaKey(options = {}) {
12037
+ const env = options.env ?? process.env;
12038
+ const envKey = env.DEEPSEEK_API_KEY?.trim();
12039
+ if (envKey)
12040
+ return envKey;
12041
+ if (options.dataDir) {
12042
+ const stored = readStoredDeepseekProvider(options.dataDir);
12043
+ if (stored?.apiKey)
12044
+ return stored.apiKey;
12045
+ }
12046
+ return readHarnessCredential("DEEPSEEK_API_KEY", env);
12047
+ }
12048
+ function resolveDeepseekApiBase(options = {}) {
12049
+ const env = options.env ?? process.env;
12050
+ const raw = env.DEEPSEEK_BASE_URL?.trim() || (options.dataDir ? readStoredDeepseekProvider(options.dataDir)?.baseUrl : undefined) || DEEPSEEK_OFFICIAL_BASE_URL;
12051
+ const trimmed = raw.replace(/\/+$/, "").replace(/\/anthropic$/i, "");
12052
+ return trimmed || "https://api.deepseek.com";
12053
+ }
12054
+ function unauthorized(runtimeId, message) {
12055
+ return { runtimeId, provider: "DeepSeek", status: "unauthorized", message, updatedAt: Date.now() };
12056
+ }
12057
+ async function probeDeepseekQuota(options = {}) {
12058
+ const runtimeId = options.runtimeId ?? "deepseek";
12059
+ const apiKey = resolveDeepseekQuotaKey(options);
12060
+ if (!apiKey) {
12061
+ return unauthorized(runtimeId, "未配置 DEEPSEEK_API_KEY / 表单 Token,无法查询余额");
12062
+ }
12063
+ const doFetch = options.fetchImpl ?? fetch;
12064
+ try {
12065
+ const response = await doFetch(`${resolveDeepseekApiBase(options)}/user/balance`, {
12066
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
12067
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
12068
+ });
12069
+ if (response.status === 401 || response.status === 403) {
12070
+ return unauthorized(runtimeId, `余额查询被拒绝 (HTTP ${response.status})`);
12071
+ }
12072
+ if (!response.ok)
12073
+ return null;
12074
+ const data = await response.json();
12075
+ const infos = Array.isArray(data.balance_infos) ? data.balance_infos : [];
12076
+ const first = infos[0];
12077
+ const total = first ? Number(first.total_balance) : Number.NaN;
12078
+ const credits = first ? {
12079
+ balance: Number.isFinite(total) ? total : first.total_balance ?? "0",
12080
+ currency: first.currency
12081
+ } : undefined;
12082
+ const balanceText = infos.map((info) => `${info.total_balance ?? "0"} ${info.currency ?? ""}`.trim()).join(" / ");
12083
+ return {
12084
+ runtimeId,
12085
+ provider: "DeepSeek",
12086
+ account: { type: "apiKey", plan: "DeepSeek API" },
12087
+ credits,
12088
+ status: data.is_available === false ? "exhausted" : "ok",
12089
+ message: data.is_available === false ? "账户余额不足,API 暂不可用" : `可用余额 ${balanceText || "未知"}`,
12090
+ rawText: JSON.stringify(data),
12091
+ updatedAt: Date.now()
12092
+ };
12093
+ } catch {
12094
+ return null;
12095
+ }
12096
+ }
12097
+
11777
12098
  // src/runtimes/deepseek/index.ts
11778
12099
  function buildDeepseekMissingKeyMessage() {
11779
- return "未检测到 DEEPSEEK_API_KEY:请先在终端导出该变量(或完成 harness 自身登录)后再连接";
12100
+ return "未检测到 DEEPSEEK_API_KEY,也未在 harness 凭证库中找到登录记录:请先在终端导出该变量,或先在该 harness(dsh)里完成登录后再连接";
12101
+ }
12102
+ function hasDshCredentials(env) {
12103
+ try {
12104
+ const text = import_node_fs16.readFileSync(resolveDshCredentialsFile(env), "utf8");
12105
+ const match = /^records\s*:(.*)$/m.exec(text);
12106
+ if (!match)
12107
+ return false;
12108
+ if (/^\s*(\[\]|\{\}|null|~)\s*$/.test(match[1]))
12109
+ return false;
12110
+ for (const line of text.slice(match.index + match[0].length).split(/\r?\n/)) {
12111
+ if (!line.trim() || line.trim().startsWith("#"))
12112
+ continue;
12113
+ if (/^\s+\S/.test(line))
12114
+ return true;
12115
+ return false;
12116
+ }
12117
+ return false;
12118
+ } catch {
12119
+ return false;
12120
+ }
11780
12121
  }
11781
- function resolveDeepseekSpawnBlocker(env) {
12122
+ function resolveDeepseekSpawnBlocker(env, dataDir) {
11782
12123
  const source = env ?? process.env;
11783
12124
  if (source.DEEPSEEK_API_KEY?.trim())
11784
12125
  return null;
12126
+ if (dataDir && readStoredDeepseekProvider(dataDir))
12127
+ return null;
12128
+ if (hasDshCredentials(source))
12129
+ return null;
11785
12130
  return buildDeepseekMissingKeyMessage();
11786
12131
  }
11787
12132
  function resolveDeepseekPackage(env) {
@@ -11797,39 +12142,86 @@ function resolveDeepseekPackage(env) {
11797
12142
  }
11798
12143
  return raw;
11799
12144
  }
12145
+ var UNSAFE_BIN = /[\u0000-\u001f;&|$()`"'<>*?~#!]/;
12146
+ function resolveDeepseekBin(env) {
12147
+ const raw = (env ?? process.env).DSH_BIN?.trim();
12148
+ if (!raw)
12149
+ return null;
12150
+ if (UNSAFE_BIN.test(raw)) {
12151
+ if (true) {
12152
+ console.warn(`[acp:deepseek] 非法 DSH_BIN 回落包解析: ${raw}`);
12153
+ }
12154
+ return null;
12155
+ }
12156
+ return raw;
12157
+ }
11800
12158
  function resolveDeepseekSpawnCommand(env) {
11801
- const pkg = resolveDeepseekPackage(env);
12159
+ const source = env ?? process.env;
12160
+ const patchFile = ensureAcpModelPatchFile(source);
12161
+ const withPatch = (args) => patchFile ? [...args, "--patch", patchFile] : args;
12162
+ const bin = resolveDeepseekBin(source);
12163
+ if (bin) {
12164
+ const args = ["--profile", "acp"];
12165
+ if (/\.(c|m)?js$/i.test(bin))
12166
+ return { command: process.execPath, args: withPatch([bin, ...args]) };
12167
+ const looksAbsolute = /^([A-Za-z]:[\\/]|\\\\|\/)/.test(bin);
12168
+ if (/\.(cmd|bat)$/i.test(bin) && /\s/.test(bin)) {
12169
+ if (true) {
12170
+ console.warn(`[acp:deepseek] DSH_BIN 为含空格的批处理,回落包解析: ${bin}`);
12171
+ }
12172
+ } else if (!looksAbsolute || import_node_fs16.existsSync(bin)) {
12173
+ return { command: bin, args: withPatch(args) };
12174
+ } else if (true) {
12175
+ console.warn(`[acp:deepseek] DSH_BIN 不存在,回落包解析: ${bin}`);
12176
+ }
12177
+ }
12178
+ if (hasManagedDshRuntime(source)) {
12179
+ const entry = resolveManagedDshEntry(source);
12180
+ return { command: process.execPath, args: withPatch([entry, "--profile", "acp"]) };
12181
+ }
12182
+ const pkg = resolveDeepseekPackage(source);
11802
12183
  const spec = pkg === DEEPSEEK_DSH_NPM_PACKAGE ? `${pkg}@latest` : pkg;
11803
- return { command: "bunx", args: ["-y", spec, "--profile", "acp"] };
12184
+ return { command: "bunx", args: withPatch(["-y", spec, "--profile", "acp"]) };
11804
12185
  }
11805
- function probeDeepseekAuth() {
11806
- const hasApiKeyEnv = Boolean(process.env.DEEPSEEK_API_KEY?.trim());
12186
+ function probeDeepseekAuth(env, dataDir) {
12187
+ const source = env ?? process.env;
12188
+ const hasApiKeyEnv = Boolean(source.DEEPSEEK_API_KEY?.trim());
12189
+ const dshHome = resolveDshHome(source);
12190
+ const hasCredentialsFile = import_node_fs16.existsSync(resolveDshCredentialsFile(source));
12191
+ const hasCredentialRecords = hasDshCredentials(source);
12192
+ const hasStoredProvider = Boolean(dataDir && readStoredDeepseekProvider(dataDir));
11807
12193
  return {
11808
- codexHome: "",
11809
- hasCodexHome: false,
11810
- hasAuthFile: false,
11811
- hasApiKeyEnv,
11812
- looksLoggedIn: hasApiKeyEnv
12194
+ codexHome: dshHome,
12195
+ hasCodexHome: import_node_fs16.existsSync(dshHome),
12196
+ hasAuthFile: hasCredentialsFile,
12197
+ hasApiKeyEnv: hasApiKeyEnv || hasStoredProvider,
12198
+ looksLoggedIn: hasApiKeyEnv || hasStoredProvider || hasCredentialRecords
11813
12199
  };
11814
12200
  }
11815
12201
  var deepseekAdapter = {
11816
12202
  id: "deepseek",
11817
12203
  prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
11818
- probeAuth: () => probeDeepseekAuth(),
12204
+ probeAuth: (context) => probeDeepseekAuth(context?.env, context?.dataDir),
11819
12205
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
11820
- resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
12206
+ resolveSpawnBlocker: (context) => resolveDeepseekSpawnBlocker(context?.env, context?.dataDir),
12207
+ getProviderEnv: ({ dataDir, env }) => buildDeepseekProviderEnv(readStoredDeepseekProvider(dataDir), env),
12208
+ probeQuota: (options) => probeDeepseekQuota({
12209
+ runtimeId: "deepseek",
12210
+ dataDir: options?.dataDir,
12211
+ env: options?.env
12212
+ }),
11821
12213
  orderAuthMethods: (methods) => methods,
11822
12214
  canSkipInteractiveAuth: () => false
11823
12215
  };
11824
12216
 
11825
12217
  // src/runtimes/agy/quota.ts
11826
- var import_node_fs14 = require("node:fs");
11827
- var import_node_path15 = require("node:path");
12218
+ var import_node_fs17 = require("node:fs");
12219
+ var import_node_path17 = require("node:path");
11828
12220
  var import_node_child_process5 = require("node:child_process");
11829
12221
  var os2 = __toESM(require("node:os"), 1);
11830
12222
  function resolveGeminiHome2() {
11831
12223
  const home = process.env.USERPROFILE || process.env.HOME || "";
11832
- return import_node_path15.join(home, ".gemini");
12224
+ return import_node_path17.join(home, ".gemini");
11833
12225
  }
11834
12226
  function resolveAntigravityAccount() {
11835
12227
  if (process.env.GOOGLE_ACCOUNT?.trim()) {
@@ -11842,14 +12234,14 @@ function resolveAntigravityAccount() {
11842
12234
  }
11843
12235
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
11844
12236
  const candidates = [
11845
- process.env.APPDATA ? import_node_path15.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
11846
- import_node_path15.join(home, ".config", "Antigravity", "app_storage.json"),
11847
- import_node_path15.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
12237
+ process.env.APPDATA ? import_node_path17.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
12238
+ import_node_path17.join(home, ".config", "Antigravity", "app_storage.json"),
12239
+ import_node_path17.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
11848
12240
  ].filter(Boolean);
11849
12241
  for (const file of candidates) {
11850
12242
  try {
11851
- if (import_node_fs14.existsSync(file)) {
11852
- const raw = import_node_fs14.readFileSync(file, "utf8");
12243
+ if (import_node_fs17.existsSync(file)) {
12244
+ const raw = import_node_fs17.readFileSync(file, "utf8");
11853
12245
  const json = JSON.parse(raw);
11854
12246
  const username = json["jetski.onboarding.lastLoginUsername"];
11855
12247
  if (username && typeof username === "string" && username.trim()) {
@@ -11870,30 +12262,30 @@ function resolveAntigravityAccount() {
11870
12262
  }
11871
12263
  function resolveAntigravityLanguageServer() {
11872
12264
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
11873
- const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path15.join(home, "AppData", "Roaming") : "");
12265
+ const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path17.join(home, "AppData", "Roaming") : "");
11874
12266
  const baseDirs = [
11875
- appData ? import_node_path15.join(appData, "Antigravity IDE", "logs") : null,
11876
- appData ? import_node_path15.join(appData, "Antigravity", "logs") : null,
11877
- import_node_path15.join(home, ".config", "Antigravity IDE", "logs"),
11878
- import_node_path15.join(home, ".config", "Antigravity", "logs"),
11879
- import_node_path15.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
11880
- import_node_path15.join(home, "Library", "Application Support", "Antigravity", "logs")
12267
+ appData ? import_node_path17.join(appData, "Antigravity IDE", "logs") : null,
12268
+ appData ? import_node_path17.join(appData, "Antigravity", "logs") : null,
12269
+ import_node_path17.join(home, ".config", "Antigravity IDE", "logs"),
12270
+ import_node_path17.join(home, ".config", "Antigravity", "logs"),
12271
+ import_node_path17.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
12272
+ import_node_path17.join(home, "Library", "Application Support", "Antigravity", "logs")
11881
12273
  ].filter(Boolean);
11882
12274
  for (const base of baseDirs) {
11883
12275
  try {
11884
- if (!import_node_fs14.existsSync(base))
12276
+ if (!import_node_fs17.existsSync(base))
11885
12277
  continue;
11886
- const sessionDirs = import_node_fs14.readdirSync(base).map((d) => {
12278
+ const sessionDirs = import_node_fs17.readdirSync(base).map((d) => {
11887
12279
  try {
11888
- return { name: d, time: import_node_fs14.statSync(import_node_path15.join(base, d)).mtimeMs };
12280
+ return { name: d, time: import_node_fs17.statSync(import_node_path17.join(base, d)).mtimeMs };
11889
12281
  } catch {
11890
12282
  return null;
11891
12283
  }
11892
12284
  }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
11893
12285
  for (const s of sessionDirs) {
11894
- const logFile = import_node_path15.join(base, s.name, "ls-main.log");
11895
- if (import_node_fs14.existsSync(logFile)) {
11896
- const content = import_node_fs14.readFileSync(logFile, "utf8");
12286
+ const logFile = import_node_path17.join(base, s.name, "ls-main.log");
12287
+ if (import_node_fs17.existsSync(logFile)) {
12288
+ const content = import_node_fs17.readFileSync(logFile, "utf8");
11897
12289
  const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
11898
12290
  const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
11899
12291
  if (csrfMatch && portMatch) {
@@ -12050,7 +12442,7 @@ async function probeAgyQuota(options) {
12050
12442
  } catch {}
12051
12443
  }
12052
12444
  const geminiHome = resolveGeminiHome2();
12053
- const hasAgyDir = import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity")) || import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity-cli"));
12445
+ const hasAgyDir = import_node_fs17.existsSync(import_node_path17.join(geminiHome, "antigravity")) || import_node_fs17.existsSync(import_node_path17.join(geminiHome, "antigravity-cli"));
12054
12446
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
12055
12447
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
12056
12448
  if (!isAvailable) {
@@ -12331,17 +12723,17 @@ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
12331
12723
 
12332
12724
  // src/client/acp-fs.ts
12333
12725
  var import_promises4 = require("node:fs/promises");
12334
- var import_node_path16 = require("node:path");
12726
+ var import_node_path18 = require("node:path");
12335
12727
  var import_promises5 = require("node:fs/promises");
12336
12728
  var MAX_READ_BYTES = 2 * 1024 * 1024;
12337
12729
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
12338
12730
  function isBinaryDocumentPath(filePath) {
12339
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path16.extname(filePath).toLowerCase());
12731
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path18.extname(filePath).toLowerCase());
12340
12732
  }
12341
12733
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
12342
- const root = import_node_path16.resolve(workspaceRoot);
12343
- const target = import_node_path16.resolve(filePath);
12344
- const rootWithSep = root.endsWith(import_node_path16.sep) ? root : root + import_node_path16.sep;
12734
+ const root = import_node_path18.resolve(workspaceRoot);
12735
+ const target = import_node_path18.resolve(filePath);
12736
+ const rootWithSep = root.endsWith(import_node_path18.sep) ? root : root + import_node_path18.sep;
12345
12737
  if (target !== root && !target.startsWith(rootWithSep)) {
12346
12738
  throw new Error(`路径不在工作区内: ${filePath}`);
12347
12739
  }
@@ -12372,7 +12764,7 @@ async function acpReadTextFile(params) {
12372
12764
  }
12373
12765
  async function acpWriteTextFile(params) {
12374
12766
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
12375
- await import_promises5.mkdir(import_node_path16.dirname(abs), { recursive: true });
12767
+ await import_promises5.mkdir(import_node_path18.dirname(abs), { recursive: true });
12376
12768
  await import_promises4.writeFile(abs, params.content, "utf-8");
12377
12769
  return {};
12378
12770
  }
@@ -12543,6 +12935,16 @@ function coerceOptionValue(raw) {
12543
12935
  return String(raw);
12544
12936
  if (typeof raw === "boolean")
12545
12937
  return String(raw);
12938
+ if (raw !== null && typeof raw === "object") {
12939
+ if (!Array.isArray(raw) && Object.keys(raw).length === 0)
12940
+ return null;
12941
+ try {
12942
+ const encoded = JSON.stringify(raw);
12943
+ return encoded && encoded !== "null" ? encoded : null;
12944
+ } catch {
12945
+ return null;
12946
+ }
12947
+ }
12546
12948
  return null;
12547
12949
  }
12548
12950
  function coerceCurrentValue(raw) {
@@ -12552,8 +12954,41 @@ function coerceCurrentValue(raw) {
12552
12954
  return raw;
12553
12955
  if (typeof raw === "number" && Number.isFinite(raw))
12554
12956
  return String(raw);
12957
+ if (raw !== null && typeof raw === "object") {
12958
+ if (!Array.isArray(raw) && Object.keys(raw).length === 0)
12959
+ return;
12960
+ try {
12961
+ const encoded = JSON.stringify(raw);
12962
+ return encoded && encoded !== "null" ? encoded : undefined;
12963
+ } catch {
12964
+ return;
12965
+ }
12966
+ }
12555
12967
  return;
12556
12968
  }
12969
+ function collectOptionValues(rows, group, out) {
12970
+ for (const opt of rows) {
12971
+ if (!opt || typeof opt !== "object")
12972
+ continue;
12973
+ const o = opt;
12974
+ const nested = Array.isArray(o.options) ? o.options : null;
12975
+ const label = typeof o.group === "string" && o.group ? o.group : group;
12976
+ if (nested && nested.length > 0) {
12977
+ const fallbackName = typeof o.name === "string" && o.name ? o.name : undefined;
12978
+ collectOptionValues(nested, label ?? fallbackName, out);
12979
+ continue;
12980
+ }
12981
+ const value = coerceOptionValue(o.value) ?? coerceOptionValue(o.id);
12982
+ if (!value)
12983
+ continue;
12984
+ out.push({
12985
+ value,
12986
+ name: typeof o.name === "string" ? o.name : String(value),
12987
+ ...typeof o.description === "string" ? { description: o.description } : {},
12988
+ ...label ? { group: label } : {}
12989
+ });
12990
+ }
12991
+ }
12557
12992
  function parseAcpConfigOptions(raw) {
12558
12993
  if (!Array.isArray(raw))
12559
12994
  return [];
@@ -12568,21 +13003,8 @@ function parseAcpConfigOptions(raw) {
12568
13003
  const name = typeof row.name === "string" ? row.name : configId;
12569
13004
  const type = typeof row.type === "string" ? row.type : "select";
12570
13005
  const values = [];
12571
- if (Array.isArray(row.options)) {
12572
- for (const opt of row.options) {
12573
- if (!opt || typeof opt !== "object")
12574
- continue;
12575
- const o = opt;
12576
- const value = coerceOptionValue(o.value) ?? coerceOptionValue(o.id);
12577
- if (!value)
12578
- continue;
12579
- values.push({
12580
- value,
12581
- name: typeof o.name === "string" ? o.name : String(value),
12582
- description: typeof o.description === "string" ? o.description : undefined
12583
- });
12584
- }
12585
- }
13006
+ if (Array.isArray(row.options))
13007
+ collectOptionValues(row.options, undefined, values);
12586
13008
  options.push({
12587
13009
  configId,
12588
13010
  name,
@@ -13058,8 +13480,8 @@ class AcpTerminalManager {
13058
13480
 
13059
13481
  // src/client/acp-proxy-service.ts
13060
13482
  var import_promises6 = require("node:fs/promises");
13061
- var import_node_fs15 = require("node:fs");
13062
- var import_node_path17 = require("node:path");
13483
+ var import_node_fs18 = require("node:fs");
13484
+ var import_node_path19 = require("node:path");
13063
13485
  var DEFAULT_ACP_PROXY_SETTINGS = {
13064
13486
  enabled: false,
13065
13487
  host: "127.0.0.1",
@@ -13068,11 +13490,11 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
13068
13490
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
13069
13491
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
13070
13492
  function proxyFilePath(dir) {
13071
- return import_node_path17.join(dir, "agent", "proxy.json");
13493
+ return import_node_path19.join(dir, "agent", "proxy.json");
13072
13494
  }
13073
13495
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
13074
13496
  const file = proxyFilePath(dir);
13075
- if (!import_node_fs15.existsSync(file))
13497
+ if (!import_node_fs18.existsSync(file))
13076
13498
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
13077
13499
  try {
13078
13500
  const raw = JSON.parse(await import_promises6.readFile(file, "utf8"));
@@ -13137,9 +13559,9 @@ function compatDeliveryKey(sessionId, generation, digest) {
13137
13559
  }
13138
13560
 
13139
13561
  // src/mcp/app-skills-mcp.ts
13140
- var import_node_path18 = require("node:path");
13562
+ var import_node_path20 = require("node:path");
13141
13563
  var import_node_url = require("node:url");
13142
- var import_node_fs16 = require("node:fs");
13564
+ var import_node_fs19 = require("node:fs");
13143
13565
  var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
13144
13566
  var APP_SKILLS_TOOLS = [
13145
13567
  {
@@ -13175,11 +13597,11 @@ function buildAppSkillsMcpServer(directory, opts) {
13175
13597
  function resolveAppSkillsRunnerPath(fromFile) {
13176
13598
  const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
13177
13599
  const candidates = [
13178
- import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.cjs"),
13179
- import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.ts")
13600
+ import_node_path20.join(import_node_path20.dirname(base), "app-skills-mcp-serve.cjs"),
13601
+ import_node_path20.join(import_node_path20.dirname(base), "app-skills-mcp-serve.ts")
13180
13602
  ];
13181
13603
  for (const candidate of candidates) {
13182
- if (import_node_fs16.existsSync(candidate))
13604
+ if (import_node_fs19.existsSync(candidate))
13183
13605
  return candidate;
13184
13606
  }
13185
13607
  throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
@@ -13338,7 +13760,10 @@ class AcpClient {
13338
13760
  const connectGen = this.connectionGen;
13339
13761
  try {
13340
13762
  this.setStatus("connecting");
13341
- const blocker = this.adapter.resolveSpawnBlocker?.();
13763
+ const blocker = this.adapter.resolveSpawnBlocker?.({
13764
+ env: { ...process.env, ...this.extraEnv },
13765
+ dataDir: this.dataDir
13766
+ });
13342
13767
  if (blocker) {
13343
13768
  this.setStatus("error", blocker);
13344
13769
  return err({ code: "ACP_SPAWN_ERROR", message: blocker });
@@ -13361,6 +13786,10 @@ class AcpClient {
13361
13786
  ...baseEnv,
13362
13787
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
13363
13788
  };
13789
+ const providerEnv = this.adapter.getProviderEnv?.({
13790
+ dataDir: this.dataDir,
13791
+ env: { ...process.env, ...spawnEnv.env }
13792
+ }) ?? {};
13364
13793
  let resourceEnv = {};
13365
13794
  let profileTag = null;
13366
13795
  if (this.resourcesDir && this.configurationScope === "session") {
@@ -13435,7 +13864,7 @@ class AcpClient {
13435
13864
  reason: "runtime-not-supported"
13436
13865
  } } : null;
13437
13866
  }
13438
- const finalEnv = { ...spawnEnv.env, ...resourceEnv };
13867
+ const finalEnv = { ...spawnEnv.env, ...providerEnv, ...resourceEnv };
13439
13868
  await this.adapter.beforeSpawn?.();
13440
13869
  if (connectGen !== this.connectionGen || this.status !== "connecting")
13441
13870
  return err({ code: "CANCELLED", message: "连接已取消" });
@@ -13547,21 +13976,25 @@ class AcpClient {
13547
13976
  }
13548
13977
  }
13549
13978
  getCachedQuota(sessionId) {
13550
- return this.quotaCache.get(sessionId, this.runtimeInfo.id);
13979
+ return this.quotaCache.applyContextUsage(this.quotaCache.get(sessionId, this.runtimeInfo.id), sessionId, this.runtimeInfo.id) ?? undefined;
13551
13980
  }
13552
13981
  async getQuota(sessionId) {
13553
- const cached = this.getCachedQuota(sessionId);
13982
+ const cached = this.quotaCache.get(sessionId, this.runtimeInfo.id);
13554
13983
  if (cached && Date.now() - cached.updatedAt < 30000) {
13555
- return cached;
13984
+ return this.quotaCache.applyContextUsage(cached, sessionId, this.runtimeInfo.id);
13556
13985
  }
13557
13986
  if (this.adapter.probeQuota) {
13558
- const probed = await this.adapter.probeQuota({ sessionId });
13987
+ const probed = await this.adapter.probeQuota({
13988
+ sessionId,
13989
+ dataDir: this.dataDir,
13990
+ env: { ...process.env, ...this.extraEnv }
13991
+ });
13559
13992
  if (probed) {
13560
13993
  this.quotaCache.set(probed, sessionId);
13561
- return probed;
13994
+ return this.quotaCache.applyContextUsage(probed, sessionId, this.runtimeInfo.id);
13562
13995
  }
13563
13996
  }
13564
- return cached ?? null;
13997
+ return this.quotaCache.applyContextUsage(cached ?? null, sessionId, this.runtimeInfo.id);
13565
13998
  }
13566
13999
  getAvailableCommands(sessionId) {
13567
14000
  return this.commandsCache.get(sessionId);