@yitom/acp-client 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -148,10 +148,19 @@ var BUILTIN_ACP_RUNTIMES = [
148
148
  args: ["-y", `${DEEPSEEK_DSH_NPM_PACKAGE}@latest`, "--profile", "acp"],
149
149
  requiredEnvKeys: ["DEEPSEEK_API_KEY"]
150
150
  },
151
+ {
152
+ id: "antigravity-cli",
153
+ name: "Antigravity",
154
+ description: "启动 Google Antigravity CLI 自带的 agy acp 服务",
155
+ authHint: "复用 Antigravity CLI 登录。需要登录时选择 Agent 提供的方式,或在终端运行 agy acp --login",
156
+ command: isWindowsPlatform() ? "agy.exe" : "agy",
157
+ args: ["acp"],
158
+ requiredEnvKeys: []
159
+ },
151
160
  {
152
161
  id: "agy",
153
- name: "agy",
154
- description: "经 bunx 直调官方桥 JS 入口(免安装,跨平台;版本跟随 bunx 解析)",
162
+ name: "Antigravity (legacy bridge)",
163
+ description: "通过 bunx 启动 @yitom/agy-acp-map,兼容旧会话 ID 和桥接扩展",
155
164
  authHint: "复用 Antigravity CLI 本地登录态;未登录先在本机终端完成 agy 登录后再连接",
156
165
  command: "bunx",
157
166
  args: ["-y", `${AGY_ACP_NPM_PACKAGE}@latest`],
@@ -162,7 +171,7 @@ function findBuiltinAcpRuntime(id) {
162
171
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
163
172
  }
164
173
  // src/version.ts
165
- var ACP_CLIENT_VERSION = "0.1.14";
174
+ var ACP_CLIENT_VERSION = "0.1.16";
166
175
  // src/client/session-open.ts
167
176
  import { RequestError } from "@agentclientprotocol/sdk";
168
177
 
@@ -395,6 +404,8 @@ async function restoreOrCreateAcpSession(input) {
395
404
  return result;
396
405
  } catch (error) {
397
406
  lastError = errorMessage(error);
407
+ if (isAuthenticationRequired(lastError))
408
+ throw error;
398
409
  log("warn", "session restore failed", {
399
410
  method: rpcMethod,
400
411
  sessionId: resumeId,
@@ -426,7 +437,7 @@ async function restoreOrCreateAcpSession(input) {
426
437
  try {
427
438
  return await request("session/new", baseParams);
428
439
  } catch (firstError) {
429
- if (isTransientAcpTransportError(firstError))
440
+ if (isAuthenticationRequired(errorMessage(firstError)) || isTransientAcpTransportError(firstError))
430
441
  throw firstError;
431
442
  if ((input.mcpServers ?? []).length === 0)
432
443
  throw firstError;
@@ -695,6 +706,64 @@ import {
695
706
  ndJsonStream
696
707
  } from "@agentclientprotocol/sdk";
697
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
+ }
698
767
  function createSdkStreamHandle(child) {
699
768
  const stdoutBridge = new PassThrough;
700
769
  const stdinBridge = new PassThrough;
@@ -725,17 +794,107 @@ function createSdkStreamHandle(child) {
725
794
  }
726
795
  };
727
796
  }
728
- function connectSdkClient(child, configure, runtimeId) {
797
+ function connectSdkClient(child, configure, runtimeId, clientInfo) {
729
798
  if (runtimeId && true) {
730
799
  console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
731
800
  }
732
- const app = createSdkClientApp({ name: "inkdown" });
801
+ const app = createSdkClientApp({
802
+ name: clientInfo?.name || "acp-client",
803
+ ...clientInfo?.version ? { version: clientInfo.version } : {}
804
+ });
733
805
  configure(app);
734
806
  const streamHandle = createSdkStreamHandle(child);
735
807
  const connection = app.connect(streamHandle.stream);
736
808
  return { app, connection, streamHandle };
737
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
+ }
738
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
+ }
739
898
  const controller = new AbortController;
740
899
  let timer;
741
900
  try {
@@ -745,8 +904,8 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
745
904
  const timeout = new Promise((_, reject) => {
746
905
  timer = setTimeout(() => {
747
906
  controller.abort();
748
- reject(new Error(`请求超时: ${method}`));
749
- }, timeoutMs);
907
+ reject(new SdkRequestTimeoutError("timeout", method, timeoutMs));
908
+ }, clampTimerMs(timeoutMs));
750
909
  timer.unref?.();
751
910
  });
752
911
  return await Promise.race([pending, timeout]);
@@ -1975,6 +2134,7 @@ var APP_RESOURCE_CAPABILITIES = {
1975
2134
  gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
1976
2135
  copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
1977
2136
  "cursor-cli": { entry: null, strategy: "compatibility", configHome: "CURSOR_CONFIG_DIR" },
2137
+ "antigravity-cli": { entry: null, strategy: "compatibility", configHome: null },
1978
2138
  agy: { entry: "_meta.appResources.directory", strategy: "native-session", configHome: null },
1979
2139
  deepseek: { entry: null, strategy: "compatibility", configHome: null }
1980
2140
  };
@@ -3263,6 +3423,11 @@ var deepseekAdapter = {
3263
3423
  canSkipInteractiveAuth: () => false
3264
3424
  };
3265
3425
 
3426
+ // src/runtimes/agy/index.ts
3427
+ import { existsSync as existsSync17 } from "node:fs";
3428
+ import { homedir as homedir15 } from "node:os";
3429
+ import { delimiter as delimiter2, join as join20 } from "node:path";
3430
+
3266
3431
  // src/runtimes/agy/quota.ts
3267
3432
  import { existsSync as existsSync16, readFileSync as readFileSync9, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
3268
3433
  import { join as join19 } from "node:path";
@@ -3370,6 +3535,7 @@ function resolveAntigravityLanguageServer() {
3370
3535
  return null;
3371
3536
  }
3372
3537
  async function probeAgyQuota(options) {
3538
+ const runtimeId = options?.runtimeId ?? "agy";
3373
3539
  const acc = resolveAntigravityAccount();
3374
3540
  const lsInfo = resolveAntigravityLanguageServer();
3375
3541
  if (lsInfo) {
@@ -3469,7 +3635,7 @@ async function probeAgyQuota(options) {
3469
3635
  toWindow(tpWeekly, "Claude and GPT models", "Weekly limit", 10080)
3470
3636
  ].filter(Boolean);
3471
3637
  return {
3472
- runtimeId: "agy",
3638
+ runtimeId,
3473
3639
  provider: "Google Antigravity",
3474
3640
  account: {
3475
3641
  email: acc.email,
@@ -3496,7 +3662,7 @@ async function probeAgyQuota(options) {
3496
3662
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
3497
3663
  if (!isAvailable) {
3498
3664
  return {
3499
- runtimeId: "agy",
3665
+ runtimeId,
3500
3666
  provider: "Google Antigravity",
3501
3667
  status: "unauthorized",
3502
3668
  message: "未检测到 Antigravity 登录凭据",
@@ -3504,7 +3670,7 @@ async function probeAgyQuota(options) {
3504
3670
  };
3505
3671
  }
3506
3672
  return {
3507
- runtimeId: "agy",
3673
+ runtimeId,
3508
3674
  provider: "Google Antigravity",
3509
3675
  account: {
3510
3676
  email: acc.email,
@@ -3552,6 +3718,53 @@ async function probeAgyQuota(options) {
3552
3718
  }
3553
3719
 
3554
3720
  // src/runtimes/agy/index.ts
3721
+ function isExecutableOnPath(command, env, platform) {
3722
+ const pathValue = env.PATH ?? env.Path ?? "";
3723
+ if (!pathValue.trim())
3724
+ return false;
3725
+ const sep = platform === "win32" ? ";" : delimiter2;
3726
+ for (const dir of pathValue.split(sep)) {
3727
+ const trimmed = dir.trim().replace(/^"|"$/g, "");
3728
+ if (!trimmed)
3729
+ continue;
3730
+ try {
3731
+ if (existsSync17(join20(trimmed, command)))
3732
+ return true;
3733
+ } catch {}
3734
+ }
3735
+ return false;
3736
+ }
3737
+ function resolveAntigravityCliCommand(overrides) {
3738
+ const args = ["acp"];
3739
+ const platform = overrides?.platform ?? process.platform;
3740
+ const env = overrides?.env ?? process.env;
3741
+ const home = overrides?.home ?? homedir15();
3742
+ const binaries = platform === "win32" ? ["agy.exe", "agy.cmd"] : ["agy"];
3743
+ for (const binary of binaries) {
3744
+ if (isExecutableOnPath(binary, env, platform)) {
3745
+ return { command: binary, args };
3746
+ }
3747
+ }
3748
+ const candidates = [];
3749
+ if (platform === "win32") {
3750
+ const localAppData = env.LOCALAPPDATA?.trim() || (env.USERPROFILE?.trim() ? join20(env.USERPROFILE.trim(), "AppData", "Local") : "");
3751
+ const userProfile = env.USERPROFILE?.trim() || home;
3752
+ if (localAppData)
3753
+ candidates.push(join20(localAppData, "antigravity", "agy.exe"));
3754
+ if (userProfile)
3755
+ candidates.push(join20(userProfile, ".local", "bin", "agy.exe"));
3756
+ } else if (home) {
3757
+ candidates.push(join20(home, ".local", "bin", "agy"));
3758
+ }
3759
+ for (const candidate of candidates) {
3760
+ try {
3761
+ if (candidate && existsSync17(candidate)) {
3762
+ return { command: candidate, args };
3763
+ }
3764
+ } catch {}
3765
+ }
3766
+ return null;
3767
+ }
3555
3768
  function probeAgyAuth() {
3556
3769
  return {
3557
3770
  codexHome: "",
@@ -3575,6 +3788,16 @@ var agyAdapter = {
3575
3788
  canSkipInteractiveAuth: () => false,
3576
3789
  tryDirectSessionFirst: true
3577
3790
  };
3791
+ var antigravityCliAdapter = {
3792
+ id: "antigravity-cli",
3793
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "runtime-not-supported"),
3794
+ probeAuth: () => probeAgyAuth(),
3795
+ probeQuota: (options) => probeAgyQuota({ ...options, runtimeId: "antigravity-cli" }),
3796
+ resolveSpawnCommand: () => resolveAntigravityCliCommand(),
3797
+ orderAuthMethods: (methods) => methods,
3798
+ canSkipInteractiveAuth: () => false,
3799
+ tryDirectSessionFirst: true
3800
+ };
3578
3801
 
3579
3802
  // src/runtimes/index.ts
3580
3803
  function getAcpRuntimeAdapter(runtimeId) {
@@ -3599,6 +3822,8 @@ function getAcpRuntimeAdapter(runtimeId) {
3599
3822
  return deepseekAdapter;
3600
3823
  case agyAdapter.id:
3601
3824
  return agyAdapter;
3825
+ case antigravityCliAdapter.id:
3826
+ return antigravityCliAdapter;
3602
3827
  default:
3603
3828
  return {
3604
3829
  id: runtimeId,
@@ -3814,7 +4039,7 @@ import { methods, RequestError as RequestError2 } from "@agentclientprotocol/sdk
3814
4039
  import { access, readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
3815
4040
  import { dirname as dirname5, extname, resolve as resolve2, sep as sep2 } from "node:path";
3816
4041
  import { mkdir as mkdir5 } from "node:fs/promises";
3817
- var MAX_READ_BYTES = 2 * 1024 * 1024;
4042
+ var ACP_FS_MAX_READ_BYTES = 2 * 1024 * 1024;
3818
4043
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
3819
4044
  function isBinaryDocumentPath(filePath) {
3820
4045
  return BINARY_DOCUMENT_EXTENSIONS.has(extname(filePath).toLowerCase());
@@ -3830,13 +4055,14 @@ function assertPathInsideWorkspace(filePath, workspaceRoot) {
3830
4055
  }
3831
4056
  async function acpReadTextFile(params) {
3832
4057
  if (isBinaryDocumentPath(params.path)) {
3833
- throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
4058
+ throw new Error(`拒绝按文本读取二进制文档/PDF:${params.path}。` + "该格式应由专有解析器读取,请改为向用户索取所需的章节、目录或文本片段。");
3834
4059
  }
3835
4060
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
3836
4061
  await access(abs);
3837
4062
  let content = await readFile5(abs, "utf-8");
3838
- if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
3839
- 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));
3840
4066
  content += `
3841
4067
 
3842
4068
  …[截断:文件过大]…`;
@@ -3868,6 +4094,8 @@ function toServerError(error, fallback) {
3868
4094
  function registerAcpClientHandlers(app, deps) {
3869
4095
  app.onRequest(methods.client.session.requestPermission, async (ctx) => {
3870
4096
  const params = ctx.params;
4097
+ const sessionId = typeof params.sessionId === "string" ? params.sessionId : undefined;
4098
+ deps.onActivity?.(sessionId);
3871
4099
  const toolCall = params.toolCall;
3872
4100
  const toolHint = toolCall && typeof toolCall === "object" ? {
3873
4101
  id: typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : undefined,
@@ -3880,20 +4108,27 @@ function registerAcpClientHandlers(app, deps) {
3880
4108
  toolCall: toolHint,
3881
4109
  optionCount: Array.isArray(params.options) ? params.options.length : undefined
3882
4110
  });
4111
+ const resumeActivity = deps.onPauseActivity?.(sessionId);
3883
4112
  try {
3884
4113
  const outcome = await deps.onPermission({
3885
- sessionId: typeof params.sessionId === "string" ? params.sessionId : undefined,
3886
- params
4114
+ sessionId,
4115
+ params,
4116
+ signal: ctx.signal
3887
4117
  });
3888
- return { outcome };
4118
+ return { outcome: !ctx.signal.aborted && isAcpPermissionOutcome(outcome, params) ? outcome : { outcome: "cancelled" } };
3889
4119
  } catch (error) {
3890
4120
  console.error("[acp] request_permission 失败", error);
3891
4121
  return { outcome: { outcome: "cancelled" } };
4122
+ } finally {
4123
+ resumeActivity?.();
4124
+ deps.onActivity?.(sessionId);
3892
4125
  }
3893
4126
  });
3894
4127
  app.onRequest(methods.client.fs.readTextFile, async (ctx) => {
3895
4128
  const workspaceRoot = deps.getWorkspaceRoot();
3896
4129
  const filePath = ctx.params.path;
4130
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4131
+ deps.onActivity?.(sessionId);
3897
4132
  if (!workspaceRoot || !filePath) {
3898
4133
  throw toInvalidParams("fs/read_text_file 需要 path 与已连接工作区");
3899
4134
  }
@@ -3907,18 +4142,19 @@ function registerAcpClientHandlers(app, deps) {
3907
4142
  });
3908
4143
  return { content };
3909
4144
  } catch (error) {
3910
- throw toServerError(error, "读取 Inkdown 快照失败");
4145
+ throw toServerError(error, "读取虚拟快照失败");
3911
4146
  }
3912
4147
  }
3913
4148
  if (isInkdownVirtualDirPath(filePath, workspaceRoot)) {
3914
- throw toInvalidParams(`Inkdown 虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
4149
+ throw toInvalidParams(`虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
3915
4150
  }
3916
4151
  try {
3917
4152
  const result = await acpReadTextFile({
3918
4153
  path: filePath,
3919
4154
  workspaceRoot,
3920
4155
  line: ctx.params.line ?? undefined,
3921
- limit: ctx.params.limit ?? undefined
4156
+ limit: ctx.params.limit ?? undefined,
4157
+ maxReadBytes: deps.maxReadBytes
3922
4158
  });
3923
4159
  console.info("[acp] fs/read_text_file ok", { path: filePath });
3924
4160
  return result;
@@ -3930,6 +4166,8 @@ function registerAcpClientHandlers(app, deps) {
3930
4166
  const workspaceRoot = deps.getWorkspaceRoot();
3931
4167
  const filePath = ctx.params.path;
3932
4168
  const content = ctx.params.content;
4169
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4170
+ deps.onActivity?.(sessionId);
3933
4171
  if (!workspaceRoot || !filePath || typeof content !== "string") {
3934
4172
  throw toInvalidParams("fs/write_text_file 需要 path、content 与已连接工作区");
3935
4173
  }
@@ -3947,6 +4185,7 @@ function registerAcpClientHandlers(app, deps) {
3947
4185
  const workspaceRoot = deps.getWorkspaceRoot();
3948
4186
  const sessionId = ctx.params.sessionId;
3949
4187
  const command = ctx.params.command;
4188
+ deps.onActivity?.(sessionId);
3950
4189
  if (!workspaceRoot || !sessionId || !command) {
3951
4190
  throw toInvalidParams("terminal/create 需要 sessionId、command 与已连接工作区");
3952
4191
  }
@@ -3966,6 +4205,8 @@ function registerAcpClientHandlers(app, deps) {
3966
4205
  });
3967
4206
  app.onRequest(methods.client.terminal.output, async (ctx) => {
3968
4207
  const terminalId = ctx.params.terminalId;
4208
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4209
+ deps.onActivity?.(sessionId);
3969
4210
  if (!terminalId) {
3970
4211
  throw toInvalidParams("terminal/output 需要 terminalId");
3971
4212
  }
@@ -3977,6 +4218,8 @@ function registerAcpClientHandlers(app, deps) {
3977
4218
  });
3978
4219
  app.onRequest(methods.client.terminal.waitForExit, async (ctx) => {
3979
4220
  const terminalId = ctx.params.terminalId;
4221
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4222
+ deps.onActivity?.(sessionId);
3980
4223
  if (!terminalId) {
3981
4224
  throw toInvalidParams("terminal/wait_for_exit 需要 terminalId");
3982
4225
  }
@@ -3988,6 +4231,8 @@ function registerAcpClientHandlers(app, deps) {
3988
4231
  });
3989
4232
  app.onRequest(methods.client.terminal.kill, async (ctx) => {
3990
4233
  const terminalId = ctx.params.terminalId;
4234
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4235
+ deps.onActivity?.(sessionId);
3991
4236
  if (!terminalId) {
3992
4237
  throw toInvalidParams("terminal/kill 需要 terminalId");
3993
4238
  }
@@ -3999,6 +4244,8 @@ function registerAcpClientHandlers(app, deps) {
3999
4244
  });
4000
4245
  app.onRequest(methods.client.terminal.release, async (ctx) => {
4001
4246
  const terminalId = ctx.params.terminalId;
4247
+ const sessionId = typeof ctx.params?.sessionId === "string" ? ctx.params.sessionId : undefined;
4248
+ deps.onActivity?.(sessionId);
4002
4249
  if (!terminalId) {
4003
4250
  throw toInvalidParams("terminal/release 需要 terminalId");
4004
4251
  }
@@ -4009,6 +4256,7 @@ function registerAcpClientHandlers(app, deps) {
4009
4256
  }
4010
4257
  });
4011
4258
  app.onNotification(methods.client.session.update, async (ctx) => {
4259
+ deps.onActivity?.(ctx.params.sessionId);
4012
4260
  deps.onSessionUpdate({
4013
4261
  sessionId: ctx.params.sessionId,
4014
4262
  update: ctx.params.update
@@ -4022,26 +4270,23 @@ function permissionOptionId(option) {
4022
4270
  return option.id;
4023
4271
  return null;
4024
4272
  }
4273
+ function permissionOptions(params) {
4274
+ return Array.isArray(params.options) ? params.options.filter((option) => !!option && typeof option === "object") : [];
4275
+ }
4276
+ function isAcpPermissionOutcome(outcome, params) {
4277
+ if (!outcome || typeof outcome !== "object")
4278
+ return false;
4279
+ const value = outcome;
4280
+ if (value.outcome === "cancelled")
4281
+ return true;
4282
+ return value.outcome === "selected" && typeof value.optionId === "string" && value.optionId.length > 0 && permissionOptions(params).some((option) => permissionOptionId(option) === value.optionId);
4283
+ }
4025
4284
  function pickAllowOptionId(params) {
4026
- const options = params.options;
4027
- if (!Array.isArray(options))
4028
- return null;
4029
- for (const item of options) {
4030
- if (!item || typeof item !== "object")
4031
- continue;
4032
- const option = item;
4033
- const id = permissionOptionId(option);
4034
- const kind = typeof option.kind === "string" ? option.kind : "";
4035
- if (id && (kind.includes("allow") || kind === "allow_once" || kind === "allow_always")) {
4036
- return id;
4037
- }
4038
- }
4039
- for (const item of options) {
4040
- if (!item || typeof item !== "object")
4041
- continue;
4042
- const id = permissionOptionId(item);
4043
- if (id)
4044
- return id;
4285
+ const options = permissionOptions(params);
4286
+ for (const kind of ["allow_once", "allow", "allow_always"]) {
4287
+ const option = options.find((entry) => entry.kind === kind && permissionOptionId(entry));
4288
+ if (option)
4289
+ return permissionOptionId(option);
4045
4290
  }
4046
4291
  return null;
4047
4292
  }
@@ -4074,7 +4319,7 @@ function appendTerminalOutput(current, chunk, byteLimit) {
4074
4319
  }
4075
4320
 
4076
4321
  // src/client/acp-terminal.ts
4077
- var DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
4322
+ var ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
4078
4323
  function resolveCwd(cwd, workspaceRoot) {
4079
4324
  if (!cwd?.trim())
4080
4325
  return assertPathInsideWorkspace(workspaceRoot, workspaceRoot);
@@ -4094,12 +4339,18 @@ function buildEnv(extra) {
4094
4339
 
4095
4340
  class AcpTerminalManager {
4096
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
+ }
4097
4348
  create(params) {
4098
4349
  const command = params.command?.trim();
4099
4350
  if (!command)
4100
4351
  throw new Error("terminal/create 需要 command");
4101
4352
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
4102
- 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;
4103
4354
  const child = spawn3(command, params.args ?? [], {
4104
4355
  cwd,
4105
4356
  env: buildEnv(params.env),
@@ -4126,6 +4377,7 @@ class AcpTerminalManager {
4126
4377
  record.output = next.output;
4127
4378
  if (next.truncated)
4128
4379
  record.truncated = true;
4380
+ this.onActivity?.(record.sessionId);
4129
4381
  };
4130
4382
  child.stdout?.on("data", onChunk);
4131
4383
  child.stderr?.on("data", onChunk);
@@ -4143,10 +4395,12 @@ class AcpTerminalManager {
4143
4395
  this.markExited(record, code, signal);
4144
4396
  });
4145
4397
  this.terminals.set(id, record);
4398
+ this.onActivity?.(record.sessionId);
4146
4399
  return { terminalId: id };
4147
4400
  }
4148
4401
  getOutput(terminalId) {
4149
4402
  const record = this.require(terminalId);
4403
+ this.onActivity?.(record.sessionId);
4150
4404
  const snapshot = {
4151
4405
  output: record.output,
4152
4406
  truncated: record.truncated
@@ -4161,6 +4415,7 @@ class AcpTerminalManager {
4161
4415
  }
4162
4416
  waitForExit(terminalId) {
4163
4417
  const record = this.require(terminalId);
4418
+ this.onActivity?.(record.sessionId);
4164
4419
  if (record.exited) {
4165
4420
  return Promise.resolve({ exitCode: record.exitCode, signal: record.signal });
4166
4421
  }
@@ -4170,6 +4425,7 @@ class AcpTerminalManager {
4170
4425
  }
4171
4426
  kill(terminalId) {
4172
4427
  const record = this.require(terminalId);
4428
+ this.onActivity?.(record.sessionId);
4173
4429
  if (!record.exited) {
4174
4430
  this.forceKill(record.child);
4175
4431
  }
@@ -4179,6 +4435,7 @@ class AcpTerminalManager {
4179
4435
  const record = this.terminals.get(terminalId);
4180
4436
  if (!record)
4181
4437
  return {};
4438
+ this.onActivity?.(record.sessionId);
4182
4439
  if (!record.exited) {
4183
4440
  this.forceKill(record.child);
4184
4441
  }
@@ -4223,6 +4480,7 @@ class AcpTerminalManager {
4223
4480
  record.exited = true;
4224
4481
  record.exitCode = code;
4225
4482
  record.signal = signal;
4483
+ this.onActivity?.(record.sessionId);
4226
4484
  const status = { exitCode: code, signal };
4227
4485
  for (const waiter of record.waiters)
4228
4486
  waiter(status);
@@ -4232,8 +4490,8 @@ class AcpTerminalManager {
4232
4490
 
4233
4491
  // src/client/acp-proxy-service.ts
4234
4492
  import { mkdir as mkdir6, readFile as readFile6, writeFile as writeFile6 } from "node:fs/promises";
4235
- import { existsSync as existsSync17 } from "node:fs";
4236
- import { join as join20 } from "node:path";
4493
+ import { existsSync as existsSync18 } from "node:fs";
4494
+ import { join as join21 } from "node:path";
4237
4495
  var DEFAULT_ACP_PROXY_SETTINGS = {
4238
4496
  enabled: false,
4239
4497
  host: "127.0.0.1",
@@ -4242,7 +4500,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
4242
4500
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
4243
4501
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
4244
4502
  function proxyFilePath(dir) {
4245
- return join20(dir, "agent", "proxy.json");
4503
+ return join21(dir, "agent", "proxy.json");
4246
4504
  }
4247
4505
  function validate2(settings) {
4248
4506
  if (!settings.host.trim())
@@ -4254,7 +4512,7 @@ function validate2(settings) {
4254
4512
  }
4255
4513
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
4256
4514
  const file = proxyFilePath(dir);
4257
- if (!existsSync17(file))
4515
+ if (!existsSync18(file))
4258
4516
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
4259
4517
  try {
4260
4518
  const raw = JSON.parse(await readFile6(file, "utf8"));
@@ -4276,7 +4534,7 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
4276
4534
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
4277
4535
  port: payload.port
4278
4536
  };
4279
- await mkdir6(join20(dir, "agent"), { recursive: true });
4537
+ await mkdir6(join21(dir, "agent"), { recursive: true });
4280
4538
  await writeFile6(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
4281
4539
  return ok(stored);
4282
4540
  }
@@ -4332,9 +4590,9 @@ function compatDeliveryKey(sessionId, generation, digest) {
4332
4590
  }
4333
4591
 
4334
4592
  // src/mcp/app-skills-mcp.ts
4335
- import { dirname as dirname6, join as join21 } from "node:path";
4593
+ import { dirname as dirname6, join as join22 } from "node:path";
4336
4594
  import { fileURLToPath } from "node:url";
4337
- import { existsSync as existsSync18, readFileSync as readFileSync10, statSync as statSync4 } from "node:fs";
4595
+ import { existsSync as existsSync19, readFileSync as readFileSync10, statSync as statSync4 } from "node:fs";
4338
4596
  var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
4339
4597
  var APP_SKILLS_TOOLS = [
4340
4598
  {
@@ -4370,11 +4628,11 @@ function buildAppSkillsMcpServer(directory, opts) {
4370
4628
  function resolveAppSkillsRunnerPath(fromFile) {
4371
4629
  const base = fromFile ?? fileURLToPath(import.meta.url);
4372
4630
  const candidates = [
4373
- join21(dirname6(base), "app-skills-mcp-serve.cjs"),
4374
- join21(dirname6(base), "app-skills-mcp-serve.ts")
4631
+ join22(dirname6(base), "app-skills-mcp-serve.cjs"),
4632
+ join22(dirname6(base), "app-skills-mcp-serve.ts")
4375
4633
  ];
4376
4634
  for (const candidate of candidates) {
4377
- if (existsSync18(candidate))
4635
+ if (existsSync19(candidate))
4378
4636
  return candidate;
4379
4637
  }
4380
4638
  throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
@@ -4411,10 +4669,10 @@ function isSupportedBridgeVersion(runtimeId, version) {
4411
4669
 
4412
4670
  // src/session/session-capabilities.ts
4413
4671
  function parseLoadSessionSupported(caps) {
4414
- return caps.loadSession === true;
4672
+ return caps?.loadSession === true;
4415
4673
  }
4416
4674
  function parseResumeSessionSupported(caps) {
4417
- const sessionCaps = caps.sessionCapabilities && typeof caps.sessionCapabilities === "object" ? caps.sessionCapabilities : null;
4675
+ const sessionCaps = caps?.sessionCapabilities && typeof caps.sessionCapabilities === "object" ? caps.sessionCapabilities : null;
4418
4676
  if (!sessionCaps)
4419
4677
  return false;
4420
4678
  const resume = sessionCaps.resume;
@@ -4480,23 +4738,32 @@ class AcpClient {
4480
4738
  commandsCache = new AvailableCommandsCache;
4481
4739
  quotaCache = new QuotaCache;
4482
4740
  runtimeInfo;
4741
+ hasCustomRuntime;
4483
4742
  adapter;
4484
4743
  workspaceRoot;
4485
4744
  clientInfo;
4486
4745
  dataDir;
4746
+ proxyOverride;
4487
4747
  extraEnv;
4748
+ requestTimeoutMs;
4749
+ promptIdleTimeoutMs;
4750
+ promptMaxDurationMs;
4751
+ quotaCacheTtlMs;
4752
+ maxReadBytes;
4488
4753
  configurationScope;
4489
4754
  sessionConfig = null;
4490
4755
  resourcesDir;
4756
+ authenticatingAgent;
4757
+ permissionRequests = new Map;
4491
4758
  processScopeKey = randomUUID2();
4492
4759
  callbacks;
4493
- terminals = new AcpTerminalManager;
4760
+ terminals;
4494
4761
  processHandle = null;
4495
4762
  sdkApp = null;
4496
4763
  sdkConnection = null;
4497
4764
  streamHandle = null;
4498
4765
  initResponse = null;
4499
- inflightPrompts = new Set;
4766
+ inflightTrackers = new Map;
4500
4767
  resourcePrep = null;
4501
4768
  connectionGen = 0;
4502
4769
  attachSkillsMcp;
@@ -4510,11 +4777,21 @@ class AcpClient {
4510
4777
  constructor(options) {
4511
4778
  this.workspaceRoot = options.workspaceRoot;
4512
4779
  this.clientInfo = {
4513
- name: options.clientInfo?.name ?? "inkdown",
4514
- version: options.clientInfo?.version ?? "0.1.1"
4780
+ name: options.clientInfo?.name ?? "acp-client",
4781
+ version: options.clientInfo?.version ?? ACP_CLIENT_VERSION
4515
4782
  };
4516
4783
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
4784
+ this.proxyOverride = options.proxy;
4517
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
+ });
4518
4795
  if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
4519
4796
  throw new Error("resources.directory 必须是本机绝对路径");
4520
4797
  }
@@ -4530,12 +4807,13 @@ class AcpClient {
4530
4807
  throw new AcpMcpRecoveryCancelledError("ACP connection closed");
4531
4808
  return this.sdkConnection.agent.request(method, params, { cancellationSignal: signal });
4532
4809
  },
4810
+ requestTimeoutMs: this.requestTimeoutMs,
4533
4811
  getCapabilities: () => ({
4534
4812
  resume: Boolean(this.initResponse && parseResumeSessionSupported(this.initResponse.agentCapabilities)),
4535
4813
  load: Boolean(this.initResponse && parseLoadSessionSupported(this.initResponse.agentCapabilities))
4536
4814
  }),
4537
4815
  isConnected: () => this.isConnected,
4538
- isBusy: (sessionId) => [...this.inflightPrompts].some((id) => id !== sessionId),
4816
+ isBusy: (sessionId) => [...this.inflightTrackers.keys()].some((id) => id !== sessionId),
4539
4817
  onSuppressUpdates: (suppress) => {
4540
4818
  this.suppressRecoveryUpdates = suppress;
4541
4819
  },
@@ -4544,8 +4822,10 @@ class AcpClient {
4544
4822
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
4545
4823
  this.adapter = getAcpRuntimeAdapter(runtimeId);
4546
4824
  if (typeof options.runtime === "object" && options.runtime !== null) {
4825
+ this.hasCustomRuntime = true;
4547
4826
  this.runtimeInfo = options.runtime;
4548
4827
  } else {
4828
+ this.hasCustomRuntime = false;
4549
4829
  const found = findBuiltinAcpRuntime(runtimeId);
4550
4830
  if (!found) {
4551
4831
  throw new Error(`未知或未注册的 ACP 运行时模板: ${runtimeId}`);
@@ -4565,8 +4845,44 @@ class AcpClient {
4565
4845
  get initializeResponse() {
4566
4846
  return this.initResponse;
4567
4847
  }
4848
+ async authenticate(methodId) {
4849
+ const agent = this.sdkConnection?.agent;
4850
+ if (!agent || !this.isConnected) {
4851
+ return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
4852
+ }
4853
+ const method = this.initResponse?.authMethods?.find((entry) => entry.id === methodId);
4854
+ if (!method) {
4855
+ return err({ code: "INVALID_ARGUMENT", message: "Agent 未声明此认证方式" });
4856
+ }
4857
+ if ("type" in method && method.type === "terminal") {
4858
+ return err({ code: "INVALID_ARGUMENT", message: "此认证方式需要在交互式终端中运行" });
4859
+ }
4860
+ if (this.authenticatingAgent === agent) {
4861
+ return err({ code: "INVALID_STATE", message: "Agent 正在认证" });
4862
+ }
4863
+ this.authenticatingAgent = agent;
4864
+ try {
4865
+ await sdkRequest(agent, methods2.agent.authenticate, { methodId }, this.requestTimeoutMs);
4866
+ if (this.sdkConnection?.agent !== agent) {
4867
+ return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
4868
+ }
4869
+ return ok(undefined);
4870
+ } catch (error) {
4871
+ if (this.sdkConnection?.agent !== agent) {
4872
+ return err({ code: "CANCELLED", message: "认证期间 Agent 连接已关闭" });
4873
+ }
4874
+ const message = error instanceof Error ? error.message : String(error);
4875
+ return err({
4876
+ code: error instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
4877
+ message
4878
+ });
4879
+ } finally {
4880
+ if (this.authenticatingAgent === agent)
4881
+ this.authenticatingAgent = undefined;
4882
+ }
4883
+ }
4568
4884
  async connect() {
4569
- if (this.inflightPrompts.size > 0)
4885
+ if (this.inflightTrackers.size > 0)
4570
4886
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
4571
4887
  if (this.isConnected && this.initResponse)
4572
4888
  return ok({ status: this.status, init: this.initResponse });
@@ -4583,7 +4899,7 @@ class AcpClient {
4583
4899
  return err({ code: "ACP_SPAWN_ERROR", message: blocker });
4584
4900
  }
4585
4901
  let effectiveRuntime = { ...this.runtimeInfo };
4586
- if (this.adapter.resolveSpawnCommand) {
4902
+ if (!this.hasCustomRuntime && this.adapter.resolveSpawnCommand) {
4587
4903
  const resolved = this.adapter.resolveSpawnCommand();
4588
4904
  if (!resolved) {
4589
4905
  const message = `运行时 CLI 未安装: ${this.runtimeInfo.id}`;
@@ -4594,8 +4910,9 @@ class AcpClient {
4594
4910
  effectiveRuntime.args = resolved.args;
4595
4911
  }
4596
4912
  const storedProxy = await readAcpProxySettings(this.dataDir);
4597
- const proxyEnv = buildAcpProxySpawnEnv(storedProxy);
4598
- 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;
4599
4916
  const spawnEnv = {
4600
4917
  ...baseEnv,
4601
4918
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
@@ -4676,7 +4993,7 @@ class AcpClient {
4676
4993
  const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
4677
4994
  expectedTag: profileTag,
4678
4995
  scopeKey: this.processScopeKey,
4679
- isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
4996
+ isBusy: (h) => this.inflightTrackers.size > 0 && this.processHandle === h
4680
4997
  });
4681
4998
  if (reuse.status === "hit") {
4682
4999
  reusedHandle = reuse.handle;
@@ -4716,25 +5033,45 @@ class AcpClient {
4716
5033
  return this.callbacks.readSnapshot(resource);
4717
5034
  },
4718
5035
  onPermission: async (payload) => {
4719
- if (this.callbacks.onPermissionRequest) {
4720
- return this.callbacks.onPermissionRequest({
5036
+ const callback = this.callbacks.onPermissionRequest;
5037
+ const cancelled = { outcome: "cancelled" };
5038
+ if (!callback || payload.signal.aborted)
5039
+ return cancelled;
5040
+ const controller = new AbortController;
5041
+ const signal = AbortSignal.any([payload.signal, controller.signal]);
5042
+ this.permissionRequests.set(controller, payload.sessionId);
5043
+ let resolveCancellation;
5044
+ const cancellation = new Promise((resolve) => {
5045
+ resolveCancellation = resolve;
5046
+ });
5047
+ const onAbort = () => resolveCancellation(cancelled);
5048
+ signal.addEventListener("abort", onAbort, { once: true });
5049
+ try {
5050
+ const outcome = await Promise.race([cancellation, callback({
4721
5051
  sessionId: payload.sessionId,
4722
5052
  toolCall: payload.params?.toolCall,
4723
- params: payload.params
4724
- });
5053
+ params: payload.params,
5054
+ signal
5055
+ })]);
5056
+ return signal.aborted ? cancelled : outcome;
5057
+ } finally {
5058
+ signal.removeEventListener("abort", onAbort);
5059
+ this.permissionRequests.delete(controller);
4725
5060
  }
4726
- return { outcome: "cancelled" };
4727
5061
  },
4728
5062
  onSessionUpdate: (params) => {
4729
5063
  this.commandsCache.observe(params);
4730
5064
  this.quotaCache.observe(params, this.runtimeInfo.id);
4731
5065
  if (!this.suppressRecoveryUpdates)
4732
5066
  this.callbacks.onSessionUpdate?.(params);
4733
- }
5067
+ },
5068
+ onActivity: (sessionId) => this.touchSessionActivity(sessionId),
5069
+ onPauseActivity: (sessionId) => this.pauseSessionActivity(sessionId),
5070
+ maxReadBytes: this.maxReadBytes
4734
5071
  };
4735
5072
  const { app, connection, streamHandle } = connectSdkClient(processHandle.child, (clientApp) => {
4736
5073
  registerAcpClientHandlers(clientApp, handlerDeps);
4737
- }, this.runtimeInfo.id);
5074
+ }, this.runtimeInfo.id, this.clientInfo);
4738
5075
  this.sdkApp = app;
4739
5076
  this.sdkConnection = connection;
4740
5077
  this.streamHandle = streamHandle;
@@ -4748,7 +5085,7 @@ class AcpClient {
4748
5085
  configOptions: { boolean: {} }
4749
5086
  }
4750
5087
  }
4751
- });
5088
+ }, this.requestTimeoutMs);
4752
5089
  this.initResponse = initResp;
4753
5090
  if (this.resourcePrep) {
4754
5091
  const agentInfo = initResp?.agentInfo;
@@ -4775,7 +5112,7 @@ class AcpClient {
4775
5112
  const message = e instanceof Error ? e.message : String(e);
4776
5113
  this.setStatus("error", message);
4777
5114
  await this.disconnect(message);
4778
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5115
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
4779
5116
  }
4780
5117
  }
4781
5118
  getCachedQuota(sessionId) {
@@ -4783,7 +5120,7 @@ class AcpClient {
4783
5120
  }
4784
5121
  async getQuota(sessionId) {
4785
5122
  const cached = this.getCachedQuota(sessionId);
4786
- if (cached && Date.now() - cached.updatedAt < 30000) {
5123
+ if (cached && this.quotaCacheTtlMs > 0 && Date.now() - cached.updatedAt < this.quotaCacheTtlMs) {
4787
5124
  return cached;
4788
5125
  }
4789
5126
  if (this.adapter.probeQuota) {
@@ -4839,7 +5176,7 @@ class AcpClient {
4839
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);
4840
5177
  const openResult = await restoreOrCreateAcpSession({
4841
5178
  request: async (method, params) => {
4842
- return sdkRequest(agent, method, params);
5179
+ return sdkRequest(agent, method, params, this.requestTimeoutMs);
4843
5180
  },
4844
5181
  cwd: this.workspaceRoot,
4845
5182
  resumeSessionId: options?.resumeSessionId ?? null,
@@ -4880,7 +5217,10 @@ class AcpClient {
4880
5217
  return ok(handle);
4881
5218
  } catch (e) {
4882
5219
  const message = e instanceof Error ? e.message : String(e);
4883
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5220
+ return err({
5221
+ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR",
5222
+ message
5223
+ });
4884
5224
  }
4885
5225
  }
4886
5226
  async promptSession(sessionId, promptText, options) {
@@ -4889,11 +5229,12 @@ class AcpClient {
4889
5229
  }
4890
5230
  if (!this.isConnected)
4891
5231
  return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
4892
- if (this.inflightPrompts.has(sessionId))
5232
+ if (this.inflightTrackers.has(sessionId))
4893
5233
  return err({ code: "ACP_PROTOCOL_ERROR", message: "Session already has an in-flight prompt" });
4894
5234
  const generation = this.connectionGen;
4895
5235
  const agent = this.sdkConnection.agent;
4896
- this.inflightPrompts.add(sessionId);
5236
+ const tracker = createSdkRequestActivityController();
5237
+ this.inflightTrackers.set(sessionId, tracker);
4897
5238
  try {
4898
5239
  await this.mcpRecovery.ensureReady(sessionId);
4899
5240
  if (generation !== this.connectionGen || !this.isConnected)
@@ -4906,17 +5247,34 @@ class AcpClient {
4906
5247
  }
4907
5248
  const compat = this.buildCompatPrepend(sessionId);
4908
5249
  const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
4909
- 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, {
4910
5255
  sessionId,
4911
5256
  prompt: blocks
4912
- }, options?.timeoutMs);
5257
+ }, {
5258
+ idleTimeoutMs,
5259
+ maxDurationMs,
5260
+ activity: tracker
5261
+ });
4913
5262
  return ok(response);
4914
5263
  } catch (e) {
4915
5264
  const message = e instanceof Error ? e.message : String(e);
4916
- return err({ code: e instanceof AcpMcpRecoveryCancelledError ? "CANCELLED" : "ACP_PROTOCOL_ERROR", message });
5265
+ if (e instanceof AcpMcpRecoveryCancelledError)
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
+ }
5274
+ return err({ code: isAuthenticationRequired(message) ? "UNAUTHORIZED" : "ACP_PROTOCOL_ERROR", message });
4917
5275
  } finally {
4918
5276
  if (generation === this.connectionGen)
4919
- this.inflightPrompts.delete(sessionId);
5277
+ this.inflightTrackers.delete(sessionId);
4920
5278
  }
4921
5279
  }
4922
5280
  buildCompatPrepend(sessionId) {
@@ -4956,7 +5314,9 @@ class AcpClient {
4956
5314
  if (!this.sdkConnection?.agent)
4957
5315
  return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
4958
5316
  try {
4959
- await this.sdkConnection.agent.notify(methods2.agent.session.cancel, { sessionId });
5317
+ const notifying = this.sdkConnection.agent.notify(methods2.agent.session.cancel, { sessionId });
5318
+ this.cancelPermissionRequests("session_cancelled", sessionId);
5319
+ await notifying;
4960
5320
  return ok(undefined);
4961
5321
  } catch (error) {
4962
5322
  return err({ code: "ACP_PROTOCOL_ERROR", message: error instanceof Error ? error.message : String(error) });
@@ -4971,17 +5331,18 @@ class AcpClient {
4971
5331
  sessionId,
4972
5332
  configId,
4973
5333
  value
4974
- });
5334
+ }, this.requestTimeoutMs);
4975
5335
  return ok(response);
4976
5336
  } catch (e) {
4977
5337
  const message = e instanceof Error ? e.message : String(e);
4978
- return err({ code: "ACP_PROTOCOL_ERROR", message });
5338
+ return err({ code: e instanceof SdkRequestTimeoutError ? "ACP_TIMEOUT" : "ACP_PROTOCOL_ERROR", message });
4979
5339
  }
4980
5340
  }
4981
5341
  async disconnect(reason) {
4982
5342
  ++this.connectionGen;
4983
5343
  this.mcpRecovery.reset();
4984
- this.inflightPrompts.clear();
5344
+ this.inflightTrackers.clear();
5345
+ this.cancelPermissionRequests("connection_closed");
4985
5346
  this.setStatus("disconnected", reason);
4986
5347
  this.resourcePrep = null;
4987
5348
  const capabilities = this.initResponse?.agentCapabilities?.sessionCapabilities;
@@ -5018,6 +5379,37 @@ class AcpClient {
5018
5379
  }
5019
5380
  }
5020
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
+ }
5407
+ cancelPermissionRequests(reason, sessionId) {
5408
+ for (const [controller, pendingSessionId] of this.permissionRequests) {
5409
+ if (sessionId === undefined || pendingSessionId === sessionId)
5410
+ controller.abort(reason);
5411
+ }
5412
+ }
5021
5413
  setStatus(status, detail) {
5022
5414
  this.status = status;
5023
5415
  this.callbacks.onStatusChange?.(status, detail);
@@ -5998,7 +6390,11 @@ export {
5998
6390
  ACP_CLIENT_VERSION,
5999
6391
  ACP_EARLY_EXIT_STDERR_TAIL_LINES,
6000
6392
  ACP_EARLY_EXIT_WINDOW_MS,
6393
+ ACP_FS_MAX_READ_BYTES,
6394
+ ACP_PROMPT_IDLE_TIMEOUT_MS,
6395
+ ACP_PROMPT_MAX_DURATION_MS,
6001
6396
  ACP_SDK_REQUEST_TIMEOUT_MS,
6397
+ ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT,
6002
6398
  AGY_ACP_NPM_PACKAGE,
6003
6399
  APP_RESOURCE_CAPABILITIES,
6004
6400
  APP_RULES_FILE,
@@ -6028,9 +6424,11 @@ export {
6028
6424
  NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
6029
6425
  OPENCODE_CLI_NPM_PACKAGE,
6030
6426
  QuotaCache,
6427
+ SdkRequestTimeoutError,
6031
6428
  acpReadTextFile,
6032
6429
  acpWriteTextFile,
6033
6430
  agyAdapter,
6431
+ antigravityCliAdapter,
6034
6432
  appendTerminalOutput,
6035
6433
  assertPathInsideWorkspace,
6036
6434
  buildAcpProxySpawnEnv,
@@ -6049,6 +6447,7 @@ export {
6049
6447
  codexAdapter,
6050
6448
  connectSdkClient,
6051
6449
  copilotAdapter,
6450
+ createSdkRequestActivityController,
6052
6451
  createSdkStreamHandle,
6053
6452
  createSessionConfigHome,
6054
6453
  cursorAdapter,
@@ -6076,6 +6475,7 @@ export {
6076
6475
  handleInkdownMcpRpc,
6077
6476
  hasDeepseekHarnessCredentials,
6078
6477
  isAbsolutePathLike,
6478
+ isAcpPermissionOutcome,
6079
6479
  isAppError,
6080
6480
  isAuthenticationRequired,
6081
6481
  isBinaryDocumentPath,
@@ -6116,6 +6516,7 @@ export {
6116
6516
  prepareCompatibilityResources,
6117
6517
  prepareOpenCodeResources,
6118
6518
  probeAgyAuth,
6519
+ probeAgyQuota,
6119
6520
  probeClaudeAuth,
6120
6521
  probeClaudeQuota,
6121
6522
  probeCodexAuth,
@@ -6135,6 +6536,9 @@ export {
6135
6536
  readStoredAcpProvider,
6136
6537
  registerAcpClientHandlers,
6137
6538
  requestSessionWithResources,
6539
+ resolveAntigravityAccount,
6540
+ resolveAntigravityCliCommand,
6541
+ resolveAntigravityLanguageServer,
6138
6542
  resolveAppCodexHome,
6139
6543
  resolveClaudeHome,
6140
6544
  resolveCodexHome,
@@ -6156,6 +6560,7 @@ export {
6156
6560
  saveAcpProvider,
6157
6561
  saveAcpProxySettings,
6158
6562
  sdkRequest,
6563
+ sdkRequestWithActivity,
6159
6564
  shouldPromptAuthWizard,
6160
6565
  spawnAcpProcess,
6161
6566
  supportsCodeMode,