@yitom/acp-client 0.1.15 → 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,6 +102,7 @@ __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,
@@ -120,6 +125,7 @@ __export(exports_src, {
120
125
  codexAdapter: () => codexAdapter,
121
126
  connectSdkClient: () => connectSdkClient,
122
127
  copilotAdapter: () => copilotAdapter,
128
+ createSdkRequestActivityController: () => createSdkRequestActivityController,
123
129
  createSdkStreamHandle: () => createSdkStreamHandle,
124
130
  createSessionConfigHome: () => createSessionConfigHome,
125
131
  cursorAdapter: () => cursorAdapter,
@@ -232,6 +238,7 @@ __export(exports_src, {
232
238
  saveAcpProvider: () => saveAcpProvider,
233
239
  saveAcpProxySettings: () => saveAcpProxySettings,
234
240
  sdkRequest: () => sdkRequest,
241
+ sdkRequestWithActivity: () => sdkRequestWithActivity,
235
242
  shouldPromptAuthWizard: () => shouldPromptAuthWizard,
236
243
  spawnAcpProcess: () => spawnAcpProcess,
237
244
  supportsCodeMode: () => supportsCodeMode,
@@ -414,7 +421,7 @@ function findBuiltinAcpRuntime(id) {
414
421
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
415
422
  }
416
423
  // src/version.ts
417
- var ACP_CLIENT_VERSION = "0.1.15";
424
+ var ACP_CLIENT_VERSION = "0.1.16";
418
425
  // src/client/session-open.ts
419
426
  var import_sdk = require("@agentclientprotocol/sdk");
420
427
 
@@ -946,6 +953,64 @@ class AcpMcpSessionRecovery {
946
953
  var import_node_stream = require("node:stream");
947
954
  var import_sdk2 = require("@agentclientprotocol/sdk");
948
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
+ }
949
1014
  function createSdkStreamHandle(child) {
950
1015
  const stdoutBridge = new import_node_stream.PassThrough;
951
1016
  const stdinBridge = new import_node_stream.PassThrough;
@@ -976,17 +1041,107 @@ function createSdkStreamHandle(child) {
976
1041
  }
977
1042
  };
978
1043
  }
979
- function connectSdkClient(child, configure, runtimeId) {
1044
+ function connectSdkClient(child, configure, runtimeId, clientInfo) {
980
1045
  if (runtimeId && true) {
981
1046
  console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
982
1047
  }
983
- 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
+ });
984
1052
  configure(app);
985
1053
  const streamHandle = createSdkStreamHandle(child);
986
1054
  const connection = app.connect(streamHandle.stream);
987
1055
  return { app, connection, streamHandle };
988
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
+ }
989
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
+ }
990
1145
  const controller = new AbortController;
991
1146
  let timer;
992
1147
  try {
@@ -996,8 +1151,8 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
996
1151
  const timeout = new Promise((_, reject) => {
997
1152
  timer = setTimeout(() => {
998
1153
  controller.abort();
999
- reject(new Error(`请求超时: ${method}`));
1000
- }, timeoutMs);
1154
+ reject(new SdkRequestTimeoutError("timeout", method, timeoutMs));
1155
+ }, clampTimerMs(timeoutMs));
1001
1156
  timer.unref?.();
1002
1157
  });
1003
1158
  return await Promise.race([pending, timeout]);
@@ -4129,7 +4284,7 @@ var import_sdk3 = require("@agentclientprotocol/sdk");
4129
4284
  var import_promises5 = require("node:fs/promises");
4130
4285
  var import_node_path20 = require("node:path");
4131
4286
  var import_promises6 = require("node:fs/promises");
4132
- var MAX_READ_BYTES = 2 * 1024 * 1024;
4287
+ var ACP_FS_MAX_READ_BYTES = 2 * 1024 * 1024;
4133
4288
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
4134
4289
  function isBinaryDocumentPath(filePath) {
4135
4290
  return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path20.extname(filePath).toLowerCase());
@@ -4145,13 +4300,14 @@ function assertPathInsideWorkspace(filePath, workspaceRoot) {
4145
4300
  }
4146
4301
  async function acpReadTextFile(params) {
4147
4302
  if (isBinaryDocumentPath(params.path)) {
4148
- throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
4303
+ throw new Error(`拒绝按文本读取二进制文档/PDF:${params.path}。` + "该格式应由专有解析器读取,请改为向用户索取所需的章节、目录或文本片段。");
4149
4304
  }
4150
4305
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
4151
4306
  await import_promises5.access(abs);
4152
4307
  let content = await import_promises5.readFile(abs, "utf-8");
4153
- if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
4154
- 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));
4155
4311
  content += `
4156
4312
 
4157
4313
  …[截断:文件过大]…`;
@@ -4183,6 +4339,8 @@ function toServerError(error, fallback) {
4183
4339
  function registerAcpClientHandlers(app, deps) {
4184
4340
  app.onRequest(import_sdk3.methods.client.session.requestPermission, async (ctx) => {
4185
4341
  const params = ctx.params;
4342
+ const sessionId = typeof params.sessionId === "string" ? params.sessionId : undefined;
4343
+ deps.onActivity?.(sessionId);
4186
4344
  const toolCall = params.toolCall;
4187
4345
  const toolHint = toolCall && typeof toolCall === "object" ? {
4188
4346
  id: typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : undefined,
@@ -4195,9 +4353,10 @@ function registerAcpClientHandlers(app, deps) {
4195
4353
  toolCall: toolHint,
4196
4354
  optionCount: Array.isArray(params.options) ? params.options.length : undefined
4197
4355
  });
4356
+ const resumeActivity = deps.onPauseActivity?.(sessionId);
4198
4357
  try {
4199
4358
  const outcome = await deps.onPermission({
4200
- sessionId: typeof params.sessionId === "string" ? params.sessionId : undefined,
4359
+ sessionId,
4201
4360
  params,
4202
4361
  signal: ctx.signal
4203
4362
  });
@@ -4205,11 +4364,16 @@ function registerAcpClientHandlers(app, deps) {
4205
4364
  } catch (error) {
4206
4365
  console.error("[acp] request_permission 失败", error);
4207
4366
  return { outcome: { outcome: "cancelled" } };
4367
+ } finally {
4368
+ resumeActivity?.();
4369
+ deps.onActivity?.(sessionId);
4208
4370
  }
4209
4371
  });
4210
4372
  app.onRequest(import_sdk3.methods.client.fs.readTextFile, async (ctx) => {
4211
4373
  const workspaceRoot = deps.getWorkspaceRoot();
4212
4374
  const filePath = ctx.params.path;
4375
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4376
+ deps.onActivity?.(sessionId);
4213
4377
  if (!workspaceRoot || !filePath) {
4214
4378
  throw toInvalidParams("fs/read_text_file 需要 path 与已连接工作区");
4215
4379
  }
@@ -4223,18 +4387,19 @@ function registerAcpClientHandlers(app, deps) {
4223
4387
  });
4224
4388
  return { content };
4225
4389
  } catch (error) {
4226
- throw toServerError(error, "读取 Inkdown 快照失败");
4390
+ throw toServerError(error, "读取虚拟快照失败");
4227
4391
  }
4228
4392
  }
4229
4393
  if (isInkdownVirtualDirPath(filePath, workspaceRoot)) {
4230
- throw toInvalidParams(`Inkdown 虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
4394
+ throw toInvalidParams(`虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
4231
4395
  }
4232
4396
  try {
4233
4397
  const result = await acpReadTextFile({
4234
4398
  path: filePath,
4235
4399
  workspaceRoot,
4236
4400
  line: ctx.params.line ?? undefined,
4237
- limit: ctx.params.limit ?? undefined
4401
+ limit: ctx.params.limit ?? undefined,
4402
+ maxReadBytes: deps.maxReadBytes
4238
4403
  });
4239
4404
  console.info("[acp] fs/read_text_file ok", { path: filePath });
4240
4405
  return result;
@@ -4246,6 +4411,8 @@ function registerAcpClientHandlers(app, deps) {
4246
4411
  const workspaceRoot = deps.getWorkspaceRoot();
4247
4412
  const filePath = ctx.params.path;
4248
4413
  const content = ctx.params.content;
4414
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4415
+ deps.onActivity?.(sessionId);
4249
4416
  if (!workspaceRoot || !filePath || typeof content !== "string") {
4250
4417
  throw toInvalidParams("fs/write_text_file 需要 path、content 与已连接工作区");
4251
4418
  }
@@ -4263,6 +4430,7 @@ function registerAcpClientHandlers(app, deps) {
4263
4430
  const workspaceRoot = deps.getWorkspaceRoot();
4264
4431
  const sessionId = ctx.params.sessionId;
4265
4432
  const command = ctx.params.command;
4433
+ deps.onActivity?.(sessionId);
4266
4434
  if (!workspaceRoot || !sessionId || !command) {
4267
4435
  throw toInvalidParams("terminal/create 需要 sessionId、command 与已连接工作区");
4268
4436
  }
@@ -4282,6 +4450,8 @@ function registerAcpClientHandlers(app, deps) {
4282
4450
  });
4283
4451
  app.onRequest(import_sdk3.methods.client.terminal.output, async (ctx) => {
4284
4452
  const terminalId = ctx.params.terminalId;
4453
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4454
+ deps.onActivity?.(sessionId);
4285
4455
  if (!terminalId) {
4286
4456
  throw toInvalidParams("terminal/output 需要 terminalId");
4287
4457
  }
@@ -4293,6 +4463,8 @@ function registerAcpClientHandlers(app, deps) {
4293
4463
  });
4294
4464
  app.onRequest(import_sdk3.methods.client.terminal.waitForExit, async (ctx) => {
4295
4465
  const terminalId = ctx.params.terminalId;
4466
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4467
+ deps.onActivity?.(sessionId);
4296
4468
  if (!terminalId) {
4297
4469
  throw toInvalidParams("terminal/wait_for_exit 需要 terminalId");
4298
4470
  }
@@ -4304,6 +4476,8 @@ function registerAcpClientHandlers(app, deps) {
4304
4476
  });
4305
4477
  app.onRequest(import_sdk3.methods.client.terminal.kill, async (ctx) => {
4306
4478
  const terminalId = ctx.params.terminalId;
4479
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4480
+ deps.onActivity?.(sessionId);
4307
4481
  if (!terminalId) {
4308
4482
  throw toInvalidParams("terminal/kill 需要 terminalId");
4309
4483
  }
@@ -4315,6 +4489,8 @@ function registerAcpClientHandlers(app, deps) {
4315
4489
  });
4316
4490
  app.onRequest(import_sdk3.methods.client.terminal.release, async (ctx) => {
4317
4491
  const terminalId = ctx.params.terminalId;
4492
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4493
+ deps.onActivity?.(sessionId);
4318
4494
  if (!terminalId) {
4319
4495
  throw toInvalidParams("terminal/release 需要 terminalId");
4320
4496
  }
@@ -4325,6 +4501,7 @@ function registerAcpClientHandlers(app, deps) {
4325
4501
  }
4326
4502
  });
4327
4503
  app.onNotification(import_sdk3.methods.client.session.update, async (ctx) => {
4504
+ deps.onActivity?.(ctx.params.sessionId);
4328
4505
  deps.onSessionUpdate({
4329
4506
  sessionId: ctx.params.sessionId,
4330
4507
  update: ctx.params.update
@@ -4387,7 +4564,7 @@ function appendTerminalOutput(current, chunk, byteLimit) {
4387
4564
  }
4388
4565
 
4389
4566
  // src/client/acp-terminal.ts
4390
- var DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
4567
+ var ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
4391
4568
  function resolveCwd(cwd, workspaceRoot) {
4392
4569
  if (!cwd?.trim())
4393
4570
  return assertPathInsideWorkspace(workspaceRoot, workspaceRoot);
@@ -4407,12 +4584,18 @@ function buildEnv(extra) {
4407
4584
 
4408
4585
  class AcpTerminalManager {
4409
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
+ }
4410
4593
  create(params) {
4411
4594
  const command = params.command?.trim();
4412
4595
  if (!command)
4413
4596
  throw new Error("terminal/create 需要 command");
4414
4597
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
4415
- 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;
4416
4599
  const child = import_node_child_process8.spawn(command, params.args ?? [], {
4417
4600
  cwd,
4418
4601
  env: buildEnv(params.env),
@@ -4439,6 +4622,7 @@ class AcpTerminalManager {
4439
4622
  record.output = next.output;
4440
4623
  if (next.truncated)
4441
4624
  record.truncated = true;
4625
+ this.onActivity?.(record.sessionId);
4442
4626
  };
4443
4627
  child.stdout?.on("data", onChunk);
4444
4628
  child.stderr?.on("data", onChunk);
@@ -4456,10 +4640,12 @@ class AcpTerminalManager {
4456
4640
  this.markExited(record, code, signal);
4457
4641
  });
4458
4642
  this.terminals.set(id, record);
4643
+ this.onActivity?.(record.sessionId);
4459
4644
  return { terminalId: id };
4460
4645
  }
4461
4646
  getOutput(terminalId) {
4462
4647
  const record = this.require(terminalId);
4648
+ this.onActivity?.(record.sessionId);
4463
4649
  const snapshot = {
4464
4650
  output: record.output,
4465
4651
  truncated: record.truncated
@@ -4474,6 +4660,7 @@ class AcpTerminalManager {
4474
4660
  }
4475
4661
  waitForExit(terminalId) {
4476
4662
  const record = this.require(terminalId);
4663
+ this.onActivity?.(record.sessionId);
4477
4664
  if (record.exited) {
4478
4665
  return Promise.resolve({ exitCode: record.exitCode, signal: record.signal });
4479
4666
  }
@@ -4483,6 +4670,7 @@ class AcpTerminalManager {
4483
4670
  }
4484
4671
  kill(terminalId) {
4485
4672
  const record = this.require(terminalId);
4673
+ this.onActivity?.(record.sessionId);
4486
4674
  if (!record.exited) {
4487
4675
  this.forceKill(record.child);
4488
4676
  }
@@ -4492,6 +4680,7 @@ class AcpTerminalManager {
4492
4680
  const record = this.terminals.get(terminalId);
4493
4681
  if (!record)
4494
4682
  return {};
4683
+ this.onActivity?.(record.sessionId);
4495
4684
  if (!record.exited) {
4496
4685
  this.forceKill(record.child);
4497
4686
  }
@@ -4536,6 +4725,7 @@ class AcpTerminalManager {
4536
4725
  record.exited = true;
4537
4726
  record.exitCode = code;
4538
4727
  record.signal = signal;
4728
+ this.onActivity?.(record.sessionId);
4539
4729
  const status = { exitCode: code, signal };
4540
4730
  for (const waiter of record.waiters)
4541
4731
  waiter(status);
@@ -4798,7 +4988,13 @@ class AcpClient {
4798
4988
  workspaceRoot;
4799
4989
  clientInfo;
4800
4990
  dataDir;
4991
+ proxyOverride;
4801
4992
  extraEnv;
4993
+ requestTimeoutMs;
4994
+ promptIdleTimeoutMs;
4995
+ promptMaxDurationMs;
4996
+ quotaCacheTtlMs;
4997
+ maxReadBytes;
4802
4998
  configurationScope;
4803
4999
  sessionConfig = null;
4804
5000
  resourcesDir;
@@ -4806,13 +5002,13 @@ class AcpClient {
4806
5002
  permissionRequests = new Map;
4807
5003
  processScopeKey = import_node_crypto4.randomUUID();
4808
5004
  callbacks;
4809
- terminals = new AcpTerminalManager;
5005
+ terminals;
4810
5006
  processHandle = null;
4811
5007
  sdkApp = null;
4812
5008
  sdkConnection = null;
4813
5009
  streamHandle = null;
4814
5010
  initResponse = null;
4815
- inflightPrompts = new Set;
5011
+ inflightTrackers = new Map;
4816
5012
  resourcePrep = null;
4817
5013
  connectionGen = 0;
4818
5014
  attachSkillsMcp;
@@ -4826,11 +5022,21 @@ class AcpClient {
4826
5022
  constructor(options) {
4827
5023
  this.workspaceRoot = options.workspaceRoot;
4828
5024
  this.clientInfo = {
4829
- name: options.clientInfo?.name ?? "inkdown",
4830
- version: options.clientInfo?.version ?? "0.1.1"
5025
+ name: options.clientInfo?.name ?? "acp-client",
5026
+ version: options.clientInfo?.version ?? ACP_CLIENT_VERSION
4831
5027
  };
4832
5028
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
5029
+ this.proxyOverride = options.proxy;
4833
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
+ });
4834
5040
  if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
4835
5041
  throw new Error("resources.directory 必须是本机绝对路径");
4836
5042
  }
@@ -4846,12 +5052,13 @@ class AcpClient {
4846
5052
  throw new AcpMcpRecoveryCancelledError("ACP connection closed");
4847
5053
  return this.sdkConnection.agent.request(method, params, { cancellationSignal: signal });
4848
5054
  },
5055
+ requestTimeoutMs: this.requestTimeoutMs,
4849
5056
  getCapabilities: () => ({
4850
5057
  resume: Boolean(this.initResponse && parseResumeSessionSupported(this.initResponse.agentCapabilities)),
4851
5058
  load: Boolean(this.initResponse && parseLoadSessionSupported(this.initResponse.agentCapabilities))
4852
5059
  }),
4853
5060
  isConnected: () => this.isConnected,
4854
- isBusy: (sessionId) => [...this.inflightPrompts].some((id) => id !== sessionId),
5061
+ isBusy: (sessionId) => [...this.inflightTrackers.keys()].some((id) => id !== sessionId),
4855
5062
  onSuppressUpdates: (suppress) => {
4856
5063
  this.suppressRecoveryUpdates = suppress;
4857
5064
  },
@@ -4900,7 +5107,7 @@ class AcpClient {
4900
5107
  }
4901
5108
  this.authenticatingAgent = agent;
4902
5109
  try {
4903
- await sdkRequest(agent, import_sdk4.methods.agent.authenticate, { methodId });
5110
+ await sdkRequest(agent, import_sdk4.methods.agent.authenticate, { methodId }, this.requestTimeoutMs);
4904
5111
  if (this.sdkConnection?.agent !== agent) {
4905
5112
  return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
4906
5113
  }
@@ -4910,14 +5117,17 @@ class AcpClient {
4910
5117
  return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
4911
5118
  }
4912
5119
  const message = error instanceof Error ? error.message : String(error);
4913
- return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
5120
+ return err({
5121
+ code: error instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
5122
+ message
5123
+ });
4914
5124
  } finally {
4915
5125
  if (this.authenticatingAgent === agent)
4916
5126
  this.authenticatingAgent = undefined;
4917
5127
  }
4918
5128
  }
4919
5129
  async connect() {
4920
- if (this.inflightPrompts.size > 0)
5130
+ if (this.inflightTrackers.size > 0)
4921
5131
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
4922
5132
  if (this.isConnected && this.initResponse)
4923
5133
  return ok({ status: this.status, init: this.initResponse });
@@ -4945,8 +5155,9 @@ class AcpClient {
4945
5155
  effectiveRuntime.args = resolved.args;
4946
5156
  }
4947
5157
  const storedProxy = await readAcpProxySettings(this.dataDir);
4948
- const proxyEnv = buildAcpProxySpawnEnv(storedProxy);
4949
- 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;
4950
5161
  const spawnEnv = {
4951
5162
  ...baseEnv,
4952
5163
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
@@ -5027,7 +5238,7 @@ class AcpClient {
5027
5238
  const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
5028
5239
  expectedTag: profileTag,
5029
5240
  scopeKey: this.processScopeKey,
5030
- isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
5241
+ isBusy: (h) => this.inflightTrackers.size > 0 && this.processHandle === h
5031
5242
  });
5032
5243
  if (reuse.status === "hit") {
5033
5244
  reusedHandle = reuse.handle;
@@ -5098,11 +5309,14 @@ class AcpClient {
5098
5309
  this.quotaCache.observe(params, this.runtimeInfo.id);
5099
5310
  if (!this.suppressRecoveryUpdates)
5100
5311
  this.callbacks.onSessionUpdate?.(params);
5101
- }
5312
+ },
5313
+ onActivity: (sessionId) => this.touchSessionActivity(sessionId),
5314
+ onPauseActivity: (sessionId) => this.pauseSessionActivity(sessionId),
5315
+ maxReadBytes: this.maxReadBytes
5102
5316
  };
5103
5317
  const { app, connection, streamHandle } = connectSdkClient(processHandle.child, (clientApp) => {
5104
5318
  registerAcpClientHandlers(clientApp, handlerDeps);
5105
- }, this.runtimeInfo.id);
5319
+ }, this.runtimeInfo.id, this.clientInfo);
5106
5320
  this.sdkApp = app;
5107
5321
  this.sdkConnection = connection;
5108
5322
  this.streamHandle = streamHandle;
@@ -5116,7 +5330,7 @@ class AcpClient {
5116
5330
  configOptions: { boolean: {} }
5117
5331
  }
5118
5332
  }
5119
- });
5333
+ }, this.requestTimeoutMs);
5120
5334
  this.initResponse = initResp;
5121
5335
  if (this.resourcePrep) {
5122
5336
  const agentInfo = initResp?.agentInfo;
@@ -5143,7 +5357,7 @@ class AcpClient {
5143
5357
  const message = e instanceof Error ? e.message : String(e);
5144
5358
  this.setStatus("error", message);
5145
5359
  await this.disconnect(message);
5146
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5360
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
5147
5361
  }
5148
5362
  }
5149
5363
  getCachedQuota(sessionId) {
@@ -5151,7 +5365,7 @@ class AcpClient {
5151
5365
  }
5152
5366
  async getQuota(sessionId) {
5153
5367
  const cached = this.getCachedQuota(sessionId);
5154
- if (cached && Date.now() - cached.updatedAt < 30000) {
5368
+ if (cached && this.quotaCacheTtlMs > 0 && Date.now() - cached.updatedAt < this.quotaCacheTtlMs) {
5155
5369
  return cached;
5156
5370
  }
5157
5371
  if (this.adapter.probeQuota) {
@@ -5207,7 +5421,7 @@ class AcpClient {
5207
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);
5208
5422
  const openResult = await restoreOrCreateAcpSession({
5209
5423
  request: async (method, params) => {
5210
- return sdkRequest(agent, method, params);
5424
+ return sdkRequest(agent, method, params, this.requestTimeoutMs);
5211
5425
  },
5212
5426
  cwd: this.workspaceRoot,
5213
5427
  resumeSessionId: options?.resumeSessionId ?? null,
@@ -5248,7 +5462,10 @@ class AcpClient {
5248
5462
  return ok(handle);
5249
5463
  } catch (e) {
5250
5464
  const message = e instanceof Error ? e.message : String(e);
5251
- return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
5465
+ return err({
5466
+ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
5467
+ message
5468
+ });
5252
5469
  }
5253
5470
  }
5254
5471
  async promptSession(sessionId, promptText, options) {
@@ -5257,11 +5474,12 @@ class AcpClient {
5257
5474
  }
5258
5475
  if (!this.isConnected)
5259
5476
  return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
5260
- if (this.inflightPrompts.has(sessionId))
5477
+ if (this.inflightTrackers.has(sessionId))
5261
5478
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Session already has an in-flight prompt" });
5262
5479
  const generation = this.connectionGen;
5263
5480
  const agent = this.sdkConnection.agent;
5264
- this.inflightPrompts.add(sessionId);
5481
+ const tracker = createSdkRequestActivityController();
5482
+ this.inflightTrackers.set(sessionId, tracker);
5265
5483
  try {
5266
5484
  await this.mcpRecovery.ensureReady(sessionId);
5267
5485
  if (generation !== this.connectionGen || !this.isConnected)
@@ -5274,19 +5492,34 @@ class AcpClient {
5274
5492
  }
5275
5493
  const compat = this.buildCompatPrepend(sessionId);
5276
5494
  const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
5277
- 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, {
5278
5500
  sessionId,
5279
5501
  prompt: blocks
5280
- }, options?.timeoutMs);
5502
+ }, {
5503
+ idleTimeoutMs,
5504
+ maxDurationMs,
5505
+ activity: tracker
5506
+ });
5281
5507
  return ok(response);
5282
5508
  } catch (e) {
5283
5509
  const message = e instanceof Error ? e.message : String(e);
5284
5510
  if (e instanceof AcpMcpRecoveryCancelledError)
5285
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
+ }
5286
5519
  return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
5287
5520
  } finally {
5288
5521
  if (generation === this.connectionGen)
5289
- this.inflightPrompts.delete(sessionId);
5522
+ this.inflightTrackers.delete(sessionId);
5290
5523
  }
5291
5524
  }
5292
5525
  buildCompatPrepend(sessionId) {
@@ -5343,17 +5576,17 @@ class AcpClient {
5343
5576
  sessionId,
5344
5577
  configId,
5345
5578
  value
5346
- });
5579
+ }, this.requestTimeoutMs);
5347
5580
  return ok(response);
5348
5581
  } catch (e) {
5349
5582
  const message = e instanceof Error ? e.message : String(e);
5350
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5583
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
5351
5584
  }
5352
5585
  }
5353
5586
  async disconnect(reason) {
5354
5587
  ++this.connectionGen;
5355
5588
  this.mcpRecovery.reset();
5356
- this.inflightPrompts.clear();
5589
+ this.inflightTrackers.clear();
5357
5590
  this.cancelPermissionRequests("connection_closed");
5358
5591
  this.setStatus("disconnected", reason);
5359
5592
  this.resourcePrep = null;
@@ -5391,6 +5624,31 @@ class AcpClient {
5391
5624
  }
5392
5625
  }
5393
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
+ }
5394
5652
  cancelPermissionRequests(reason, sessionId) {
5395
5653
  for (const [controller, pendingSessionId] of this.permissionRequests) {
5396
5654
  if (sessionId === undefined || pendingSessionId === sessionId)