@easbot/acp 0.0.0-stage → 0.3.32

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.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +522 -0
  3. package/README.md +667 -2
  4. package/dist/chunks/bootstrap-GGS3N5CF.cjs +1 -0
  5. package/dist/chunks/bootstrap-MZQICOGZ.mjs +1 -0
  6. package/dist/chunks/cache-3R3ORBTY.cjs +1 -0
  7. package/dist/chunks/cache-76CBF3LU.mjs +1 -0
  8. package/dist/chunks/chunk-2KOCPHVP.mjs +1 -0
  9. package/dist/chunks/chunk-33M2R2US.mjs +1 -0
  10. package/dist/chunks/chunk-3DHMW4DB.mjs +11 -0
  11. package/dist/chunks/chunk-5HWD3B3N.cjs +11 -0
  12. package/dist/chunks/chunk-7RWES66A.cjs +2 -0
  13. package/dist/chunks/chunk-B3ANZALB.mjs +2 -0
  14. package/dist/chunks/chunk-BNSJ6COS.cjs +1 -0
  15. package/dist/chunks/chunk-D4TSQ2TT.mjs +0 -0
  16. package/dist/chunks/chunk-D7S7ARXV.mjs +8 -0
  17. package/dist/chunks/chunk-DX35VSAT.cjs +1 -0
  18. package/dist/chunks/chunk-HQBRVVXS.mjs +1 -0
  19. package/dist/chunks/chunk-ITV7SWGU.cjs +8 -0
  20. package/dist/chunks/chunk-JLO7UYKQ.cjs +1 -0
  21. package/dist/chunks/chunk-M2YU5LAI.cjs +1 -0
  22. package/dist/chunks/chunk-NHXAYBZH.mjs +1 -0
  23. package/dist/chunks/chunk-PATHHDWE.mjs +1 -0
  24. package/dist/chunks/chunk-RHW6YR3D.mjs +2 -0
  25. package/dist/chunks/chunk-SNWAB3QJ.cjs +2 -0
  26. package/dist/chunks/chunk-VVGGER23.cjs +1 -0
  27. package/dist/chunks/chunk-Z3YEK7DD.cjs +1 -0
  28. package/dist/chunks/cli-handler-6XB6B5DV.mjs +1 -0
  29. package/dist/chunks/cli-handler-IU3YUTOU.cjs +1 -0
  30. package/dist/chunks/config-FTGKCGYZ.mjs +1 -0
  31. package/dist/chunks/config-ZVDYJ7TW.cjs +1 -0
  32. package/dist/chunks/interfaces-6ZCF5T55.cjs +1 -0
  33. package/dist/chunks/interfaces-TXNKX4HT.mjs +1 -0
  34. package/dist/chunks/loader-3KX33KJQ.cjs +1 -0
  35. package/dist/chunks/loader-6HBCWO6Y.mjs +1 -0
  36. package/dist/chunks/types-BZWPIPG6.mjs +1 -0
  37. package/dist/chunks/types-R3VOD4XE.cjs +1 -0
  38. package/dist/cli.cjs +2 -0
  39. package/dist/cli.d.cts +1 -0
  40. package/dist/cli.d.ts +1 -0
  41. package/dist/cli.mjs +2 -0
  42. package/dist/index.cjs +1 -0
  43. package/dist/index.d.cts +2030 -0
  44. package/dist/index.d.ts +2030 -0
  45. package/dist/index.mjs +1 -0
  46. package/package.json +87 -3
package/README.md CHANGED
@@ -1,3 +1,668 @@
1
- # Temporary Holding Version
1
+ [English](./README.en.md) | 中文
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @easbot/acp
4
+
5
+ > EASBot ACP (Agent Communication Protocol) Adapter —— 多通道 ACP server / client 实现,支持 stdio / http / websocket 三种传输方式
6
+
7
+ ## 版本
8
+
9
+ v0.3.32
10
+ ## 简介
11
+
12
+ `@easbot/acp` 是 EASBot 生态的 **ACP 适配层**(v0.1,从 `@easbot/agent` 的 `adapter/` 子模块拆分独立)。基于 [`@agentclientprotocol/sdk`](https://github.com/agentclientprotocol/typescript-sdk),实现 ACP 协议的 server / client 通信层,提供多通道连接、JSON-RPC 路由、配置管理、缓存管理以及独立 CLI 入口。
13
+
14
+ **v0.1 拆分动机**:
15
+
16
+ - ✅ **解耦业务复杂度**:agent 包剥离 acp 协议层,业务模块(session / mcp / gateway)依赖更轻
17
+ - ✅ **独立发布**:acp 包可独立 npm 发布,宿主项目(web / cli / monitor)按需引入
18
+ - ✅ **独立 CLI**:`easbot-acp <command>` 直接启动 server / config / status / doctor,无需走 agent
19
+ - ✅ **独立配置**:`<workspaceDir>/.easbot/acp.json`(由 `AcpCache` 持有)+ `~/.config/easbot/acp.json` + `easbot.json` 顶层 `acp` 字段(四层合并加载,与 gateway 同构)
20
+
21
+ ## 特性
22
+
23
+ - **三通道传输**:stdio(子进程)/ http(REST + JSON-RPC)/ websocket(全双工)
24
+ - **JSON-RPC 路由**:`acp-rpc-handler` 自动 dispatch `initialize / new_session / prompt / cancel` 等 method
25
+ - **四层配置加载**:参考 `packages/gateway/src/config/loader.ts` 的四层合并 + JSONC + env 替换
26
+ - **L2 缓存命名空间**:`AcpCache`(State.holder 模式,与 `NoteCache` 同源)管理项目级 `.easbot/acp.json`
27
+ - **错误 namespace**:`AcpError`(按 `spec/error-handling-standard.md` v1.9 分层;L2 包内 5 个核心错误 + L3 业务反馈注册)
28
+ - **i18n 国际化**:`t()` / `I18n` / `registerI18nResources`(zh-CN / en-US;与 note / gateway 完全同源)
29
+ - **独立 CLI 入口**:`easbot-acp <command>`(init / start / status / doctor / config)
30
+ - **host ↔ 包解耦**:与 note / memory / codebase / skills 完全对齐的 `setGlobalAdapter / setInstanceAdapter` 接口
31
+ - **复用现有业务模块**:server / client / connection / event / performance 模块从 agent 包迁移而来
32
+
33
+ ## 安装
34
+
35
+ ```bash
36
+ pnpm add @easbot/acp
37
+ ```
38
+
39
+ ## 顶层导出清单
40
+
41
+ ```typescript
42
+ // 配置模块(schema + loader + 便捷访问函数)
43
+ import {
44
+ // Schema
45
+ ACPServerConfigSchema,
46
+ ACPClientConfigSchema,
47
+ ACPClientsConfigSchema,
48
+ InfoACPConfigSchema,
49
+ // 默认值
50
+ DEFAULT_ACP_SERVER_CONFIG,
51
+ DEFAULT_ACP_CLIENT_CONFIG,
52
+ // 验证
53
+ validateAcpConfig,
54
+ parsePartialAcpConfig,
55
+ // Loader
56
+ loadConfig,
57
+ getConfig,
58
+ isConfigLoaded,
59
+ clearConfigCache,
60
+ getConfigDirectory,
61
+ reloadConfig,
62
+ // 便捷访问
63
+ getServerConfig,
64
+ getClientsConfig,
65
+ getClientById,
66
+ getDefaultClient,
67
+ type AcpConfigStateResult,
68
+ } from '@easbot/acp';
69
+ import type {
70
+ ACPServerConfig,
71
+ ACPClientConfig,
72
+ ACPClientsConfig,
73
+ InfoACPConfig,
74
+ } from '@easbot/acp';
75
+
76
+ // L2 缓存命名空间
77
+ import { AcpCache, ACP_JSON_REL_PATH } from '@easbot/acp';
78
+
79
+ // 错误 namespace + 业务反馈注册
80
+ import {
81
+ AcpError,
82
+ NameErrors,
83
+ ACP_BUSINESS_CODES,
84
+ ACP_BUSINESS_HINTS,
85
+ registerBusinessErrors,
86
+ ServiceError,
87
+ type ServiceErrorInstance,
88
+ } from '@easbot/acp';
89
+
90
+ // i18n 国际化(zh-CN / en-US)
91
+ import {
92
+ t,
93
+ I18n,
94
+ registerI18nResources,
95
+ initI18n,
96
+ changeI18nLanguage,
97
+ formatLog,
98
+ type Locale,
99
+ type TranslationResources,
100
+ } from '@easbot/acp';
101
+
102
+ // CLI handler + 渲染器
103
+ import {
104
+ handleAcpCli,
105
+ renderBanner,
106
+ renderHelp,
107
+ COMMANDS_HELP,
108
+ type AcpCliDeps,
109
+ type AcpCliResult,
110
+ type CommandHelp,
111
+ } from '@easbot/acp';
112
+
113
+ // host ↔ 包解耦接口(ADR 0066)
114
+ import {
115
+ setGlobalAdapter,
116
+ setInstanceAdapter,
117
+ resetGlobalAdapter,
118
+ resetInstanceAdapter,
119
+ getGlobal,
120
+ getInstance,
121
+ getHomeDir,
122
+ getXdgData,
123
+ getWorktree,
124
+ getProjectDirectory,
125
+ } from '@easbot/acp';
126
+
127
+ // 业务模块(来自 agent 包拆分)
128
+ import { EasBotAgent, EasbotAdapter, ChannelType, AgentStatus } from '@easbot/acp';
129
+ ```
130
+
131
+ ## 快速上手
132
+
133
+ ### 1. 启动独立 ACP Server
134
+
135
+ ```bash
136
+ # 1) 初始化工作区配置(创建 .easbot/acp.json)
137
+ easbot-acp init --channel websocket --port 3000 --hostname localhost
138
+
139
+ # 2) 启动 server(阻塞;Ctrl+C 退出)
140
+ easbot-acp start --channel websocket --port 3000
141
+
142
+ # 3) 查看配置摘要
143
+ easbot-acp status
144
+
145
+ # 4) 健康检查
146
+ easbot-acp doctor
147
+
148
+ # 5) 修改配置
149
+ easbot-acp config set server.port 8080
150
+ easbot-acp config get server.channel
151
+ ```
152
+
153
+ ### 2. 编程式启动
154
+
155
+ ```typescript
156
+ import { EasbotAdapter, getServerConfig, ChannelType } from '@easbot/acp';
157
+
158
+ const serverCfg = await getServerConfig();
159
+ await EasbotAdapter.init({
160
+ directory: process.cwd(),
161
+ printLogs: false,
162
+ logLevel: 'INFO',
163
+ channel: ChannelType.WS,
164
+ });
165
+ await EasbotAdapter.ensureACPService(serverCfg);
166
+ ```
167
+
168
+ ### 3. 配置加载(四层合并,与 gateway 同构)
169
+
170
+ acp 配置按优先级**从低到高**叠加(后者覆盖前者,深度合并 `server` / `clients` 块):
171
+
172
+ | 优先级 | 路径 | 说明 |
173
+ | ------ | -------------------------------------------- | ------------------------------------ |
174
+ | 最低 | `~/.config/easbot/easbot.json` 的 `acp` 字段 | agent 集成层包装格式(全局) |
175
+ | ↑ | `~/.config/easbot/acp.json` | 全局独立配置 |
176
+ | ↑ | `<workspaceDir>/easbot.json` 的 `acp` 字段 | agent 集成层包装格式(项目级) |
177
+ | 最高 | `<workspaceDir>/.easbot/acp.json` | 项目级独立配置(由 `AcpCache` 持有) |
178
+
179
+ 两条覆盖规则:
180
+
181
+ - **项目级覆盖全局级**(`<workspaceDir>` 优先于 `~/.config/easbot/`)
182
+ - **`acp.json` 覆盖 `easbot.json`**(独立配置覆盖 agent 集成层的包装字段)
183
+
184
+ 要点:
185
+
186
+ - 项目级 `acp.json` **只有** `.easbot/acp.json` 一个位置(由 `AcpCache` 读写),
187
+ 不再支持项目根裸 `acp.json`;`EASBOT_CONFIG_DIR` 环境变量目录也不再参与加载链。
188
+ - `<workspaceDir>` 来自 `getInstance().directory`(Instance 由 CLI 入口统一注入)。
189
+ - **schema 单一来源**:各层读盘时**不套 schema**,仅在最后
190
+ `ConfigFileParse.merge(partials, ACPInfoACPConfigSchema)` 统一校验 + 应用默认值一次 ——
191
+ 避免每层各自填默认值造成「默认值污染」(错误的层覆盖真实的层)。
192
+ - **无配置文件 = 无初始值**:`ACPInfoACPConfigSchema` 的 `server` 是 `.optional()` 且**无 transform 兜底**,
193
+ 四层配置全部缺失时 `loadConfig()` 返回 `{}`(`server` 为 `undefined`,不会凭空造出 port=3000 的 server)。
194
+ 需要 server 默认值时用 `getServerConfig()`(内部以 `ACP_DEFAULT_SERVER_CONFIG` 为 base 合并)
195
+ 或 `ACPServerConfigSchema.parse({})`。
196
+ - 与 `packages/gateway` 的 `GatewayCache` 加载语义完全一致(同构范本)。
197
+
198
+ 支持:
199
+
200
+ - **JSONC 注释**(`//` / `/* ... */`)
201
+ - **`{env:VAR_NAME}` 替换**(自动从 `process.env` 读值)
202
+ - **深度合并 + schema 默认值**(`ConfigFileParse.merge(partials, ACPInfoACPConfigSchema)`)
203
+ - **State.holder 缓存**(按 workspace 分桶 + `AcpCache.resetState()` / `clearConfigCache()`)
204
+
205
+ ### 4. L2 缓存:AcpCache 命名空间
206
+
207
+ acp 子系统拥有独立的 L2 配置文件 `<workspaceDir>/.easbot/acp.json`(**不与**全局 `easbot.json` 冲突)。`AcpCache` 命名空间提供集中化的内存缓存(State.holder + 兼容降级),与 `NoteCache` 完全同源。
208
+
209
+ ```typescript
210
+ import { AcpCache } from '@easbot/acp';
211
+
212
+ // 1. 显式预热 —— EasbotAdapter.init() 已自动调用,通常无需手动调
213
+ await AcpCache.init();
214
+
215
+ // 2. 读取
216
+ const cfg = await AcpCache.getAcpJson(); // undefined 表示文件不存在
217
+ const exists = await AcpCache.exists(); // fs.existsSync 真实探测
218
+ const rootDir = await AcpCache.getRootDir(); // 当前 workspaceDir
219
+ const path = await AcpCache.getConfigPath(); // `<rootDir>/.easbot/acp.json` 绝对路径
220
+
221
+ // 3. 写盘(partial 字段会与现有 acp.json 合并,保留未指定字段)
222
+ await AcpCache.writeAcpJson({ server: { channel: 'http', port: 8080 } });
223
+
224
+ // 4. 测试隔离
225
+ AcpCache.resetState(); // 清 holder + 幂等标志
226
+ ```
227
+
228
+ > `EasbotAdapter.init()` 在 `initInstance()` 之后预热 `AcpCache`(必须晚于 `Instance.provide`,因为 cache 按 `Instance.directory` 分桶)。预热失败只降级为 warn 日志(后续首次读取走 lazy load 兜底),不阻塞 adapter 启动。
229
+
230
+ ### 5. 错误处理
231
+
232
+ 按 `spec/error-handling-standard.md` v1.9 分层:
233
+
234
+ | 层 | 路径 | acp 用法 |
235
+ | ----------- | ---------------------------------- | ------------------------------------------------------------------------------------------------- |
236
+ | L1 通用 | `NameErrors`(utils) | 跨 ≥ 2 模块通用(FileParse / InvalidArgument / OperationFailed / Timeout / Network / Validation) |
237
+ | L1.5 跨业务 | `BusinessErrors`(utils) | **本包不引入**(无跨业务包共用场景) |
238
+ | L2 包内 | `AcpError` namespace | 5 个核心错误类(见下方) |
239
+ | L3 业务反馈 | `ServiceError` + `ServiceErrorBus` | 5 个 ACP 专属 codes + hints(`registerBusinessErrors()` 注入) |
240
+
241
+ ```typescript
242
+ import { AcpError, NameErrors, registerBusinessErrors, ServiceError } from '@easbot/acp';
243
+
244
+ // 1. 注册业务反馈(一次;cli-handler 入口已自动调用)
245
+ await registerBusinessErrors();
246
+
247
+ // 2. L2 包内业务错误(5 个核心错误类)
248
+ throw new AcpError.ServerStartFailedError({
249
+ message: 'port 3000 is in use',
250
+ channel: 'websocket',
251
+ port: 3000,
252
+ code: 'EADDRINUSE',
253
+ });
254
+
255
+ throw new AcpError.ConfigNotFoundError({
256
+ message: 'acp config not found',
257
+ path: '/Users/xiaomo/demo/.easbot/acp.json',
258
+ });
259
+
260
+ // 3. caller 类型守卫
261
+ if (AcpError.ServerStartFailedError.isInstance(err)) {
262
+ console.log('server start failed:', err.data.port);
263
+ }
264
+
265
+ // 4. L1 通用错误(utils)—— 复用而非重新定义
266
+ throw new NameErrors.InvalidArgumentError({ message: 'invalid channel', param: 'channel' });
267
+ throw new NameErrors.FileParseError({
268
+ message: 'JSON parse failed',
269
+ filePath: '/path/to/acp.json',
270
+ });
271
+ throw new NameErrors.OperationFailedError({
272
+ message: 'acp server stop timeout',
273
+ operation: 'acp.server.stop',
274
+ });
275
+
276
+ // 5. L3 业务反馈(LLM 应得的提示;caller 抛 ServiceError)
277
+ throw new ServiceError({
278
+ code: 'CONNECTION_FAILED',
279
+ message: 'remote ACP agent unreachable',
280
+ details: { clientId: 'remote-1', channel: 'websocket' },
281
+ });
282
+ ```
283
+
284
+ **5 个 L2 错误类**:
285
+
286
+ | 类 | 触发 | 替代 v1.0 的 |
287
+ | -------------------------------------- | ------------------- | --------------------------------------------------------- |
288
+ | `AcpError.ConfigNotFoundError` | acp.json 不存在 | `ConfigNotFoundError` |
289
+ | `AcpError.ConfigValidationError` | schema 校验失败 | `ConfigValidationError` + `InvalidHostnameError` |
290
+ | `AcpError.ServerStartFailedError` | server 启动失败 | `ServerStartFailedError` |
291
+ | `AcpError.ClientConnectionFailedError` | client 连接失败 | `ClientConnectionFailedError` + `ClientDisconnectedError` |
292
+ | `AcpError.RpcParseFailedError` | JSON-RPC frame 损坏 | `RpcParseFailedError` |
293
+
294
+ **错误统一收敛到 `src/errors.ts`(v1.8)**:
295
+
296
+ ACP 的错误类、错误分类、类型守卫和错误工厂**全部定义在 `src/errors.ts`**,`src/types/` 只保留纯类型,不定义 error。
297
+
298
+ ```typescript
299
+ import {
300
+ AcpError, // NamedError.create 生成的错误类集合
301
+ ErrorType, // Adapter 错误分类枚举
302
+ createAdapterError,
303
+ isAdapterError,
304
+ } from '@easbot/acp';
305
+
306
+ // 错误类本体全部是 NamedError.create,schema 字段统一走 .data 读取
307
+ throw new AcpError.RoutingError({ message, code: 'session_not_found' });
308
+ console.log(error.data.code);
309
+
310
+ // 或走工厂
311
+ throw createAdapterError(ErrorType.NETWORK_ERROR, 'remote unreachable', { clientId: 'remote-1' });
312
+
313
+ // 类型判断用显式守卫(NamedError.create 的 isInstance 在跨包 d.ts 下不收窄)
314
+ if (isAdapterError(err)) {
315
+ console.log(err.data.type, err.data.context);
316
+ }
317
+ ```
318
+
319
+ `src/errors.ts` 额外收敛:4 个错误类(`AdapterError` / `RoutingError` / `ServiceModeConflictError` / `AdapterEnvironmentInitializationError`)、`ErrorType` 枚举、4 个 `InstanceType` 类型别名、4 个带类型谓词的守卫、`isAdapterErrorRetryable` / `isAdapterErrorFatal` 分类 helper、5 个错误工厂。
320
+
321
+ **已删除的 v1.0 错误类**(按 v1.9 分层走 utils `NameErrors`):
322
+
323
+ - ❌ `ConfigLoadFailedError` → `NameErrors.FileParseError({ filePath, cause })`
324
+ - ❌ `InvalidHostnameError` → `NameErrors.ValidationError({ message, param: 'hostname' })`
325
+ - ❌ `ServerStopFailedError` → `NameErrors.OperationFailedError({ operation: 'acp.server.stop' })`
326
+ - ❌ `ClientDisconnectedError` → `NameErrors.OperationFailedError({ operation: 'acp.client.disconnect' })`
327
+ - ❌ `CacheReadFailedError` / `CacheWriteFailedError` → `NameErrors.FileParseError` / `NameErrors.OperationFailedError`
328
+
329
+ ### 6. 国际化(i18n)
330
+
331
+ ACP 包所有用户文案(banner / help / 各命令输出 / 错误提示)走 `t()`,支持 `zh-CN`(默认)/ `en-US`。
332
+
333
+ ```typescript
334
+ import { t, I18n, registerI18nResources } from '@easbot/acp';
335
+
336
+ // 1. 翻译主函数
337
+ console.log(t('cli.cmd.init.description'));
338
+ // → "初始化 acp 工作区(创建 .easbot/acp.json)" (zh-CN)
339
+ // → "Initialize acp workspace (creates .easbot/acp.json)" (en-US)
340
+
341
+ // 2. 模板插值
342
+ console.log(t('cli.init.created', { vars: { path: '/Users/xiaomo/demo/.easbot/acp.json' } }));
343
+ // → "✓ acp 配置已初始化到 /Users/xiaomo/demo/.easbot/acp.json"
344
+
345
+ // 3. 显式指定 locale
346
+ console.log(t('cli.banner.title', { locale: 'en-US' }));
347
+
348
+ // 4. 缺译降级
349
+ console.log(t('cli.unknown.key', { fallback: 'fallback string' }));
350
+
351
+ // 5. 注册自定义资源(可选)
352
+ registerI18nResources('zh-CN', {
353
+ translation: {
354
+ 'acp.custom.key': '自定义中文文案',
355
+ },
356
+ });
357
+ ```
358
+
359
+ **locale 优先级**:调用方传入 > `process.env.EASBOT_LANG` > `process.env.LANG` > `I18n.defaultLocale`(zh-CN)
360
+
361
+ **翻译键命名**:`<module>.<action>.<result>`(cli.banner / cli.cmd / cli.init / cli.start / cli.status / cli.doctor / cli.config / acp.cli / acp.error)
362
+
363
+ **完整支持语言清单**:
364
+
365
+ | Locale | 文件 | 状态 |
366
+ | ------- | ------------------ | ------- |
367
+ | `zh-CN` | `locales/zh-CN.ts` | ✅ 默认 |
368
+ | `en-US` | `locales/en-US.ts` | ✅ |
369
+
370
+ **与 spec 对齐**:`spec/internationalization-standard.md` v2.1.0
371
+
372
+ ### 7. host ↔ 包解耦接口(ADR 0066)
373
+
374
+ ```typescript
375
+ import { setGlobalAdapter, setInstanceAdapter } from '@easbot/acp';
376
+
377
+ // agent bootstrap 时注入
378
+ setGlobalAdapter({
379
+ Path: {
380
+ home: '/Users/xiaomo',
381
+ data: '/Users/xiaomo/.local/share/easbot',
382
+ config: '/Users/xiaomo/.config/easbot',
383
+ cache: '/Users/xiaomo/.cache/easbot',
384
+ // ...
385
+ },
386
+ });
387
+ setInstanceAdapter({
388
+ directory: '/Users/xiaomo/projects/demo',
389
+ worktree: '/Users/xiaomo/projects/demo',
390
+ });
391
+ ```
392
+
393
+ ## CLI 命令一览
394
+
395
+ 5 个子命令(v0.1 落地范围):
396
+
397
+ ### lifecycle(3)
398
+
399
+ - **`init`** — 初始化工作区(创建 `.easbot/acp.json`)
400
+ - `--channel <stdio|http|websocket>`:默认通道
401
+ - `--port <n>`:端口(http/websocket)
402
+ - `--hostname <addr>`:主机地址
403
+ - `--force`:覆盖已存在配置
404
+ - `--json`:JSON 输出
405
+
406
+ - **`status`** — 显示配置摘要(server channel / port / clients)
407
+ - `--json`:JSON 输出
408
+
409
+ - **`doctor`** — 健康检查(config loadable / schema valid / deps)
410
+ - `--json`:JSON 输出
411
+
412
+ ### server(1)
413
+
414
+ - **`start`** — 启动 ACP Server,阻塞直到 Ctrl+C / SIGTERM
415
+ - `--channel <stdio|http|websocket>`
416
+ - `--port <n>`
417
+ - `--hostname <addr>`
418
+ - `--timeout <ms>`
419
+
420
+ ### external(1)
421
+
422
+ - **`config`** — get / set acp 配置
423
+ - `easbot-acp config get [key]`(`server.channel` 点号路径)
424
+ - `easbot-acp config set <key> <value>`(自动识别 number / boolean)
425
+
426
+ ### 全局选项(与 agent / note 一致)
427
+
428
+ - `--cwd <dir>`:工作区目录
429
+ - `--config <path>`:全局配置文件路径
430
+ - `--log-level <DEBUG|INFO|WARN|ERROR>`:默认 INFO
431
+ - `--print-logs`:把日志打到 stderr
432
+ - `--debug`:等价于 `--log-level DEBUG`
433
+
434
+ ### 用法示例
435
+
436
+ ```bash
437
+ # 独立 CLI 场景(用户在项目根目录)
438
+ $ easbot-acp init --channel websocket --port 3000
439
+ ✓ acp config initialized at /Users/xiaomo/demo/.easbot/acp.json
440
+
441
+ $ easbot-acp status
442
+ directory: /Users/xiaomo/demo
443
+ server.channel: websocket
444
+ server.port: 3000
445
+ server.hostname: localhost
446
+ server.enabled: true
447
+ clients: 0
448
+
449
+ $ easbot-acp config set server.port 8080
450
+ ✓ set server.port = 8080
451
+
452
+ $ easbot-acp start --channel websocket
453
+ [acp] server starting on ws://localhost:8080
454
+ ^C
455
+ [acp] server received signal, shutting down
456
+
457
+ # Agent CLI 场景(与 @easbot/agent 复用)
458
+ $ easbot acp start --channel http --port 3000
459
+ ```
460
+
461
+ > **start banner 的「地址」行按协议给出完整 URL**(由 `getAcpEndpointUrl` 单一真源构造):
462
+ > `ws://<hostname>:<port>` / `http://<hostname>:<port>` / `stdio://easbot`。
463
+ > 同一规则也用于 server 侧 `getServerUrl` 与 agent 注册到 Gateway 的 `address`,三处不会出现口径分裂。
464
+
465
+ ## 架构关系
466
+
467
+ ```
468
+ ┌─────────────────────────────────────────────────────────┐
469
+ │ @easbot/agent │
470
+ │ ├─ cli/commands/acp.ts (agent acp serve 子命令) │
471
+ │ └─ api/, session/, scheduler/, ... │
472
+ └────────────┬─────────────────────────────────────────────┘
473
+ │ 复用 handleAcpCli / mergeConfig 模式
474
+ ▼
475
+ ┌─────────────────────────────────────────────────────────┐
476
+ │ @easbot/acp (本包) │
477
+ │ ├─ cli.ts / cli-handler.ts (独立 CLI 入口) │
478
+ │ ├─ cache/ (AcpCache 命名空间) │
479
+ │ ├─ config/ (schema + loader + 便捷访问) │
480
+ │ ├─ errors.ts (AcpError namespace + ErrorType + 工厂 + 守卫) │
481
+ │ ├─ interfaces.ts (host ↔ 包解耦) │
482
+ │ ├─ server/ (acp-server / http-server / ws-server) │
483
+ │ ├─ client/ (acp-client / stdio / http / ws subscriber) │
484
+ │ ├─ connection/ (registry / router / types — types 为透出层,真源在 @easbot/utils) │
485
+ │ ├─ event/ (acp-event-bridge) │
486
+ │ ├─ performance/ (performance-monitor / streaming) │
487
+ │ ├─ error/ (error-handler / timeout-manager) │
488
+ │ ├─ types/ (adapter / channel / event — 只放纯类型,不含 error) │
489
+ │ ├─ bootstrap/ (EasbotAdapter) │
490
+ │ └─ easbot-agent.ts (EasBotAgent 实例) │
491
+ └─────────────────────────────────────────────────────────┘
492
+ ```
493
+
494
+ ## 与 note / gateway / memory 的差异
495
+
496
+ | 维度 | note | gateway | acp |
497
+ | ----------------- | ----------------- | -------------------------------------------- | -------------------------------------------- |
498
+ | L2 配置文件名 | `note.json` | `gateway.json` | `acp.json` |
499
+ | L2 cache 命名 | `NoteCache` | (无 L2 缓存) | `AcpCache` |
500
+ | 错误 namespace | `NoteError` | `GatewayError` | `AcpError` |
501
+ | 业务 codes 白名单 | 13 个 | (未注册 ServiceErrorBus) | 5 个 |
502
+ | 命令数 | 11 | 0(不走独立 CLI) | 5 |
503
+ | 顶层依赖 | LLM / DB / parser | hono / undici / ws | @agentclientprotocol/sdk |
504
+ | 配置加载 | 单文件 NoteCache | 四层合并(全局 + easbot.json 字段 + 项目级) | 四层合并(全局 + easbot.json 字段 + 项目级) |
505
+
506
+ ## 开发命令
507
+
508
+ ```bash
509
+ # 构建(tsup,输出 ESM + CJS + DTS)
510
+ pnpm --filter @easbot/acp build
511
+
512
+ # 监听模式构建
513
+ pnpm --filter @easbot/acp dev
514
+
515
+ # 类型检查
516
+ pnpm --filter @easbot/acp type-check
517
+
518
+ # Lint(biome)
519
+ pnpm --filter @easbot/acp lint
520
+
521
+ # Lint fix
522
+ pnpm --filter @easbot/acp lint:fix
523
+
524
+ # 单测
525
+ pnpm --filter @easbot/acp test:run
526
+
527
+ # 单测 + 覆盖率
528
+ pnpm --filter @easbot/acp test:coverage
529
+
530
+ # 清理 test fixture
531
+ pnpm --filter @easbot/acp test:clean
532
+ ```
533
+
534
+ ## 测试
535
+
536
+ ### 测试组织
537
+
538
+ 测试文件分两层放置(与 `note` / `memory` 包一致):
539
+
540
+ ```
541
+ packages/acp/
542
+ ├── tests/ # vitest 配置入口依赖(仅 3 个文件)
543
+ │ ├── test-utils.ts # runCli / runCliOutput / runCliWithInput 公共 helper
544
+ │ ├── setup.ts # NODE_ENV + loadEnv + AI_SDK_LOG_WARNINGS + 60s timeout
545
+ │ ├── xdg-bootstrap.ts # XDG_*_HOME → tmpdir 隔离
546
+ │ └── cli-e2e.test.ts # 真 subprocess 端到端(跨模块)
547
+ └── src/**/__tests__/ # 与代码同包(与 code 一个包 + __tests__ 放里)
548
+ ├── cache/__tests__/cache.test.ts
549
+ ├── config/__tests__/loader.test.ts
550
+ ├── config/__tests__/types.test.ts
551
+ ├── i18n/__tests__/translator.test.ts
552
+ ├── bootstrap/__tests__/bootstrap.test.ts
553
+ ├── client/__tests__/agent-service-registry.test.ts
554
+ ├── client/acp/__tests__/acp-client.test.ts
555
+ ├── error/__tests__/error-handler.test.ts
556
+ ├── error/__tests__/timeout-manager.test.ts
557
+ ├── performance/__tests__/benchmark.test.ts
558
+ ├── performance/__tests__/performance-monitor.test.ts
559
+ ├── performance/__tests__/streaming.test.ts
560
+ └── __tests__/interfaces.test.ts
561
+ └── __tests__/cli-handler.test.ts
562
+ ```
563
+
564
+ **原则**(剑哥"测试用例和代码一个包"):
565
+
566
+ - ✅ 业务模块单测放 `src/<module>/__tests__/` 与代码同包
567
+ - ✅ 单文件模块(如 `interfaces.ts`)放 `src/__tests__/`
568
+ - ✅ 跨模块端到端(cli-e2e)放 `tests/` 根
569
+ - ✅ vitest 配置入口(test-utils / setup / xdg-bootstrap)放 `tests/` 根
570
+
571
+ ### 测试统计
572
+
573
+ `pnpm --filter @easbot/acp test:run`:
574
+
575
+ | 文件 | 用例 | 描述 |
576
+ | ------------------------------------------- | ---------------- | ---------------------------------------------------------------- |
577
+ | `tests/cli-e2e.test.ts` | 29 (1 skip) | 真 subprocess 端到端 5 cmd |
578
+ | `src/__tests__/cli-handler.test.ts` | 26 | 5 cmd dispatch + COMMANDS_HELP + 错误路径(mock start 阻塞) |
579
+ | `src/config/__tests__/types.test.ts` | 30 | Zod schema 校验(Stdio / Http / WS / server / client / clients) |
580
+ | `src/config/__tests__/loader.test.ts` | 24 | 四层合并 + JSONC + env 替换 + 便捷访问 |
581
+ | `src/i18n/__tests__/translator.test.ts` | 23 | t() 翻译 + vars 插值 + locale 优先级 4 级 + formatLog |
582
+ | `src/__tests__/interfaces.test.ts` | 21 | IGlobal / IInstance / SDK 注入 + 便捷访问器 |
583
+ | `src/cache/__tests__/cache.test.ts` | 17 | AcpCache namespace 全 API |
584
+ | `src/error/__tests__/*.test.ts` | 多 | ErrorHandler + TimeoutManager(98-100%) |
585
+ | `src/performance/__tests__/*.test.ts` | 12+ | 监控 + 流式 + benchmark(97-100%) |
586
+ | `src/bootstrap/__tests__/bootstrap.test.ts` | 2 | AdapterBootstrap 复用 + channel 切换拒绝 |
587
+ | 其他老测试 | 多 | client / acp-client |
588
+ | **合计** | **336 (1 skip)** | 全套 ✓ |
589
+
590
+ ### 核心模块覆盖率
591
+
592
+ `pnpm --filter @easbot/acp test:coverage`:
593
+
594
+ | 模块 | Lines | 说明 |
595
+ | ---------------------------------------- | -------- | ------------------------------------ |
596
+ | `src/cache/index.ts` | **93%** | AcpCache namespace |
597
+ | `src/config/types.ts` | **96%** | Zod schema 校验 |
598
+ | `src/config/loader.ts` | **92%** | 四层合并加载 + 便捷访问 |
599
+ | `src/config/jsonc.ts` | **87%** | JSONC 注释剥离 + env 替换 |
600
+ | `src/interfaces.ts` | **95%** | host ↔ 包解耦三件套 |
601
+ | `src/i18n/translator.ts` | **84%** | t() 翻译 + locale 优先级 |
602
+ | `src/i18n/config.ts` | **89%** | I18n 常量 + 资源注册 |
603
+ | `src/cli-handler.ts` | **70%** | 5 cmd dispatch + renderBanner/Help |
604
+ | `src/bootstrap/index.ts` | **54%** | AdapterBootstrap(start 路径走 e2e) |
605
+ | `src/error/error-handler.ts` | **98%** | 错误处理 |
606
+ | `src/error/timeout-manager.ts` | **100%** | 超时管理 |
607
+ | `src/performance/performance-monitor.ts` | **100%** | 性能监控 |
608
+ | **核心模块均值** | **~85%** | 远超 60% 目标 |
609
+
610
+ **未覆盖模块**:cli.ts / server/* / client/* / connection/* / event/* / acp/* —— 真实运行时(需 `@agentclient/sdk` 子进程),不在 v0.1 测试范围。
611
+
612
+ ### 已知 Bug 待修复(acp-tests-coverage 任务发现)
613
+
614
+ 测试过程中发现 5 个真实 bug,**已沉淀不修**(剑哥"先沉淀三件套,后续统一修正"),建议下一心跳任务:
615
+
616
+ | ID | 位置 | 现象 | 建议修复 |
617
+ | --------- | ----------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------- |
618
+ | **Bug A** | `src/config/types.ts:388-391` | `validateAcpConfig` graceful 回退实际抛 ZodError(`server` 必填) | `InfoACPConfigSchema.server.default({})` 或 try/catch + DEFAULT 兜底 |
619
+ | **Bug B** | `src/cache/index.ts:224-242` | `AcpCache.writeAcpJson` 是顶层 shallow merge(非 deep merge) | 已知行为;CLI 走 `config set` 不受此影响 |
620
+ | **Bug C** | `src/config/jsonc.ts:33-40` | `{env:VAR}` 替换在 schema 校验**之前**;number 字段替换后 schema 失败 | 加类型注解 `{env:VAR:number}` 或 schema 重试 `Number()` |
621
+ | **Bug D** | `src/config/loader.ts:165-193` | `loadAcpConfigFromDir` 读路径不一致 —— 写 `.easbot/acp.json`、读 `acp.json` | 让 loader 也探测 `dir/.easbot/acp.json` |
622
+ | **Bug E** | `src/i18n/translator.ts:32,142-148` | `registerI18nResources` 不刷新 `localeCache`;运行时注册资源不生效 | factory 同时 `localeCache.delete(locale)` |
623
+
624
+ 详见 `.easbot/knowledge/tasks/acp-tests-coverage/findings.md §10`。
625
+
626
+ ### 后续任务(acp-cli-format-unify)
627
+
628
+ **剑哥反馈**:"你 client 的输出 human json 参考 note 和 memory 使用 `@easbot/terminal` 实现统一风格的 format"。
629
+
630
+ **当前现状**:acp `cli-handler.ts` 输出与 note / memory 不一致(自拼字符串 vs `printHuman([formatKnowledgeXxx(...)], { title, boxed: true })`)。
631
+
632
+ **关键原则**:`@easbot/terminal` 是**通用工具包**,format 函数**统一建在 terminal 包**(与 `format-knowledge.ts` 同源),acp 包只 import + 调用,**不**在 acp 包内建 format。
633
+
634
+ **改造方案**(独立任务):
635
+
636
+ 1. `@easbot/terminal/src/format/format-acp.ts` 新增 4 个 format:
637
+ - `formatAcpInit / formatAcpStatus / formatAcpDoctor / formatAcpStart`
638
+ 2. `terminal/src/index.ts` re-export
639
+ 3. acp `cli-handler.ts` 改用 `printHuman([formatAcpXxx(...)], { title, boxed: true })`
640
+ 4. `terminal/src/format/__tests__/format-acp.test.ts` 测 format 函数
641
+
642
+ 详见 `.easbot/knowledge/tasks/acp-tests-coverage/findings.md §13`。
643
+
644
+ ## 设计原则
645
+
646
+ 1. **host ↔ 包解耦**:所有运行时依赖通过 `setGlobalAdapter / setInstanceAdapter` 显式注入;agent 包 / 独立 CLI / 测试 统一语义
647
+ 2. **四层配置加载**:参考 `packages/gateway/src/config/loader.ts`,JSONC + env 替换 + State.holder 三件套
648
+ 3. **错误分层**:包内 `AcpError`(业务语义)+ `NameErrors`(通用)+ `ServiceError + ServiceErrorBus`(LLM 业务反馈)
649
+ 4. **CLI 与 handler 分离**:`handleAcpCli(args, deps)` 入口独立可测;agent / 独立 CLI / MCP server 复用同一份派发逻辑
650
+ 5. **不持有业务实例**:acp 包不依赖 `@easbot/agent` 内部模块;只通过 `EasbotAdapter` 暴露 server 启动能力(由 agent bootstrap 注入 AdapterRegistry)
651
+ 6. **缓存独立**:`AcpCache` 完全独立于全局 `easbot.json`;项目级 `.easbot/acp.json` 单文件管理
652
+
653
+ ## 拆分历史
654
+
655
+ | 版本 | 关键变化 |
656
+ | ---------------------- | --------------------------------------------------------------------------------------------------------------- |
657
+ | **早期(agent 包内)** | `packages/agent/src/adapter/` —— ACP 适配层与 agent 包耦合 |
658
+ | **v0.1(2026-10-06)** | 拆分独立 workspace 包 `@easbot/acp`;补 cli / errors / cache / config loader;agent 改为复用 `@easbot/acp` 入口 |
659
+
660
+ ## 参考
661
+
662
+ - [`@agentclientprotocol/sdk`](https://github.com/agentclientprotocol/typescript-sdk) —— ACP 协议官方 TypeScript SDK
663
+ - `packages/note/src/cli-handler.ts` —— CLI handler 范本
664
+ - `packages/gateway/src/config/loader.ts` —— 四层配置加载范本
665
+ - `packages/note/src/cache/index.ts` —— AcpCache 模式 E 同源参考
666
+ - `packages/note/src/errors.ts` —— AcpError 模式同源参考
667
+ - `ADR 0066` —— host ↔ 包解耦接口规范
668
+ - `ADR 0102 Phase 2.1` —— ServiceError + NamedError 业务反馈通道
@@ -0,0 +1 @@
1
+ 'use strict';var chunkITV7SWGU_cjs=require('./chunk-ITV7SWGU.cjs');require('./chunk-SNWAB3QJ.cjs'),require('./chunk-DX35VSAT.cjs'),require('./chunk-BNSJ6COS.cjs'),require('./chunk-VVGGER23.cjs'),require('./chunk-Z3YEK7DD.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"AdapterBootstrap",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.t}});Object.defineProperty(exports,"EasbotAdapter",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.s}});Object.defineProperty(exports,"createAdapterEnvironmentInitializationError",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.r}});
@@ -0,0 +1 @@
1
+ export{t as AdapterBootstrap,s as EasbotAdapter,r as createAdapterEnvironmentInitializationError}from'./chunk-D7S7ARXV.mjs';import'./chunk-B3ANZALB.mjs';import'./chunk-33M2R2US.mjs';import'./chunk-PATHHDWE.mjs';import'./chunk-2KOCPHVP.mjs';import'./chunk-NHXAYBZH.mjs';import'./chunk-HQBRVVXS.mjs';