@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.js CHANGED
@@ -171,7 +171,7 @@ function findBuiltinAcpRuntime(id) {
171
171
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
172
172
  }
173
173
  // src/version.ts
174
- var ACP_CLIENT_VERSION = "0.1.15";
174
+ var ACP_CLIENT_VERSION = "0.1.16";
175
175
  // src/client/session-open.ts
176
176
  import { RequestError } from "@agentclientprotocol/sdk";
177
177
 
@@ -706,6 +706,64 @@ import {
706
706
  ndJsonStream
707
707
  } from "@agentclientprotocol/sdk";
708
708
  var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
709
+ var ACP_PROMPT_IDLE_TIMEOUT_MS = 300000;
710
+ var ACP_PROMPT_MAX_DURATION_MS = 0;
711
+ var MAX_SAFE_TIMER_MS = 2147483647;
712
+
713
+ class SdkRequestTimeoutError extends Error {
714
+ kind;
715
+ method;
716
+ durationMs;
717
+ constructor(kind, method, durationMs) {
718
+ const secs = Math.max(1, Math.round(durationMs / 1000));
719
+ const message = kind === "idle" ? `请求超时 (${secs}s 无活动): ${method}` : kind === "max_duration" ? `请求超时 (超过最大时长 ${secs}s): ${method}` : `请求超时: ${method}`;
720
+ super(message);
721
+ this.name = "SdkRequestTimeoutError";
722
+ this.kind = kind;
723
+ this.method = method;
724
+ this.durationMs = durationMs;
725
+ }
726
+ }
727
+ var activitySubscribers = new WeakMap;
728
+ function createSdkRequestActivityController() {
729
+ let pauseCount = 0;
730
+ const subscribers = new Set;
731
+ const controller = {
732
+ touch() {
733
+ for (const sub of subscribers) {
734
+ sub.onTouch();
735
+ }
736
+ },
737
+ pause() {
738
+ let released = false;
739
+ pauseCount += 1;
740
+ if (pauseCount === 1) {
741
+ for (const sub of subscribers) {
742
+ sub.onPauseChange(true);
743
+ }
744
+ }
745
+ return () => {
746
+ if (released)
747
+ return;
748
+ released = true;
749
+ pauseCount = Math.max(0, pauseCount - 1);
750
+ if (pauseCount === 0) {
751
+ for (const sub of subscribers) {
752
+ sub.onPauseChange(false);
753
+ }
754
+ }
755
+ };
756
+ }
757
+ };
758
+ activitySubscribers.set(controller, {
759
+ subscribers,
760
+ isPaused: () => pauseCount > 0
761
+ });
762
+ return controller;
763
+ }
764
+ function clampTimerMs(ms) {
765
+ return Math.max(1, Math.min(MAX_SAFE_TIMER_MS, Math.floor(ms)));
766
+ }
709
767
  function createSdkStreamHandle(child) {
710
768
  const stdoutBridge = new PassThrough;
711
769
  const stdinBridge = new PassThrough;
@@ -736,17 +794,107 @@ function createSdkStreamHandle(child) {
736
794
  }
737
795
  };
738
796
  }
739
- function connectSdkClient(child, configure, runtimeId) {
797
+ function connectSdkClient(child, configure, runtimeId, clientInfo) {
740
798
  if (runtimeId && true) {
741
799
  console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
742
800
  }
743
- const app = createSdkClientApp({ name: "inkdown" });
801
+ const app = createSdkClientApp({
802
+ name: clientInfo?.name || "acp-client",
803
+ ...clientInfo?.version ? { version: clientInfo.version } : {}
804
+ });
744
805
  configure(app);
745
806
  const streamHandle = createSdkStreamHandle(child);
746
807
  const connection = app.connect(streamHandle.stream);
747
808
  return { app, connection, streamHandle };
748
809
  }
810
+ async function sdkRequestWithActivity(agent, method, params, options = {}) {
811
+ const idleTimeoutMs = options.idleTimeoutMs;
812
+ const maxDurationMs = options.maxDurationMs;
813
+ const hasIdle = typeof idleTimeoutMs === "number" && Number.isFinite(idleTimeoutMs) && idleTimeoutMs > 0;
814
+ const hasMax = typeof maxDurationMs === "number" && Number.isFinite(maxDurationMs) && maxDurationMs > 0;
815
+ if (!hasIdle && !hasMax) {
816
+ return await agent.request(method, params);
817
+ }
818
+ const controller = new AbortController;
819
+ let idleTimer;
820
+ let maxTimer;
821
+ let settled = false;
822
+ let rejectTimeout;
823
+ let paused = false;
824
+ const meta = options.activity ? activitySubscribers.get(options.activity) : undefined;
825
+ if (meta)
826
+ paused = meta.isPaused();
827
+ const clearIdleTimer = () => {
828
+ if (idleTimer !== undefined) {
829
+ clearTimeout(idleTimer);
830
+ idleTimer = undefined;
831
+ }
832
+ };
833
+ const armIdleTimer = () => {
834
+ clearIdleTimer();
835
+ if (settled || paused || !hasIdle)
836
+ return;
837
+ idleTimer = setTimeout(() => {
838
+ if (settled)
839
+ return;
840
+ settled = true;
841
+ controller.abort();
842
+ rejectTimeout(new SdkRequestTimeoutError("idle", method, idleTimeoutMs));
843
+ }, clampTimerMs(idleTimeoutMs));
844
+ idleTimer.unref?.();
845
+ };
846
+ const subscriber = {
847
+ onTouch() {
848
+ if (!paused)
849
+ armIdleTimer();
850
+ },
851
+ onPauseChange(nextPaused) {
852
+ paused = nextPaused;
853
+ if (paused) {
854
+ clearIdleTimer();
855
+ } else {
856
+ armIdleTimer();
857
+ }
858
+ }
859
+ };
860
+ if (meta) {
861
+ meta.subscribers.add(subscriber);
862
+ }
863
+ try {
864
+ const pending = agent.request(method, params, {
865
+ cancellationSignal: controller.signal
866
+ });
867
+ const timeout = new Promise((_, reject) => {
868
+ rejectTimeout = reject;
869
+ if (hasIdle && !paused) {
870
+ armIdleTimer();
871
+ }
872
+ if (hasMax) {
873
+ maxTimer = setTimeout(() => {
874
+ if (settled)
875
+ return;
876
+ settled = true;
877
+ controller.abort();
878
+ reject(new SdkRequestTimeoutError("max_duration", method, maxDurationMs));
879
+ }, clampTimerMs(maxDurationMs));
880
+ maxTimer.unref?.();
881
+ }
882
+ });
883
+ return await Promise.race([pending, timeout]);
884
+ } finally {
885
+ settled = true;
886
+ clearIdleTimer();
887
+ if (maxTimer !== undefined)
888
+ clearTimeout(maxTimer);
889
+ if (meta) {
890
+ meta.subscribers.delete(subscriber);
891
+ }
892
+ }
893
+ }
749
894
  async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
895
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
896
+ return await agent.request(method, params);
897
+ }
750
898
  const controller = new AbortController;
751
899
  let timer;
752
900
  try {
@@ -756,8 +904,8 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
756
904
  const timeout = new Promise((_, reject) => {
757
905
  timer = setTimeout(() => {
758
906
  controller.abort();
759
- reject(new Error(`请求超时: ${method}`));
760
- }, timeoutMs);
907
+ reject(new SdkRequestTimeoutError("timeout", method, timeoutMs));
908
+ }, clampTimerMs(timeoutMs));
761
909
  timer.unref?.();
762
910
  });
763
911
  return await Promise.race([pending, timeout]);
@@ -3891,7 +4039,7 @@ import { methods, RequestError as RequestError2 } from "@agentclientprotocol/sdk
3891
4039
  import { access, readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
3892
4040
  import { dirname as dirname5, extname, resolve as resolve2, sep as sep2 } from "node:path";
3893
4041
  import { mkdir as mkdir5 } from "node:fs/promises";
3894
- var MAX_READ_BYTES = 2 * 1024 * 1024;
4042
+ var ACP_FS_MAX_READ_BYTES = 2 * 1024 * 1024;
3895
4043
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
3896
4044
  function isBinaryDocumentPath(filePath) {
3897
4045
  return BINARY_DOCUMENT_EXTENSIONS.has(extname(filePath).toLowerCase());
@@ -3907,13 +4055,14 @@ function assertPathInsideWorkspace(filePath, workspaceRoot) {
3907
4055
  }
3908
4056
  async function acpReadTextFile(params) {
3909
4057
  if (isBinaryDocumentPath(params.path)) {
3910
- throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
4058
+ throw new Error(`拒绝按文本读取二进制文档/PDF:${params.path}。` + "该格式应由专有解析器读取,请改为向用户索取所需的章节、目录或文本片段。");
3911
4059
  }
3912
4060
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
3913
4061
  await access(abs);
3914
4062
  let content = await readFile5(abs, "utf-8");
3915
- if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
3916
- content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
4063
+ const maxBytes = typeof params.maxReadBytes === "number" && params.maxReadBytes > 0 ? params.maxReadBytes : ACP_FS_MAX_READ_BYTES;
4064
+ if (Buffer.byteLength(content, "utf-8") > maxBytes) {
4065
+ content = content.slice(0, Math.floor(maxBytes / 2));
3917
4066
  content += `
3918
4067
 
3919
4068
  …[截断:文件过大]…`;
@@ -3945,6 +4094,8 @@ function toServerError(error, fallback) {
3945
4094
  function registerAcpClientHandlers(app, deps) {
3946
4095
  app.onRequest(methods.client.session.requestPermission, async (ctx) => {
3947
4096
  const params = ctx.params;
4097
+ const sessionId = typeof params.sessionId === "string" ? params.sessionId : undefined;
4098
+ deps.onActivity?.(sessionId);
3948
4099
  const toolCall = params.toolCall;
3949
4100
  const toolHint = toolCall && typeof toolCall === "object" ? {
3950
4101
  id: typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : undefined,
@@ -3957,9 +4108,10 @@ function registerAcpClientHandlers(app, deps) {
3957
4108
  toolCall: toolHint,
3958
4109
  optionCount: Array.isArray(params.options) ? params.options.length : undefined
3959
4110
  });
4111
+ const resumeActivity = deps.onPauseActivity?.(sessionId);
3960
4112
  try {
3961
4113
  const outcome = await deps.onPermission({
3962
- sessionId: typeof params.sessionId === "string" ? params.sessionId : undefined,
4114
+ sessionId,
3963
4115
  params,
3964
4116
  signal: ctx.signal
3965
4117
  });
@@ -3967,11 +4119,16 @@ function registerAcpClientHandlers(app, deps) {
3967
4119
  } catch (error) {
3968
4120
  console.error("[acp] request_permission 失败", error);
3969
4121
  return { outcome: { outcome: "cancelled" } };
4122
+ } finally {
4123
+ resumeActivity?.();
4124
+ deps.onActivity?.(sessionId);
3970
4125
  }
3971
4126
  });
3972
4127
  app.onRequest(methods.client.fs.readTextFile, async (ctx) => {
3973
4128
  const workspaceRoot = deps.getWorkspaceRoot();
3974
4129
  const filePath = ctx.params.path;
4130
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4131
+ deps.onActivity?.(sessionId);
3975
4132
  if (!workspaceRoot || !filePath) {
3976
4133
  throw toInvalidParams("fs/read_text_file 需要 path 与已连接工作区");
3977
4134
  }
@@ -3985,18 +4142,19 @@ function registerAcpClientHandlers(app, deps) {
3985
4142
  });
3986
4143
  return { content };
3987
4144
  } catch (error) {
3988
- throw toServerError(error, "读取 Inkdown 快照失败");
4145
+ throw toServerError(error, "读取虚拟快照失败");
3989
4146
  }
3990
4147
  }
3991
4148
  if (isInkdownVirtualDirPath(filePath, workspaceRoot)) {
3992
- throw toInvalidParams(`Inkdown 虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
4149
+ throw toInvalidParams(`虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
3993
4150
  }
3994
4151
  try {
3995
4152
  const result = await acpReadTextFile({
3996
4153
  path: filePath,
3997
4154
  workspaceRoot,
3998
4155
  line: ctx.params.line ?? undefined,
3999
- limit: ctx.params.limit ?? undefined
4156
+ limit: ctx.params.limit ?? undefined,
4157
+ maxReadBytes: deps.maxReadBytes
4000
4158
  });
4001
4159
  console.info("[acp] fs/read_text_file ok", { path: filePath });
4002
4160
  return result;
@@ -4008,6 +4166,8 @@ function registerAcpClientHandlers(app, deps) {
4008
4166
  const workspaceRoot = deps.getWorkspaceRoot();
4009
4167
  const filePath = ctx.params.path;
4010
4168
  const content = ctx.params.content;
4169
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4170
+ deps.onActivity?.(sessionId);
4011
4171
  if (!workspaceRoot || !filePath || typeof content !== "string") {
4012
4172
  throw toInvalidParams("fs/write_text_file 需要 path、content 与已连接工作区");
4013
4173
  }
@@ -4025,6 +4185,7 @@ function registerAcpClientHandlers(app, deps) {
4025
4185
  const workspaceRoot = deps.getWorkspaceRoot();
4026
4186
  const sessionId = ctx.params.sessionId;
4027
4187
  const command = ctx.params.command;
4188
+ deps.onActivity?.(sessionId);
4028
4189
  if (!workspaceRoot || !sessionId || !command) {
4029
4190
  throw toInvalidParams("terminal/create 需要 sessionId、command 与已连接工作区");
4030
4191
  }
@@ -4044,6 +4205,8 @@ function registerAcpClientHandlers(app, deps) {
4044
4205
  });
4045
4206
  app.onRequest(methods.client.terminal.output, async (ctx) => {
4046
4207
  const terminalId = ctx.params.terminalId;
4208
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4209
+ deps.onActivity?.(sessionId);
4047
4210
  if (!terminalId) {
4048
4211
  throw toInvalidParams("terminal/output 需要 terminalId");
4049
4212
  }
@@ -4055,6 +4218,8 @@ function registerAcpClientHandlers(app, deps) {
4055
4218
  });
4056
4219
  app.onRequest(methods.client.terminal.waitForExit, async (ctx) => {
4057
4220
  const terminalId = ctx.params.terminalId;
4221
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4222
+ deps.onActivity?.(sessionId);
4058
4223
  if (!terminalId) {
4059
4224
  throw toInvalidParams("terminal/wait_for_exit 需要 terminalId");
4060
4225
  }
@@ -4066,6 +4231,8 @@ function registerAcpClientHandlers(app, deps) {
4066
4231
  });
4067
4232
  app.onRequest(methods.client.terminal.kill, async (ctx) => {
4068
4233
  const terminalId = ctx.params.terminalId;
4234
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4235
+ deps.onActivity?.(sessionId);
4069
4236
  if (!terminalId) {
4070
4237
  throw toInvalidParams("terminal/kill 需要 terminalId");
4071
4238
  }
@@ -4077,6 +4244,8 @@ function registerAcpClientHandlers(app, deps) {
4077
4244
  });
4078
4245
  app.onRequest(methods.client.terminal.release, async (ctx) => {
4079
4246
  const terminalId = ctx.params.terminalId;
4247
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4248
+ deps.onActivity?.(sessionId);
4080
4249
  if (!terminalId) {
4081
4250
  throw toInvalidParams("terminal/release 需要 terminalId");
4082
4251
  }
@@ -4087,6 +4256,7 @@ function registerAcpClientHandlers(app, deps) {
4087
4256
  }
4088
4257
  });
4089
4258
  app.onNotification(methods.client.session.update, async (ctx) => {
4259
+ deps.onActivity?.(ctx.params.sessionId);
4090
4260
  deps.onSessionUpdate({
4091
4261
  sessionId: ctx.params.sessionId,
4092
4262
  update: ctx.params.update
@@ -4149,7 +4319,7 @@ function appendTerminalOutput(current, chunk, byteLimit) {
4149
4319
  }
4150
4320
 
4151
4321
  // src/client/acp-terminal.ts
4152
- var DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
4322
+ var ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
4153
4323
  function resolveCwd(cwd, workspaceRoot) {
4154
4324
  if (!cwd?.trim())
4155
4325
  return assertPathInsideWorkspace(workspaceRoot, workspaceRoot);
@@ -4169,12 +4339,18 @@ function buildEnv(extra) {
4169
4339
 
4170
4340
  class AcpTerminalManager {
4171
4341
  terminals = new Map;
4342
+ defaultOutputByteLimit;
4343
+ onActivity;
4344
+ constructor(options) {
4345
+ this.defaultOutputByteLimit = typeof options?.defaultOutputByteLimit === "number" && options.defaultOutputByteLimit > 0 ? options.defaultOutputByteLimit : ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT;
4346
+ this.onActivity = options?.onActivity;
4347
+ }
4172
4348
  create(params) {
4173
4349
  const command = params.command?.trim();
4174
4350
  if (!command)
4175
4351
  throw new Error("terminal/create 需要 command");
4176
4352
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
4177
- const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
4353
+ const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : this.defaultOutputByteLimit;
4178
4354
  const child = spawn3(command, params.args ?? [], {
4179
4355
  cwd,
4180
4356
  env: buildEnv(params.env),
@@ -4201,6 +4377,7 @@ class AcpTerminalManager {
4201
4377
  record.output = next.output;
4202
4378
  if (next.truncated)
4203
4379
  record.truncated = true;
4380
+ this.onActivity?.(record.sessionId);
4204
4381
  };
4205
4382
  child.stdout?.on("data", onChunk);
4206
4383
  child.stderr?.on("data", onChunk);
@@ -4218,10 +4395,12 @@ class AcpTerminalManager {
4218
4395
  this.markExited(record, code, signal);
4219
4396
  });
4220
4397
  this.terminals.set(id, record);
4398
+ this.onActivity?.(record.sessionId);
4221
4399
  return { terminalId: id };
4222
4400
  }
4223
4401
  getOutput(terminalId) {
4224
4402
  const record = this.require(terminalId);
4403
+ this.onActivity?.(record.sessionId);
4225
4404
  const snapshot = {
4226
4405
  output: record.output,
4227
4406
  truncated: record.truncated
@@ -4236,6 +4415,7 @@ class AcpTerminalManager {
4236
4415
  }
4237
4416
  waitForExit(terminalId) {
4238
4417
  const record = this.require(terminalId);
4418
+ this.onActivity?.(record.sessionId);
4239
4419
  if (record.exited) {
4240
4420
  return Promise.resolve({ exitCode: record.exitCode, signal: record.signal });
4241
4421
  }
@@ -4245,6 +4425,7 @@ class AcpTerminalManager {
4245
4425
  }
4246
4426
  kill(terminalId) {
4247
4427
  const record = this.require(terminalId);
4428
+ this.onActivity?.(record.sessionId);
4248
4429
  if (!record.exited) {
4249
4430
  this.forceKill(record.child);
4250
4431
  }
@@ -4254,6 +4435,7 @@ class AcpTerminalManager {
4254
4435
  const record = this.terminals.get(terminalId);
4255
4436
  if (!record)
4256
4437
  return {};
4438
+ this.onActivity?.(record.sessionId);
4257
4439
  if (!record.exited) {
4258
4440
  this.forceKill(record.child);
4259
4441
  }
@@ -4298,6 +4480,7 @@ class AcpTerminalManager {
4298
4480
  record.exited = true;
4299
4481
  record.exitCode = code;
4300
4482
  record.signal = signal;
4483
+ this.onActivity?.(record.sessionId);
4301
4484
  const status = { exitCode: code, signal };
4302
4485
  for (const waiter of record.waiters)
4303
4486
  waiter(status);
@@ -4560,7 +4743,13 @@ class AcpClient {
4560
4743
  workspaceRoot;
4561
4744
  clientInfo;
4562
4745
  dataDir;
4746
+ proxyOverride;
4563
4747
  extraEnv;
4748
+ requestTimeoutMs;
4749
+ promptIdleTimeoutMs;
4750
+ promptMaxDurationMs;
4751
+ quotaCacheTtlMs;
4752
+ maxReadBytes;
4564
4753
  configurationScope;
4565
4754
  sessionConfig = null;
4566
4755
  resourcesDir;
@@ -4568,13 +4757,13 @@ class AcpClient {
4568
4757
  permissionRequests = new Map;
4569
4758
  processScopeKey = randomUUID2();
4570
4759
  callbacks;
4571
- terminals = new AcpTerminalManager;
4760
+ terminals;
4572
4761
  processHandle = null;
4573
4762
  sdkApp = null;
4574
4763
  sdkConnection = null;
4575
4764
  streamHandle = null;
4576
4765
  initResponse = null;
4577
- inflightPrompts = new Set;
4766
+ inflightTrackers = new Map;
4578
4767
  resourcePrep = null;
4579
4768
  connectionGen = 0;
4580
4769
  attachSkillsMcp;
@@ -4588,11 +4777,21 @@ class AcpClient {
4588
4777
  constructor(options) {
4589
4778
  this.workspaceRoot = options.workspaceRoot;
4590
4779
  this.clientInfo = {
4591
- name: options.clientInfo?.name ?? "inkdown",
4592
- version: options.clientInfo?.version ?? "0.1.1"
4780
+ name: options.clientInfo?.name ?? "acp-client",
4781
+ version: options.clientInfo?.version ?? ACP_CLIENT_VERSION
4593
4782
  };
4594
4783
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
4784
+ this.proxyOverride = options.proxy;
4595
4785
  this.extraEnv = options.env ?? {};
4786
+ this.requestTimeoutMs = typeof options.requestTimeoutMs === "number" && options.requestTimeoutMs > 0 ? options.requestTimeoutMs : ACP_SDK_REQUEST_TIMEOUT_MS;
4787
+ this.promptIdleTimeoutMs = typeof options.promptIdleTimeoutMs === "number" && options.promptIdleTimeoutMs >= 0 ? options.promptIdleTimeoutMs : ACP_PROMPT_IDLE_TIMEOUT_MS;
4788
+ this.promptMaxDurationMs = typeof options.promptMaxDurationMs === "number" && options.promptMaxDurationMs >= 0 ? options.promptMaxDurationMs : ACP_PROMPT_MAX_DURATION_MS;
4789
+ this.quotaCacheTtlMs = typeof options.quotaCacheTtlMs === "number" && options.quotaCacheTtlMs >= 0 ? options.quotaCacheTtlMs : 30000;
4790
+ this.maxReadBytes = typeof options.maxReadBytes === "number" && options.maxReadBytes > 0 ? options.maxReadBytes : ACP_FS_MAX_READ_BYTES;
4791
+ this.terminals = new AcpTerminalManager({
4792
+ defaultOutputByteLimit: options.terminalOutputByteLimit ?? ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT,
4793
+ onActivity: (sid) => this.touchSessionActivity(sid)
4794
+ });
4596
4795
  if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
4597
4796
  throw new Error("resources.directory 必须是本机绝对路径");
4598
4797
  }
@@ -4608,12 +4807,13 @@ class AcpClient {
4608
4807
  throw new AcpMcpRecoveryCancelledError("ACP connection closed");
4609
4808
  return this.sdkConnection.agent.request(method, params, { cancellationSignal: signal });
4610
4809
  },
4810
+ requestTimeoutMs: this.requestTimeoutMs,
4611
4811
  getCapabilities: () => ({
4612
4812
  resume: Boolean(this.initResponse && parseResumeSessionSupported(this.initResponse.agentCapabilities)),
4613
4813
  load: Boolean(this.initResponse && parseLoadSessionSupported(this.initResponse.agentCapabilities))
4614
4814
  }),
4615
4815
  isConnected: () => this.isConnected,
4616
- isBusy: (sessionId) => [...this.inflightPrompts].some((id) => id !== sessionId),
4816
+ isBusy: (sessionId) => [...this.inflightTrackers.keys()].some((id) => id !== sessionId),
4617
4817
  onSuppressUpdates: (suppress) => {
4618
4818
  this.suppressRecoveryUpdates = suppress;
4619
4819
  },
@@ -4662,7 +4862,7 @@ class AcpClient {
4662
4862
  }
4663
4863
  this.authenticatingAgent = agent;
4664
4864
  try {
4665
- await sdkRequest(agent, methods2.agent.authenticate, { methodId });
4865
+ await sdkRequest(agent, methods2.agent.authenticate, { methodId }, this.requestTimeoutMs);
4666
4866
  if (this.sdkConnection?.agent !== agent) {
4667
4867
  return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
4668
4868
  }
@@ -4672,14 +4872,17 @@ class AcpClient {
4672
4872
  return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
4673
4873
  }
4674
4874
  const message = error instanceof Error ? error.message : String(error);
4675
- return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
4875
+ return err({
4876
+ code: error instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
4877
+ message
4878
+ });
4676
4879
  } finally {
4677
4880
  if (this.authenticatingAgent === agent)
4678
4881
  this.authenticatingAgent = undefined;
4679
4882
  }
4680
4883
  }
4681
4884
  async connect() {
4682
- if (this.inflightPrompts.size > 0)
4885
+ if (this.inflightTrackers.size > 0)
4683
4886
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
4684
4887
  if (this.isConnected && this.initResponse)
4685
4888
  return ok({ status: this.status, init: this.initResponse });
@@ -4707,8 +4910,9 @@ class AcpClient {
4707
4910
  effectiveRuntime.args = resolved.args;
4708
4911
  }
4709
4912
  const storedProxy = await readAcpProxySettings(this.dataDir);
4710
- const proxyEnv = buildAcpProxySpawnEnv(storedProxy);
4711
- const baseEnv = this.adapter.getSpawnEnv?.(storedProxy) ?? proxyEnv;
4913
+ const effectiveProxy = this.proxyOverride ? { ...storedProxy, ...this.proxyOverride } : storedProxy;
4914
+ const proxyEnv = buildAcpProxySpawnEnv(effectiveProxy);
4915
+ const baseEnv = this.adapter.getSpawnEnv?.(effectiveProxy) ?? proxyEnv;
4712
4916
  const spawnEnv = {
4713
4917
  ...baseEnv,
4714
4918
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
@@ -4789,7 +4993,7 @@ class AcpClient {
4789
4993
  const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
4790
4994
  expectedTag: profileTag,
4791
4995
  scopeKey: this.processScopeKey,
4792
- isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
4996
+ isBusy: (h) => this.inflightTrackers.size > 0 && this.processHandle === h
4793
4997
  });
4794
4998
  if (reuse.status === "hit") {
4795
4999
  reusedHandle = reuse.handle;
@@ -4860,11 +5064,14 @@ class AcpClient {
4860
5064
  this.quotaCache.observe(params, this.runtimeInfo.id);
4861
5065
  if (!this.suppressRecoveryUpdates)
4862
5066
  this.callbacks.onSessionUpdate?.(params);
4863
- }
5067
+ },
5068
+ onActivity: (sessionId) => this.touchSessionActivity(sessionId),
5069
+ onPauseActivity: (sessionId) => this.pauseSessionActivity(sessionId),
5070
+ maxReadBytes: this.maxReadBytes
4864
5071
  };
4865
5072
  const { app, connection, streamHandle } = connectSdkClient(processHandle.child, (clientApp) => {
4866
5073
  registerAcpClientHandlers(clientApp, handlerDeps);
4867
- }, this.runtimeInfo.id);
5074
+ }, this.runtimeInfo.id, this.clientInfo);
4868
5075
  this.sdkApp = app;
4869
5076
  this.sdkConnection = connection;
4870
5077
  this.streamHandle = streamHandle;
@@ -4878,7 +5085,7 @@ class AcpClient {
4878
5085
  configOptions: { boolean: {} }
4879
5086
  }
4880
5087
  }
4881
- });
5088
+ }, this.requestTimeoutMs);
4882
5089
  this.initResponse = initResp;
4883
5090
  if (this.resourcePrep) {
4884
5091
  const agentInfo = initResp?.agentInfo;
@@ -4905,7 +5112,7 @@ class AcpClient {
4905
5112
  const message = e instanceof Error ? e.message : String(e);
4906
5113
  this.setStatus("error", message);
4907
5114
  await this.disconnect(message);
4908
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5115
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
4909
5116
  }
4910
5117
  }
4911
5118
  getCachedQuota(sessionId) {
@@ -4913,7 +5120,7 @@ class AcpClient {
4913
5120
  }
4914
5121
  async getQuota(sessionId) {
4915
5122
  const cached = this.getCachedQuota(sessionId);
4916
- if (cached && Date.now() - cached.updatedAt < 30000) {
5123
+ if (cached && this.quotaCacheTtlMs > 0 && Date.now() - cached.updatedAt < this.quotaCacheTtlMs) {
4917
5124
  return cached;
4918
5125
  }
4919
5126
  if (this.adapter.probeQuota) {
@@ -4969,7 +5176,7 @@ class AcpClient {
4969
5176
  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);
4970
5177
  const openResult = await restoreOrCreateAcpSession({
4971
5178
  request: async (method, params) => {
4972
- return sdkRequest(agent, method, params);
5179
+ return sdkRequest(agent, method, params, this.requestTimeoutMs);
4973
5180
  },
4974
5181
  cwd: this.workspaceRoot,
4975
5182
  resumeSessionId: options?.resumeSessionId ?? null,
@@ -5010,7 +5217,10 @@ class AcpClient {
5010
5217
  return ok(handle);
5011
5218
  } catch (e) {
5012
5219
  const message = e instanceof Error ? e.message : String(e);
5013
- return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
5220
+ return err({
5221
+ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
5222
+ message
5223
+ });
5014
5224
  }
5015
5225
  }
5016
5226
  async promptSession(sessionId, promptText, options) {
@@ -5019,11 +5229,12 @@ class AcpClient {
5019
5229
  }
5020
5230
  if (!this.isConnected)
5021
5231
  return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
5022
- if (this.inflightPrompts.has(sessionId))
5232
+ if (this.inflightTrackers.has(sessionId))
5023
5233
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Session already has an in-flight prompt" });
5024
5234
  const generation = this.connectionGen;
5025
5235
  const agent = this.sdkConnection.agent;
5026
- this.inflightPrompts.add(sessionId);
5236
+ const tracker = createSdkRequestActivityController();
5237
+ this.inflightTrackers.set(sessionId, tracker);
5027
5238
  try {
5028
5239
  await this.mcpRecovery.ensureReady(sessionId);
5029
5240
  if (generation !== this.connectionGen || !this.isConnected)
@@ -5036,19 +5247,34 @@ class AcpClient {
5036
5247
  }
5037
5248
  const compat = this.buildCompatPrepend(sessionId);
5038
5249
  const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
5039
- const response = await sdkRequest(agent, methods2.agent.session.prompt, {
5250
+ const hasIdleOption = options?.idleTimeoutMs !== undefined;
5251
+ const hasTimeoutOption = options?.timeoutMs !== undefined;
5252
+ const idleTimeoutMs = hasIdleOption ? options.idleTimeoutMs : hasTimeoutOption ? 0 : this.promptIdleTimeoutMs;
5253
+ const maxDurationMs = options?.maxDurationMs ?? options?.timeoutMs ?? this.promptMaxDurationMs;
5254
+ const response = await sdkRequestWithActivity(agent, methods2.agent.session.prompt, {
5040
5255
  sessionId,
5041
5256
  prompt: blocks
5042
- }, options?.timeoutMs);
5257
+ }, {
5258
+ idleTimeoutMs,
5259
+ maxDurationMs,
5260
+ activity: tracker
5261
+ });
5043
5262
  return ok(response);
5044
5263
  } catch (e) {
5045
5264
  const message = e instanceof Error ? e.message : String(e);
5046
5265
  if (e instanceof AcpMcpRecoveryCancelledError)
5047
5266
  return err({ code: "CANCELLED", message });
5267
+ if (e instanceof SdkRequestTimeoutError) {
5268
+ this.cancelPermissionRequests("session_cancelled", sessionId);
5269
+ this.sdkConnection?.agent?.notify(methods2.agent.session.cancel, { sessionId }).catch(() => {
5270
+ return;
5271
+ });
5272
+ return err({ code: "ACP_TIMEOUT", message });
5273
+ }
5048
5274
  return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
5049
5275
  } finally {
5050
5276
  if (generation === this.connectionGen)
5051
- this.inflightPrompts.delete(sessionId);
5277
+ this.inflightTrackers.delete(sessionId);
5052
5278
  }
5053
5279
  }
5054
5280
  buildCompatPrepend(sessionId) {
@@ -5105,17 +5331,17 @@ class AcpClient {
5105
5331
  sessionId,
5106
5332
  configId,
5107
5333
  value
5108
- });
5334
+ }, this.requestTimeoutMs);
5109
5335
  return ok(response);
5110
5336
  } catch (e) {
5111
5337
  const message = e instanceof Error ? e.message : String(e);
5112
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5338
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
5113
5339
  }
5114
5340
  }
5115
5341
  async disconnect(reason) {
5116
5342
  ++this.connectionGen;
5117
5343
  this.mcpRecovery.reset();
5118
- this.inflightPrompts.clear();
5344
+ this.inflightTrackers.clear();
5119
5345
  this.cancelPermissionRequests("connection_closed");
5120
5346
  this.setStatus("disconnected", reason);
5121
5347
  this.resourcePrep = null;
@@ -5153,6 +5379,31 @@ class AcpClient {
5153
5379
  }
5154
5380
  }
5155
5381
  }
5382
+ touchSessionActivity(sessionId) {
5383
+ if (sessionId) {
5384
+ this.inflightTrackers.get(sessionId)?.touch();
5385
+ return;
5386
+ }
5387
+ for (const tracker of this.inflightTrackers.values()) {
5388
+ tracker.touch();
5389
+ }
5390
+ }
5391
+ pauseSessionActivity(sessionId) {
5392
+ if (sessionId) {
5393
+ return this.inflightTrackers.get(sessionId)?.pause() ?? (() => {
5394
+ return;
5395
+ });
5396
+ }
5397
+ const resumes = [...this.inflightTrackers.values()].map((tracker) => tracker.pause());
5398
+ let released = false;
5399
+ return () => {
5400
+ if (released)
5401
+ return;
5402
+ released = true;
5403
+ for (const resume of resumes)
5404
+ resume();
5405
+ };
5406
+ }
5156
5407
  cancelPermissionRequests(reason, sessionId) {
5157
5408
  for (const [controller, pendingSessionId] of this.permissionRequests) {
5158
5409
  if (sessionId === undefined || pendingSessionId === sessionId)
@@ -6139,7 +6390,11 @@ export {
6139
6390
  ACP_CLIENT_VERSION,
6140
6391
  ACP_EARLY_EXIT_STDERR_TAIL_LINES,
6141
6392
  ACP_EARLY_EXIT_WINDOW_MS,
6393
+ ACP_FS_MAX_READ_BYTES,
6394
+ ACP_PROMPT_IDLE_TIMEOUT_MS,
6395
+ ACP_PROMPT_MAX_DURATION_MS,
6142
6396
  ACP_SDK_REQUEST_TIMEOUT_MS,
6397
+ ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT,
6143
6398
  AGY_ACP_NPM_PACKAGE,
6144
6399
  APP_RESOURCE_CAPABILITIES,
6145
6400
  APP_RULES_FILE,
@@ -6169,6 +6424,7 @@ export {
6169
6424
  NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
6170
6425
  OPENCODE_CLI_NPM_PACKAGE,
6171
6426
  QuotaCache,
6427
+ SdkRequestTimeoutError,
6172
6428
  acpReadTextFile,
6173
6429
  acpWriteTextFile,
6174
6430
  agyAdapter,
@@ -6191,6 +6447,7 @@ export {
6191
6447
  codexAdapter,
6192
6448
  connectSdkClient,
6193
6449
  copilotAdapter,
6450
+ createSdkRequestActivityController,
6194
6451
  createSdkStreamHandle,
6195
6452
  createSessionConfigHome,
6196
6453
  cursorAdapter,
@@ -6303,6 +6560,7 @@ export {
6303
6560
  saveAcpProvider,
6304
6561
  saveAcpProxySettings,
6305
6562
  sdkRequest,
6563
+ sdkRequestWithActivity,
6306
6564
  shouldPromptAuthWizard,
6307
6565
  spawnAcpProcess,
6308
6566
  supportsCodeMode,