@yitom/acp-client 0.1.11 → 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/index.cjs CHANGED
@@ -82,8 +82,12 @@ __export(exports_src, {
82
82
  CLAUDE_ACP_NPM_PACKAGE: () => CLAUDE_ACP_NPM_PACKAGE,
83
83
  CODEX_ACP_NPM_PACKAGE: () => CODEX_ACP_NPM_PACKAGE,
84
84
  DEEPSEEK_DSH_NPM_PACKAGE: () => DEEPSEEK_DSH_NPM_PACKAGE,
85
+ DEEPSEEK_OFFICIAL_BASE_URL: () => DEEPSEEK_OFFICIAL_BASE_URL,
85
86
  DEFAULT_ACP_PROXY_SETTINGS: () => DEFAULT_ACP_PROXY_SETTINGS,
86
87
  DEFAULT_ACP_RUNTIME_ID: () => DEFAULT_ACP_RUNTIME_ID,
88
+ DSH_ACP_DEFAULT_MODEL: () => DSH_ACP_DEFAULT_MODEL,
89
+ DSH_ACP_DEFAULT_PROVIDER: () => DSH_ACP_DEFAULT_PROVIDER,
90
+ DSH_ACP_PINNED_VERSION: () => DSH_ACP_PINNED_VERSION,
87
91
  INKDOWN_MCP_TOOLS: () => INKDOWN_MCP_TOOLS,
88
92
  INKDOWN_PROVIDER_API_KEY_ENV: () => INKDOWN_PROVIDER_API_KEY_ENV,
89
93
  INKDOWN_PROVIDER_ID: () => INKDOWN_PROVIDER_ID,
@@ -100,19 +104,23 @@ __export(exports_src, {
100
104
  agyAdapter: () => agyAdapter,
101
105
  appendTerminalOutput: () => appendTerminalOutput,
102
106
  assertPathInsideWorkspace: () => assertPathInsideWorkspace,
107
+ buildAcpModelPatch: () => buildAcpModelPatch,
103
108
  buildAcpProxySpawnEnv: () => buildAcpProxySpawnEnv,
104
109
  buildCursorMissingCliMessage: () => buildCursorMissingCliMessage,
105
110
  buildCustomProviderConfigToml: () => buildCustomProviderConfigToml,
106
111
  buildCustomProviderSpawnEnv: () => buildCustomProviderSpawnEnv,
107
112
  buildDeepseekMissingKeyMessage: () => buildDeepseekMissingKeyMessage,
113
+ buildDeepseekProviderEnv: () => buildDeepseekProviderEnv,
108
114
  callInkdownMcpTool: () => callInkdownMcpTool,
109
115
  callInkdownTocTool: () => callInkdownTocTool,
110
116
  claudeAdapter: () => claudeAdapter,
111
117
  claudeResourceSessionMeta: () => claudeResourceSessionMeta,
112
118
  clearAcpProvider: () => clearAcpProvider,
113
119
  clearCursorCatalogCache: () => clearCursorCatalogCache,
120
+ clearDeepseekProvider: () => clearDeepseekProvider,
114
121
  closeAcpSessions: () => closeAcpSessions,
115
122
  codexAdapter: () => codexAdapter,
123
+ compareDshVersions: () => compareDshVersions,
116
124
  connectSdkClient: () => connectSdkClient,
117
125
  copilotAdapter: () => copilotAdapter,
118
126
  createSdkStreamHandle: () => createSdkStreamHandle,
@@ -123,6 +131,7 @@ __export(exports_src, {
123
131
  digestAppResources: () => digestAppResources,
124
132
  disposeAllAcpProcesses: () => disposeAllAcpProcesses,
125
133
  emptyAcpAuthPreflight: () => emptyAcpAuthPreflight,
134
+ ensureAcpModelPatchFile: () => ensureAcpModelPatchFile,
126
135
  err: () => err,
127
136
  extractAvailableCommands: () => extractAvailableCommands,
128
137
  findBuiltinAcpRuntime: () => findBuiltinAcpRuntime,
@@ -136,12 +145,16 @@ __export(exports_src, {
136
145
  getAcpRuntimeAdapter: () => getAcpRuntimeAdapter,
137
146
  getActiveAcpProcess: () => getActiveAcpProcess,
138
147
  getCursorCatalogIds: () => getCursorCatalogIds,
148
+ getDeepseekProviderStatus: () => getDeepseekProviderStatus,
139
149
  getDefaultAcpRuntime: () => getDefaultAcpRuntime,
140
150
  getDefaultAgentDataDir: () => getDefaultAgentDataDir,
141
151
  getLiveAcpProcess: () => getLiveAcpProcess,
142
152
  handleInkdownMcpRpc: () => handleInkdownMcpRpc,
153
+ hasDshCredentials: () => hasDshCredentials,
154
+ hasManagedDshRuntime: () => hasManagedDshRuntime,
143
155
  isAbsolutePathLike: () => isAbsolutePathLike,
144
156
  isAppError: () => isAppError,
157
+ isAuthenticationRequired: () => isAuthenticationRequired,
145
158
  isBinaryDocumentPath: () => isBinaryDocumentPath,
146
159
  isCancelled: () => isCancelled,
147
160
  isCodexPreflightRuntime: () => isCodexPreflightRuntime,
@@ -159,7 +172,9 @@ __export(exports_src, {
159
172
  mergeCodexConfigJson: () => mergeCodexConfigJson,
160
173
  mergeConfigTomlPreserving: () => mergeConfigTomlPreserving,
161
174
  mergeOpenCodeAppConfig: () => mergeOpenCodeAppConfig,
175
+ mergeOpenCodeQuestionConfig: () => mergeOpenCodeQuestionConfig,
162
176
  mergeTopLevelModelsIntoConfigOptions: () => mergeTopLevelModelsIntoConfigOptions,
177
+ normalizeDeepseekBaseUrl: () => normalizeDeepseekBaseUrl,
163
178
  ok: () => ok,
164
179
  opencodeAdapter: () => opencodeAdapter,
165
180
  opencodeV2Adapter: () => opencodeV2Adapter,
@@ -186,6 +201,7 @@ __export(exports_src, {
186
201
  probeCursorAuth: () => probeCursorAuth,
187
202
  probeCursorQuota: () => probeCursorQuota,
188
203
  probeDeepseekAuth: () => probeDeepseekAuth,
204
+ probeDeepseekQuota: () => probeDeepseekQuota,
189
205
  probeGeminiAuth: () => probeGeminiAuth,
190
206
  probeOpencodeAuth: () => probeOpencodeAuth,
191
207
  probeOpencodeQuota: () => probeOpencodeQuota,
@@ -193,18 +209,32 @@ __export(exports_src, {
193
209
  readAcpProxySettings: () => readAcpProxySettings,
194
210
  readAppResourcesDir: () => readAppResourcesDir,
195
211
  readAppRulesText: () => readAppRulesText,
212
+ readHarnessCredential: () => readHarnessCredential,
196
213
  readStoredAcpProvider: () => readStoredAcpProvider,
214
+ readStoredDeepseekProvider: () => readStoredDeepseekProvider,
197
215
  registerAcpClientHandlers: () => registerAcpClientHandlers,
216
+ requestSessionWithResources: () => requestSessionWithResources,
217
+ resetAcpModelPatchCache: () => resetAcpModelPatchCache,
218
+ resolveAcpModelOverride: () => resolveAcpModelOverride,
198
219
  resolveClaudeHome: () => resolveClaudeHome,
199
220
  resolveCodexHome: () => resolveCodexHome,
200
221
  resolveCopilotHome: () => resolveCopilotHome,
201
222
  resolveCursorAuthCandidates: () => resolveCursorAuthCandidates,
202
223
  resolveCursorCommand: () => resolveCursorCommand,
203
224
  resolveCursorSpawnCommand: () => resolveCursorSpawnCommand,
225
+ resolveDeepseekApiBase: () => resolveDeepseekApiBase,
226
+ resolveDeepseekBin: () => resolveDeepseekBin,
204
227
  resolveDeepseekPackage: () => resolveDeepseekPackage,
228
+ resolveDeepseekQuotaKey: () => resolveDeepseekQuotaKey,
205
229
  resolveDeepseekSpawnBlocker: () => resolveDeepseekSpawnBlocker,
206
230
  resolveDeepseekSpawnCommand: () => resolveDeepseekSpawnCommand,
231
+ resolveDshCredentialsFile: () => resolveDshCredentialsFile,
232
+ resolveDshHome: () => resolveDshHome,
233
+ resolveDshRuntimeRoot: () => resolveDshRuntimeRoot,
207
234
  resolveGeminiHome: () => resolveGeminiHome,
235
+ resolveManagedDshEntry: () => resolveManagedDshEntry,
236
+ resolveManagedDshVersion: () => resolveManagedDshVersion,
237
+ resolveOpenCodeQuestionMode: () => resolveOpenCodeQuestionMode,
208
238
  resolveOpencodeAuthCandidates: () => resolveOpencodeAuthCandidates,
209
239
  resolveOpencodeAuthFile: () => resolveOpencodeAuthFile,
210
240
  resolveOpencodeAuthPath: () => resolveOpencodeAuthPath,
@@ -213,6 +243,7 @@ __export(exports_src, {
213
243
  runConnectAuthGate: () => runConnectAuthGate,
214
244
  saveAcpProvider: () => saveAcpProvider,
215
245
  saveAcpProxySettings: () => saveAcpProxySettings,
246
+ saveDeepseekProvider: () => saveDeepseekProvider,
216
247
  sdkRequest: () => sdkRequest,
217
248
  shouldPromptAuthWizard: () => shouldPromptAuthWizard,
218
249
  spawnAcpProcess: () => spawnAcpProcess,
@@ -365,8 +396,8 @@ var BUILTIN_ACP_RUNTIMES = [
365
396
  {
366
397
  id: "deepseek",
367
398
  name: "DeepSeek",
368
- description: "通过 bunx 启动 @deepseek-ai/dsh(--profile acp);无 ACP 登录,靠 harness 自身凭证(DEEPSEEK_API_KEY / harness 配置);模型经 session 到达,无需额外动作",
369
- authHint: "无 ACP 登录,靠 harness 自身凭证(DEEPSEEK_API_KEY / harness 配置);未配置先导出 DEEPSEEK_API_KEY;模型经 session 到达,无需额外动作;若官方最新 dsh 存在坏依赖(如 rc.3 缺失),可设 DSH_PACKAGE pin 旧版",
399
+ description: "通过 dsh 启动 @deepseek-ai/dsh(--profile acp);无 ACP 登录,靠 harness 自身凭证(DEEPSEEK_API_KEY 或 $DSH_HOME/.credentials.yaml);模型经 session 到达(V4.1-Flash 的 id 是 deepseek-flash)",
400
+ authHint: "无 ACP 登录,靠 harness 自身凭证;先导出 DEEPSEEK_API_KEY 或在 dsh 里完成登录;稳定安装可设 DSH_BIN 指向 dsh 入口(bunx 临时目录被清理会让 profile 断链);pin 包版本用 DSH_PACKAGE(如 @deepseek-ai/dsh@0.2.1-rc.2)",
370
401
  command: "bunx",
371
402
  args: ["-y", `${DEEPSEEK_DSH_NPM_PACKAGE}@latest`, "--profile", "acp"],
372
403
  requiredEnvKeys: ["DEEPSEEK_API_KEY"]
@@ -385,7 +416,7 @@ function findBuiltinAcpRuntime(id) {
385
416
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
386
417
  }
387
418
  // src/version.ts
388
- var ACP_CLIENT_VERSION = "0.1.11";
419
+ var ACP_CLIENT_VERSION = "0.1.13";
389
420
  // src/client/sdk-client.ts
390
421
  var import_node_stream = require("node:stream");
391
422
  var import_sdk = require("@agentclientprotocol/sdk");
@@ -393,6 +424,8 @@ var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
393
424
  function createSdkStreamHandle(child) {
394
425
  const stdoutBridge = new import_node_stream.PassThrough;
395
426
  const stdinBridge = new import_node_stream.PassThrough;
427
+ stdoutBridge.on("error", () => {});
428
+ stdinBridge.on("error", () => {});
396
429
  child.stdout.pipe(stdoutBridge);
397
430
  stdinBridge.pipe(child.stdin, { end: false });
398
431
  const output = import_node_stream.Writable.toWeb(stdinBridge);
@@ -420,11 +453,11 @@ function createSdkStreamHandle(child) {
420
453
  }
421
454
  };
422
455
  }
423
- function connectSdkClient(child, configure, runtimeId) {
456
+ function connectSdkClient(child, configure, runtimeId, options = {}) {
424
457
  if (runtimeId && true) {
425
458
  console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
426
459
  }
427
- const app = import_sdk.client({ name: "inkdown" });
460
+ const app = import_sdk.client({ name: options.name ?? "inkdown" });
428
461
  configure(app);
429
462
  const streamHandle = createSdkStreamHandle(child);
430
463
  const connection = app.connect(streamHandle.stream);
@@ -454,7 +487,7 @@ async function closeAcpSessions(agent, sessionIds, timeoutMs = 2000) {
454
487
  const failed = [];
455
488
  await Promise.all([...new Set(sessionIds)].map(async (sessionId) => {
456
489
  try {
457
- await sdkRequest(agent, "session/close", { sessionId }, timeoutMs);
490
+ await sdkRequest(agent, import_sdk.methods.agent.session.close, { sessionId }, timeoutMs);
458
491
  } catch {
459
492
  failed.push(sessionId);
460
493
  }
@@ -896,11 +929,24 @@ function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
896
929
  class QuotaCache {
897
930
  bySession = new Map;
898
931
  byRuntime = new Map;
932
+ usageBySession = new Map;
933
+ usageByRuntime = new Map;
899
934
  observe(params, defaultRuntimeId = "unknown") {
900
935
  if (!params || typeof params !== "object")
901
936
  return null;
902
937
  const p = params;
903
938
  const sessionId = typeof p.sessionId === "string" ? p.sessionId : undefined;
939
+ if (p.update?.sessionUpdate === "usage_update") {
940
+ const used = Number(p.update.used);
941
+ const size = Number(p.update.size);
942
+ if (Number.isFinite(used) && Number.isFinite(size) && size > 0) {
943
+ const usage = { used, size, updatedAt: Date.now() };
944
+ if (sessionId)
945
+ this.usageBySession.set(sessionId, usage);
946
+ this.usageByRuntime.set(defaultRuntimeId, usage);
947
+ }
948
+ return null;
949
+ }
904
950
  let textToParse = "";
905
951
  if (p.update?.content && p.update.content.type === "text" && typeof p.update.content.text === "string") {
906
952
  textToParse = p.update.content.text;
@@ -936,9 +982,29 @@ class QuotaCache {
936
982
  }
937
983
  return;
938
984
  }
985
+ applyContextUsage(quota, sessionId, runtimeId = "unknown") {
986
+ const usage = (sessionId ? this.usageBySession.get(sessionId) : undefined) ?? this.usageByRuntime.get(runtimeId);
987
+ if (!usage)
988
+ return quota ?? null;
989
+ const usedPercent = usage.size > 0 ? Math.min(100, Math.round(usage.used / usage.size * 100)) : 0;
990
+ const window = {
991
+ label: "Context",
992
+ used: usage.used,
993
+ total: usage.size,
994
+ usedPercent,
995
+ percentLeft: Math.max(0, 100 - usedPercent)
996
+ };
997
+ if (!quota) {
998
+ return { runtimeId, primaryWindow: window, status: "ok", updatedAt: usage.updatedAt };
999
+ }
1000
+ const rest = (quota.extraWindows ?? []).filter((item) => item.label !== "Context");
1001
+ return { ...quota, extraWindows: [window, ...rest] };
1002
+ }
939
1003
  clear() {
940
1004
  this.bySession.clear();
941
1005
  this.byRuntime.clear();
1006
+ this.usageBySession.clear();
1007
+ this.usageByRuntime.clear();
942
1008
  }
943
1009
  }
944
1010
 
@@ -1534,7 +1600,7 @@ var import_node_util = require("node:util");
1534
1600
  var APP_RESOURCE_CAPABILITIES = {
1535
1601
  "codex-acp": { entry: "CODEX_CONFIG", strategy: "native-overlay", configHome: "CODEX_HOME" },
1536
1602
  opencode: { entry: "OPENCODE_CONFIG_CONTENT", strategy: "native-overlay", configHome: "OPENCODE_CONFIG_DIR" },
1537
- "opencode-v2": { entry: null, strategy: "compatibility", configHome: null },
1603
+ "opencode-v2": { entry: "OPENCODE_CONFIG_CONTENT (questions only)", strategy: "compatibility", configHome: null },
1538
1604
  claude: { entry: "_meta.systemPrompt + _meta.claudeCode.options.plugins", strategy: "native-session", configHome: "CLAUDE_CONFIG_DIR" },
1539
1605
  gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
1540
1606
  copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
@@ -1572,18 +1638,49 @@ function mergeOpenCodeAppConfig(raw, directory) {
1572
1638
  skills: { ...skills, paths: [...new Set([...skills.paths ?? [], import_node_path8.join(directory, "skills")])] }
1573
1639
  });
1574
1640
  }
1641
+ function resolveOpenCodeQuestionMode(version) {
1642
+ const normalized = version.trim().replace(/^opencode\s+v?/i, "");
1643
+ return ["1.18.35", "2.0.6"].includes(normalized) ? "fallback" : "unverified";
1644
+ }
1645
+ function mergeOpenCodeQuestionConfig(raw) {
1646
+ const value = raw?.trim() ? JSON.parse(raw) : {};
1647
+ if (!value || typeof value !== "object" || Array.isArray(value))
1648
+ throw new Error("invalid-opencode-config");
1649
+ const config = value;
1650
+ const permission = config.permission;
1651
+ if (permission !== undefined && (typeof permission !== "string" || !["allow", "ask", "deny"].includes(permission)) && (!permission || typeof permission !== "object" || Array.isArray(permission)))
1652
+ throw new Error("invalid-opencode-permission");
1653
+ const rules = typeof permission === "string" ? { "*": permission } : permission ?? {};
1654
+ return JSON.stringify({ ...config, permission: { ...rules, question: "deny" } });
1655
+ }
1575
1656
  async function prepareOpenCodeResources(input) {
1576
1657
  const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
1577
- if (!input.command || !readAppRulesText(input.directory))
1658
+ prep.report.openCodeQuestions = { mode: "unverified", configuration: "unchanged", reason: "version-not-verified" };
1659
+ if (!input.command)
1578
1660
  return prep;
1579
1661
  try {
1580
1662
  const { stdout } = await import_node_util.promisify(import_node_child_process2.execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
1581
- if (stdout.trim() !== "1.18.35")
1663
+ const version = stdout.trim().replace(/^opencode\s+v?/i, "");
1664
+ if (resolveOpenCodeQuestionMode(version) !== "fallback") {
1665
+ prep.report.openCodeQuestions.version = version;
1582
1666
  return prep;
1583
- const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
1584
- return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
1667
+ }
1668
+ let json = mergeOpenCodeQuestionConfig(input.env?.OPENCODE_CONFIG_CONTENT);
1669
+ const hasRules = version === "1.18.35" && !!readAppRulesText(input.directory);
1670
+ if (hasRules)
1671
+ json = mergeOpenCodeAppConfig(json, input.directory);
1672
+ return { env: { OPENCODE_CONFIG_CONTENT: json }, report: {
1673
+ ...prep.report,
1674
+ rulesPrepared: hasRules,
1675
+ reason: hasRules ? undefined : version === "2.0.6" ? "native-entry-not-verified" : "missing-app-rules",
1676
+ openCodeQuestions: { version, mode: "fallback", configuration: "prepared", reason: "acp-question-not-forwarded" }
1677
+ } };
1585
1678
  } catch {
1586
- return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
1679
+ return { ...prep, report: {
1680
+ ...prep.report,
1681
+ reason: "native-config-prepare-failed",
1682
+ openCodeQuestions: { mode: "unverified", configuration: "unchanged", reason: "prepare-failed" }
1683
+ } };
1587
1684
  }
1588
1685
  }
1589
1686
  function prepareClaudeResources(directory) {
@@ -2179,7 +2276,7 @@ var opencodeAdapter = {
2179
2276
  // src/runtimes/opencode-v2/index.ts
2180
2277
  var opencodeV2Adapter = {
2181
2278
  id: "opencode-v2",
2182
- prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
2279
+ prepareAppResources: prepareOpenCodeResources,
2183
2280
  probeAuth: () => probeOpencodeAuth(),
2184
2281
  orderAuthMethods: (methods) => methods,
2185
2282
  canSkipInteractiveAuth: () => false,
@@ -2479,14 +2576,383 @@ function getCursorCatalogIds(execFile, overrides) {
2479
2576
  }
2480
2577
  }
2481
2578
 
2579
+ // src/runtimes/deepseek/index.ts
2580
+ var import_node_fs16 = require("node:fs");
2581
+
2582
+ // src/runtimes/deepseek/deepseek-provider.ts
2583
+ var import_node_fs14 = require("node:fs");
2584
+ var import_node_os11 = require("node:os");
2585
+ var import_node_path15 = require("node:path");
2586
+ var DEEPSEEK_OFFICIAL_BASE_URL = "https://api.deepseek.com/anthropic";
2587
+ function resolveDshHome(env = process.env) {
2588
+ const override = env.DSH_HOME?.trim();
2589
+ return override || import_node_path15.join(import_node_os11.homedir(), ".dsh");
2590
+ }
2591
+ function resolveDshCredentialsFile(env = process.env) {
2592
+ return import_node_path15.join(resolveDshHome(env), ".credentials.yaml");
2593
+ }
2594
+ function escapeRegExp(value) {
2595
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2596
+ }
2597
+ function readHarnessCredential(name, env = process.env) {
2598
+ try {
2599
+ const text = import_node_fs14.readFileSync(resolveDshCredentialsFile(env), "utf8");
2600
+ const pattern = new RegExp(`^\\s+${escapeRegExp(name)}\\s*:\\s*(.+)$`);
2601
+ let inRefs = false;
2602
+ for (const line of text.split(/\r?\n/)) {
2603
+ if (/^refs\s*:/.test(line)) {
2604
+ inRefs = true;
2605
+ continue;
2606
+ }
2607
+ if (!inRefs)
2608
+ continue;
2609
+ if (/^\S/.test(line))
2610
+ break;
2611
+ const match = pattern.exec(line);
2612
+ if (match) {
2613
+ const value = match[1].trim().replace(/^['"]|['"]$/g, "");
2614
+ return value || null;
2615
+ }
2616
+ }
2617
+ return null;
2618
+ } catch {
2619
+ return null;
2620
+ }
2621
+ }
2622
+ function normalizeDeepseekBaseUrl(raw) {
2623
+ const trimmed = (raw ?? "").trim();
2624
+ if (!trimmed)
2625
+ return DEEPSEEK_OFFICIAL_BASE_URL;
2626
+ const withoutSlash = trimmed.replace(/\/+$/, "");
2627
+ try {
2628
+ const url = new URL(withoutSlash);
2629
+ if (url.host.toLowerCase() === "api.deepseek.com" && (url.pathname === "" || url.pathname === "/")) {
2630
+ return DEEPSEEK_OFFICIAL_BASE_URL;
2631
+ }
2632
+ return withoutSlash;
2633
+ } catch {
2634
+ return withoutSlash;
2635
+ }
2636
+ }
2637
+ function providerFilePath2(dir) {
2638
+ return import_node_path15.join(dir, "agent", "deepseek-provider.json");
2639
+ }
2640
+ function readStoredDeepseekProvider(dir = getDefaultAgentDataDir()) {
2641
+ const file = providerFilePath2(dir);
2642
+ if (!import_node_fs14.existsSync(file))
2643
+ return null;
2644
+ try {
2645
+ const raw = JSON.parse(import_node_fs14.readFileSync(file, "utf8"));
2646
+ if (typeof raw.baseUrl !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
2647
+ return null;
2648
+ }
2649
+ return { baseUrl: normalizeDeepseekBaseUrl(raw.baseUrl), apiKey: raw.apiKey };
2650
+ } catch {
2651
+ return null;
2652
+ }
2653
+ }
2654
+ function getDeepseekProviderStatus(dir = getDefaultAgentDataDir()) {
2655
+ const stored = readStoredDeepseekProvider(dir);
2656
+ if (!stored)
2657
+ return { configured: false, isOfficial: true, hasApiKey: false };
2658
+ return {
2659
+ configured: true,
2660
+ baseUrl: stored.baseUrl,
2661
+ isOfficial: stored.baseUrl === DEEPSEEK_OFFICIAL_BASE_URL,
2662
+ hasApiKey: Boolean(stored.apiKey)
2663
+ };
2664
+ }
2665
+ function validateBaseUrl(baseUrl) {
2666
+ try {
2667
+ const url = new URL(baseUrl);
2668
+ if (url.protocol !== "http:" && url.protocol !== "https:")
2669
+ return "URL 必须是 http(s) 地址";
2670
+ if (!url.hostname)
2671
+ return "URL 缺少主机名";
2672
+ return null;
2673
+ } catch {
2674
+ return "URL 不是合法地址";
2675
+ }
2676
+ }
2677
+ function saveDeepseekProvider(payload, dir = getDefaultAgentDataDir()) {
2678
+ const baseUrl = normalizeDeepseekBaseUrl(payload.baseUrl);
2679
+ const invalid = validateBaseUrl(baseUrl);
2680
+ if (invalid)
2681
+ return err({ code: "INVALID_ARGUMENT", message: invalid });
2682
+ const apiKey = payload.apiKey?.trim() || readStoredDeepseekProvider(dir)?.apiKey || "";
2683
+ if (!apiKey)
2684
+ return err({ code: "INVALID_ARGUMENT", message: "Token/API Key 不能为空" });
2685
+ const file = providerFilePath2(dir);
2686
+ try {
2687
+ import_node_fs14.mkdirSync(import_node_path15.dirname(file), { recursive: true });
2688
+ import_node_fs14.writeFileSync(file, JSON.stringify({ baseUrl, apiKey }, null, 2), "utf8");
2689
+ } catch (error) {
2690
+ return err({
2691
+ code: "FILE_WRITE_ERROR",
2692
+ message: error instanceof Error ? error.message : "写入 DeepSeek 配置失败"
2693
+ });
2694
+ }
2695
+ return ok(getDeepseekProviderStatus(dir));
2696
+ }
2697
+ function clearDeepseekProvider(dir = getDefaultAgentDataDir()) {
2698
+ try {
2699
+ import_node_fs14.rmSync(providerFilePath2(dir), { force: true });
2700
+ return ok(undefined);
2701
+ } catch (error) {
2702
+ return err({
2703
+ code: "FILE_WRITE_ERROR",
2704
+ message: error instanceof Error ? error.message : "删除 DeepSeek 配置失败"
2705
+ });
2706
+ }
2707
+ }
2708
+ function buildDeepseekProviderEnv(stored, currentEnv = process.env) {
2709
+ if (!stored)
2710
+ return {};
2711
+ const env = {};
2712
+ if (!currentEnv.DEEPSEEK_BASE_URL?.trim())
2713
+ env.DEEPSEEK_BASE_URL = stored.baseUrl;
2714
+ if (!currentEnv.DEEPSEEK_API_KEY?.trim())
2715
+ env.DEEPSEEK_API_KEY = stored.apiKey;
2716
+ return env;
2717
+ }
2718
+
2719
+ // src/runtimes/deepseek/dsh-acp-bootstrap.ts
2720
+ var import_node_fs15 = require("node:fs");
2721
+ var import_node_os12 = require("node:os");
2722
+ var import_node_path16 = require("node:path");
2723
+ var DSH_ACP_PINNED_VERSION = "0.2.1-rc.2";
2724
+ var DSH_ACP_DEFAULT_MODEL = "deepseek-flash";
2725
+ var DSH_ACP_DEFAULT_PROVIDER = "deepseek-official";
2726
+ function resolveDshRuntimeRoot(env = process.env) {
2727
+ const override = env.DSH_RUNTIME_DIR?.trim();
2728
+ if (override)
2729
+ return override;
2730
+ if (process.platform === "win32") {
2731
+ const localAppData = env.LOCALAPPDATA?.trim() || import_node_path16.join(import_node_os12.homedir(), "AppData", "Local");
2732
+ return import_node_path16.join(localAppData, "acp-dsh");
2733
+ }
2734
+ if (process.platform === "darwin") {
2735
+ return import_node_path16.join(import_node_os12.homedir(), "Library", "Application Support", "acp-dsh");
2736
+ }
2737
+ const dataHome = env.XDG_DATA_HOME?.trim() || import_node_path16.join(import_node_os12.homedir(), ".local", "share");
2738
+ return import_node_path16.join(dataHome, "acp-dsh");
2739
+ }
2740
+ function resolveManagedDshEntry(env = process.env, version = resolveManagedDshVersion(env)) {
2741
+ return import_node_path16.join(resolveDshRuntimeRoot(env), version, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js");
2742
+ }
2743
+ function parseVersion(value) {
2744
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(value);
2745
+ if (!match)
2746
+ return null;
2747
+ return {
2748
+ nums: [Number(match[1]), Number(match[2]), Number(match[3])],
2749
+ pre: match[4] ? match[4].split(".") : []
2750
+ };
2751
+ }
2752
+ function compareDshVersions(a, b) {
2753
+ const left = parseVersion(a);
2754
+ const right = parseVersion(b);
2755
+ if (!left || !right)
2756
+ return a.localeCompare(b);
2757
+ for (let i = 0;i < 3; i += 1) {
2758
+ if (left.nums[i] !== right.nums[i])
2759
+ return left.nums[i] - right.nums[i];
2760
+ }
2761
+ if (left.pre.length === 0 && right.pre.length > 0)
2762
+ return 1;
2763
+ if (left.pre.length > 0 && right.pre.length === 0)
2764
+ return -1;
2765
+ for (let i = 0;i < Math.max(left.pre.length, right.pre.length); i += 1) {
2766
+ const x = left.pre[i];
2767
+ const y = right.pre[i];
2768
+ if (x === undefined)
2769
+ return -1;
2770
+ if (y === undefined)
2771
+ return 1;
2772
+ const nx = Number(x);
2773
+ const ny = Number(y);
2774
+ if (!Number.isNaN(nx) && !Number.isNaN(ny) && nx !== ny)
2775
+ return nx - ny;
2776
+ if (x !== y)
2777
+ return x < y ? -1 : 1;
2778
+ }
2779
+ return 0;
2780
+ }
2781
+ function hasManagedEntry(root, version) {
2782
+ return import_node_fs15.existsSync(import_node_path16.join(root, version, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"));
2783
+ }
2784
+ function resolveManagedDshVersion(env = process.env) {
2785
+ const explicit = env.DSH_RUNTIME_VERSION?.trim();
2786
+ if (explicit)
2787
+ return explicit;
2788
+ const root = resolveDshRuntimeRoot(env);
2789
+ let best = null;
2790
+ try {
2791
+ for (const name of import_node_fs15.readdirSync(root)) {
2792
+ if (!parseVersion(name))
2793
+ continue;
2794
+ if (!hasManagedEntry(root, name))
2795
+ continue;
2796
+ if (best === null || compareDshVersions(name, best) > 0)
2797
+ best = name;
2798
+ }
2799
+ } catch {}
2800
+ return best ?? DSH_ACP_PINNED_VERSION;
2801
+ }
2802
+ function hasManagedDshRuntime(env = process.env) {
2803
+ return import_node_fs15.existsSync(resolveManagedDshEntry(env));
2804
+ }
2805
+ function safeId(raw, fallback) {
2806
+ const value = raw?.trim();
2807
+ return value && /^[A-Za-z0-9._-]+$/.test(value) ? value : fallback;
2808
+ }
2809
+ function resolveAcpModelOverride(env = process.env) {
2810
+ const flag = env.DSH_ACP_MODEL_PATCH?.trim().toLowerCase();
2811
+ if (flag === "off" || flag === "0" || flag === "false" || flag === "none")
2812
+ return null;
2813
+ return {
2814
+ provider: safeId(env.DSH_PROVIDER, DSH_ACP_DEFAULT_PROVIDER),
2815
+ model: safeId(env.DSH_MODEL, DSH_ACP_DEFAULT_MODEL)
2816
+ };
2817
+ }
2818
+ function buildAcpModelPatch(override) {
2819
+ return [
2820
+ "# 由 @yitom/acp-client 生成:修正 ACP 会话默认模型。",
2821
+ "# dsh-acp-app 自带补丁把 model 写死为 deepseek-v4-flash,该 id 不在 provider catalog 中;",
2822
+ "# V4.1-Flash 的 catalog id 是 deepseek-flash(桌面端 1017 只是 UI 徽标)。",
2823
+ "- id: acp",
2824
+ " name: '@deepseek-ai/dsh-acp'",
2825
+ " config:",
2826
+ ` provider: ${override.provider}`,
2827
+ ` model: ${override.model}`,
2828
+ ""
2829
+ ].join(`
2830
+ `);
2831
+ }
2832
+ var patchFileCache = new Map;
2833
+ function ensureAcpModelPatchFile(env = process.env) {
2834
+ const override = resolveAcpModelOverride(env);
2835
+ if (!override)
2836
+ return null;
2837
+ const key = `${override.provider}/${override.model}`;
2838
+ const cached = patchFileCache.get(key);
2839
+ if (cached !== undefined)
2840
+ return cached;
2841
+ try {
2842
+ const dir = import_node_path16.join(import_node_os12.tmpdir(), "acp-dsh-runtime");
2843
+ import_node_fs15.mkdirSync(dir, { recursive: true });
2844
+ const file = import_node_path16.join(dir, `acp-model-${override.provider}--${override.model}.patch.yml`);
2845
+ const body = buildAcpModelPatch(override);
2846
+ if (!import_node_fs15.existsSync(file) || import_node_fs15.readFileSync(file, "utf8") !== body) {
2847
+ import_node_fs15.writeFileSync(file, body, "utf8");
2848
+ }
2849
+ patchFileCache.set(key, file);
2850
+ return file;
2851
+ } catch {
2852
+ patchFileCache.set(key, null);
2853
+ return null;
2854
+ }
2855
+ }
2856
+ function resetAcpModelPatchCache() {
2857
+ patchFileCache.clear();
2858
+ }
2859
+
2860
+ // src/runtimes/deepseek/quota.ts
2861
+ var DEFAULT_TIMEOUT_MS = 4000;
2862
+ function resolveDeepseekQuotaKey(options = {}) {
2863
+ const env = options.env ?? process.env;
2864
+ const envKey = env.DEEPSEEK_API_KEY?.trim();
2865
+ if (envKey)
2866
+ return envKey;
2867
+ if (options.dataDir) {
2868
+ const stored = readStoredDeepseekProvider(options.dataDir);
2869
+ if (stored?.apiKey)
2870
+ return stored.apiKey;
2871
+ }
2872
+ return readHarnessCredential("DEEPSEEK_API_KEY", env);
2873
+ }
2874
+ function resolveDeepseekApiBase(options = {}) {
2875
+ const env = options.env ?? process.env;
2876
+ const raw = env.DEEPSEEK_BASE_URL?.trim() || (options.dataDir ? readStoredDeepseekProvider(options.dataDir)?.baseUrl : undefined) || DEEPSEEK_OFFICIAL_BASE_URL;
2877
+ const trimmed = raw.replace(/\/+$/, "").replace(/\/anthropic$/i, "");
2878
+ return trimmed || "https://api.deepseek.com";
2879
+ }
2880
+ function unauthorized(runtimeId, message) {
2881
+ return { runtimeId, provider: "DeepSeek", status: "unauthorized", message, updatedAt: Date.now() };
2882
+ }
2883
+ async function probeDeepseekQuota(options = {}) {
2884
+ const runtimeId = options.runtimeId ?? "deepseek";
2885
+ const apiKey = resolveDeepseekQuotaKey(options);
2886
+ if (!apiKey) {
2887
+ return unauthorized(runtimeId, "未配置 DEEPSEEK_API_KEY / 表单 Token,无法查询余额");
2888
+ }
2889
+ const doFetch = options.fetchImpl ?? fetch;
2890
+ try {
2891
+ const response = await doFetch(`${resolveDeepseekApiBase(options)}/user/balance`, {
2892
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
2893
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
2894
+ });
2895
+ if (response.status === 401 || response.status === 403) {
2896
+ return unauthorized(runtimeId, `余额查询被拒绝 (HTTP ${response.status})`);
2897
+ }
2898
+ if (!response.ok)
2899
+ return null;
2900
+ const data = await response.json();
2901
+ const infos = Array.isArray(data.balance_infos) ? data.balance_infos : [];
2902
+ const first = infos[0];
2903
+ const total = first ? Number(first.total_balance) : Number.NaN;
2904
+ const credits = first ? {
2905
+ balance: Number.isFinite(total) ? total : first.total_balance ?? "0",
2906
+ currency: first.currency
2907
+ } : undefined;
2908
+ const balanceText = infos.map((info) => `${info.total_balance ?? "0"} ${info.currency ?? ""}`.trim()).join(" / ");
2909
+ return {
2910
+ runtimeId,
2911
+ provider: "DeepSeek",
2912
+ account: { type: "apiKey", plan: "DeepSeek API" },
2913
+ credits,
2914
+ status: data.is_available === false ? "exhausted" : "ok",
2915
+ message: data.is_available === false ? "账户余额不足,API 暂不可用" : `可用余额 ${balanceText || "未知"}`,
2916
+ rawText: JSON.stringify(data),
2917
+ updatedAt: Date.now()
2918
+ };
2919
+ } catch {
2920
+ return null;
2921
+ }
2922
+ }
2923
+
2482
2924
  // src/runtimes/deepseek/index.ts
2483
2925
  function buildDeepseekMissingKeyMessage() {
2484
- return "未检测到 DEEPSEEK_API_KEY:请先在终端导出该变量(或完成 harness 自身登录)后再连接";
2926
+ return "未检测到 DEEPSEEK_API_KEY,也未在 harness 凭证库中找到登录记录:请先在终端导出该变量,或先在该 harness(dsh)里完成登录后再连接";
2927
+ }
2928
+ function hasDshCredentials(env) {
2929
+ try {
2930
+ const text = import_node_fs16.readFileSync(resolveDshCredentialsFile(env), "utf8");
2931
+ const match = /^records\s*:(.*)$/m.exec(text);
2932
+ if (!match)
2933
+ return false;
2934
+ if (/^\s*(\[\]|\{\}|null|~)\s*$/.test(match[1]))
2935
+ return false;
2936
+ for (const line of text.slice(match.index + match[0].length).split(/\r?\n/)) {
2937
+ if (!line.trim() || line.trim().startsWith("#"))
2938
+ continue;
2939
+ if (/^\s+\S/.test(line))
2940
+ return true;
2941
+ return false;
2942
+ }
2943
+ return false;
2944
+ } catch {
2945
+ return false;
2946
+ }
2485
2947
  }
2486
- function resolveDeepseekSpawnBlocker(env) {
2948
+ function resolveDeepseekSpawnBlocker(env, dataDir) {
2487
2949
  const source = env ?? process.env;
2488
2950
  if (source.DEEPSEEK_API_KEY?.trim())
2489
2951
  return null;
2952
+ if (dataDir && readStoredDeepseekProvider(dataDir))
2953
+ return null;
2954
+ if (hasDshCredentials(source))
2955
+ return null;
2490
2956
  return buildDeepseekMissingKeyMessage();
2491
2957
  }
2492
2958
  function resolveDeepseekPackage(env) {
@@ -2502,39 +2968,86 @@ function resolveDeepseekPackage(env) {
2502
2968
  }
2503
2969
  return raw;
2504
2970
  }
2971
+ var UNSAFE_BIN = /[\u0000-\u001f;&|$()`"'<>*?~#!]/;
2972
+ function resolveDeepseekBin(env) {
2973
+ const raw = (env ?? process.env).DSH_BIN?.trim();
2974
+ if (!raw)
2975
+ return null;
2976
+ if (UNSAFE_BIN.test(raw)) {
2977
+ if (true) {
2978
+ console.warn(`[acp:deepseek] 非法 DSH_BIN 回落包解析: ${raw}`);
2979
+ }
2980
+ return null;
2981
+ }
2982
+ return raw;
2983
+ }
2505
2984
  function resolveDeepseekSpawnCommand(env) {
2506
- const pkg = resolveDeepseekPackage(env);
2985
+ const source = env ?? process.env;
2986
+ const patchFile = ensureAcpModelPatchFile(source);
2987
+ const withPatch = (args) => patchFile ? [...args, "--patch", patchFile] : args;
2988
+ const bin = resolveDeepseekBin(source);
2989
+ if (bin) {
2990
+ const args = ["--profile", "acp"];
2991
+ if (/\.(c|m)?js$/i.test(bin))
2992
+ return { command: process.execPath, args: withPatch([bin, ...args]) };
2993
+ const looksAbsolute = /^([A-Za-z]:[\\/]|\\\\|\/)/.test(bin);
2994
+ if (/\.(cmd|bat)$/i.test(bin) && /\s/.test(bin)) {
2995
+ if (true) {
2996
+ console.warn(`[acp:deepseek] DSH_BIN 为含空格的批处理,回落包解析: ${bin}`);
2997
+ }
2998
+ } else if (!looksAbsolute || import_node_fs16.existsSync(bin)) {
2999
+ return { command: bin, args: withPatch(args) };
3000
+ } else if (true) {
3001
+ console.warn(`[acp:deepseek] DSH_BIN 不存在,回落包解析: ${bin}`);
3002
+ }
3003
+ }
3004
+ if (hasManagedDshRuntime(source)) {
3005
+ const entry = resolveManagedDshEntry(source);
3006
+ return { command: process.execPath, args: withPatch([entry, "--profile", "acp"]) };
3007
+ }
3008
+ const pkg = resolveDeepseekPackage(source);
2507
3009
  const spec = pkg === DEEPSEEK_DSH_NPM_PACKAGE ? `${pkg}@latest` : pkg;
2508
- return { command: "bunx", args: ["-y", spec, "--profile", "acp"] };
3010
+ return { command: "bunx", args: withPatch(["-y", spec, "--profile", "acp"]) };
2509
3011
  }
2510
- function probeDeepseekAuth() {
2511
- const hasApiKeyEnv = Boolean(process.env.DEEPSEEK_API_KEY?.trim());
3012
+ function probeDeepseekAuth(env, dataDir) {
3013
+ const source = env ?? process.env;
3014
+ const hasApiKeyEnv = Boolean(source.DEEPSEEK_API_KEY?.trim());
3015
+ const dshHome = resolveDshHome(source);
3016
+ const hasCredentialsFile = import_node_fs16.existsSync(resolveDshCredentialsFile(source));
3017
+ const hasCredentialRecords = hasDshCredentials(source);
3018
+ const hasStoredProvider = Boolean(dataDir && readStoredDeepseekProvider(dataDir));
2512
3019
  return {
2513
- codexHome: "",
2514
- hasCodexHome: false,
2515
- hasAuthFile: false,
2516
- hasApiKeyEnv,
2517
- looksLoggedIn: hasApiKeyEnv
3020
+ codexHome: dshHome,
3021
+ hasCodexHome: import_node_fs16.existsSync(dshHome),
3022
+ hasAuthFile: hasCredentialsFile,
3023
+ hasApiKeyEnv: hasApiKeyEnv || hasStoredProvider,
3024
+ looksLoggedIn: hasApiKeyEnv || hasStoredProvider || hasCredentialRecords
2518
3025
  };
2519
3026
  }
2520
3027
  var deepseekAdapter = {
2521
3028
  id: "deepseek",
2522
3029
  prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
2523
- probeAuth: () => probeDeepseekAuth(),
3030
+ probeAuth: (context) => probeDeepseekAuth(context?.env, context?.dataDir),
2524
3031
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
2525
- resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
3032
+ resolveSpawnBlocker: (context) => resolveDeepseekSpawnBlocker(context?.env, context?.dataDir),
3033
+ getProviderEnv: ({ dataDir, env }) => buildDeepseekProviderEnv(readStoredDeepseekProvider(dataDir), env),
3034
+ probeQuota: (options) => probeDeepseekQuota({
3035
+ runtimeId: "deepseek",
3036
+ dataDir: options?.dataDir,
3037
+ env: options?.env
3038
+ }),
2526
3039
  orderAuthMethods: (methods) => methods,
2527
3040
  canSkipInteractiveAuth: () => false
2528
3041
  };
2529
3042
 
2530
3043
  // src/runtimes/agy/quota.ts
2531
- var import_node_fs14 = require("node:fs");
2532
- var import_node_path15 = require("node:path");
3044
+ var import_node_fs17 = require("node:fs");
3045
+ var import_node_path17 = require("node:path");
2533
3046
  var import_node_child_process6 = require("node:child_process");
2534
3047
  var os2 = __toESM(require("node:os"), 1);
2535
3048
  function resolveGeminiHome2() {
2536
3049
  const home = process.env.USERPROFILE || process.env.HOME || "";
2537
- return import_node_path15.join(home, ".gemini");
3050
+ return import_node_path17.join(home, ".gemini");
2538
3051
  }
2539
3052
  function resolveAntigravityAccount() {
2540
3053
  if (process.env.GOOGLE_ACCOUNT?.trim()) {
@@ -2547,14 +3060,14 @@ function resolveAntigravityAccount() {
2547
3060
  }
2548
3061
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
2549
3062
  const candidates = [
2550
- process.env.APPDATA ? import_node_path15.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
2551
- import_node_path15.join(home, ".config", "Antigravity", "app_storage.json"),
2552
- import_node_path15.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
3063
+ process.env.APPDATA ? import_node_path17.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
3064
+ import_node_path17.join(home, ".config", "Antigravity", "app_storage.json"),
3065
+ import_node_path17.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
2553
3066
  ].filter(Boolean);
2554
3067
  for (const file of candidates) {
2555
3068
  try {
2556
- if (import_node_fs14.existsSync(file)) {
2557
- const raw = import_node_fs14.readFileSync(file, "utf8");
3069
+ if (import_node_fs17.existsSync(file)) {
3070
+ const raw = import_node_fs17.readFileSync(file, "utf8");
2558
3071
  const json = JSON.parse(raw);
2559
3072
  const username = json["jetski.onboarding.lastLoginUsername"];
2560
3073
  if (username && typeof username === "string" && username.trim()) {
@@ -2575,30 +3088,30 @@ function resolveAntigravityAccount() {
2575
3088
  }
2576
3089
  function resolveAntigravityLanguageServer() {
2577
3090
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
2578
- const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path15.join(home, "AppData", "Roaming") : "");
3091
+ const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path17.join(home, "AppData", "Roaming") : "");
2579
3092
  const baseDirs = [
2580
- appData ? import_node_path15.join(appData, "Antigravity IDE", "logs") : null,
2581
- appData ? import_node_path15.join(appData, "Antigravity", "logs") : null,
2582
- import_node_path15.join(home, ".config", "Antigravity IDE", "logs"),
2583
- import_node_path15.join(home, ".config", "Antigravity", "logs"),
2584
- import_node_path15.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
2585
- import_node_path15.join(home, "Library", "Application Support", "Antigravity", "logs")
3093
+ appData ? import_node_path17.join(appData, "Antigravity IDE", "logs") : null,
3094
+ appData ? import_node_path17.join(appData, "Antigravity", "logs") : null,
3095
+ import_node_path17.join(home, ".config", "Antigravity IDE", "logs"),
3096
+ import_node_path17.join(home, ".config", "Antigravity", "logs"),
3097
+ import_node_path17.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
3098
+ import_node_path17.join(home, "Library", "Application Support", "Antigravity", "logs")
2586
3099
  ].filter(Boolean);
2587
3100
  for (const base of baseDirs) {
2588
3101
  try {
2589
- if (!import_node_fs14.existsSync(base))
3102
+ if (!import_node_fs17.existsSync(base))
2590
3103
  continue;
2591
- const sessionDirs = import_node_fs14.readdirSync(base).map((d) => {
3104
+ const sessionDirs = import_node_fs17.readdirSync(base).map((d) => {
2592
3105
  try {
2593
- return { name: d, time: import_node_fs14.statSync(import_node_path15.join(base, d)).mtimeMs };
3106
+ return { name: d, time: import_node_fs17.statSync(import_node_path17.join(base, d)).mtimeMs };
2594
3107
  } catch {
2595
3108
  return null;
2596
3109
  }
2597
3110
  }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
2598
3111
  for (const s of sessionDirs) {
2599
- const logFile = import_node_path15.join(base, s.name, "ls-main.log");
2600
- if (import_node_fs14.existsSync(logFile)) {
2601
- const content = import_node_fs14.readFileSync(logFile, "utf8");
3112
+ const logFile = import_node_path17.join(base, s.name, "ls-main.log");
3113
+ if (import_node_fs17.existsSync(logFile)) {
3114
+ const content = import_node_fs17.readFileSync(logFile, "utf8");
2602
3115
  const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
2603
3116
  const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
2604
3117
  if (csrfMatch && portMatch) {
@@ -2755,7 +3268,7 @@ async function probeAgyQuota(options) {
2755
3268
  } catch {}
2756
3269
  }
2757
3270
  const geminiHome = resolveGeminiHome2();
2758
- const hasAgyDir = import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity")) || import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity-cli"));
3271
+ const hasAgyDir = import_node_fs17.existsSync(import_node_path17.join(geminiHome, "antigravity")) || import_node_fs17.existsSync(import_node_path17.join(geminiHome, "antigravity-cli"));
2759
3272
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
2760
3273
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
2761
3274
  if (!isAvailable) {
@@ -3076,17 +3589,17 @@ var import_sdk2 = require("@agentclientprotocol/sdk");
3076
3589
 
3077
3590
  // src/client/acp-fs.ts
3078
3591
  var import_promises4 = require("node:fs/promises");
3079
- var import_node_path16 = require("node:path");
3592
+ var import_node_path18 = require("node:path");
3080
3593
  var import_promises5 = require("node:fs/promises");
3081
3594
  var MAX_READ_BYTES = 2 * 1024 * 1024;
3082
3595
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
3083
3596
  function isBinaryDocumentPath(filePath) {
3084
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path16.extname(filePath).toLowerCase());
3597
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path18.extname(filePath).toLowerCase());
3085
3598
  }
3086
3599
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
3087
- const root = import_node_path16.resolve(workspaceRoot);
3088
- const target = import_node_path16.resolve(filePath);
3089
- const rootWithSep = root.endsWith(import_node_path16.sep) ? root : root + import_node_path16.sep;
3600
+ const root = import_node_path18.resolve(workspaceRoot);
3601
+ const target = import_node_path18.resolve(filePath);
3602
+ const rootWithSep = root.endsWith(import_node_path18.sep) ? root : root + import_node_path18.sep;
3090
3603
  if (target !== root && !target.startsWith(rootWithSep)) {
3091
3604
  throw new Error(`路径不在工作区内: ${filePath}`);
3092
3605
  }
@@ -3117,7 +3630,7 @@ async function acpReadTextFile(params) {
3117
3630
  }
3118
3631
  async function acpWriteTextFile(params) {
3119
3632
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
3120
- await import_promises5.mkdir(import_node_path16.dirname(abs), { recursive: true });
3633
+ await import_promises5.mkdir(import_node_path18.dirname(abs), { recursive: true });
3121
3634
  await import_promises4.writeFile(abs, params.content, "utf-8");
3122
3635
  return {};
3123
3636
  }
@@ -3321,6 +3834,16 @@ function coerceOptionValue(raw) {
3321
3834
  return String(raw);
3322
3835
  if (typeof raw === "boolean")
3323
3836
  return String(raw);
3837
+ if (raw !== null && typeof raw === "object") {
3838
+ if (!Array.isArray(raw) && Object.keys(raw).length === 0)
3839
+ return null;
3840
+ try {
3841
+ const encoded = JSON.stringify(raw);
3842
+ return encoded && encoded !== "null" ? encoded : null;
3843
+ } catch {
3844
+ return null;
3845
+ }
3846
+ }
3324
3847
  return null;
3325
3848
  }
3326
3849
  function coerceCurrentValue(raw) {
@@ -3330,8 +3853,41 @@ function coerceCurrentValue(raw) {
3330
3853
  return raw;
3331
3854
  if (typeof raw === "number" && Number.isFinite(raw))
3332
3855
  return String(raw);
3856
+ if (raw !== null && typeof raw === "object") {
3857
+ if (!Array.isArray(raw) && Object.keys(raw).length === 0)
3858
+ return;
3859
+ try {
3860
+ const encoded = JSON.stringify(raw);
3861
+ return encoded && encoded !== "null" ? encoded : undefined;
3862
+ } catch {
3863
+ return;
3864
+ }
3865
+ }
3333
3866
  return;
3334
3867
  }
3868
+ function collectOptionValues(rows, group, out) {
3869
+ for (const opt of rows) {
3870
+ if (!opt || typeof opt !== "object")
3871
+ continue;
3872
+ const o = opt;
3873
+ const nested = Array.isArray(o.options) ? o.options : null;
3874
+ const label = typeof o.group === "string" && o.group ? o.group : group;
3875
+ if (nested && nested.length > 0) {
3876
+ const fallbackName = typeof o.name === "string" && o.name ? o.name : undefined;
3877
+ collectOptionValues(nested, label ?? fallbackName, out);
3878
+ continue;
3879
+ }
3880
+ const value = coerceOptionValue(o.value) ?? coerceOptionValue(o.id);
3881
+ if (!value)
3882
+ continue;
3883
+ out.push({
3884
+ value,
3885
+ name: typeof o.name === "string" ? o.name : String(value),
3886
+ ...typeof o.description === "string" ? { description: o.description } : {},
3887
+ ...label ? { group: label } : {}
3888
+ });
3889
+ }
3890
+ }
3335
3891
  function parseAcpConfigOptions(raw) {
3336
3892
  if (!Array.isArray(raw))
3337
3893
  return [];
@@ -3346,21 +3902,8 @@ function parseAcpConfigOptions(raw) {
3346
3902
  const name = typeof row.name === "string" ? row.name : configId;
3347
3903
  const type = typeof row.type === "string" ? row.type : "select";
3348
3904
  const values = [];
3349
- if (Array.isArray(row.options)) {
3350
- for (const opt of row.options) {
3351
- if (!opt || typeof opt !== "object")
3352
- continue;
3353
- const o = opt;
3354
- const value = coerceOptionValue(o.value) ?? coerceOptionValue(o.id);
3355
- if (!value)
3356
- continue;
3357
- values.push({
3358
- value,
3359
- name: typeof o.name === "string" ? o.name : String(value),
3360
- description: typeof o.description === "string" ? o.description : undefined
3361
- });
3362
- }
3363
- }
3905
+ if (Array.isArray(row.options))
3906
+ collectOptionValues(row.options, undefined, values);
3364
3907
  options.push({
3365
3908
  configId,
3366
3909
  name,
@@ -3457,6 +4000,9 @@ function mergeTopLevelModelsIntoConfigOptions(configOptionsRaw, response) {
3457
4000
  }
3458
4001
 
3459
4002
  // src/client/session-open.ts
4003
+ function isAuthenticationRequired(message) {
4004
+ return !/\bmcp\b/i.test(message) && /authentication required|not authenticated|please (?:log|sign) in|需要认证|尚未认证/i.test(message);
4005
+ }
3460
4006
  function errorMessage(error) {
3461
4007
  return error instanceof Error ? error.message : String(error);
3462
4008
  }
@@ -3476,29 +4022,30 @@ function isTransientAcpTransportError(error) {
3476
4022
  return /ACP connection closed|connection closed|closed|abort|超时|timeout|timed out|econnreset|epipe|stdio|stream/i.test(message);
3477
4023
  }
3478
4024
  async function restoreOrCreateAcpSession(input) {
3479
- const resumeId = input.resumeSessionId?.trim() || null;
3480
- const restoreAttempts = [];
3481
4025
  let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
3482
4026
  let nativeSessionAccepted = false;
4027
+ let recoveredToolOutputs;
3483
4028
  const request = async (method, params) => {
3484
- if (!input.sessionMeta)
3485
- return input.request(method, params);
3486
- try {
3487
- const result = await input.request(method, { ...params, _meta: input.sessionMeta });
3488
- nativeSessionAccepted = true;
3489
- return result;
3490
- } catch (error) {
3491
- const rejected = error instanceof import_sdk3.RequestError && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
3492
- if (!rejected || isTransientAcpTransportError(error))
3493
- throw error;
3494
- log("warn", "native resource options failed; retry without extension");
3495
- const result = await input.request(method, params);
3496
- nativeSessionAccepted = false;
3497
- return result;
3498
- }
4029
+ const opened = await requestSessionWithResources(input.request, method, params, input.sessionMeta);
4030
+ nativeSessionAccepted = opened.nativeSessionAccepted;
4031
+ const meta = opened.result._meta;
4032
+ const outputs = meta?.toolOutputRecovery?.outputs;
4033
+ let total = 0;
4034
+ recoveredToolOutputs = Array.isArray(outputs) ? outputs.slice(0, 20).filter((row) => {
4035
+ if (!row || typeof row.toolCallId !== "string" || row.toolCallId.length > 120 || typeof row.text !== "string")
4036
+ return false;
4037
+ const bytes = Buffer.byteLength(row.text);
4038
+ if (bytes > 128 * 1024 || total + bytes > 256 * 1024)
4039
+ return false;
4040
+ total += bytes;
4041
+ return true;
4042
+ }) : undefined;
4043
+ return opened.result;
3499
4044
  };
4045
+ const resumeId = input.resumeSessionId?.trim() || null;
4046
+ const restoreAttempts = [];
3500
4047
  const delayMs = input.retryDelayMs ?? 250;
3501
- const log = input.log ?? ((level, message, data) => {
4048
+ const outputLog = input.log ?? ((level, message, data) => {
3502
4049
  if (level === "info" && false)
3503
4050
  ;
3504
4051
  const line = `[acp] ${message}`;
@@ -3507,6 +4054,7 @@ async function restoreOrCreateAcpSession(input) {
3507
4054
  else
3508
4055
  console.info(line, data ?? "");
3509
4056
  });
4057
+ const log = outputLog;
3510
4058
  const tryRestoreMethod = async (method, rpcMethod) => {
3511
4059
  const maxTries = 2;
3512
4060
  let lastError = "";
@@ -3557,19 +4105,17 @@ async function restoreOrCreateAcpSession(input) {
3557
4105
  mcpServers: input.mcpServers ?? []
3558
4106
  };
3559
4107
  try {
3560
- return await request("session/new", baseParams);
4108
+ return await request(import_sdk3.methods.agent.session.new, baseParams);
3561
4109
  } catch (firstError) {
3562
4110
  if ((input.mcpServers ?? []).length === 0)
3563
4111
  throw firstError;
3564
- log("warn", "session/new failed, retry without mcpServers", {
4112
+ log("warn", input.preserveMcpOnRetry ? "session/new failed, retry with mcpServers" : "session/new failed, retry without mcpServers", {
3565
4113
  error: errorMessage(firstError)
3566
4114
  });
3567
4115
  try {
3568
- const result = await request("session/new", {
3569
- cwd: input.cwd,
3570
- mcpServers: []
3571
- });
3572
- mcpServersAccepted = false;
4116
+ const retryServers = input.preserveMcpOnRetry ? input.mcpServers ?? [] : [];
4117
+ const result = await request(import_sdk3.methods.agent.session.new, { cwd: input.cwd, mcpServers: retryServers });
4118
+ mcpServersAccepted = retryServers.length > 0;
3573
4119
  return result;
3574
4120
  } catch {
3575
4121
  throw firstError;
@@ -3578,16 +4124,17 @@ async function restoreOrCreateAcpSession(input) {
3578
4124
  };
3579
4125
  const withModelsFallback = (result) => mergeTopLevelModelsIntoConfigOptions(result.configOptions, result);
3580
4126
  if (resumeId && input.resumeSupported) {
3581
- const resumed = await tryRestoreMethod("resume", "session/resume");
4127
+ const resumed = await tryRestoreMethod("resume", import_sdk3.methods.agent.session.resume);
3582
4128
  if (resumed) {
3583
4129
  const id = typeof resumed.sessionId === "string" ? resumed.sessionId : resumeId;
3584
4130
  return {
3585
4131
  sessionId: id,
4132
+ mcpServersAccepted,
4133
+ recoveredToolOutputs,
4134
+ nativeSessionAccepted,
3586
4135
  configOptions: withModelsFallback(resumed),
3587
4136
  restoreMethod: "resume",
3588
4137
  sessionRestored: true,
3589
- mcpServersAccepted,
3590
- nativeSessionAccepted,
3591
4138
  requestedSessionId: resumeId,
3592
4139
  restoreAttempts
3593
4140
  };
@@ -3598,16 +4145,17 @@ async function restoreOrCreateAcpSession(input) {
3598
4145
  if (resumeId && input.loadSupported) {
3599
4146
  input.onSuppressUpdates?.(true);
3600
4147
  try {
3601
- const loaded = await tryRestoreMethod("load", "session/load");
4148
+ const loaded = await tryRestoreMethod("load", import_sdk3.methods.agent.session.load);
3602
4149
  if (loaded) {
3603
4150
  const id = typeof loaded.sessionId === "string" ? loaded.sessionId : resumeId;
3604
4151
  return {
3605
4152
  sessionId: id,
4153
+ mcpServersAccepted,
4154
+ recoveredToolOutputs,
4155
+ nativeSessionAccepted,
3606
4156
  configOptions: withModelsFallback(loaded),
3607
4157
  restoreMethod: "load",
3608
4158
  sessionRestored: true,
3609
- mcpServersAccepted,
3610
- nativeSessionAccepted,
3611
4159
  requestedSessionId: resumeId,
3612
4160
  restoreAttempts
3613
4161
  };
@@ -3626,15 +4174,27 @@ async function restoreOrCreateAcpSession(input) {
3626
4174
  }
3627
4175
  return {
3628
4176
  sessionId: newSessionId,
4177
+ mcpServersAccepted,
4178
+ nativeSessionAccepted,
3629
4179
  configOptions: withModelsFallback(sessionResult),
3630
4180
  restoreMethod: "new",
3631
4181
  sessionRestored: false,
3632
- mcpServersAccepted,
3633
- nativeSessionAccepted,
3634
4182
  requestedSessionId: resumeId ?? undefined,
3635
4183
  restoreAttempts
3636
4184
  };
3637
4185
  }
4186
+ async function requestSessionWithResources(request, method, params, sessionMeta) {
4187
+ if (!sessionMeta)
4188
+ return { result: await request(method, params), nativeSessionAccepted: false };
4189
+ try {
4190
+ return { result: await request(method, { ...params, _meta: sessionMeta }), nativeSessionAccepted: true };
4191
+ } catch (error) {
4192
+ const rejected = error instanceof import_sdk3.RequestError && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
4193
+ if (!rejected || isTransientAcpTransportError(error))
4194
+ throw error;
4195
+ return { result: await request(method, params), nativeSessionAccepted: false };
4196
+ }
4197
+ }
3638
4198
 
3639
4199
  // src/client/acp-terminal.ts
3640
4200
  var import_node_child_process8 = require("node:child_process");
@@ -3822,8 +4382,8 @@ class AcpTerminalManager {
3822
4382
 
3823
4383
  // src/client/acp-proxy-service.ts
3824
4384
  var import_promises6 = require("node:fs/promises");
3825
- var import_node_fs15 = require("node:fs");
3826
- var import_node_path17 = require("node:path");
4385
+ var import_node_fs18 = require("node:fs");
4386
+ var import_node_path19 = require("node:path");
3827
4387
  var DEFAULT_ACP_PROXY_SETTINGS = {
3828
4388
  enabled: false,
3829
4389
  host: "127.0.0.1",
@@ -3832,7 +4392,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
3832
4392
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
3833
4393
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
3834
4394
  function proxyFilePath(dir) {
3835
- return import_node_path17.join(dir, "agent", "proxy.json");
4395
+ return import_node_path19.join(dir, "agent", "proxy.json");
3836
4396
  }
3837
4397
  function validate2(settings) {
3838
4398
  if (!settings.host.trim())
@@ -3844,7 +4404,7 @@ function validate2(settings) {
3844
4404
  }
3845
4405
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
3846
4406
  const file = proxyFilePath(dir);
3847
- if (!import_node_fs15.existsSync(file))
4407
+ if (!import_node_fs18.existsSync(file))
3848
4408
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
3849
4409
  try {
3850
4410
  const raw = JSON.parse(await import_promises6.readFile(file, "utf8"));
@@ -3866,7 +4426,7 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
3866
4426
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
3867
4427
  port: payload.port
3868
4428
  };
3869
- await import_promises6.mkdir(import_node_path17.join(dir, "agent"), { recursive: true });
4429
+ await import_promises6.mkdir(import_node_path19.join(dir, "agent"), { recursive: true });
3870
4430
  await import_promises6.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3871
4431
  return ok(stored);
3872
4432
  }
@@ -3922,9 +4482,9 @@ function compatDeliveryKey(sessionId, generation, digest) {
3922
4482
  }
3923
4483
 
3924
4484
  // src/mcp/app-skills-mcp.ts
3925
- var import_node_path18 = require("node:path");
4485
+ var import_node_path20 = require("node:path");
3926
4486
  var import_node_url = require("node:url");
3927
- var import_node_fs16 = require("node:fs");
4487
+ var import_node_fs19 = require("node:fs");
3928
4488
  var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
3929
4489
  var APP_SKILLS_TOOLS = [
3930
4490
  {
@@ -3960,11 +4520,11 @@ function buildAppSkillsMcpServer(directory, opts) {
3960
4520
  function resolveAppSkillsRunnerPath(fromFile) {
3961
4521
  const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
3962
4522
  const candidates = [
3963
- import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.cjs"),
3964
- import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.ts")
4523
+ import_node_path20.join(import_node_path20.dirname(base), "app-skills-mcp-serve.cjs"),
4524
+ import_node_path20.join(import_node_path20.dirname(base), "app-skills-mcp-serve.ts")
3965
4525
  ];
3966
4526
  for (const candidate of candidates) {
3967
- if (import_node_fs16.existsSync(candidate))
4527
+ if (import_node_fs19.existsSync(candidate))
3968
4528
  return candidate;
3969
4529
  }
3970
4530
  throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
@@ -4144,7 +4704,10 @@ class AcpClient {
4144
4704
  const connectGen = this.connectionGen;
4145
4705
  try {
4146
4706
  this.setStatus("connecting");
4147
- const blocker = this.adapter.resolveSpawnBlocker?.();
4707
+ const blocker = this.adapter.resolveSpawnBlocker?.({
4708
+ env: { ...process.env, ...this.extraEnv },
4709
+ dataDir: this.dataDir
4710
+ });
4148
4711
  if (blocker) {
4149
4712
  this.setStatus("error", blocker);
4150
4713
  return err({ code: "ACP_SPAWN_ERROR", message: blocker });
@@ -4167,6 +4730,10 @@ class AcpClient {
4167
4730
  ...baseEnv,
4168
4731
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
4169
4732
  };
4733
+ const providerEnv = this.adapter.getProviderEnv?.({
4734
+ dataDir: this.dataDir,
4735
+ env: { ...process.env, ...spawnEnv.env }
4736
+ }) ?? {};
4170
4737
  let resourceEnv = {};
4171
4738
  let profileTag = null;
4172
4739
  if (this.resourcesDir && this.configurationScope === "session") {
@@ -4177,6 +4744,13 @@ class AcpClient {
4177
4744
  }
4178
4745
  this.sessionConfig = profile;
4179
4746
  resourceEnv = this.sessionConfig.env;
4747
+ const interactions = ["opencode", "opencode-v2"].includes(this.runtimeInfo.id) && this.adapter.prepareAppResources ? await this.adapter.prepareAppResources({
4748
+ directory: this.resourcesDir,
4749
+ command: effectiveRuntime.command,
4750
+ workspaceRoot: this.workspaceRoot,
4751
+ env: { ...process.env, ...spawnEnv.env, ...resourceEnv }
4752
+ }) : undefined;
4753
+ Object.assign(resourceEnv, interactions?.env);
4180
4754
  const load = readAppResourcesDir(this.resourcesDir);
4181
4755
  this.resourcePrep = { profileTag: null, report: {
4182
4756
  rulesApplied: false,
@@ -4185,6 +4759,7 @@ class AcpClient {
4185
4759
  rulesChars: load.rules?.chars ?? 0,
4186
4760
  profileDigest: digestAppResources(load),
4187
4761
  skillsFound: load.skills.map((s) => s.name),
4762
+ openCodeQuestions: interactions?.report.openCodeQuestions,
4188
4763
  configurationScope: "session",
4189
4764
  configurationDirectory: this.sessionConfig.directory,
4190
4765
  configurationRulesFile: this.sessionConfig.rulesFile,
@@ -4233,7 +4808,7 @@ class AcpClient {
4233
4808
  reason: "runtime-not-supported"
4234
4809
  } } : null;
4235
4810
  }
4236
- const finalEnv = { ...spawnEnv.env, ...resourceEnv };
4811
+ const finalEnv = { ...spawnEnv.env, ...providerEnv, ...resourceEnv };
4237
4812
  await this.adapter.beforeSpawn?.();
4238
4813
  if (connectGen !== this.connectionGen || this.status !== "connecting")
4239
4814
  return err({ code: "CANCELLED", message: "连接已取消" });
@@ -4345,21 +4920,25 @@ class AcpClient {
4345
4920
  }
4346
4921
  }
4347
4922
  getCachedQuota(sessionId) {
4348
- return this.quotaCache.get(sessionId, this.runtimeInfo.id);
4923
+ return this.quotaCache.applyContextUsage(this.quotaCache.get(sessionId, this.runtimeInfo.id), sessionId, this.runtimeInfo.id) ?? undefined;
4349
4924
  }
4350
4925
  async getQuota(sessionId) {
4351
- const cached = this.getCachedQuota(sessionId);
4926
+ const cached = this.quotaCache.get(sessionId, this.runtimeInfo.id);
4352
4927
  if (cached && Date.now() - cached.updatedAt < 30000) {
4353
- return cached;
4928
+ return this.quotaCache.applyContextUsage(cached, sessionId, this.runtimeInfo.id);
4354
4929
  }
4355
4930
  if (this.adapter.probeQuota) {
4356
- const probed = await this.adapter.probeQuota({ sessionId });
4931
+ const probed = await this.adapter.probeQuota({
4932
+ sessionId,
4933
+ dataDir: this.dataDir,
4934
+ env: { ...process.env, ...this.extraEnv }
4935
+ });
4357
4936
  if (probed) {
4358
4937
  this.quotaCache.set(probed, sessionId);
4359
- return probed;
4938
+ return this.quotaCache.applyContextUsage(probed, sessionId, this.runtimeInfo.id);
4360
4939
  }
4361
4940
  }
4362
- return cached ?? null;
4941
+ return this.quotaCache.applyContextUsage(cached ?? null, sessionId, this.runtimeInfo.id);
4363
4942
  }
4364
4943
  getAvailableCommands(sessionId) {
4365
4944
  return this.commandsCache.get(sessionId);