@yitom/acp-client 0.1.14 → 0.1.16

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
@@ -68,7 +68,11 @@ __export(exports_src, {
68
68
  ACP_CLIENT_VERSION: () => ACP_CLIENT_VERSION,
69
69
  ACP_EARLY_EXIT_STDERR_TAIL_LINES: () => ACP_EARLY_EXIT_STDERR_TAIL_LINES,
70
70
  ACP_EARLY_EXIT_WINDOW_MS: () => ACP_EARLY_EXIT_WINDOW_MS,
71
+ ACP_FS_MAX_READ_BYTES: () => ACP_FS_MAX_READ_BYTES,
72
+ ACP_PROMPT_IDLE_TIMEOUT_MS: () => ACP_PROMPT_IDLE_TIMEOUT_MS,
73
+ ACP_PROMPT_MAX_DURATION_MS: () => ACP_PROMPT_MAX_DURATION_MS,
71
74
  ACP_SDK_REQUEST_TIMEOUT_MS: () => ACP_SDK_REQUEST_TIMEOUT_MS,
75
+ ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT: () => ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT,
72
76
  AGY_ACP_NPM_PACKAGE: () => AGY_ACP_NPM_PACKAGE,
73
77
  APP_RESOURCE_CAPABILITIES: () => APP_RESOURCE_CAPABILITIES,
74
78
  APP_RULES_FILE: () => APP_RULES_FILE,
@@ -98,9 +102,11 @@ __export(exports_src, {
98
102
  NATIVE_ELIGIBLE_BRIDGE_VERSIONS: () => NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
99
103
  OPENCODE_CLI_NPM_PACKAGE: () => OPENCODE_CLI_NPM_PACKAGE,
100
104
  QuotaCache: () => QuotaCache,
105
+ SdkRequestTimeoutError: () => SdkRequestTimeoutError,
101
106
  acpReadTextFile: () => acpReadTextFile,
102
107
  acpWriteTextFile: () => acpWriteTextFile,
103
108
  agyAdapter: () => agyAdapter,
109
+ antigravityCliAdapter: () => antigravityCliAdapter,
104
110
  appendTerminalOutput: () => appendTerminalOutput,
105
111
  assertPathInsideWorkspace: () => assertPathInsideWorkspace,
106
112
  buildAcpProxySpawnEnv: () => buildAcpProxySpawnEnv,
@@ -119,6 +125,7 @@ __export(exports_src, {
119
125
  codexAdapter: () => codexAdapter,
120
126
  connectSdkClient: () => connectSdkClient,
121
127
  copilotAdapter: () => copilotAdapter,
128
+ createSdkRequestActivityController: () => createSdkRequestActivityController,
122
129
  createSdkStreamHandle: () => createSdkStreamHandle,
123
130
  createSessionConfigHome: () => createSessionConfigHome,
124
131
  cursorAdapter: () => cursorAdapter,
@@ -146,6 +153,7 @@ __export(exports_src, {
146
153
  handleInkdownMcpRpc: () => handleInkdownMcpRpc,
147
154
  hasDeepseekHarnessCredentials: () => hasDeepseekHarnessCredentials,
148
155
  isAbsolutePathLike: () => isAbsolutePathLike,
156
+ isAcpPermissionOutcome: () => isAcpPermissionOutcome,
149
157
  isAppError: () => isAppError,
150
158
  isAuthenticationRequired: () => isAuthenticationRequired,
151
159
  isBinaryDocumentPath: () => isBinaryDocumentPath,
@@ -186,6 +194,7 @@ __export(exports_src, {
186
194
  prepareCompatibilityResources: () => prepareCompatibilityResources,
187
195
  prepareOpenCodeResources: () => prepareOpenCodeResources,
188
196
  probeAgyAuth: () => probeAgyAuth,
197
+ probeAgyQuota: () => probeAgyQuota,
189
198
  probeClaudeAuth: () => probeClaudeAuth,
190
199
  probeClaudeQuota: () => probeClaudeQuota,
191
200
  probeCodexAuth: () => probeCodexAuth,
@@ -205,6 +214,9 @@ __export(exports_src, {
205
214
  readStoredAcpProvider: () => readStoredAcpProvider,
206
215
  registerAcpClientHandlers: () => registerAcpClientHandlers,
207
216
  requestSessionWithResources: () => requestSessionWithResources,
217
+ resolveAntigravityAccount: () => resolveAntigravityAccount,
218
+ resolveAntigravityCliCommand: () => resolveAntigravityCliCommand,
219
+ resolveAntigravityLanguageServer: () => resolveAntigravityLanguageServer,
208
220
  resolveAppCodexHome: () => resolveAppCodexHome,
209
221
  resolveClaudeHome: () => resolveClaudeHome,
210
222
  resolveCodexHome: () => resolveCodexHome,
@@ -226,6 +238,7 @@ __export(exports_src, {
226
238
  saveAcpProvider: () => saveAcpProvider,
227
239
  saveAcpProxySettings: () => saveAcpProxySettings,
228
240
  sdkRequest: () => sdkRequest,
241
+ sdkRequestWithActivity: () => sdkRequestWithActivity,
229
242
  shouldPromptAuthWizard: () => shouldPromptAuthWizard,
230
243
  spawnAcpProcess: () => spawnAcpProcess,
231
244
  supportsCodeMode: () => supportsCodeMode,
@@ -385,10 +398,19 @@ var BUILTIN_ACP_RUNTIMES = [
385
398
  args: ["-y", `${DEEPSEEK_DSH_NPM_PACKAGE}@latest`, "--profile", "acp"],
386
399
  requiredEnvKeys: ["DEEPSEEK_API_KEY"]
387
400
  },
401
+ {
402
+ id: "antigravity-cli",
403
+ name: "Antigravity",
404
+ description: "启动 Google Antigravity CLI 自带的 agy acp 服务",
405
+ authHint: "复用 Antigravity CLI 登录。需要登录时选择 Agent 提供的方式,或在终端运行 agy acp --login",
406
+ command: isWindowsPlatform() ? "agy.exe" : "agy",
407
+ args: ["acp"],
408
+ requiredEnvKeys: []
409
+ },
388
410
  {
389
411
  id: "agy",
390
- name: "agy",
391
- description: "经 bunx 直调官方桥 JS 入口(免安装,跨平台;版本跟随 bunx 解析)",
412
+ name: "Antigravity (legacy bridge)",
413
+ description: "通过 bunx 启动 @yitom/agy-acp-map,兼容旧会话 ID 和桥接扩展",
392
414
  authHint: "复用 Antigravity CLI 本地登录态;未登录先在本机终端完成 agy 登录后再连接",
393
415
  command: "bunx",
394
416
  args: ["-y", `${AGY_ACP_NPM_PACKAGE}@latest`],
@@ -399,7 +421,7 @@ function findBuiltinAcpRuntime(id) {
399
421
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
400
422
  }
401
423
  // src/version.ts
402
- var ACP_CLIENT_VERSION = "0.1.14";
424
+ var ACP_CLIENT_VERSION = "0.1.16";
403
425
  // src/client/session-open.ts
404
426
  var import_sdk = require("@agentclientprotocol/sdk");
405
427
 
@@ -632,6 +654,8 @@ async function restoreOrCreateAcpSession(input) {
632
654
  return result;
633
655
  } catch (error) {
634
656
  lastError = errorMessage(error);
657
+ if (isAuthenticationRequired(lastError))
658
+ throw error;
635
659
  log("warn", "session restore failed", {
636
660
  method: rpcMethod,
637
661
  sessionId: resumeId,
@@ -663,7 +687,7 @@ async function restoreOrCreateAcpSession(input) {
663
687
  try {
664
688
  return await request("session/new", baseParams);
665
689
  } catch (firstError) {
666
- if (isTransientAcpTransportError(firstError))
690
+ if (isAuthenticationRequired(errorMessage(firstError)) || isTransientAcpTransportError(firstError))
667
691
  throw firstError;
668
692
  if ((input.mcpServers ?? []).length === 0)
669
693
  throw firstError;
@@ -929,6 +953,64 @@ class AcpMcpSessionRecovery {
929
953
  var import_node_stream = require("node:stream");
930
954
  var import_sdk2 = require("@agentclientprotocol/sdk");
931
955
  var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
956
+ var ACP_PROMPT_IDLE_TIMEOUT_MS = 300000;
957
+ var ACP_PROMPT_MAX_DURATION_MS = 0;
958
+ var MAX_SAFE_TIMER_MS = 2147483647;
959
+
960
+ class SdkRequestTimeoutError extends Error {
961
+ kind;
962
+ method;
963
+ durationMs;
964
+ constructor(kind, method, durationMs) {
965
+ const secs = Math.max(1, Math.round(durationMs / 1000));
966
+ const message = kind === "idle" ? `请求超时 (${secs}s 无活动): ${method}` : kind === "max_duration" ? `请求超时 (超过最大时长 ${secs}s): ${method}` : `请求超时: ${method}`;
967
+ super(message);
968
+ this.name = "SdkRequestTimeoutError";
969
+ this.kind = kind;
970
+ this.method = method;
971
+ this.durationMs = durationMs;
972
+ }
973
+ }
974
+ var activitySubscribers = new WeakMap;
975
+ function createSdkRequestActivityController() {
976
+ let pauseCount = 0;
977
+ const subscribers = new Set;
978
+ const controller = {
979
+ touch() {
980
+ for (const sub of subscribers) {
981
+ sub.onTouch();
982
+ }
983
+ },
984
+ pause() {
985
+ let released = false;
986
+ pauseCount += 1;
987
+ if (pauseCount === 1) {
988
+ for (const sub of subscribers) {
989
+ sub.onPauseChange(true);
990
+ }
991
+ }
992
+ return () => {
993
+ if (released)
994
+ return;
995
+ released = true;
996
+ pauseCount = Math.max(0, pauseCount - 1);
997
+ if (pauseCount === 0) {
998
+ for (const sub of subscribers) {
999
+ sub.onPauseChange(false);
1000
+ }
1001
+ }
1002
+ };
1003
+ }
1004
+ };
1005
+ activitySubscribers.set(controller, {
1006
+ subscribers,
1007
+ isPaused: () => pauseCount > 0
1008
+ });
1009
+ return controller;
1010
+ }
1011
+ function clampTimerMs(ms) {
1012
+ return Math.max(1, Math.min(MAX_SAFE_TIMER_MS, Math.floor(ms)));
1013
+ }
932
1014
  function createSdkStreamHandle(child) {
933
1015
  const stdoutBridge = new import_node_stream.PassThrough;
934
1016
  const stdinBridge = new import_node_stream.PassThrough;
@@ -959,17 +1041,107 @@ function createSdkStreamHandle(child) {
959
1041
  }
960
1042
  };
961
1043
  }
962
- function connectSdkClient(child, configure, runtimeId) {
1044
+ function connectSdkClient(child, configure, runtimeId, clientInfo) {
963
1045
  if (runtimeId && true) {
964
1046
  console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
965
1047
  }
966
- const app = import_sdk2.client({ name: "inkdown" });
1048
+ const app = import_sdk2.client({
1049
+ name: clientInfo?.name || "acp-client",
1050
+ ...clientInfo?.version ? { version: clientInfo.version } : {}
1051
+ });
967
1052
  configure(app);
968
1053
  const streamHandle = createSdkStreamHandle(child);
969
1054
  const connection = app.connect(streamHandle.stream);
970
1055
  return { app, connection, streamHandle };
971
1056
  }
1057
+ async function sdkRequestWithActivity(agent, method, params, options = {}) {
1058
+ const idleTimeoutMs = options.idleTimeoutMs;
1059
+ const maxDurationMs = options.maxDurationMs;
1060
+ const hasIdle = typeof idleTimeoutMs === "number" && Number.isFinite(idleTimeoutMs) && idleTimeoutMs > 0;
1061
+ const hasMax = typeof maxDurationMs === "number" && Number.isFinite(maxDurationMs) && maxDurationMs > 0;
1062
+ if (!hasIdle && !hasMax) {
1063
+ return await agent.request(method, params);
1064
+ }
1065
+ const controller = new AbortController;
1066
+ let idleTimer;
1067
+ let maxTimer;
1068
+ let settled = false;
1069
+ let rejectTimeout;
1070
+ let paused = false;
1071
+ const meta = options.activity ? activitySubscribers.get(options.activity) : undefined;
1072
+ if (meta)
1073
+ paused = meta.isPaused();
1074
+ const clearIdleTimer = () => {
1075
+ if (idleTimer !== undefined) {
1076
+ clearTimeout(idleTimer);
1077
+ idleTimer = undefined;
1078
+ }
1079
+ };
1080
+ const armIdleTimer = () => {
1081
+ clearIdleTimer();
1082
+ if (settled || paused || !hasIdle)
1083
+ return;
1084
+ idleTimer = setTimeout(() => {
1085
+ if (settled)
1086
+ return;
1087
+ settled = true;
1088
+ controller.abort();
1089
+ rejectTimeout(new SdkRequestTimeoutError("idle", method, idleTimeoutMs));
1090
+ }, clampTimerMs(idleTimeoutMs));
1091
+ idleTimer.unref?.();
1092
+ };
1093
+ const subscriber = {
1094
+ onTouch() {
1095
+ if (!paused)
1096
+ armIdleTimer();
1097
+ },
1098
+ onPauseChange(nextPaused) {
1099
+ paused = nextPaused;
1100
+ if (paused) {
1101
+ clearIdleTimer();
1102
+ } else {
1103
+ armIdleTimer();
1104
+ }
1105
+ }
1106
+ };
1107
+ if (meta) {
1108
+ meta.subscribers.add(subscriber);
1109
+ }
1110
+ try {
1111
+ const pending = agent.request(method, params, {
1112
+ cancellationSignal: controller.signal
1113
+ });
1114
+ const timeout = new Promise((_, reject) => {
1115
+ rejectTimeout = reject;
1116
+ if (hasIdle && !paused) {
1117
+ armIdleTimer();
1118
+ }
1119
+ if (hasMax) {
1120
+ maxTimer = setTimeout(() => {
1121
+ if (settled)
1122
+ return;
1123
+ settled = true;
1124
+ controller.abort();
1125
+ reject(new SdkRequestTimeoutError("max_duration", method, maxDurationMs));
1126
+ }, clampTimerMs(maxDurationMs));
1127
+ maxTimer.unref?.();
1128
+ }
1129
+ });
1130
+ return await Promise.race([pending, timeout]);
1131
+ } finally {
1132
+ settled = true;
1133
+ clearIdleTimer();
1134
+ if (maxTimer !== undefined)
1135
+ clearTimeout(maxTimer);
1136
+ if (meta) {
1137
+ meta.subscribers.delete(subscriber);
1138
+ }
1139
+ }
1140
+ }
972
1141
  async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
1142
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
1143
+ return await agent.request(method, params);
1144
+ }
973
1145
  const controller = new AbortController;
974
1146
  let timer;
975
1147
  try {
@@ -979,8 +1151,8 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
979
1151
  const timeout = new Promise((_, reject) => {
980
1152
  timer = setTimeout(() => {
981
1153
  controller.abort();
982
- reject(new Error(`请求超时: ${method}`));
983
- }, timeoutMs);
1154
+ reject(new SdkRequestTimeoutError("timeout", method, timeoutMs));
1155
+ }, clampTimerMs(timeoutMs));
984
1156
  timer.unref?.();
985
1157
  });
986
1158
  return await Promise.race([pending, timeout]);
@@ -2207,6 +2379,7 @@ var APP_RESOURCE_CAPABILITIES = {
2207
2379
  gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
2208
2380
  copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
2209
2381
  "cursor-cli": { entry: null, strategy: "compatibility", configHome: "CURSOR_CONFIG_DIR" },
2382
+ "antigravity-cli": { entry: null, strategy: "compatibility", configHome: null },
2210
2383
  agy: { entry: "_meta.appResources.directory", strategy: "native-session", configHome: null },
2211
2384
  deepseek: { entry: null, strategy: "compatibility", configHome: null }
2212
2385
  };
@@ -3495,6 +3668,11 @@ var deepseekAdapter = {
3495
3668
  canSkipInteractiveAuth: () => false
3496
3669
  };
3497
3670
 
3671
+ // src/runtimes/agy/index.ts
3672
+ var import_node_fs18 = require("node:fs");
3673
+ var import_node_os14 = require("node:os");
3674
+ var import_node_path19 = require("node:path");
3675
+
3498
3676
  // src/runtimes/agy/quota.ts
3499
3677
  var import_node_fs17 = require("node:fs");
3500
3678
  var import_node_path18 = require("node:path");
@@ -3602,6 +3780,7 @@ function resolveAntigravityLanguageServer() {
3602
3780
  return null;
3603
3781
  }
3604
3782
  async function probeAgyQuota(options) {
3783
+ const runtimeId = options?.runtimeId ?? "agy";
3605
3784
  const acc = resolveAntigravityAccount();
3606
3785
  const lsInfo = resolveAntigravityLanguageServer();
3607
3786
  if (lsInfo) {
@@ -3701,7 +3880,7 @@ async function probeAgyQuota(options) {
3701
3880
  toWindow(tpWeekly, "Claude and GPT models", "Weekly limit", 10080)
3702
3881
  ].filter(Boolean);
3703
3882
  return {
3704
- runtimeId: "agy",
3883
+ runtimeId,
3705
3884
  provider: "Google Antigravity",
3706
3885
  account: {
3707
3886
  email: acc.email,
@@ -3728,7 +3907,7 @@ async function probeAgyQuota(options) {
3728
3907
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
3729
3908
  if (!isAvailable) {
3730
3909
  return {
3731
- runtimeId: "agy",
3910
+ runtimeId,
3732
3911
  provider: "Google Antigravity",
3733
3912
  status: "unauthorized",
3734
3913
  message: "未检测到 Antigravity 登录凭据",
@@ -3736,7 +3915,7 @@ async function probeAgyQuota(options) {
3736
3915
  };
3737
3916
  }
3738
3917
  return {
3739
- runtimeId: "agy",
3918
+ runtimeId,
3740
3919
  provider: "Google Antigravity",
3741
3920
  account: {
3742
3921
  email: acc.email,
@@ -3784,6 +3963,53 @@ async function probeAgyQuota(options) {
3784
3963
  }
3785
3964
 
3786
3965
  // src/runtimes/agy/index.ts
3966
+ function isExecutableOnPath(command, env, platform) {
3967
+ const pathValue = env.PATH ?? env.Path ?? "";
3968
+ if (!pathValue.trim())
3969
+ return false;
3970
+ const sep = platform === "win32" ? ";" : import_node_path19.delimiter;
3971
+ for (const dir of pathValue.split(sep)) {
3972
+ const trimmed = dir.trim().replace(/^"|"$/g, "");
3973
+ if (!trimmed)
3974
+ continue;
3975
+ try {
3976
+ if (import_node_fs18.existsSync(import_node_path19.join(trimmed, command)))
3977
+ return true;
3978
+ } catch {}
3979
+ }
3980
+ return false;
3981
+ }
3982
+ function resolveAntigravityCliCommand(overrides) {
3983
+ const args = ["acp"];
3984
+ const platform = overrides?.platform ?? process.platform;
3985
+ const env = overrides?.env ?? process.env;
3986
+ const home = overrides?.home ?? import_node_os14.homedir();
3987
+ const binaries = platform === "win32" ? ["agy.exe", "agy.cmd"] : ["agy"];
3988
+ for (const binary of binaries) {
3989
+ if (isExecutableOnPath(binary, env, platform)) {
3990
+ return { command: binary, args };
3991
+ }
3992
+ }
3993
+ const candidates = [];
3994
+ if (platform === "win32") {
3995
+ const localAppData = env.LOCALAPPDATA?.trim() || (env.USERPROFILE?.trim() ? import_node_path19.join(env.USERPROFILE.trim(), "AppData", "Local") : "");
3996
+ const userProfile = env.USERPROFILE?.trim() || home;
3997
+ if (localAppData)
3998
+ candidates.push(import_node_path19.join(localAppData, "antigravity", "agy.exe"));
3999
+ if (userProfile)
4000
+ candidates.push(import_node_path19.join(userProfile, ".local", "bin", "agy.exe"));
4001
+ } else if (home) {
4002
+ candidates.push(import_node_path19.join(home, ".local", "bin", "agy"));
4003
+ }
4004
+ for (const candidate of candidates) {
4005
+ try {
4006
+ if (candidate && import_node_fs18.existsSync(candidate)) {
4007
+ return { command: candidate, args };
4008
+ }
4009
+ } catch {}
4010
+ }
4011
+ return null;
4012
+ }
3787
4013
  function probeAgyAuth() {
3788
4014
  return {
3789
4015
  codexHome: "",
@@ -3807,6 +4033,16 @@ var agyAdapter = {
3807
4033
  canSkipInteractiveAuth: () => false,
3808
4034
  tryDirectSessionFirst: true
3809
4035
  };
4036
+ var antigravityCliAdapter = {
4037
+ id: "antigravity-cli",
4038
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "runtime-not-supported"),
4039
+ probeAuth: () => probeAgyAuth(),
4040
+ probeQuota: (options) => probeAgyQuota({ ...options, runtimeId: "antigravity-cli" }),
4041
+ resolveSpawnCommand: () => resolveAntigravityCliCommand(),
4042
+ orderAuthMethods: (methods) => methods,
4043
+ canSkipInteractiveAuth: () => false,
4044
+ tryDirectSessionFirst: true
4045
+ };
3810
4046
 
3811
4047
  // src/runtimes/index.ts
3812
4048
  function getAcpRuntimeAdapter(runtimeId) {
@@ -3831,6 +4067,8 @@ function getAcpRuntimeAdapter(runtimeId) {
3831
4067
  return deepseekAdapter;
3832
4068
  case agyAdapter.id:
3833
4069
  return agyAdapter;
4070
+ case antigravityCliAdapter.id:
4071
+ return antigravityCliAdapter;
3834
4072
  default:
3835
4073
  return {
3836
4074
  id: runtimeId,
@@ -4044,17 +4282,17 @@ var import_sdk3 = require("@agentclientprotocol/sdk");
4044
4282
 
4045
4283
  // src/client/acp-fs.ts
4046
4284
  var import_promises5 = require("node:fs/promises");
4047
- var import_node_path19 = require("node:path");
4285
+ var import_node_path20 = require("node:path");
4048
4286
  var import_promises6 = require("node:fs/promises");
4049
- var MAX_READ_BYTES = 2 * 1024 * 1024;
4287
+ var ACP_FS_MAX_READ_BYTES = 2 * 1024 * 1024;
4050
4288
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
4051
4289
  function isBinaryDocumentPath(filePath) {
4052
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path19.extname(filePath).toLowerCase());
4290
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path20.extname(filePath).toLowerCase());
4053
4291
  }
4054
4292
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
4055
- const root = import_node_path19.resolve(workspaceRoot);
4056
- const target = import_node_path19.resolve(filePath);
4057
- const rootWithSep = root.endsWith(import_node_path19.sep) ? root : root + import_node_path19.sep;
4293
+ const root = import_node_path20.resolve(workspaceRoot);
4294
+ const target = import_node_path20.resolve(filePath);
4295
+ const rootWithSep = root.endsWith(import_node_path20.sep) ? root : root + import_node_path20.sep;
4058
4296
  if (target !== root && !target.startsWith(rootWithSep)) {
4059
4297
  throw new Error(`路径不在工作区内: ${filePath}`);
4060
4298
  }
@@ -4062,13 +4300,14 @@ function assertPathInsideWorkspace(filePath, workspaceRoot) {
4062
4300
  }
4063
4301
  async function acpReadTextFile(params) {
4064
4302
  if (isBinaryDocumentPath(params.path)) {
4065
- throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
4303
+ throw new Error(`拒绝按文本读取二进制文档/PDF:${params.path}。` + "该格式应由专有解析器读取,请改为向用户索取所需的章节、目录或文本片段。");
4066
4304
  }
4067
4305
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
4068
4306
  await import_promises5.access(abs);
4069
4307
  let content = await import_promises5.readFile(abs, "utf-8");
4070
- if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
4071
- content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
4308
+ const maxBytes = typeof params.maxReadBytes === "number" && params.maxReadBytes > 0 ? params.maxReadBytes : ACP_FS_MAX_READ_BYTES;
4309
+ if (Buffer.byteLength(content, "utf-8") > maxBytes) {
4310
+ content = content.slice(0, Math.floor(maxBytes / 2));
4072
4311
  content += `
4073
4312
 
4074
4313
  …[截断:文件过大]…`;
@@ -4085,7 +4324,7 @@ async function acpReadTextFile(params) {
4085
4324
  }
4086
4325
  async function acpWriteTextFile(params) {
4087
4326
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
4088
- await import_promises6.mkdir(import_node_path19.dirname(abs), { recursive: true });
4327
+ await import_promises6.mkdir(import_node_path20.dirname(abs), { recursive: true });
4089
4328
  await import_promises5.writeFile(abs, params.content, "utf-8");
4090
4329
  return {};
4091
4330
  }
@@ -4100,6 +4339,8 @@ function toServerError(error, fallback) {
4100
4339
  function registerAcpClientHandlers(app, deps) {
4101
4340
  app.onRequest(import_sdk3.methods.client.session.requestPermission, async (ctx) => {
4102
4341
  const params = ctx.params;
4342
+ const sessionId = typeof params.sessionId === "string" ? params.sessionId : undefined;
4343
+ deps.onActivity?.(sessionId);
4103
4344
  const toolCall = params.toolCall;
4104
4345
  const toolHint = toolCall && typeof toolCall === "object" ? {
4105
4346
  id: typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : undefined,
@@ -4112,20 +4353,27 @@ function registerAcpClientHandlers(app, deps) {
4112
4353
  toolCall: toolHint,
4113
4354
  optionCount: Array.isArray(params.options) ? params.options.length : undefined
4114
4355
  });
4356
+ const resumeActivity = deps.onPauseActivity?.(sessionId);
4115
4357
  try {
4116
4358
  const outcome = await deps.onPermission({
4117
- sessionId: typeof params.sessionId === "string" ? params.sessionId : undefined,
4118
- params
4359
+ sessionId,
4360
+ params,
4361
+ signal: ctx.signal
4119
4362
  });
4120
- return { outcome };
4363
+ return { outcome: !ctx.signal.aborted && isAcpPermissionOutcome(outcome, params) ? outcome : { outcome: "cancelled" } };
4121
4364
  } catch (error) {
4122
4365
  console.error("[acp] request_permission 失败", error);
4123
4366
  return { outcome: { outcome: "cancelled" } };
4367
+ } finally {
4368
+ resumeActivity?.();
4369
+ deps.onActivity?.(sessionId);
4124
4370
  }
4125
4371
  });
4126
4372
  app.onRequest(import_sdk3.methods.client.fs.readTextFile, async (ctx) => {
4127
4373
  const workspaceRoot = deps.getWorkspaceRoot();
4128
4374
  const filePath = ctx.params.path;
4375
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4376
+ deps.onActivity?.(sessionId);
4129
4377
  if (!workspaceRoot || !filePath) {
4130
4378
  throw toInvalidParams("fs/read_text_file 需要 path 与已连接工作区");
4131
4379
  }
@@ -4139,18 +4387,19 @@ function registerAcpClientHandlers(app, deps) {
4139
4387
  });
4140
4388
  return { content };
4141
4389
  } catch (error) {
4142
- throw toServerError(error, "读取 Inkdown 快照失败");
4390
+ throw toServerError(error, "读取虚拟快照失败");
4143
4391
  }
4144
4392
  }
4145
4393
  if (isInkdownVirtualDirPath(filePath, workspaceRoot)) {
4146
- throw toInvalidParams(`Inkdown 虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
4394
+ throw toInvalidParams(`虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
4147
4395
  }
4148
4396
  try {
4149
4397
  const result = await acpReadTextFile({
4150
4398
  path: filePath,
4151
4399
  workspaceRoot,
4152
4400
  line: ctx.params.line ?? undefined,
4153
- limit: ctx.params.limit ?? undefined
4401
+ limit: ctx.params.limit ?? undefined,
4402
+ maxReadBytes: deps.maxReadBytes
4154
4403
  });
4155
4404
  console.info("[acp] fs/read_text_file ok", { path: filePath });
4156
4405
  return result;
@@ -4162,6 +4411,8 @@ function registerAcpClientHandlers(app, deps) {
4162
4411
  const workspaceRoot = deps.getWorkspaceRoot();
4163
4412
  const filePath = ctx.params.path;
4164
4413
  const content = ctx.params.content;
4414
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4415
+ deps.onActivity?.(sessionId);
4165
4416
  if (!workspaceRoot || !filePath || typeof content !== "string") {
4166
4417
  throw toInvalidParams("fs/write_text_file 需要 path、content 与已连接工作区");
4167
4418
  }
@@ -4179,6 +4430,7 @@ function registerAcpClientHandlers(app, deps) {
4179
4430
  const workspaceRoot = deps.getWorkspaceRoot();
4180
4431
  const sessionId = ctx.params.sessionId;
4181
4432
  const command = ctx.params.command;
4433
+ deps.onActivity?.(sessionId);
4182
4434
  if (!workspaceRoot || !sessionId || !command) {
4183
4435
  throw toInvalidParams("terminal/create 需要 sessionId、command 与已连接工作区");
4184
4436
  }
@@ -4198,6 +4450,8 @@ function registerAcpClientHandlers(app, deps) {
4198
4450
  });
4199
4451
  app.onRequest(import_sdk3.methods.client.terminal.output, async (ctx) => {
4200
4452
  const terminalId = ctx.params.terminalId;
4453
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4454
+ deps.onActivity?.(sessionId);
4201
4455
  if (!terminalId) {
4202
4456
  throw toInvalidParams("terminal/output 需要 terminalId");
4203
4457
  }
@@ -4209,6 +4463,8 @@ function registerAcpClientHandlers(app, deps) {
4209
4463
  });
4210
4464
  app.onRequest(import_sdk3.methods.client.terminal.waitForExit, async (ctx) => {
4211
4465
  const terminalId = ctx.params.terminalId;
4466
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4467
+ deps.onActivity?.(sessionId);
4212
4468
  if (!terminalId) {
4213
4469
  throw toInvalidParams("terminal/wait_for_exit 需要 terminalId");
4214
4470
  }
@@ -4220,6 +4476,8 @@ function registerAcpClientHandlers(app, deps) {
4220
4476
  });
4221
4477
  app.onRequest(import_sdk3.methods.client.terminal.kill, async (ctx) => {
4222
4478
  const terminalId = ctx.params.terminalId;
4479
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4480
+ deps.onActivity?.(sessionId);
4223
4481
  if (!terminalId) {
4224
4482
  throw toInvalidParams("terminal/kill 需要 terminalId");
4225
4483
  }
@@ -4231,6 +4489,8 @@ function registerAcpClientHandlers(app, deps) {
4231
4489
  });
4232
4490
  app.onRequest(import_sdk3.methods.client.terminal.release, async (ctx) => {
4233
4491
  const terminalId = ctx.params.terminalId;
4492
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4493
+ deps.onActivity?.(sessionId);
4234
4494
  if (!terminalId) {
4235
4495
  throw toInvalidParams("terminal/release 需要 terminalId");
4236
4496
  }
@@ -4241,6 +4501,7 @@ function registerAcpClientHandlers(app, deps) {
4241
4501
  }
4242
4502
  });
4243
4503
  app.onNotification(import_sdk3.methods.client.session.update, async (ctx) => {
4504
+ deps.onActivity?.(ctx.params.sessionId);
4244
4505
  deps.onSessionUpdate({
4245
4506
  sessionId: ctx.params.sessionId,
4246
4507
  update: ctx.params.update
@@ -4254,26 +4515,23 @@ function permissionOptionId(option) {
4254
4515
  return option.id;
4255
4516
  return null;
4256
4517
  }
4518
+ function permissionOptions(params) {
4519
+ return Array.isArray(params.options) ? params.options.filter((option) => !!option && typeof option === "object") : [];
4520
+ }
4521
+ function isAcpPermissionOutcome(outcome, params) {
4522
+ if (!outcome || typeof outcome !== "object")
4523
+ return false;
4524
+ const value = outcome;
4525
+ if (value.outcome === "cancelled")
4526
+ return true;
4527
+ return value.outcome === "selected" && typeof value.optionId === "string" && value.optionId.length > 0 && permissionOptions(params).some((option) => permissionOptionId(option) === value.optionId);
4528
+ }
4257
4529
  function pickAllowOptionId(params) {
4258
- const options = params.options;
4259
- if (!Array.isArray(options))
4260
- return null;
4261
- for (const item of options) {
4262
- if (!item || typeof item !== "object")
4263
- continue;
4264
- const option = item;
4265
- const id = permissionOptionId(option);
4266
- const kind = typeof option.kind === "string" ? option.kind : "";
4267
- if (id && (kind.includes("allow") || kind === "allow_once" || kind === "allow_always")) {
4268
- return id;
4269
- }
4270
- }
4271
- for (const item of options) {
4272
- if (!item || typeof item !== "object")
4273
- continue;
4274
- const id = permissionOptionId(item);
4275
- if (id)
4276
- return id;
4530
+ const options = permissionOptions(params);
4531
+ for (const kind of ["allow_once", "allow", "allow_always"]) {
4532
+ const option = options.find((entry) => entry.kind === kind && permissionOptionId(entry));
4533
+ if (option)
4534
+ return permissionOptionId(option);
4277
4535
  }
4278
4536
  return null;
4279
4537
  }
@@ -4306,7 +4564,7 @@ function appendTerminalOutput(current, chunk, byteLimit) {
4306
4564
  }
4307
4565
 
4308
4566
  // src/client/acp-terminal.ts
4309
- var DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
4567
+ var ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
4310
4568
  function resolveCwd(cwd, workspaceRoot) {
4311
4569
  if (!cwd?.trim())
4312
4570
  return assertPathInsideWorkspace(workspaceRoot, workspaceRoot);
@@ -4326,12 +4584,18 @@ function buildEnv(extra) {
4326
4584
 
4327
4585
  class AcpTerminalManager {
4328
4586
  terminals = new Map;
4587
+ defaultOutputByteLimit;
4588
+ onActivity;
4589
+ constructor(options) {
4590
+ this.defaultOutputByteLimit = typeof options?.defaultOutputByteLimit === "number" && options.defaultOutputByteLimit > 0 ? options.defaultOutputByteLimit : ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT;
4591
+ this.onActivity = options?.onActivity;
4592
+ }
4329
4593
  create(params) {
4330
4594
  const command = params.command?.trim();
4331
4595
  if (!command)
4332
4596
  throw new Error("terminal/create 需要 command");
4333
4597
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
4334
- const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
4598
+ const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : this.defaultOutputByteLimit;
4335
4599
  const child = import_node_child_process8.spawn(command, params.args ?? [], {
4336
4600
  cwd,
4337
4601
  env: buildEnv(params.env),
@@ -4358,6 +4622,7 @@ class AcpTerminalManager {
4358
4622
  record.output = next.output;
4359
4623
  if (next.truncated)
4360
4624
  record.truncated = true;
4625
+ this.onActivity?.(record.sessionId);
4361
4626
  };
4362
4627
  child.stdout?.on("data", onChunk);
4363
4628
  child.stderr?.on("data", onChunk);
@@ -4375,10 +4640,12 @@ class AcpTerminalManager {
4375
4640
  this.markExited(record, code, signal);
4376
4641
  });
4377
4642
  this.terminals.set(id, record);
4643
+ this.onActivity?.(record.sessionId);
4378
4644
  return { terminalId: id };
4379
4645
  }
4380
4646
  getOutput(terminalId) {
4381
4647
  const record = this.require(terminalId);
4648
+ this.onActivity?.(record.sessionId);
4382
4649
  const snapshot = {
4383
4650
  output: record.output,
4384
4651
  truncated: record.truncated
@@ -4393,6 +4660,7 @@ class AcpTerminalManager {
4393
4660
  }
4394
4661
  waitForExit(terminalId) {
4395
4662
  const record = this.require(terminalId);
4663
+ this.onActivity?.(record.sessionId);
4396
4664
  if (record.exited) {
4397
4665
  return Promise.resolve({ exitCode: record.exitCode, signal: record.signal });
4398
4666
  }
@@ -4402,6 +4670,7 @@ class AcpTerminalManager {
4402
4670
  }
4403
4671
  kill(terminalId) {
4404
4672
  const record = this.require(terminalId);
4673
+ this.onActivity?.(record.sessionId);
4405
4674
  if (!record.exited) {
4406
4675
  this.forceKill(record.child);
4407
4676
  }
@@ -4411,6 +4680,7 @@ class AcpTerminalManager {
4411
4680
  const record = this.terminals.get(terminalId);
4412
4681
  if (!record)
4413
4682
  return {};
4683
+ this.onActivity?.(record.sessionId);
4414
4684
  if (!record.exited) {
4415
4685
  this.forceKill(record.child);
4416
4686
  }
@@ -4455,6 +4725,7 @@ class AcpTerminalManager {
4455
4725
  record.exited = true;
4456
4726
  record.exitCode = code;
4457
4727
  record.signal = signal;
4728
+ this.onActivity?.(record.sessionId);
4458
4729
  const status = { exitCode: code, signal };
4459
4730
  for (const waiter of record.waiters)
4460
4731
  waiter(status);
@@ -4464,8 +4735,8 @@ class AcpTerminalManager {
4464
4735
 
4465
4736
  // src/client/acp-proxy-service.ts
4466
4737
  var import_promises7 = require("node:fs/promises");
4467
- var import_node_fs18 = require("node:fs");
4468
- var import_node_path20 = require("node:path");
4738
+ var import_node_fs19 = require("node:fs");
4739
+ var import_node_path21 = require("node:path");
4469
4740
  var DEFAULT_ACP_PROXY_SETTINGS = {
4470
4741
  enabled: false,
4471
4742
  host: "127.0.0.1",
@@ -4474,7 +4745,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
4474
4745
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
4475
4746
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
4476
4747
  function proxyFilePath(dir) {
4477
- return import_node_path20.join(dir, "agent", "proxy.json");
4748
+ return import_node_path21.join(dir, "agent", "proxy.json");
4478
4749
  }
4479
4750
  function validate2(settings) {
4480
4751
  if (!settings.host.trim())
@@ -4486,7 +4757,7 @@ function validate2(settings) {
4486
4757
  }
4487
4758
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
4488
4759
  const file = proxyFilePath(dir);
4489
- if (!import_node_fs18.existsSync(file))
4760
+ if (!import_node_fs19.existsSync(file))
4490
4761
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
4491
4762
  try {
4492
4763
  const raw = JSON.parse(await import_promises7.readFile(file, "utf8"));
@@ -4508,7 +4779,7 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
4508
4779
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
4509
4780
  port: payload.port
4510
4781
  };
4511
- await import_promises7.mkdir(import_node_path20.join(dir, "agent"), { recursive: true });
4782
+ await import_promises7.mkdir(import_node_path21.join(dir, "agent"), { recursive: true });
4512
4783
  await import_promises7.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
4513
4784
  return ok(stored);
4514
4785
  }
@@ -4564,9 +4835,9 @@ function compatDeliveryKey(sessionId, generation, digest) {
4564
4835
  }
4565
4836
 
4566
4837
  // src/mcp/app-skills-mcp.ts
4567
- var import_node_path21 = require("node:path");
4838
+ var import_node_path22 = require("node:path");
4568
4839
  var import_node_url = require("node:url");
4569
- var import_node_fs19 = require("node:fs");
4840
+ var import_node_fs20 = require("node:fs");
4570
4841
  var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
4571
4842
  var APP_SKILLS_TOOLS = [
4572
4843
  {
@@ -4602,11 +4873,11 @@ function buildAppSkillsMcpServer(directory, opts) {
4602
4873
  function resolveAppSkillsRunnerPath(fromFile) {
4603
4874
  const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
4604
4875
  const candidates = [
4605
- import_node_path21.join(import_node_path21.dirname(base), "app-skills-mcp-serve.cjs"),
4606
- import_node_path21.join(import_node_path21.dirname(base), "app-skills-mcp-serve.ts")
4876
+ import_node_path22.join(import_node_path22.dirname(base), "app-skills-mcp-serve.cjs"),
4877
+ import_node_path22.join(import_node_path22.dirname(base), "app-skills-mcp-serve.ts")
4607
4878
  ];
4608
4879
  for (const candidate of candidates) {
4609
- if (import_node_fs19.existsSync(candidate))
4880
+ if (import_node_fs20.existsSync(candidate))
4610
4881
  return candidate;
4611
4882
  }
4612
4883
  throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
@@ -4643,10 +4914,10 @@ function isSupportedBridgeVersion(runtimeId, version) {
4643
4914
 
4644
4915
  // src/session/session-capabilities.ts
4645
4916
  function parseLoadSessionSupported(caps) {
4646
- return caps.loadSession === true;
4917
+ return caps?.loadSession === true;
4647
4918
  }
4648
4919
  function parseResumeSessionSupported(caps) {
4649
- const sessionCaps = caps.sessionCapabilities && typeof caps.sessionCapabilities === "object" ? caps.sessionCapabilities : null;
4920
+ const sessionCaps = caps?.sessionCapabilities && typeof caps.sessionCapabilities === "object" ? caps.sessionCapabilities : null;
4650
4921
  if (!sessionCaps)
4651
4922
  return false;
4652
4923
  const resume = sessionCaps.resume;
@@ -4712,23 +4983,32 @@ class AcpClient {
4712
4983
  commandsCache = new AvailableCommandsCache;
4713
4984
  quotaCache = new QuotaCache;
4714
4985
  runtimeInfo;
4986
+ hasCustomRuntime;
4715
4987
  adapter;
4716
4988
  workspaceRoot;
4717
4989
  clientInfo;
4718
4990
  dataDir;
4991
+ proxyOverride;
4719
4992
  extraEnv;
4993
+ requestTimeoutMs;
4994
+ promptIdleTimeoutMs;
4995
+ promptMaxDurationMs;
4996
+ quotaCacheTtlMs;
4997
+ maxReadBytes;
4720
4998
  configurationScope;
4721
4999
  sessionConfig = null;
4722
5000
  resourcesDir;
5001
+ authenticatingAgent;
5002
+ permissionRequests = new Map;
4723
5003
  processScopeKey = import_node_crypto4.randomUUID();
4724
5004
  callbacks;
4725
- terminals = new AcpTerminalManager;
5005
+ terminals;
4726
5006
  processHandle = null;
4727
5007
  sdkApp = null;
4728
5008
  sdkConnection = null;
4729
5009
  streamHandle = null;
4730
5010
  initResponse = null;
4731
- inflightPrompts = new Set;
5011
+ inflightTrackers = new Map;
4732
5012
  resourcePrep = null;
4733
5013
  connectionGen = 0;
4734
5014
  attachSkillsMcp;
@@ -4742,11 +5022,21 @@ class AcpClient {
4742
5022
  constructor(options) {
4743
5023
  this.workspaceRoot = options.workspaceRoot;
4744
5024
  this.clientInfo = {
4745
- name: options.clientInfo?.name ?? "inkdown",
4746
- version: options.clientInfo?.version ?? "0.1.1"
5025
+ name: options.clientInfo?.name ?? "acp-client",
5026
+ version: options.clientInfo?.version ?? ACP_CLIENT_VERSION
4747
5027
  };
4748
5028
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
5029
+ this.proxyOverride = options.proxy;
4749
5030
  this.extraEnv = options.env ?? {};
5031
+ this.requestTimeoutMs = typeof options.requestTimeoutMs === "number" && options.requestTimeoutMs > 0 ? options.requestTimeoutMs : ACP_SDK_REQUEST_TIMEOUT_MS;
5032
+ this.promptIdleTimeoutMs = typeof options.promptIdleTimeoutMs === "number" && options.promptIdleTimeoutMs >= 0 ? options.promptIdleTimeoutMs : ACP_PROMPT_IDLE_TIMEOUT_MS;
5033
+ this.promptMaxDurationMs = typeof options.promptMaxDurationMs === "number" && options.promptMaxDurationMs >= 0 ? options.promptMaxDurationMs : ACP_PROMPT_MAX_DURATION_MS;
5034
+ this.quotaCacheTtlMs = typeof options.quotaCacheTtlMs === "number" && options.quotaCacheTtlMs >= 0 ? options.quotaCacheTtlMs : 30000;
5035
+ this.maxReadBytes = typeof options.maxReadBytes === "number" && options.maxReadBytes > 0 ? options.maxReadBytes : ACP_FS_MAX_READ_BYTES;
5036
+ this.terminals = new AcpTerminalManager({
5037
+ defaultOutputByteLimit: options.terminalOutputByteLimit ?? ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT,
5038
+ onActivity: (sid) => this.touchSessionActivity(sid)
5039
+ });
4750
5040
  if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
4751
5041
  throw new Error("resources.directory 必须是本机绝对路径");
4752
5042
  }
@@ -4762,12 +5052,13 @@ class AcpClient {
4762
5052
  throw new AcpMcpRecoveryCancelledError("ACP connection closed");
4763
5053
  return this.sdkConnection.agent.request(method, params, { cancellationSignal: signal });
4764
5054
  },
5055
+ requestTimeoutMs: this.requestTimeoutMs,
4765
5056
  getCapabilities: () => ({
4766
5057
  resume: Boolean(this.initResponse && parseResumeSessionSupported(this.initResponse.agentCapabilities)),
4767
5058
  load: Boolean(this.initResponse && parseLoadSessionSupported(this.initResponse.agentCapabilities))
4768
5059
  }),
4769
5060
  isConnected: () => this.isConnected,
4770
- isBusy: (sessionId) => [...this.inflightPrompts].some((id) => id !== sessionId),
5061
+ isBusy: (sessionId) => [...this.inflightTrackers.keys()].some((id) => id !== sessionId),
4771
5062
  onSuppressUpdates: (suppress) => {
4772
5063
  this.suppressRecoveryUpdates = suppress;
4773
5064
  },
@@ -4776,8 +5067,10 @@ class AcpClient {
4776
5067
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
4777
5068
  this.adapter = getAcpRuntimeAdapter(runtimeId);
4778
5069
  if (typeof options.runtime === "object" && options.runtime !== null) {
5070
+ this.hasCustomRuntime = true;
4779
5071
  this.runtimeInfo = options.runtime;
4780
5072
  } else {
5073
+ this.hasCustomRuntime = false;
4781
5074
  const found = findBuiltinAcpRuntime(runtimeId);
4782
5075
  if (!found) {
4783
5076
  throw new Error(`未知或未注册的 ACP 运行时模板: ${runtimeId}`);
@@ -4797,8 +5090,44 @@ class AcpClient {
4797
5090
  get initializeResponse() {
4798
5091
  return this.initResponse;
4799
5092
  }
5093
+ async authenticate(methodId) {
5094
+ const agent = this.sdkConnection?.agent;
5095
+ if (!agent || !this.isConnected) {
5096
+ return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
5097
+ }
5098
+ const method = this.initResponse?.authMethods?.find((entry) => entry.id === methodId);
5099
+ if (!method) {
5100
+ return err({ code: "INVALID_ARGUMENT", message: "Agent 未声明此认证方式" });
5101
+ }
5102
+ if ("type" in method && method.type === "terminal") {
5103
+ return err({ code: "INVALID_ARGUMENT", message: "此认证方式需要在交互式终端中运行" });
5104
+ }
5105
+ if (this.authenticatingAgent === agent) {
5106
+ return err({ code: "INVALID_STATE", message: "Agent 正在认证" });
5107
+ }
5108
+ this.authenticatingAgent = agent;
5109
+ try {
5110
+ await sdkRequest(agent, import_sdk4.methods.agent.authenticate, { methodId }, this.requestTimeoutMs);
5111
+ if (this.sdkConnection?.agent !== agent) {
5112
+ return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
5113
+ }
5114
+ return ok(undefined);
5115
+ } catch (error) {
5116
+ if (this.sdkConnection?.agent !== agent) {
5117
+ return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
5118
+ }
5119
+ const message = error instanceof Error ? error.message : String(error);
5120
+ return err({
5121
+ code: error instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
5122
+ message
5123
+ });
5124
+ } finally {
5125
+ if (this.authenticatingAgent === agent)
5126
+ this.authenticatingAgent = undefined;
5127
+ }
5128
+ }
4800
5129
  async connect() {
4801
- if (this.inflightPrompts.size > 0)
5130
+ if (this.inflightTrackers.size > 0)
4802
5131
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
4803
5132
  if (this.isConnected && this.initResponse)
4804
5133
  return ok({ status: this.status, init: this.initResponse });
@@ -4815,7 +5144,7 @@ class AcpClient {
4815
5144
  return err({ code: "ACP_SPAWN_ERROR", message: blocker });
4816
5145
  }
4817
5146
  let effectiveRuntime = { ...this.runtimeInfo };
4818
- if (this.adapter.resolveSpawnCommand) {
5147
+ if (!this.hasCustomRuntime && this.adapter.resolveSpawnCommand) {
4819
5148
  const resolved = this.adapter.resolveSpawnCommand();
4820
5149
  if (!resolved) {
4821
5150
  const message = `运行时 CLI 未安装: ${this.runtimeInfo.id}`;
@@ -4826,8 +5155,9 @@ class AcpClient {
4826
5155
  effectiveRuntime.args = resolved.args;
4827
5156
  }
4828
5157
  const storedProxy = await readAcpProxySettings(this.dataDir);
4829
- const proxyEnv = buildAcpProxySpawnEnv(storedProxy);
4830
- const baseEnv = this.adapter.getSpawnEnv?.(storedProxy) ?? proxyEnv;
5158
+ const effectiveProxy = this.proxyOverride ? { ...storedProxy, ...this.proxyOverride } : storedProxy;
5159
+ const proxyEnv = buildAcpProxySpawnEnv(effectiveProxy);
5160
+ const baseEnv = this.adapter.getSpawnEnv?.(effectiveProxy) ?? proxyEnv;
4831
5161
  const spawnEnv = {
4832
5162
  ...baseEnv,
4833
5163
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
@@ -4908,7 +5238,7 @@ class AcpClient {
4908
5238
  const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
4909
5239
  expectedTag: profileTag,
4910
5240
  scopeKey: this.processScopeKey,
4911
- isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
5241
+ isBusy: (h) => this.inflightTrackers.size > 0 && this.processHandle === h
4912
5242
  });
4913
5243
  if (reuse.status === "hit") {
4914
5244
  reusedHandle = reuse.handle;
@@ -4948,25 +5278,45 @@ class AcpClient {
4948
5278
  return this.callbacks.readSnapshot(resource);
4949
5279
  },
4950
5280
  onPermission: async (payload) => {
4951
- if (this.callbacks.onPermissionRequest) {
4952
- return this.callbacks.onPermissionRequest({
5281
+ const callback = this.callbacks.onPermissionRequest;
5282
+ const cancelled = { outcome: "cancelled" };
5283
+ if (!callback || payload.signal.aborted)
5284
+ return cancelled;
5285
+ const controller = new AbortController;
5286
+ const signal = AbortSignal.any([payload.signal, controller.signal]);
5287
+ this.permissionRequests.set(controller, payload.sessionId);
5288
+ let resolveCancellation;
5289
+ const cancellation = new Promise((resolve) => {
5290
+ resolveCancellation = resolve;
5291
+ });
5292
+ const onAbort = () => resolveCancellation(cancelled);
5293
+ signal.addEventListener("abort", onAbort, { once: true });
5294
+ try {
5295
+ const outcome = await Promise.race([cancellation, callback({
4953
5296
  sessionId: payload.sessionId,
4954
5297
  toolCall: payload.params?.toolCall,
4955
- params: payload.params
4956
- });
5298
+ params: payload.params,
5299
+ signal
5300
+ })]);
5301
+ return signal.aborted ? cancelled : outcome;
5302
+ } finally {
5303
+ signal.removeEventListener("abort", onAbort);
5304
+ this.permissionRequests.delete(controller);
4957
5305
  }
4958
- return { outcome: "cancelled" };
4959
5306
  },
4960
5307
  onSessionUpdate: (params) => {
4961
5308
  this.commandsCache.observe(params);
4962
5309
  this.quotaCache.observe(params, this.runtimeInfo.id);
4963
5310
  if (!this.suppressRecoveryUpdates)
4964
5311
  this.callbacks.onSessionUpdate?.(params);
4965
- }
5312
+ },
5313
+ onActivity: (sessionId) => this.touchSessionActivity(sessionId),
5314
+ onPauseActivity: (sessionId) => this.pauseSessionActivity(sessionId),
5315
+ maxReadBytes: this.maxReadBytes
4966
5316
  };
4967
5317
  const { app, connection, streamHandle } = connectSdkClient(processHandle.child, (clientApp) => {
4968
5318
  registerAcpClientHandlers(clientApp, handlerDeps);
4969
- }, this.runtimeInfo.id);
5319
+ }, this.runtimeInfo.id, this.clientInfo);
4970
5320
  this.sdkApp = app;
4971
5321
  this.sdkConnection = connection;
4972
5322
  this.streamHandle = streamHandle;
@@ -4980,7 +5330,7 @@ class AcpClient {
4980
5330
  configOptions: { boolean: {} }
4981
5331
  }
4982
5332
  }
4983
- });
5333
+ }, this.requestTimeoutMs);
4984
5334
  this.initResponse = initResp;
4985
5335
  if (this.resourcePrep) {
4986
5336
  const agentInfo = initResp?.agentInfo;
@@ -5007,7 +5357,7 @@ class AcpClient {
5007
5357
  const message = e instanceof Error ? e.message : String(e);
5008
5358
  this.setStatus("error", message);
5009
5359
  await this.disconnect(message);
5010
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5360
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
5011
5361
  }
5012
5362
  }
5013
5363
  getCachedQuota(sessionId) {
@@ -5015,7 +5365,7 @@ class AcpClient {
5015
5365
  }
5016
5366
  async getQuota(sessionId) {
5017
5367
  const cached = this.getCachedQuota(sessionId);
5018
- if (cached && Date.now() - cached.updatedAt < 30000) {
5368
+ if (cached && this.quotaCacheTtlMs > 0 && Date.now() - cached.updatedAt < this.quotaCacheTtlMs) {
5019
5369
  return cached;
5020
5370
  }
5021
5371
  if (this.adapter.probeQuota) {
@@ -5071,7 +5421,7 @@ class AcpClient {
5071
5421
  const sessionMeta = mergeSessionMeta((!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined, options?.codeMode, this.initResponse?.agentCapabilities ?? undefined);
5072
5422
  const openResult = await restoreOrCreateAcpSession({
5073
5423
  request: async (method, params) => {
5074
- return sdkRequest(agent, method, params);
5424
+ return sdkRequest(agent, method, params, this.requestTimeoutMs);
5075
5425
  },
5076
5426
  cwd: this.workspaceRoot,
5077
5427
  resumeSessionId: options?.resumeSessionId ?? null,
@@ -5112,7 +5462,10 @@ class AcpClient {
5112
5462
  return ok(handle);
5113
5463
  } catch (e) {
5114
5464
  const message = e instanceof Error ? e.message : String(e);
5115
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5465
+ return err({
5466
+ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
5467
+ message
5468
+ });
5116
5469
  }
5117
5470
  }
5118
5471
  async promptSession(sessionId, promptText, options) {
@@ -5121,11 +5474,12 @@ class AcpClient {
5121
5474
  }
5122
5475
  if (!this.isConnected)
5123
5476
  return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
5124
- if (this.inflightPrompts.has(sessionId))
5477
+ if (this.inflightTrackers.has(sessionId))
5125
5478
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Session already has an in-flight prompt" });
5126
5479
  const generation = this.connectionGen;
5127
5480
  const agent = this.sdkConnection.agent;
5128
- this.inflightPrompts.add(sessionId);
5481
+ const tracker = createSdkRequestActivityController();
5482
+ this.inflightTrackers.set(sessionId, tracker);
5129
5483
  try {
5130
5484
  await this.mcpRecovery.ensureReady(sessionId);
5131
5485
  if (generation !== this.connectionGen || !this.isConnected)
@@ -5138,17 +5492,34 @@ class AcpClient {
5138
5492
  }
5139
5493
  const compat = this.buildCompatPrepend(sessionId);
5140
5494
  const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
5141
- const response = await sdkRequest(agent, import_sdk4.methods.agent.session.prompt, {
5495
+ const hasIdleOption = options?.idleTimeoutMs !== undefined;
5496
+ const hasTimeoutOption = options?.timeoutMs !== undefined;
5497
+ const idleTimeoutMs = hasIdleOption ? options.idleTimeoutMs : hasTimeoutOption ? 0 : this.promptIdleTimeoutMs;
5498
+ const maxDurationMs = options?.maxDurationMs ?? options?.timeoutMs ?? this.promptMaxDurationMs;
5499
+ const response = await sdkRequestWithActivity(agent, import_sdk4.methods.agent.session.prompt, {
5142
5500
  sessionId,
5143
5501
  prompt: blocks
5144
- }, options?.timeoutMs);
5502
+ }, {
5503
+ idleTimeoutMs,
5504
+ maxDurationMs,
5505
+ activity: tracker
5506
+ });
5145
5507
  return ok(response);
5146
5508
  } catch (e) {
5147
5509
  const message = e instanceof Error ? e.message : String(e);
5148
- return err({ code: e instanceof AcpMcpRecoveryCancelledError ? "CANCELLED" : "ACP_PROTOCOL_ERROR", message });
5510
+ if (e instanceof AcpMcpRecoveryCancelledError)
5511
+ return err({ code: "CANCELLED", message });
5512
+ if (e instanceof SdkRequestTimeoutError) {
5513
+ this.cancelPermissionRequests("session_cancelled", sessionId);
5514
+ this.sdkConnection?.agent?.notify(import_sdk4.methods.agent.session.cancel, { sessionId }).catch(() => {
5515
+ return;
5516
+ });
5517
+ return err({ code: "ACP_TIMEOUT", message });
5518
+ }
5519
+ return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
5149
5520
  } finally {
5150
5521
  if (generation === this.connectionGen)
5151
- this.inflightPrompts.delete(sessionId);
5522
+ this.inflightTrackers.delete(sessionId);
5152
5523
  }
5153
5524
  }
5154
5525
  buildCompatPrepend(sessionId) {
@@ -5188,7 +5559,9 @@ class AcpClient {
5188
5559
  if (!this.sdkConnection?.agent)
5189
5560
  return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
5190
5561
  try {
5191
- await this.sdkConnection.agent.notify(import_sdk4.methods.agent.session.cancel, { sessionId });
5562
+ const notifying = this.sdkConnection.agent.notify(import_sdk4.methods.agent.session.cancel, { sessionId });
5563
+ this.cancelPermissionRequests("session_cancelled", sessionId);
5564
+ await notifying;
5192
5565
  return ok(undefined);
5193
5566
  } catch (error) {
5194
5567
  return err({ code: "ACP_PROTOCOL_ERROR", message: error instanceof Error ? error.message : String(error) });
@@ -5203,17 +5576,18 @@ class AcpClient {
5203
5576
  sessionId,
5204
5577
  configId,
5205
5578
  value
5206
- });
5579
+ }, this.requestTimeoutMs);
5207
5580
  return ok(response);
5208
5581
  } catch (e) {
5209
5582
  const message = e instanceof Error ? e.message : String(e);
5210
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5583
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
5211
5584
  }
5212
5585
  }
5213
5586
  async disconnect(reason) {
5214
5587
  ++this.connectionGen;
5215
5588
  this.mcpRecovery.reset();
5216
- this.inflightPrompts.clear();
5589
+ this.inflightTrackers.clear();
5590
+ this.cancelPermissionRequests("connection_closed");
5217
5591
  this.setStatus("disconnected", reason);
5218
5592
  this.resourcePrep = null;
5219
5593
  const capabilities = this.initResponse?.agentCapabilities?.sessionCapabilities;
@@ -5250,6 +5624,37 @@ class AcpClient {
5250
5624
  }
5251
5625
  }
5252
5626
  }
5627
+ touchSessionActivity(sessionId) {
5628
+ if (sessionId) {
5629
+ this.inflightTrackers.get(sessionId)?.touch();
5630
+ return;
5631
+ }
5632
+ for (const tracker of this.inflightTrackers.values()) {
5633
+ tracker.touch();
5634
+ }
5635
+ }
5636
+ pauseSessionActivity(sessionId) {
5637
+ if (sessionId) {
5638
+ return this.inflightTrackers.get(sessionId)?.pause() ?? (() => {
5639
+ return;
5640
+ });
5641
+ }
5642
+ const resumes = [...this.inflightTrackers.values()].map((tracker) => tracker.pause());
5643
+ let released = false;
5644
+ return () => {
5645
+ if (released)
5646
+ return;
5647
+ released = true;
5648
+ for (const resume of resumes)
5649
+ resume();
5650
+ };
5651
+ }
5652
+ cancelPermissionRequests(reason, sessionId) {
5653
+ for (const [controller, pendingSessionId] of this.permissionRequests) {
5654
+ if (sessionId === undefined || pendingSessionId === sessionId)
5655
+ controller.abort(reason);
5656
+ }
5657
+ }
5253
5658
  setStatus(status, detail) {
5254
5659
  this.status = status;
5255
5660
  this.callbacks.onStatusChange?.(status, detail);