@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/sidecar.cjs CHANGED
@@ -37,7 +37,7 @@ var readline2 = __toESM(require("node:readline"), 1);
37
37
  var import_node_crypto5 = require("node:crypto");
38
38
 
39
39
  // src/version.ts
40
- var ACP_CLIENT_VERSION = "0.1.15";
40
+ var ACP_CLIENT_VERSION = "0.1.16";
41
41
  // src/contracts/index.ts
42
42
  function ok(value) {
43
43
  return { ok: true, value };
@@ -10197,6 +10197,64 @@ class AcpMcpSessionRecovery {
10197
10197
  // src/client/sdk-client.ts
10198
10198
  var import_node_stream = require("node:stream");
10199
10199
  var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
10200
+ var ACP_PROMPT_IDLE_TIMEOUT_MS = 300000;
10201
+ var ACP_PROMPT_MAX_DURATION_MS = 0;
10202
+ var MAX_SAFE_TIMER_MS = 2147483647;
10203
+
10204
+ class SdkRequestTimeoutError extends Error {
10205
+ kind;
10206
+ method;
10207
+ durationMs;
10208
+ constructor(kind, method, durationMs) {
10209
+ const secs = Math.max(1, Math.round(durationMs / 1000));
10210
+ const message = kind === "idle" ? `请求超时 (${secs}s 无活动): ${method}` : kind === "max_duration" ? `请求超时 (超过最大时长 ${secs}s): ${method}` : `请求超时: ${method}`;
10211
+ super(message);
10212
+ this.name = "SdkRequestTimeoutError";
10213
+ this.kind = kind;
10214
+ this.method = method;
10215
+ this.durationMs = durationMs;
10216
+ }
10217
+ }
10218
+ var activitySubscribers = new WeakMap;
10219
+ function createSdkRequestActivityController() {
10220
+ let pauseCount = 0;
10221
+ const subscribers = new Set;
10222
+ const controller = {
10223
+ touch() {
10224
+ for (const sub of subscribers) {
10225
+ sub.onTouch();
10226
+ }
10227
+ },
10228
+ pause() {
10229
+ let released = false;
10230
+ pauseCount += 1;
10231
+ if (pauseCount === 1) {
10232
+ for (const sub of subscribers) {
10233
+ sub.onPauseChange(true);
10234
+ }
10235
+ }
10236
+ return () => {
10237
+ if (released)
10238
+ return;
10239
+ released = true;
10240
+ pauseCount = Math.max(0, pauseCount - 1);
10241
+ if (pauseCount === 0) {
10242
+ for (const sub of subscribers) {
10243
+ sub.onPauseChange(false);
10244
+ }
10245
+ }
10246
+ };
10247
+ }
10248
+ };
10249
+ activitySubscribers.set(controller, {
10250
+ subscribers,
10251
+ isPaused: () => pauseCount > 0
10252
+ });
10253
+ return controller;
10254
+ }
10255
+ function clampTimerMs(ms) {
10256
+ return Math.max(1, Math.min(MAX_SAFE_TIMER_MS, Math.floor(ms)));
10257
+ }
10200
10258
  function createSdkStreamHandle(child) {
10201
10259
  const stdoutBridge = new import_node_stream.PassThrough;
10202
10260
  const stdinBridge = new import_node_stream.PassThrough;
@@ -10227,17 +10285,107 @@ function createSdkStreamHandle(child) {
10227
10285
  }
10228
10286
  };
10229
10287
  }
10230
- function connectSdkClient(child, configure, runtimeId) {
10288
+ function connectSdkClient(child, configure, runtimeId, clientInfo) {
10231
10289
  if (runtimeId && true) {
10232
10290
  console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
10233
10291
  }
10234
- const app = client({ name: "inkdown" });
10292
+ const app = client({
10293
+ name: clientInfo?.name || "acp-client",
10294
+ ...clientInfo?.version ? { version: clientInfo.version } : {}
10295
+ });
10235
10296
  configure(app);
10236
10297
  const streamHandle = createSdkStreamHandle(child);
10237
10298
  const connection = app.connect(streamHandle.stream);
10238
10299
  return { app, connection, streamHandle };
10239
10300
  }
10301
+ async function sdkRequestWithActivity(agent, method, params, options = {}) {
10302
+ const idleTimeoutMs = options.idleTimeoutMs;
10303
+ const maxDurationMs = options.maxDurationMs;
10304
+ const hasIdle = typeof idleTimeoutMs === "number" && Number.isFinite(idleTimeoutMs) && idleTimeoutMs > 0;
10305
+ const hasMax = typeof maxDurationMs === "number" && Number.isFinite(maxDurationMs) && maxDurationMs > 0;
10306
+ if (!hasIdle && !hasMax) {
10307
+ return await agent.request(method, params);
10308
+ }
10309
+ const controller = new AbortController;
10310
+ let idleTimer;
10311
+ let maxTimer;
10312
+ let settled = false;
10313
+ let rejectTimeout;
10314
+ let paused = false;
10315
+ const meta = options.activity ? activitySubscribers.get(options.activity) : undefined;
10316
+ if (meta)
10317
+ paused = meta.isPaused();
10318
+ const clearIdleTimer = () => {
10319
+ if (idleTimer !== undefined) {
10320
+ clearTimeout(idleTimer);
10321
+ idleTimer = undefined;
10322
+ }
10323
+ };
10324
+ const armIdleTimer = () => {
10325
+ clearIdleTimer();
10326
+ if (settled || paused || !hasIdle)
10327
+ return;
10328
+ idleTimer = setTimeout(() => {
10329
+ if (settled)
10330
+ return;
10331
+ settled = true;
10332
+ controller.abort();
10333
+ rejectTimeout(new SdkRequestTimeoutError("idle", method, idleTimeoutMs));
10334
+ }, clampTimerMs(idleTimeoutMs));
10335
+ idleTimer.unref?.();
10336
+ };
10337
+ const subscriber = {
10338
+ onTouch() {
10339
+ if (!paused)
10340
+ armIdleTimer();
10341
+ },
10342
+ onPauseChange(nextPaused) {
10343
+ paused = nextPaused;
10344
+ if (paused) {
10345
+ clearIdleTimer();
10346
+ } else {
10347
+ armIdleTimer();
10348
+ }
10349
+ }
10350
+ };
10351
+ if (meta) {
10352
+ meta.subscribers.add(subscriber);
10353
+ }
10354
+ try {
10355
+ const pending = agent.request(method, params, {
10356
+ cancellationSignal: controller.signal
10357
+ });
10358
+ const timeout = new Promise((_, reject) => {
10359
+ rejectTimeout = reject;
10360
+ if (hasIdle && !paused) {
10361
+ armIdleTimer();
10362
+ }
10363
+ if (hasMax) {
10364
+ maxTimer = setTimeout(() => {
10365
+ if (settled)
10366
+ return;
10367
+ settled = true;
10368
+ controller.abort();
10369
+ reject(new SdkRequestTimeoutError("max_duration", method, maxDurationMs));
10370
+ }, clampTimerMs(maxDurationMs));
10371
+ maxTimer.unref?.();
10372
+ }
10373
+ });
10374
+ return await Promise.race([pending, timeout]);
10375
+ } finally {
10376
+ settled = true;
10377
+ clearIdleTimer();
10378
+ if (maxTimer !== undefined)
10379
+ clearTimeout(maxTimer);
10380
+ if (meta) {
10381
+ meta.subscribers.delete(subscriber);
10382
+ }
10383
+ }
10384
+ }
10240
10385
  async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
10386
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
10387
+ return await agent.request(method, params);
10388
+ }
10241
10389
  const controller = new AbortController;
10242
10390
  let timer;
10243
10391
  try {
@@ -10247,8 +10395,8 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
10247
10395
  const timeout = new Promise((_, reject) => {
10248
10396
  timer = setTimeout(() => {
10249
10397
  controller.abort();
10250
- reject(new Error(`请求超时: ${method}`));
10251
- }, timeoutMs);
10398
+ reject(new SdkRequestTimeoutError("timeout", method, timeoutMs));
10399
+ }, clampTimerMs(timeoutMs));
10252
10400
  timer.unref?.();
10253
10401
  });
10254
10402
  return await Promise.race([pending, timeout]);
@@ -13076,7 +13224,7 @@ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
13076
13224
  var import_promises4 = require("node:fs/promises");
13077
13225
  var import_node_path19 = require("node:path");
13078
13226
  var import_promises5 = require("node:fs/promises");
13079
- var MAX_READ_BYTES = 2 * 1024 * 1024;
13227
+ var ACP_FS_MAX_READ_BYTES = 2 * 1024 * 1024;
13080
13228
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
13081
13229
  function isBinaryDocumentPath(filePath) {
13082
13230
  return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path19.extname(filePath).toLowerCase());
@@ -13092,13 +13240,14 @@ function assertPathInsideWorkspace(filePath, workspaceRoot) {
13092
13240
  }
13093
13241
  async function acpReadTextFile(params) {
13094
13242
  if (isBinaryDocumentPath(params.path)) {
13095
- throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
13243
+ throw new Error(`拒绝按文本读取二进制文档/PDF:${params.path}。` + "该格式应由专有解析器读取,请改为向用户索取所需的章节、目录或文本片段。");
13096
13244
  }
13097
13245
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
13098
13246
  await import_promises4.access(abs);
13099
13247
  let content = await import_promises4.readFile(abs, "utf-8");
13100
- if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
13101
- content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
13248
+ const maxBytes = typeof params.maxReadBytes === "number" && params.maxReadBytes > 0 ? params.maxReadBytes : ACP_FS_MAX_READ_BYTES;
13249
+ if (Buffer.byteLength(content, "utf-8") > maxBytes) {
13250
+ content = content.slice(0, Math.floor(maxBytes / 2));
13102
13251
  content += `
13103
13252
 
13104
13253
  …[截断:文件过大]…`;
@@ -13130,6 +13279,8 @@ function toServerError(error, fallback) {
13130
13279
  function registerAcpClientHandlers(app, deps) {
13131
13280
  app.onRequest(methods.client.session.requestPermission, async (ctx) => {
13132
13281
  const params = ctx.params;
13282
+ const sessionId = typeof params.sessionId === "string" ? params.sessionId : undefined;
13283
+ deps.onActivity?.(sessionId);
13133
13284
  const toolCall = params.toolCall;
13134
13285
  const toolHint = toolCall && typeof toolCall === "object" ? {
13135
13286
  id: typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : undefined,
@@ -13142,9 +13293,10 @@ function registerAcpClientHandlers(app, deps) {
13142
13293
  toolCall: toolHint,
13143
13294
  optionCount: Array.isArray(params.options) ? params.options.length : undefined
13144
13295
  });
13296
+ const resumeActivity = deps.onPauseActivity?.(sessionId);
13145
13297
  try {
13146
13298
  const outcome = await deps.onPermission({
13147
- sessionId: typeof params.sessionId === "string" ? params.sessionId : undefined,
13299
+ sessionId,
13148
13300
  params,
13149
13301
  signal: ctx.signal
13150
13302
  });
@@ -13152,11 +13304,16 @@ function registerAcpClientHandlers(app, deps) {
13152
13304
  } catch (error) {
13153
13305
  console.error("[acp] request_permission 失败", error);
13154
13306
  return { outcome: { outcome: "cancelled" } };
13307
+ } finally {
13308
+ resumeActivity?.();
13309
+ deps.onActivity?.(sessionId);
13155
13310
  }
13156
13311
  });
13157
13312
  app.onRequest(methods.client.fs.readTextFile, async (ctx) => {
13158
13313
  const workspaceRoot = deps.getWorkspaceRoot();
13159
13314
  const filePath = ctx.params.path;
13315
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
13316
+ deps.onActivity?.(sessionId);
13160
13317
  if (!workspaceRoot || !filePath) {
13161
13318
  throw toInvalidParams("fs/read_text_file 需要 path 与已连接工作区");
13162
13319
  }
@@ -13170,18 +13327,19 @@ function registerAcpClientHandlers(app, deps) {
13170
13327
  });
13171
13328
  return { content };
13172
13329
  } catch (error) {
13173
- throw toServerError(error, "读取 Inkdown 快照失败");
13330
+ throw toServerError(error, "读取虚拟快照失败");
13174
13331
  }
13175
13332
  }
13176
13333
  if (isInkdownVirtualDirPath(filePath, workspaceRoot)) {
13177
- throw toInvalidParams(`Inkdown 虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
13334
+ throw toInvalidParams(`虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
13178
13335
  }
13179
13336
  try {
13180
13337
  const result = await acpReadTextFile({
13181
13338
  path: filePath,
13182
13339
  workspaceRoot,
13183
13340
  line: ctx.params.line ?? undefined,
13184
- limit: ctx.params.limit ?? undefined
13341
+ limit: ctx.params.limit ?? undefined,
13342
+ maxReadBytes: deps.maxReadBytes
13185
13343
  });
13186
13344
  console.info("[acp] fs/read_text_file ok", { path: filePath });
13187
13345
  return result;
@@ -13193,6 +13351,8 @@ function registerAcpClientHandlers(app, deps) {
13193
13351
  const workspaceRoot = deps.getWorkspaceRoot();
13194
13352
  const filePath = ctx.params.path;
13195
13353
  const content = ctx.params.content;
13354
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
13355
+ deps.onActivity?.(sessionId);
13196
13356
  if (!workspaceRoot || !filePath || typeof content !== "string") {
13197
13357
  throw toInvalidParams("fs/write_text_file 需要 path、content 与已连接工作区");
13198
13358
  }
@@ -13210,6 +13370,7 @@ function registerAcpClientHandlers(app, deps) {
13210
13370
  const workspaceRoot = deps.getWorkspaceRoot();
13211
13371
  const sessionId = ctx.params.sessionId;
13212
13372
  const command = ctx.params.command;
13373
+ deps.onActivity?.(sessionId);
13213
13374
  if (!workspaceRoot || !sessionId || !command) {
13214
13375
  throw toInvalidParams("terminal/create 需要 sessionId、command 与已连接工作区");
13215
13376
  }
@@ -13229,6 +13390,8 @@ function registerAcpClientHandlers(app, deps) {
13229
13390
  });
13230
13391
  app.onRequest(methods.client.terminal.output, async (ctx) => {
13231
13392
  const terminalId = ctx.params.terminalId;
13393
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
13394
+ deps.onActivity?.(sessionId);
13232
13395
  if (!terminalId) {
13233
13396
  throw toInvalidParams("terminal/output 需要 terminalId");
13234
13397
  }
@@ -13240,6 +13403,8 @@ function registerAcpClientHandlers(app, deps) {
13240
13403
  });
13241
13404
  app.onRequest(methods.client.terminal.waitForExit, async (ctx) => {
13242
13405
  const terminalId = ctx.params.terminalId;
13406
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
13407
+ deps.onActivity?.(sessionId);
13243
13408
  if (!terminalId) {
13244
13409
  throw toInvalidParams("terminal/wait_for_exit 需要 terminalId");
13245
13410
  }
@@ -13251,6 +13416,8 @@ function registerAcpClientHandlers(app, deps) {
13251
13416
  });
13252
13417
  app.onRequest(methods.client.terminal.kill, async (ctx) => {
13253
13418
  const terminalId = ctx.params.terminalId;
13419
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
13420
+ deps.onActivity?.(sessionId);
13254
13421
  if (!terminalId) {
13255
13422
  throw toInvalidParams("terminal/kill 需要 terminalId");
13256
13423
  }
@@ -13262,6 +13429,8 @@ function registerAcpClientHandlers(app, deps) {
13262
13429
  });
13263
13430
  app.onRequest(methods.client.terminal.release, async (ctx) => {
13264
13431
  const terminalId = ctx.params.terminalId;
13432
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
13433
+ deps.onActivity?.(sessionId);
13265
13434
  if (!terminalId) {
13266
13435
  throw toInvalidParams("terminal/release 需要 terminalId");
13267
13436
  }
@@ -13272,6 +13441,7 @@ function registerAcpClientHandlers(app, deps) {
13272
13441
  }
13273
13442
  });
13274
13443
  app.onNotification(methods.client.session.update, async (ctx) => {
13444
+ deps.onActivity?.(ctx.params.sessionId);
13275
13445
  deps.onSessionUpdate({
13276
13446
  sessionId: ctx.params.sessionId,
13277
13447
  update: ctx.params.update
@@ -13325,7 +13495,7 @@ function appendTerminalOutput(current, chunk, byteLimit) {
13325
13495
  }
13326
13496
 
13327
13497
  // src/client/acp-terminal.ts
13328
- var DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
13498
+ var ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
13329
13499
  function resolveCwd(cwd, workspaceRoot) {
13330
13500
  if (!cwd?.trim())
13331
13501
  return assertPathInsideWorkspace(workspaceRoot, workspaceRoot);
@@ -13345,12 +13515,18 @@ function buildEnv(extra) {
13345
13515
 
13346
13516
  class AcpTerminalManager {
13347
13517
  terminals = new Map;
13518
+ defaultOutputByteLimit;
13519
+ onActivity;
13520
+ constructor(options) {
13521
+ this.defaultOutputByteLimit = typeof options?.defaultOutputByteLimit === "number" && options.defaultOutputByteLimit > 0 ? options.defaultOutputByteLimit : ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT;
13522
+ this.onActivity = options?.onActivity;
13523
+ }
13348
13524
  create(params) {
13349
13525
  const command = params.command?.trim();
13350
13526
  if (!command)
13351
13527
  throw new Error("terminal/create 需要 command");
13352
13528
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
13353
- const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
13529
+ const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : this.defaultOutputByteLimit;
13354
13530
  const child = import_node_child_process7.spawn(command, params.args ?? [], {
13355
13531
  cwd,
13356
13532
  env: buildEnv(params.env),
@@ -13377,6 +13553,7 @@ class AcpTerminalManager {
13377
13553
  record.output = next.output;
13378
13554
  if (next.truncated)
13379
13555
  record.truncated = true;
13556
+ this.onActivity?.(record.sessionId);
13380
13557
  };
13381
13558
  child.stdout?.on("data", onChunk);
13382
13559
  child.stderr?.on("data", onChunk);
@@ -13394,10 +13571,12 @@ class AcpTerminalManager {
13394
13571
  this.markExited(record, code, signal);
13395
13572
  });
13396
13573
  this.terminals.set(id, record);
13574
+ this.onActivity?.(record.sessionId);
13397
13575
  return { terminalId: id };
13398
13576
  }
13399
13577
  getOutput(terminalId) {
13400
13578
  const record = this.require(terminalId);
13579
+ this.onActivity?.(record.sessionId);
13401
13580
  const snapshot = {
13402
13581
  output: record.output,
13403
13582
  truncated: record.truncated
@@ -13412,6 +13591,7 @@ class AcpTerminalManager {
13412
13591
  }
13413
13592
  waitForExit(terminalId) {
13414
13593
  const record = this.require(terminalId);
13594
+ this.onActivity?.(record.sessionId);
13415
13595
  if (record.exited) {
13416
13596
  return Promise.resolve({ exitCode: record.exitCode, signal: record.signal });
13417
13597
  }
@@ -13421,6 +13601,7 @@ class AcpTerminalManager {
13421
13601
  }
13422
13602
  kill(terminalId) {
13423
13603
  const record = this.require(terminalId);
13604
+ this.onActivity?.(record.sessionId);
13424
13605
  if (!record.exited) {
13425
13606
  this.forceKill(record.child);
13426
13607
  }
@@ -13430,6 +13611,7 @@ class AcpTerminalManager {
13430
13611
  const record = this.terminals.get(terminalId);
13431
13612
  if (!record)
13432
13613
  return {};
13614
+ this.onActivity?.(record.sessionId);
13433
13615
  if (!record.exited) {
13434
13616
  this.forceKill(record.child);
13435
13617
  }
@@ -13474,6 +13656,7 @@ class AcpTerminalManager {
13474
13656
  record.exited = true;
13475
13657
  record.exitCode = code;
13476
13658
  record.signal = signal;
13659
+ this.onActivity?.(record.sessionId);
13477
13660
  const status = { exitCode: code, signal };
13478
13661
  for (const waiter of record.waiters)
13479
13662
  waiter(status);
@@ -13694,7 +13877,13 @@ class AcpClient {
13694
13877
  workspaceRoot;
13695
13878
  clientInfo;
13696
13879
  dataDir;
13880
+ proxyOverride;
13697
13881
  extraEnv;
13882
+ requestTimeoutMs;
13883
+ promptIdleTimeoutMs;
13884
+ promptMaxDurationMs;
13885
+ quotaCacheTtlMs;
13886
+ maxReadBytes;
13698
13887
  configurationScope;
13699
13888
  sessionConfig = null;
13700
13889
  resourcesDir;
@@ -13702,13 +13891,13 @@ class AcpClient {
13702
13891
  permissionRequests = new Map;
13703
13892
  processScopeKey = import_node_crypto4.randomUUID();
13704
13893
  callbacks;
13705
- terminals = new AcpTerminalManager;
13894
+ terminals;
13706
13895
  processHandle = null;
13707
13896
  sdkApp = null;
13708
13897
  sdkConnection = null;
13709
13898
  streamHandle = null;
13710
13899
  initResponse = null;
13711
- inflightPrompts = new Set;
13900
+ inflightTrackers = new Map;
13712
13901
  resourcePrep = null;
13713
13902
  connectionGen = 0;
13714
13903
  attachSkillsMcp;
@@ -13722,11 +13911,21 @@ class AcpClient {
13722
13911
  constructor(options) {
13723
13912
  this.workspaceRoot = options.workspaceRoot;
13724
13913
  this.clientInfo = {
13725
- name: options.clientInfo?.name ?? "inkdown",
13726
- version: options.clientInfo?.version ?? "0.1.1"
13914
+ name: options.clientInfo?.name ?? "acp-client",
13915
+ version: options.clientInfo?.version ?? ACP_CLIENT_VERSION
13727
13916
  };
13728
13917
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
13918
+ this.proxyOverride = options.proxy;
13729
13919
  this.extraEnv = options.env ?? {};
13920
+ this.requestTimeoutMs = typeof options.requestTimeoutMs === "number" && options.requestTimeoutMs > 0 ? options.requestTimeoutMs : ACP_SDK_REQUEST_TIMEOUT_MS;
13921
+ this.promptIdleTimeoutMs = typeof options.promptIdleTimeoutMs === "number" && options.promptIdleTimeoutMs >= 0 ? options.promptIdleTimeoutMs : ACP_PROMPT_IDLE_TIMEOUT_MS;
13922
+ this.promptMaxDurationMs = typeof options.promptMaxDurationMs === "number" && options.promptMaxDurationMs >= 0 ? options.promptMaxDurationMs : ACP_PROMPT_MAX_DURATION_MS;
13923
+ this.quotaCacheTtlMs = typeof options.quotaCacheTtlMs === "number" && options.quotaCacheTtlMs >= 0 ? options.quotaCacheTtlMs : 30000;
13924
+ this.maxReadBytes = typeof options.maxReadBytes === "number" && options.maxReadBytes > 0 ? options.maxReadBytes : ACP_FS_MAX_READ_BYTES;
13925
+ this.terminals = new AcpTerminalManager({
13926
+ defaultOutputByteLimit: options.terminalOutputByteLimit ?? ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT,
13927
+ onActivity: (sid) => this.touchSessionActivity(sid)
13928
+ });
13730
13929
  if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
13731
13930
  throw new Error("resources.directory 必须是本机绝对路径");
13732
13931
  }
@@ -13742,12 +13941,13 @@ class AcpClient {
13742
13941
  throw new AcpMcpRecoveryCancelledError("ACP connection closed");
13743
13942
  return this.sdkConnection.agent.request(method, params, { cancellationSignal: signal });
13744
13943
  },
13944
+ requestTimeoutMs: this.requestTimeoutMs,
13745
13945
  getCapabilities: () => ({
13746
13946
  resume: Boolean(this.initResponse && parseResumeSessionSupported(this.initResponse.agentCapabilities)),
13747
13947
  load: Boolean(this.initResponse && parseLoadSessionSupported(this.initResponse.agentCapabilities))
13748
13948
  }),
13749
13949
  isConnected: () => this.isConnected,
13750
- isBusy: (sessionId) => [...this.inflightPrompts].some((id) => id !== sessionId),
13950
+ isBusy: (sessionId) => [...this.inflightTrackers.keys()].some((id) => id !== sessionId),
13751
13951
  onSuppressUpdates: (suppress) => {
13752
13952
  this.suppressRecoveryUpdates = suppress;
13753
13953
  },
@@ -13796,7 +13996,7 @@ class AcpClient {
13796
13996
  }
13797
13997
  this.authenticatingAgent = agent;
13798
13998
  try {
13799
- await sdkRequest(agent, methods.agent.authenticate, { methodId });
13999
+ await sdkRequest(agent, methods.agent.authenticate, { methodId }, this.requestTimeoutMs);
13800
14000
  if (this.sdkConnection?.agent !== agent) {
13801
14001
  return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
13802
14002
  }
@@ -13806,14 +14006,17 @@ class AcpClient {
13806
14006
  return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
13807
14007
  }
13808
14008
  const message = error instanceof Error ? error.message : String(error);
13809
- return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
14009
+ return err({
14010
+ code: error instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
14011
+ message
14012
+ });
13810
14013
  } finally {
13811
14014
  if (this.authenticatingAgent === agent)
13812
14015
  this.authenticatingAgent = undefined;
13813
14016
  }
13814
14017
  }
13815
14018
  async connect() {
13816
- if (this.inflightPrompts.size > 0)
14019
+ if (this.inflightTrackers.size > 0)
13817
14020
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
13818
14021
  if (this.isConnected && this.initResponse)
13819
14022
  return ok({ status: this.status, init: this.initResponse });
@@ -13841,8 +14044,9 @@ class AcpClient {
13841
14044
  effectiveRuntime.args = resolved.args;
13842
14045
  }
13843
14046
  const storedProxy = await readAcpProxySettings(this.dataDir);
13844
- const proxyEnv = buildAcpProxySpawnEnv(storedProxy);
13845
- const baseEnv = this.adapter.getSpawnEnv?.(storedProxy) ?? proxyEnv;
14047
+ const effectiveProxy = this.proxyOverride ? { ...storedProxy, ...this.proxyOverride } : storedProxy;
14048
+ const proxyEnv = buildAcpProxySpawnEnv(effectiveProxy);
14049
+ const baseEnv = this.adapter.getSpawnEnv?.(effectiveProxy) ?? proxyEnv;
13846
14050
  const spawnEnv = {
13847
14051
  ...baseEnv,
13848
14052
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
@@ -13923,7 +14127,7 @@ class AcpClient {
13923
14127
  const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
13924
14128
  expectedTag: profileTag,
13925
14129
  scopeKey: this.processScopeKey,
13926
- isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
14130
+ isBusy: (h) => this.inflightTrackers.size > 0 && this.processHandle === h
13927
14131
  });
13928
14132
  if (reuse.status === "hit") {
13929
14133
  reusedHandle = reuse.handle;
@@ -13994,11 +14198,14 @@ class AcpClient {
13994
14198
  this.quotaCache.observe(params, this.runtimeInfo.id);
13995
14199
  if (!this.suppressRecoveryUpdates)
13996
14200
  this.callbacks.onSessionUpdate?.(params);
13997
- }
14201
+ },
14202
+ onActivity: (sessionId) => this.touchSessionActivity(sessionId),
14203
+ onPauseActivity: (sessionId) => this.pauseSessionActivity(sessionId),
14204
+ maxReadBytes: this.maxReadBytes
13998
14205
  };
13999
14206
  const { app, connection, streamHandle } = connectSdkClient(processHandle.child, (clientApp) => {
14000
14207
  registerAcpClientHandlers(clientApp, handlerDeps);
14001
- }, this.runtimeInfo.id);
14208
+ }, this.runtimeInfo.id, this.clientInfo);
14002
14209
  this.sdkApp = app;
14003
14210
  this.sdkConnection = connection;
14004
14211
  this.streamHandle = streamHandle;
@@ -14012,7 +14219,7 @@ class AcpClient {
14012
14219
  configOptions: { boolean: {} }
14013
14220
  }
14014
14221
  }
14015
- });
14222
+ }, this.requestTimeoutMs);
14016
14223
  this.initResponse = initResp;
14017
14224
  if (this.resourcePrep) {
14018
14225
  const agentInfo = initResp?.agentInfo;
@@ -14039,7 +14246,7 @@ class AcpClient {
14039
14246
  const message = e instanceof Error ? e.message : String(e);
14040
14247
  this.setStatus("error", message);
14041
14248
  await this.disconnect(message);
14042
- return err({ code: "ACP_PROTOCOL_ERROR", message });
14249
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
14043
14250
  }
14044
14251
  }
14045
14252
  getCachedQuota(sessionId) {
@@ -14047,7 +14254,7 @@ class AcpClient {
14047
14254
  }
14048
14255
  async getQuota(sessionId) {
14049
14256
  const cached = this.getCachedQuota(sessionId);
14050
- if (cached && Date.now() - cached.updatedAt < 30000) {
14257
+ if (cached && this.quotaCacheTtlMs > 0 && Date.now() - cached.updatedAt < this.quotaCacheTtlMs) {
14051
14258
  return cached;
14052
14259
  }
14053
14260
  if (this.adapter.probeQuota) {
@@ -14103,7 +14310,7 @@ class AcpClient {
14103
14310
  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);
14104
14311
  const openResult = await restoreOrCreateAcpSession({
14105
14312
  request: async (method, params) => {
14106
- return sdkRequest(agent, method, params);
14313
+ return sdkRequest(agent, method, params, this.requestTimeoutMs);
14107
14314
  },
14108
14315
  cwd: this.workspaceRoot,
14109
14316
  resumeSessionId: options?.resumeSessionId ?? null,
@@ -14144,7 +14351,10 @@ class AcpClient {
14144
14351
  return ok(handle);
14145
14352
  } catch (e) {
14146
14353
  const message = e instanceof Error ? e.message : String(e);
14147
- return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
14354
+ return err({
14355
+ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
14356
+ message
14357
+ });
14148
14358
  }
14149
14359
  }
14150
14360
  async promptSession(sessionId, promptText, options) {
@@ -14153,11 +14363,12 @@ class AcpClient {
14153
14363
  }
14154
14364
  if (!this.isConnected)
14155
14365
  return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
14156
- if (this.inflightPrompts.has(sessionId))
14366
+ if (this.inflightTrackers.has(sessionId))
14157
14367
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Session already has an in-flight prompt" });
14158
14368
  const generation = this.connectionGen;
14159
14369
  const agent = this.sdkConnection.agent;
14160
- this.inflightPrompts.add(sessionId);
14370
+ const tracker = createSdkRequestActivityController();
14371
+ this.inflightTrackers.set(sessionId, tracker);
14161
14372
  try {
14162
14373
  await this.mcpRecovery.ensureReady(sessionId);
14163
14374
  if (generation !== this.connectionGen || !this.isConnected)
@@ -14170,19 +14381,34 @@ class AcpClient {
14170
14381
  }
14171
14382
  const compat = this.buildCompatPrepend(sessionId);
14172
14383
  const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
14173
- const response = await sdkRequest(agent, methods.agent.session.prompt, {
14384
+ const hasIdleOption = options?.idleTimeoutMs !== undefined;
14385
+ const hasTimeoutOption = options?.timeoutMs !== undefined;
14386
+ const idleTimeoutMs = hasIdleOption ? options.idleTimeoutMs : hasTimeoutOption ? 0 : this.promptIdleTimeoutMs;
14387
+ const maxDurationMs = options?.maxDurationMs ?? options?.timeoutMs ?? this.promptMaxDurationMs;
14388
+ const response = await sdkRequestWithActivity(agent, methods.agent.session.prompt, {
14174
14389
  sessionId,
14175
14390
  prompt: blocks
14176
- }, options?.timeoutMs);
14391
+ }, {
14392
+ idleTimeoutMs,
14393
+ maxDurationMs,
14394
+ activity: tracker
14395
+ });
14177
14396
  return ok(response);
14178
14397
  } catch (e) {
14179
14398
  const message = e instanceof Error ? e.message : String(e);
14180
14399
  if (e instanceof AcpMcpRecoveryCancelledError)
14181
14400
  return err({ code: "CANCELLED", message });
14401
+ if (e instanceof SdkRequestTimeoutError) {
14402
+ this.cancelPermissionRequests("session_cancelled", sessionId);
14403
+ this.sdkConnection?.agent?.notify(methods.agent.session.cancel, { sessionId }).catch(() => {
14404
+ return;
14405
+ });
14406
+ return err({ code: "ACP_TIMEOUT", message });
14407
+ }
14182
14408
  return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
14183
14409
  } finally {
14184
14410
  if (generation === this.connectionGen)
14185
- this.inflightPrompts.delete(sessionId);
14411
+ this.inflightTrackers.delete(sessionId);
14186
14412
  }
14187
14413
  }
14188
14414
  buildCompatPrepend(sessionId) {
@@ -14239,17 +14465,17 @@ class AcpClient {
14239
14465
  sessionId,
14240
14466
  configId,
14241
14467
  value
14242
- });
14468
+ }, this.requestTimeoutMs);
14243
14469
  return ok(response);
14244
14470
  } catch (e) {
14245
14471
  const message = e instanceof Error ? e.message : String(e);
14246
- return err({ code: "ACP_PROTOCOL_ERROR", message });
14472
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
14247
14473
  }
14248
14474
  }
14249
14475
  async disconnect(reason) {
14250
14476
  ++this.connectionGen;
14251
14477
  this.mcpRecovery.reset();
14252
- this.inflightPrompts.clear();
14478
+ this.inflightTrackers.clear();
14253
14479
  this.cancelPermissionRequests("connection_closed");
14254
14480
  this.setStatus("disconnected", reason);
14255
14481
  this.resourcePrep = null;
@@ -14287,6 +14513,31 @@ class AcpClient {
14287
14513
  }
14288
14514
  }
14289
14515
  }
14516
+ touchSessionActivity(sessionId) {
14517
+ if (sessionId) {
14518
+ this.inflightTrackers.get(sessionId)?.touch();
14519
+ return;
14520
+ }
14521
+ for (const tracker of this.inflightTrackers.values()) {
14522
+ tracker.touch();
14523
+ }
14524
+ }
14525
+ pauseSessionActivity(sessionId) {
14526
+ if (sessionId) {
14527
+ return this.inflightTrackers.get(sessionId)?.pause() ?? (() => {
14528
+ return;
14529
+ });
14530
+ }
14531
+ const resumes = [...this.inflightTrackers.values()].map((tracker) => tracker.pause());
14532
+ let released = false;
14533
+ return () => {
14534
+ if (released)
14535
+ return;
14536
+ released = true;
14537
+ for (const resume of resumes)
14538
+ resume();
14539
+ };
14540
+ }
14290
14541
  cancelPermissionRequests(reason, sessionId) {
14291
14542
  for (const [controller, pendingSessionId] of this.permissionRequests) {
14292
14543
  if (sessionId === undefined || pendingSessionId === sessionId)
@@ -14840,21 +15091,44 @@ async function handleRpcRequest(id, method, params) {
14840
15091
  sendError(id, -32800, "Connection request superseded");
14841
15092
  return;
14842
15093
  }
14843
- const { runtime, workspaceRoot, clientInfo, dataDir, proxy, env, customCommand, customArgs } = params ?? {};
15094
+ const {
15095
+ runtime,
15096
+ workspaceRoot,
15097
+ clientInfo,
15098
+ dataDir,
15099
+ proxy,
15100
+ env,
15101
+ customCommand,
15102
+ customArgs,
15103
+ requestTimeoutMs,
15104
+ promptIdleTimeoutMs,
15105
+ promptMaxDurationMs,
15106
+ permissionTimeoutMs,
15107
+ quotaCacheTtlMs,
15108
+ maxReadBytes,
15109
+ terminalOutputByteLimit
15110
+ } = params ?? {};
15111
+ const effectivePermissionTimeoutMs = typeof permissionTimeoutMs === "number" && Number.isFinite(permissionTimeoutMs) && permissionTimeoutMs >= 0 ? permissionTimeoutMs : 300000;
14844
15112
  const next = new AcpClient({
14845
15113
  runtime: customCommand ? {
14846
15114
  id: runtime ?? "custom",
14847
15115
  name: runtime ?? "Custom Agent",
14848
- description: "Custom command launched via Dawnsight",
15116
+ description: "Custom command launched via acp-engine",
14849
15117
  command: customCommand,
14850
15118
  args: Array.isArray(customArgs) ? customArgs : [],
14851
15119
  requiredEnvKeys: []
14852
15120
  } : runtime ?? "codex-acp",
14853
15121
  workspaceRoot: workspaceRoot ?? process.cwd(),
14854
- clientInfo: clientInfo ?? { name: "dawnsight-desktop", version: "0.4.0" },
15122
+ clientInfo: clientInfo ?? { name: "acp-engine", version: ACP_CLIENT_VERSION },
14855
15123
  dataDir,
14856
15124
  proxy,
14857
15125
  env,
15126
+ requestTimeoutMs,
15127
+ promptIdleTimeoutMs,
15128
+ promptMaxDurationMs,
15129
+ quotaCacheTtlMs,
15130
+ maxReadBytes,
15131
+ terminalOutputByteLimit,
14858
15132
  callbacks: {
14859
15133
  onStatusChange: (status, detail) => {
14860
15134
  if (generation !== connectionGeneration)
@@ -14882,18 +15156,22 @@ async function handleRpcRequest(id, method, params) {
14882
15156
  return { outcome: "cancelled" };
14883
15157
  const requestId = `req_${import_node_crypto5.randomUUID()}`;
14884
15158
  return new Promise((resolve) => {
15159
+ let timer;
14885
15160
  const finish = (outcome, reason) => {
14886
15161
  if (!pendingPermissions.delete(requestId))
14887
15162
  return;
14888
- clearTimeout(timer);
15163
+ if (timer !== undefined)
15164
+ clearTimeout(timer);
14889
15165
  signal.removeEventListener("abort", onAbort);
14890
15166
  if (reason)
14891
15167
  sendNotification("permission/cancelled", { requestId, sessionId, reason });
14892
15168
  resolve(outcome);
14893
15169
  };
14894
15170
  const onAbort = () => finish({ outcome: "cancelled" }, signal.reason === "session_cancelled" || signal.reason === "connection_closed" ? signal.reason : "agent_cancelled");
14895
- const timer = setTimeout(() => finish({ outcome: "cancelled" }, "timeout"), 120000);
14896
- timer.unref();
15171
+ if (effectivePermissionTimeoutMs > 0) {
15172
+ timer = setTimeout(() => finish({ outcome: "cancelled" }, "timeout"), effectivePermissionTimeoutMs);
15173
+ timer.unref();
15174
+ }
14897
15175
  pendingPermissions.set(requestId, { params: permParams, finish });
14898
15176
  signal.addEventListener("abort", onAbort, { once: true });
14899
15177
  sendNotification("permission/request", {
@@ -14985,13 +15263,13 @@ async function handleRpcRequest(id, method, params) {
14985
15263
  }
14986
15264
  case "session/prompt": {
14987
15265
  try {
14988
- const { sessionId, promptText, timeoutMs, images } = params ?? {};
15266
+ const { sessionId, promptText, timeoutMs, idleTimeoutMs, maxDurationMs, images } = params ?? {};
14989
15267
  const session = activeSessions.get(sessionId);
14990
15268
  if (!session) {
14991
15269
  sendError(id, -32004, `Session ${sessionId} not found`);
14992
15270
  return;
14993
15271
  }
14994
- const promptResult = await session.prompt(promptText, { timeoutMs, images });
15272
+ const promptResult = await session.prompt(promptText, { timeoutMs, idleTimeoutMs, maxDurationMs, images });
14995
15273
  if (!promptResult.ok) {
14996
15274
  sendError(id, promptResult.error.code === "UNAUTHORIZED" ? -32000 : -32005, promptResult.error.message, promptResult.error);
14997
15275
  return;