@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/README.md CHANGED
@@ -19,8 +19,8 @@
19
19
 
20
20
  ## ⚡ 核心特性
21
21
 
22
- - **多 Agent 统一适配(8 大主流运行时)**:
23
- 开箱即用支持 `codex-acp` (ChatGPT)、`claude`、`cursor-cli`、`deepseek`、`gemini`、`copilot`、`opencode`、`agy`。新增 Agent 只需在该包实现一个适配器,全局所有项目自动生效。
22
+ - **多 Agent 统一适配(10 大内置运行时)**:
23
+ 开箱即用支持 `codex-acp` (ChatGPT)、`claude`、`cursor-cli`、`deepseek`、`gemini`、`copilot`、`opencode`、`opencode-v2`、`antigravity-cli`、`agy`。新增 Agent 只需在该包实现一个适配器,全局所有项目自动生效。
24
24
  - **纯 Node.js / Headless 架构**:
25
25
  不依赖任何 Electron API、React 或特定前端框架。配置目录跨平台自动检测回落(支持自定义 `dataDir`)。
26
26
  - **生命周期全托管**:
@@ -47,7 +47,9 @@
47
47
  | `gemini` | Gemini | `~/.gemini/oauth_creds.json` / `GEMINI_API_KEY` | 自动探测 OAuth 凭证与系统 Key |
48
48
  | `copilot` | Copilot | `~/.copilot/config.json` / `GH_TOKEN` | 自动提取 `loggedInUsers` 凭证列表 |
49
49
  | `opencode` | OpenCode | `$XDG_DATA_HOME/opencode/auth.json` | 遵循 XDG / `%LOCALAPPDATA%` 规范 |
50
- | `agy` | agy | 官方桥接器免密直连 | `tryDirectSessionFirst` 免鉴权直通 |
50
+ | `opencode-v2` | OpenCode v2 | v2 SQLite 登录态 | 通过 `npx @opencode/cli acp` 启动 |
51
+ | `antigravity-cli` | Antigravity | Antigravity CLI 登录态 (`agy acp`) | 自动探测 `PATH` 与 `~/.local/bin/agy`,支持配额探测与浏览器认证 |
52
+ | `agy` | Antigravity (legacy bridge) | `@yitom/agy-acp-map` 桥接器 | `tryDirectSessionFirst` 免鉴权直通,保留旧会话 ID 与扩展 |
51
53
 
52
54
  ---
53
55
 
@@ -70,11 +72,9 @@ const client = new AcpClient({
70
72
  },
71
73
  onPermissionRequest: async ({ toolCall, params }) => {
72
74
  console.log(`Agent 请求调用工具:`, toolCall)
73
- // 交互式批准(y)或自动放行:协议层只有 selected/cancelled,
74
- // 允许项用 pickAllowOptionId 从 Agent 给的 options 里挑(无 'approved')。
75
- return pickAllowOptionId(params)
76
- ? { outcome: 'selected' as const, optionId: pickAllowOptionId(params)! }
77
- : { outcome: 'cancelled' as const }
75
+ console.log('审批选项', params.options)
76
+ // 交互宿主展示选项,并返回用户选择的 optionId。
77
+ return { outcome: 'cancelled' as const }
78
78
  },
79
79
  onSessionUpdate: (event) => {
80
80
  console.log(`[Stream Event]:`, event)
@@ -92,7 +92,7 @@ if (!connectResult.ok) {
92
92
  // 3. 创建/恢复会话
93
93
  const sessionResult = await client.createSession()
94
94
  if (sessionResult.ok) {
95
- const session = sessionResult.data
95
+ const session = sessionResult.value
96
96
  // 4. 发送提示词 / 消息交互
97
97
  await session.prompt('请帮我分析当前项目目录结构')
98
98
  }
@@ -122,7 +122,7 @@ Sidecar:`session/open` 结果带 `availableCommands`(若已收到),并
122
122
  在本包根目录一键构建生成 `dist`(ESM / CJS / `.d.ts`):
123
123
 
124
124
  ```bash
125
- bun run build:acp
125
+ bun run build
126
126
  ```
127
127
 
128
128
  产物说明:
@@ -137,7 +137,7 @@ bun run build:acp
137
137
  我们在 [`examples/standalone-acp-demo.ts`](./examples/standalone-acp-demo.ts) 提供了可在终端直接运行的验证脚本:
138
138
 
139
139
  ```bash
140
- bun run packages/acp/examples/standalone-acp-demo.ts
140
+ bun run examples/standalone-acp-demo.ts
141
141
  ```
142
142
 
143
143
  资源接口当前为未发布试点:规则准备与会话应用分开记录;已有磁盘配置保守回退;skillsFound 仅 SDK 文件扫描,尚无原生技能挂载或通用兼容提示词注入。详见 docs/api-reference.md 第 5 节。
@@ -148,7 +148,25 @@ bun run packages/acp/examples/standalone-acp-demo.ts
148
148
 
149
149
  会话专属配置环境:`resources: { directory, configurationScope: 'session' }`。仅替换子进程原生配置根,生成规则/纯文档技能、断开清理;不复制用户认证。支持范围、Cursor 规则边界及 agy/DeepSeek 的明确拒绝见 `docs/api-reference.md`。实现与测试:`src/resources/session-config.ts` / `session-config.test.ts`。
150
150
 
151
- ### Antigravity session resources
151
+ ### Agent 启动方式
152
+
153
+ Codex、Claude 和 DeepSeek 的启动命令会解析各自发布包的 `latest`,OpenCode v2 由 npm 启动。Antigravity、Gemini、Copilot、Cursor 和 `opencode` 入口使用宿主安装的 CLI。握手使用 ACP v1。
154
+
155
+ 需要安装包时,在 GitHub Actions 手动运行 `CI & Publish`。测试通过后,Artifacts 中的 `acp-client-npm-package` 包含 npm `.tgz`。
156
+
157
+ ### Antigravity CLI
158
+
159
+ Use `new AcpClient({ runtime: 'antigravity-cli', workspaceRoot })` to start Google's `agy acp` (auto-resolved from `PATH` or `~/.local/bin/agy`, and `%LOCALAPPDATA%\antigravity\agy.exe` / `%USERPROFILE%\.local\bin\agy.exe` on Windows). If the host needs extra flags or a custom path, pass a runtime object with an explicit `command` and `args` (explicit custom runtimes are never overwritten by `resolveSpawnCommand`). Also supports `session.getQuota()` / `probeAgyQuota({ runtimeId: 'antigravity-cli' })`. The sidecar accepts the same runtime ID in `client/connect`.
160
+
161
+ For session-supplied HTTP MCP servers, include `--process-per-session` in the runtime arguments.
162
+
163
+ Call `createSession()` after `connect()` to reuse the CLI's cached sign-in. When the server requires sign-in, the SDK returns `UNAUTHORIZED`. Let the user select an advertised browser method from `init.authMethods`, call `client.authenticate(methodId)` (sidecar `client/authenticate`), and retry. For terminal login, run `agy acp --login` interactively and reconnect. Google stores the credentials through its CLI. See the [official ACP setup](https://antigravity.google/docs/ide/extensions/acp/#authentication).
164
+
165
+ The CLI sends ACP permission requests when its policy requires review. Display the agent's choices and return the exact option ID the user selected. The sidecar sends `permission/request` with `requestId`, `sessionId`, `toolCall` and `options`. Reply via `permission/respond` with `{ requestId, outcome: { outcome: 'selected', optionId } }`. Dismissing the prompt uses `{ outcome: 'cancelled' }` as its outcome. Cancellation, timeout and connection changes emit `permission/cancelled` so the host can dismiss stale prompts. SDK hosts receive an `AbortSignal` for the same purpose. See the [CLI permission settings](https://antigravity.google/docs/cli-permissions) to configure which operations require review.
166
+
167
+ Keep the `agy` runtime ID for sessions created by `@yitom/agy-acp-map` and for its resource extension. Keep session IDs paired with their runtime when saving history.
168
+
169
+ ### Antigravity bridge session resources
152
170
 
153
171
  With `@yitom/agy-acp-map` 0.1.24 / 0.1.25 / 0.1.26, `resources.directory` is delivered through the bridge session extension `_meta.appResources.directory`. Rules, native Skills and session MCP live in a private temporary additional workspace; cwd, global configuration and authentication remain unchanged. Close/delete/orderly shutdown remove the temporary workspace. Unknown bridge versions keep compatibility guidance and the app-skills MCP fallback. This extension is bridge-specific, not a standard ACP configuration-home API. `configurationScope: "session"` also supports agy; its configuration report remains conservative until the bridge accepts the session extension.
154
172
 
@@ -16,6 +16,7 @@ export interface AcpClientCallbacks {
16
16
  kind?: string;
17
17
  };
18
18
  params: Record<string, unknown>;
19
+ signal: AbortSignal;
19
20
  }) => Promise<AcpPermissionOutcome>;
20
21
  /** 会话内容流式/状态更新通知 */
21
22
  onSessionUpdate?: (params: Record<string, unknown>) => void;
@@ -28,6 +29,19 @@ export interface AcpClientCallbacks {
28
29
  /** 日志打印 */
29
30
  onLog?: (level: 'info' | 'warn' | 'error', message: string, meta?: unknown) => void;
30
31
  }
32
+ export interface AcpPromptOptions {
33
+ /** 显式硬性总时长上限(毫秒;向后兼容旧参数,若未同时传 idleTimeoutMs 则禁用静默重置) */
34
+ timeoutMs?: number;
35
+ /** 活动重置的静默超时(毫秒;默认取 client promptIdleTimeoutMs 即 300_000;0 表示不限制) */
36
+ idleTimeoutMs?: number;
37
+ /** 可选硬性最大总时长上限(毫秒;默认取 client promptMaxDurationMs 即 0 不限制) */
38
+ maxDurationMs?: number;
39
+ /** 随 Prompt 一并发送的图片列表 */
40
+ images?: Array<{
41
+ mimeType: string;
42
+ data: string;
43
+ }>;
44
+ }
31
45
  export interface AcpClientOptions {
32
46
  /** 运行时标识,如 'codex-acp', 'claude', 'cursor-cli', 'deepseek', 'gemini' 等 */
33
47
  runtime?: string | AcpRuntimeInfo;
@@ -44,6 +58,18 @@ export interface AcpClientOptions {
44
58
  proxy?: Partial<AcpProxySettings>;
45
59
  /** 附加环境变量 */
46
60
  env?: NodeJS.ProcessEnv;
61
+ /** 控制面 RPC 默认超时(毫秒,默认 120_000) */
62
+ requestTimeoutMs?: number;
63
+ /** Prompt 流式静默超时(毫秒,收到事件/FS/终端/审批活动自动重置,默认 300_000;0 表示关闭) */
64
+ promptIdleTimeoutMs?: number;
65
+ /** Prompt 最大总时长上限(毫秒,默认 0 表示不限) */
66
+ promptMaxDurationMs?: number;
67
+ /** 配额缓存有效期(毫秒,默认 30_000) */
68
+ quotaCacheTtlMs?: number;
69
+ /** fs/read_text_file 单次最大读取字节上限(默认 2MB) */
70
+ maxReadBytes?: number;
71
+ /** 终端输出缓冲区上限(字节,默认 1MB) */
72
+ terminalOutputByteLimit?: number;
47
73
  /**
48
74
  * 应用资源目录(单目录接口):`{ directory: 绝对路径 }`,
49
75
  * 含 AGENTS.md 与 skills/ 下 SKILL.md。提供即走原生资源准备
@@ -72,13 +98,7 @@ export declare class AcpSessionHandle {
72
98
  /** 建会话时刻的应用资源加载报告快照(规则/技能分开记录) */
73
99
  resourceReport?: AppResourceReport | null | undefined);
74
100
  /** 向当前会话发送 Prompt / 消息交互 */
75
- prompt(promptText: string, options?: {
76
- timeoutMs?: number;
77
- images?: Array<{
78
- mimeType: string;
79
- data: string;
80
- }>;
81
- }): Promise<Result<unknown, AppError>>;
101
+ prompt(promptText: string, options?: AcpPromptOptions): Promise<Result<unknown, AppError>>;
82
102
  /** Agent 通过 available_commands_update 提供的斜杠命令(调用 = prompt 发送 `/name args` 文本) */
83
103
  /** 当前会话最近获取或解析到的配额(5h / 周额度 / 余额) */
84
104
  get quota(): AcpAgentQuota | undefined;
@@ -104,14 +124,23 @@ export declare class AcpClient {
104
124
  private readonly commandsCache;
105
125
  private readonly quotaCache;
106
126
  private runtimeInfo;
127
+ private readonly hasCustomRuntime;
107
128
  private adapter;
108
129
  private readonly workspaceRoot;
109
130
  private readonly clientInfo;
110
131
  private readonly dataDir;
132
+ private readonly proxyOverride?;
111
133
  private readonly extraEnv;
134
+ private readonly requestTimeoutMs;
135
+ private readonly promptIdleTimeoutMs;
136
+ private readonly promptMaxDurationMs;
137
+ private readonly quotaCacheTtlMs;
138
+ private readonly maxReadBytes;
112
139
  private readonly configurationScope;
113
140
  private sessionConfig;
114
141
  private readonly resourcesDir;
142
+ private authenticatingAgent?;
143
+ private readonly permissionRequests;
115
144
  private readonly processScopeKey;
116
145
  private readonly callbacks;
117
146
  private readonly terminals;
@@ -120,8 +149,8 @@ export declare class AcpClient {
120
149
  private sdkConnection;
121
150
  private streamHandle;
122
151
  private initResponse;
123
- /** 在途 prompt 会话集合(忙时不打断温进程的判定依据) */
124
- private readonly inflightPrompts;
152
+ /** 在途 prompt 会话活动追踪器(忙时不打断温进程 + 支持事件重置静默超时) */
153
+ private readonly inflightTrackers;
125
154
  /** 本次连接周期的应用资源准备结果(无 resources 入口时为 null) */
126
155
  private resourcePrep;
127
156
  /** 连接代次(connect 推进;兼容记账与重连后重附带的诊断依据) */
@@ -146,6 +175,8 @@ export declare class AcpClient {
146
175
  /** 获取底层当前 Agent 的 RPC 客户端句柄 */
147
176
  get agent(): import("@agentclientprotocol/sdk").ClientContext | null;
148
177
  get initializeResponse(): InitializeResponse | null;
178
+ /** Authenticate explicitly using a method advertised by the connected agent. */
179
+ authenticate(methodId: string): Promise<Result<void, AppError>>;
149
180
  /**
150
181
  * 启动并连接 Agent:
151
182
  * 1. 预检判停(如缺少 API Key、未安装 CLI);
@@ -177,13 +208,7 @@ export declare class AcpClient {
177
208
  codeMode?: AcpCodeMode;
178
209
  }): Promise<Result<AcpSessionHandle, AppError>>;
179
210
  /** 向指定会话发送消息 */
180
- promptSession(sessionId: string, promptText: string, options?: {
181
- timeoutMs?: number;
182
- images?: Array<{
183
- mimeType: string;
184
- data: string;
185
- }>;
186
- }): Promise<Result<unknown, AppError>>;
211
+ promptSession(sessionId: string, promptText: string, options?: AcpPromptOptions): Promise<Result<unknown, AppError>>;
187
212
  /**
188
213
  * 兼容引导前置文本(首轮一次制):
189
214
  * - 无 resources / 未知会话 / 原生已交付 → null(原文不动);
@@ -198,5 +223,8 @@ export declare class AcpClient {
198
223
  setSessionConfigOption(sessionId: string, configId: string, value: string | boolean): Promise<Result<unknown, AppError>>;
199
224
  /** 断开连接并清理资源 */
200
225
  disconnect(reason?: string): Promise<void>;
226
+ private touchSessionActivity;
227
+ private pauseSessionActivity;
228
+ private cancelPermissionRequests;
201
229
  private setStatus;
202
230
  }
@@ -1,3 +1,4 @@
1
+ export declare const ACP_FS_MAX_READ_BYTES: number;
1
2
  export declare function isBinaryDocumentPath(filePath: string): boolean;
2
3
  export declare function assertPathInsideWorkspace(filePath: string, workspaceRoot: string): string;
3
4
  export declare function acpReadTextFile(params: {
@@ -5,6 +6,7 @@ export declare function acpReadTextFile(params: {
5
6
  workspaceRoot: string;
6
7
  line?: number;
7
8
  limit?: number;
9
+ maxReadBytes?: number;
8
10
  }): Promise<{
9
11
  content: string;
10
12
  }>;
@@ -1,3 +1,8 @@
1
+ export declare const ACP_TERMINAL_DEFAULT_OUTPUT_BYTE_LIMIT = 1048576;
2
+ export interface AcpTerminalManagerOptions {
3
+ defaultOutputByteLimit?: number;
4
+ onActivity?: (sessionId: string) => void;
5
+ }
1
6
  export interface AcpTerminalExitStatus {
2
7
  exitCode: number | null;
3
8
  signal: string | null;
@@ -22,6 +27,9 @@ export interface CreateAcpTerminalParams {
22
27
  /** ACP Client 侧无头终端:spawn 命令,供 Agent 轮询 output / wait / kill / release */
23
28
  export declare class AcpTerminalManager {
24
29
  private terminals;
30
+ private readonly defaultOutputByteLimit;
31
+ private readonly onActivity?;
32
+ constructor(options?: AcpTerminalManagerOptions);
25
33
  create(params: CreateAcpTerminalParams): {
26
34
  terminalId: string;
27
35
  };
@@ -13,9 +13,16 @@ export interface AcpClientHandlerDeps {
13
13
  onPermission: (payload: {
14
14
  sessionId?: string;
15
15
  params: Record<string, unknown>;
16
+ signal: AbortSignal;
16
17
  }) => Promise<AcpPermissionOutcome>;
17
18
  /** session/update 通知透传(回放压制由调用方做) */
18
19
  onSessionUpdate: (params: Record<string, unknown>) => void;
20
+ /** 协议或工具活跃事件通知(用于重置 Prompt 静默超时) */
21
+ onActivity?: (sessionId?: string) => void;
22
+ /** 进入阻塞等待(如人工审批)时暂停静默超时,返回恢复函数 */
23
+ onPauseActivity?: (sessionId?: string) => () => void;
24
+ /** fs/read_text_file 单次最大读取字节上限 */
25
+ maxReadBytes?: number;
19
26
  }
20
27
  /**
21
28
  * Agent → Client 回调:permission + fs + terminal(声明能力后才会收到)。
@@ -23,5 +30,7 @@ export interface AcpClientHandlerDeps {
23
30
  * 无需手写 transport.respond/respondError。
24
31
  */
25
32
  export declare function registerAcpClientHandlers(app: ClientApp, deps: AcpClientHandlerDeps): void;
26
- /** 从 permission options 中挑一个「允许」类 optionId,否则 cancelled */
33
+ /** Accept cancellation or a selection explicitly advertised for this request. */
34
+ export declare function isAcpPermissionOutcome(outcome: unknown, params: Record<string, unknown>): outcome is AcpPermissionOutcome;
35
+ /** Find an allow option after user approval, preferring a one-time grant. */
27
36
  export declare function pickAllowOptionId(params: Record<string, unknown>): string | null;
@@ -1,7 +1,33 @@
1
1
  import type { ChildProcessWithoutNullStreams } from 'node:child_process';
2
2
  import { type ClientApp, type ClientConnection, type ClientContext, type Stream } from '@agentclientprotocol/sdk';
3
- /** SDK 请求超时:沿用旧手搓传输的 120s,显式透传 */
3
+ /** SDK 控制面请求默认超时:120s */
4
4
  export declare const ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
5
+ /** 长流式 Prompt 默认静默超时:连续 5 分钟无任何事件/FS/终端/权限活动才超时 */
6
+ export declare const ACP_PROMPT_IDLE_TIMEOUT_MS = 300000;
7
+ /** 长流式 Prompt 默认最大总时长上限:0 表示不限(仅受静默超时约束) */
8
+ export declare const ACP_PROMPT_MAX_DURATION_MS = 0;
9
+ export type SdkRequestTimeoutKind = 'timeout' | 'idle' | 'max_duration';
10
+ export declare class SdkRequestTimeoutError extends Error {
11
+ readonly kind: SdkRequestTimeoutKind;
12
+ readonly method: string;
13
+ readonly durationMs: number;
14
+ constructor(kind: SdkRequestTimeoutKind, method: string, durationMs: number);
15
+ }
16
+ export interface SdkRequestActivityController {
17
+ /** 重置静默超时计时器(例如收到 session/update、fs、terminal 输出) */
18
+ touch(): void;
19
+ /** 暂停静默超时计时器(如等待用户权限审批),返回幂等恢复函数 */
20
+ pause(): () => void;
21
+ }
22
+ export declare function createSdkRequestActivityController(): SdkRequestActivityController;
23
+ export interface SdkRequestActivityOptions {
24
+ /** 活动重置的静默超时(毫秒);0 或未传且 maxDurationMs 存在时禁用 */
25
+ idleTimeoutMs?: number;
26
+ /** 硬性最大总时长上限(毫秒);0 或未传则不限制总时长 */
27
+ maxDurationMs?: number;
28
+ /** 关联的活动控制器 */
29
+ activity?: SdkRequestActivityController;
30
+ }
5
31
  export interface SdkStreamHandle {
6
32
  stream: Stream;
7
33
  /** 摘掉桥接(温进程复用时保住子进程 stdio,不关 fd) */
@@ -17,18 +43,30 @@ export interface SdkStreamHandle {
17
43
  */
18
44
  export declare function createSdkStreamHandle(child: ChildProcessWithoutNullStreams): SdkStreamHandle;
19
45
  /**
20
- * 长驻连接:client({ name: 'inkdown' }).connect(),持有 ClientConnection。
46
+ * 长驻连接:client(...).connect(),持有 ClientConnection。
21
47
  * 不用 connectWith 作用域式;调用方用返回的 connection.agent 发请求,
22
48
  * 断开时 connection.close() 取消在途请求。
23
49
  */
24
50
  export declare function connectSdkClient(child: ChildProcessWithoutNullStreams, configure: (app: ClientApp) => void,
25
51
  /** 所属运行时 id:仅日志/隔离用,不改变 SDK 建连形态;缺省向后兼容单 codex 路径 */
26
- runtimeId?: string): {
52
+ runtimeId?: string,
53
+ /** 客户端身份信息(默认 'acp-client') */
54
+ clientInfo?: {
55
+ name: string;
56
+ version?: string;
57
+ }): {
27
58
  app: ClientApp;
28
59
  connection: ClientConnection;
29
60
  streamHandle: SdkStreamHandle;
30
61
  };
31
- /** 带显式超时的 agent.request:超时 abort(触发 $/cancel_request)并拒绝 */
62
+ /**
63
+ * 支持活动静默重置 + 最大总时长上限的 agent.request:
64
+ * - idleTimeoutMs > 0:每次收到事件(touch)自动重置倒计时;等待人工审批等 pause() 期间暂停计时;
65
+ * - maxDurationMs > 0:可选硬性总时长天花板;
66
+ * - 任一触发即 abort(触发 $/cancel_request)并抛出 SdkRequestTimeoutError。
67
+ */
68
+ export declare function sdkRequestWithActivity<Response, Params>(agent: ClientContext, method: string, params: Params, options?: SdkRequestActivityOptions): Promise<Response>;
69
+ /** 带显式超时的 agent.request:超时 abort(触发 $/cancel_request)并拒绝;timeoutMs <= 0 时不设超时 */
32
70
  export declare function sdkRequest<Response, Params>(agent: ClientContext, method: string, params: Params, timeoutMs?: number): Promise<Response>;
33
71
  /** Close owned sessions before transport/process teardown; unsupported failures stay bounded. */
34
72
  export declare function closeAcpSessions(agent: ClientContext, sessionIds: Iterable<string>, timeoutMs?: number): Promise<string[]>;