@yitom/acp-client 0.1.13 → 0.1.14

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
@@ -26,11 +26,13 @@
26
26
  - **生命周期全托管**:
27
27
  负责跨平台后台进程拉起(Windows PID 级联杀进程)、Stdio ndJson 传输桥接、协议初始化(Initialize 握手)、温进程池长驻复用、错误诊断(stderr 尾部日志聚合)。
28
28
  - **会话状态机与容错**:
29
- 自动处理 `resume` → `load` → `new` 会话恢复流程,处理模型方言(models 数组/对象)、无 MCP 自动降级与网络抖动重试。
29
+ 自动处理 `resume` → `load` → `new` 会话恢复流程,处理模型方言(models 数组/对象)、默认保留 MCP 配置重试;提供健康监测后,在下一轮 prompt 前恢复失效的工具挂载。
30
30
  - **解耦的事件钩子与审批**:
31
31
  工具调用审批、权限请求、会话流式更新采用标准的回调与事件驱动,宿主自由决定如何确认(命令行交互 / 桌面弹窗 / Web 消息)。
32
32
  - **应用资源目录(单目录接口)**:
33
33
  宿主只传 `resources: { directory }`(`AGENTS.md` + `skills/<name>/SKILL.md`),SDK 负责读取、摘要、配置合并、资格/版本门、会话级记录与温复用标签;详见 `docs/api-reference.md §5` 与 `examples/app-resources-demo.ts`。
34
+ - **会话级 Code Mode(PTC)**:
35
+ Agent 在 `initialize` 声明 `agentCapabilities._meta.toolsMode.values` 后,`createSession({ codeMode: 'on' })` 会通过 `_meta.toolsMode = 'ptc'` 请求该表现层;模型改为写代码、以 `tools.<name>()` 调用全部可见工具(含本次会话挂载的 MCP 工具)。未声明的 Agent 不会被请求,也不会出现“开关无效”的假支持。详见 `docs/api-reference.md §1`。
34
36
 
35
37
  ---
36
38
 
@@ -41,32 +43,12 @@
41
43
  | `codex-acp` | ChatGPT | `~/.codex/auth.json` / 自定义供应商 API Key | 支持隔离 `CODEX_HOME` 生成 `config.toml` |
42
44
  | `claude` | Claude | `~/.claude.json` / `ANTHROPIC_API_KEY` | 自动复用本机 Claude Code CLI 登录态 |
43
45
  | `cursor-cli` | Cursor | `CURSOR_API_KEY` / 系统 Keychain 登录态 | 自动探测 `%LOCALAPPDATA%\cursor-agent\agent.cmd` |
44
- | `deepseek` | DeepSeek | `DEEPSEEK_API_KEY` 或 `~/.dsh/.credentials.yaml` | 缺凭证提前判停;`DSH_BIN` 指向稳定安装,`DSH_PACKAGE` pin 版本 |
46
+ | `deepseek` | DeepSeek | `DEEPSEEK_API_KEY` | 缺 key 提前拦截判停,避免子进程秒退 |
45
47
  | `gemini` | Gemini | `~/.gemini/oauth_creds.json` / `GEMINI_API_KEY` | 自动探测 OAuth 凭证与系统 Key |
46
48
  | `copilot` | Copilot | `~/.copilot/config.json` / `GH_TOKEN` | 自动提取 `loggedInUsers` 凭证列表 |
47
49
  | `opencode` | OpenCode | `$XDG_DATA_HOME/opencode/auth.json` | 遵循 XDG / `%LOCALAPPDATA%` 规范 |
48
50
  | `agy` | agy | 官方桥接器免密直连 | `tryDirectSessionFirst` 免鉴权直通 |
49
51
 
50
- ### DeepSeek(dsh)在新机器上接入
51
-
52
- 不需要改任何本机 profile,三步即可复现:
53
-
54
- ```bash
55
- node scripts/setup-dsh-acp.mjs # 装/复用用户级运行时并自检 ACP 握手
56
- export DEEPSEEK_API_KEY=sk-... # 或在 dsh/桌面版里登录(二选一)
57
- ```
58
-
59
- 如果用户本机根本没装/没登录 harness,宿主可以直接用内置的「URL + Token」表单,免环境变量:
60
-
61
- ```typescript
62
- import { saveDeepseekProvider, getDeepseekProviderStatus } from '@yitom/acp-client'
63
-
64
- getDeepseekProviderStatus() // { configured, baseUrl?, isOfficial, hasApiKey }
65
- saveDeepseekProvider({ baseUrl: 'https://api.deepseek.com', apiKey: 'sk-...' }) // URL 留空即官方端点
66
- ```
67
-
68
- SDK 会按 `DSH_BIN` → 用户级稳定安装(自动取已装最高版本)→ `DSH_PACKAGE` → `bunx` 的顺序解析启动目标,并在 spawn 时附加 `--patch` 覆盖层把会话模型修正为 `deepseek-flash`(= DeepSeek-V4.1-Flash;桌面端的 `1017` 只是 UI 徽标)。详见 [API 参考 §DeepSeek](./docs/api-reference.md)。
69
-
70
52
  ---
71
53
 
72
54
  ## 🚀 快速上手 (1 分钟代码)
@@ -172,26 +154,19 @@ With `@yitom/agy-acp-map` 0.1.24 / 0.1.25 / 0.1.26, `resources.directory` is del
172
154
 
173
155
  Normal disconnect closes owned sessions on agents advertising `sessionCapabilities.close` before terminating the transport/process. Requests are bounded to two seconds; failures are logged and teardown continues. This permits session resource cleanup on Windows as well.
174
156
 
175
- ### OpenCode ACP question compatibility
157
+ ## MCP 长会话恢复
176
158
 
177
- When a host supplies application resources, OpenCode 1.18.35 and 2.0.6 receive a child-process-only
178
- OPENCODE_CONFIG_CONTENT overlay setting permission.question to deny. Its upstream ACP event
179
- dispatcher omits native questions in 1.18.35 and cancels form.created in 2.0.6.
180
- The v2 adapter prepares only the question overlay; native rules and skills remain unverified. The SDK preserves existing providers,
181
- models, MCP servers, instructions and all unrelated permission rules, including shorthand
182
- permission defaults. It never edits project/global OpenCode config files or authentication homes.
183
- Overlay and isolated session configuration use the same policy.
159
+ SDK 导出 `McpConnectionHealth`(传输/发现观测)与 `AcpMcpSessionRecovery`(通用恢复管理器),不依赖 Electron、窗口、管道或应用名称。
160
+ 宿主把 MCP 工具发现和连接关闭通知给监测器,并通过 `createSession({ mcpServers, mcpHealth })` 绑定;随后 `AcpClient.promptSession()` / 会话 `prompt()` 会在已知断连后先恢复原会话、重新下发相同 MCP 配置并等待新的工具发现,再发送本轮消息。
161
+ 失败阻止发送;不创建替代会话,不重发 prompt。取消、断连、恢复互斥、RPC 与发现超时统一由 SDK 处理。详见 [API 参考:MCP 恢复](./docs/api-reference.md#mcp-长会话恢复)。
162
+ 没有监测信号时不凭空推断 MCP 可用性,也不以恢复 RPC 成功冒充工具可用;工具发现仍不等同于模型目录/工具执行验证。
163
+ 此能力属于客户端兜底,不能修复 Agent 自身工作区服务回收后的内部状态。
184
164
 
185
- Inspect resourceReport.openCodeQuestions: fallback + prepared means the overlay was prepared,
186
- not proof that the runtime applied it. Unknown releases report unverified + unchanged; no semver
187
- range or permission capability is treated as proof of question support. Hosts should provide
188
- an available MCP question tool or a textual question, wait for the user, and keep security
189
- approval separate. Standard ACP request_permission remains independent; elicitation support
190
- is negotiated separately and is not implied by permissions or this fallback.
165
+ ## 测试入口
191
166
 
192
- GitHub Actions builds and smoke-checks Linux, Windows and macOS packages and uploads a dist
193
- artifact per OS. Only version-tag pushes publish to npm; branch/PR builds do not publish.
167
+ 本项目统一使用 Vitest。Bun 用于安装依赖及启动 package.json 脚本;直接执行 bun test 会启动 Bun 内置测试器,不是项目测试入口。
194
168
 
195
- ### 宿主接入的通用生命周期
196
-
197
- `src/client/sdk-client.ts` 统一官方 SDK 流桥接、请求超时与方法类型推导;`connectSdkClient` 可传第四参 `{ name }`。`src/client/session-open.ts` 统一恢复/新建、原生扩展回退与有界工具输出恢复。`preserveMcpOnRetry: true` 保留重试时的 MCP 工具;缺省保持旧客户端的裸调回退策略。窗口、IPC、诊断日志由宿主提供,不进入协议包。
169
+ ```bash
170
+ bun run test # 全量 Vitest
171
+ bun run test:mcp # 仅 MCP 恢复与客户端接入测试
172
+ ```
@@ -1,6 +1,8 @@
1
+ import type { AcpMcpHealthMonitor } from '../mcp/connection-health';
1
2
  import { type AcpAvailableCommand } from '../session/available-commands';
3
+ import { type AcpCodeMode } from '../session/code-mode';
2
4
  import type { AcpAgentQuota } from '../contracts';
3
- import { type InitializeResponse, type McpServer } from '@agentclientprotocol/sdk';
5
+ import { type InitializeResponse } from '@agentclientprotocol/sdk';
4
6
  import type { AcpConnectionStatus, AcpPermissionOutcome, AcpProxySettings, AcpRuntimeInfo, AcpSessionRestoreMethod, AppError, InkdownVirtualResource } from "../contracts";
5
7
  import { type Result } from "../contracts";
6
8
  import type { AppResourceReport } from '../resources/app-resources';
@@ -83,6 +85,8 @@ export declare class AcpSessionHandle {
83
85
  /** 主动获取/刷新配额(优先缓存,过期或无缓存时触发适配器探针) */
84
86
  getQuota(): Promise<AcpAgentQuota | null>;
85
87
  get availableCommands(): AcpAvailableCommand[] | undefined;
88
+ /** Cancel an in-flight prompt or MCP recovery. */
89
+ cancel(): Promise<Result<void, AppError>>;
86
90
  /** 修改会话配置项(如模型 ID、模式等) */
87
91
  setConfigOption(configId: string, value: string | boolean): Promise<Result<unknown, AppError>>;
88
92
  }
@@ -94,6 +98,8 @@ export declare class AcpSessionHandle {
94
98
  * - 可在任意 Node.js 项目、CLI 命令行工具或 Web 服务中直接复用。
95
99
  */
96
100
  export declare class AcpClient {
101
+ private readonly mcpRecovery;
102
+ private suppressRecoveryUpdates;
97
103
  private status;
98
104
  private readonly commandsCache;
99
105
  private readonly quotaCache;
@@ -161,7 +167,14 @@ export declare class AcpClient {
161
167
  /** 创建或恢复会话 */
162
168
  createSession(options?: {
163
169
  resumeSessionId?: string | null;
164
- mcpServers?: McpServer[];
170
+ mcpServers?: unknown[];
171
+ /** Host MCP discovery/close observations enable automatic recovery before prompts. */
172
+ mcpHealth?: AcpMcpHealthMonitor;
173
+ /**
174
+ * 会话级 code mode(PTC):模型改为写代码、以 `tools.<name>()` 调用全部可见工具,
175
+ * 包括本次会话挂载的 MCP 工具。仅对声明支持的运行时生效(见 supportsCodeMode)。
176
+ */
177
+ codeMode?: AcpCodeMode;
165
178
  }): Promise<Result<AcpSessionHandle, AppError>>;
166
179
  /** 向指定会话发送消息 */
167
180
  promptSession(sessionId: string, promptText: string, options?: {
@@ -179,6 +192,8 @@ export declare class AcpClient {
179
192
  * 恢复会话因送达状态未知,按新代次重新附带一次(有界、可诊断,不声称 exactly-once)。
180
193
  */
181
194
  private buildCompatPrepend;
195
+ /** Cancel recovery before notifying the agent; prompts are never automatically replayed. */
196
+ cancelSession(sessionId: string): Promise<Result<void, AppError>>;
182
197
  /** 动态更新会话配置项(如模型 ID) */
183
198
  setSessionConfigOption(sessionId: string, configId: string, value: string | boolean): Promise<Result<unknown, AppError>>;
184
199
  /** 断开连接并清理资源 */
@@ -1,5 +1,5 @@
1
1
  import { type AcpPermissionOutcome, type InkdownVirtualResource } from "../contracts";
2
- import { type ClientApp, type RequestPermissionRequest, type SessionNotification } from '@agentclientprotocol/sdk';
2
+ import { type ClientApp } from '@agentclientprotocol/sdk';
3
3
  import type { AcpTerminalManager } from './acp-terminal';
4
4
  export interface AcpClientHandlerDeps {
5
5
  getWorkspaceRoot: () => string | null;
@@ -12,10 +12,10 @@ export interface AcpClientHandlerDeps {
12
12
  */
13
13
  onPermission: (payload: {
14
14
  sessionId?: string;
15
- params: RequestPermissionRequest;
15
+ params: Record<string, unknown>;
16
16
  }) => Promise<AcpPermissionOutcome>;
17
17
  /** session/update 通知透传(回放压制由调用方做) */
18
- onSessionUpdate: (params: SessionNotification) => void;
18
+ onSessionUpdate: (params: Record<string, unknown>) => void;
19
19
  }
20
20
  /**
21
21
  * Agent → Client 回调:permission + fs + terminal(声明能力后才会收到)。
@@ -0,0 +1,47 @@
1
+ import type { AcpMcpHealthMonitor } from '../mcp/connection-health';
2
+ export declare class AcpMcpRecoveryCancelledError extends Error {
3
+ }
4
+ export interface AcpMcpRecoveryEvent {
5
+ type: 'started' | 'failed' | 'discovered' | 'cancelled';
6
+ sessionId: string;
7
+ method?: string;
8
+ }
9
+ export interface AcpMcpRecoveryOptions {
10
+ request: AcpMcpRecoveryRequest;
11
+ getCapabilities: () => {
12
+ resume: boolean;
13
+ load: boolean;
14
+ };
15
+ isConnected: () => boolean;
16
+ isBusy?: (sessionId: string) => boolean;
17
+ onSuppressUpdates?: (suppress: boolean) => void;
18
+ onEvent?: (event: AcpMcpRecoveryEvent) => void;
19
+ discoveryTimeoutMs?: number;
20
+ requestTimeoutMs?: number;
21
+ }
22
+ export type AcpMcpRecoveryRequest = (method: string, params: unknown, signal?: AbortSignal) => Promise<unknown>;
23
+ export interface AcpMcpSessionBinding {
24
+ sessionId: string;
25
+ cwd: string;
26
+ mcpServers: unknown[];
27
+ sessionMeta?: Record<string, unknown>;
28
+ monitor: AcpMcpHealthMonitor;
29
+ }
30
+ /** One manager per ACP connection owner. Does not own MCP transports or send prompts. */
31
+ export declare class AcpMcpSessionRecovery {
32
+ private readonly options;
33
+ private readonly sessions;
34
+ private generation;
35
+ private suppressing;
36
+ private active?;
37
+ constructor(options: AcpMcpRecoveryOptions);
38
+ get isRecovering(): boolean;
39
+ register(input: AcpMcpSessionBinding): void;
40
+ cancel(sessionId?: string): void;
41
+ reset(): void;
42
+ ensureReady(sessionId: string): Promise<void>;
43
+ private emit;
44
+ private recover;
45
+ private boundedRequest;
46
+ private bounded;
47
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ChildProcessWithoutNullStreams } from 'node:child_process';
2
- import { type ClientApp, type ClientConnection, type ClientContext, type AgentRequestMethod, type AgentRequestParamsByMethod, type AgentRequestResponsesByMethod, type Stream } from '@agentclientprotocol/sdk';
2
+ import { type ClientApp, type ClientConnection, type ClientContext, type Stream } from '@agentclientprotocol/sdk';
3
3
  /** SDK 请求超时:沿用旧手搓传输的 120s,显式透传 */
4
4
  export declare const ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
5
5
  export interface SdkStreamHandle {
@@ -23,16 +23,12 @@ export declare function createSdkStreamHandle(child: ChildProcessWithoutNullStre
23
23
  */
24
24
  export declare function connectSdkClient(child: ChildProcessWithoutNullStreams, configure: (app: ClientApp) => void,
25
25
  /** 所属运行时 id:仅日志/隔离用,不改变 SDK 建连形态;缺省向后兼容单 codex 路径 */
26
- runtimeId?: string, options?: {
27
- name?: string;
28
- }): {
26
+ runtimeId?: string): {
29
27
  app: ClientApp;
30
28
  connection: ClientConnection;
31
29
  streamHandle: SdkStreamHandle;
32
30
  };
33
31
  /** 带显式超时的 agent.request:超时 abort(触发 $/cancel_request)并拒绝 */
34
- export declare function sdkRequest<Method extends AgentRequestMethod>(agent: ClientContext, method: Method, params: AgentRequestParamsByMethod[Method], timeoutMs?: number): Promise<AgentRequestResponsesByMethod[Method]>;
35
- /** Explicit generic overload for vendor extensions and legacy callers. */
36
32
  export declare function sdkRequest<Response, Params>(agent: ClientContext, method: string, params: Params, timeoutMs?: number): Promise<Response>;
37
33
  /** Close owned sessions before transport/process teardown; unsupported failures stay bounded. */
38
34
  export declare function closeAcpSessions(agent: ClientContext, sessionIds: Iterable<string>, timeoutMs?: number): Promise<string[]>;
@@ -1,7 +1,5 @@
1
- import { type McpServer } from '@agentclientprotocol/sdk';
2
- import type { AcpSessionRestoreAttempt, AcpSessionRestoreMethod } from '../contracts';
1
+ import type { AcpSessionRestoreAttempt, AcpSessionRestoreMethod } from "../contracts";
3
2
  export type AcpRpcRequest = (method: string, params?: unknown) => Promise<unknown>;
4
- export declare function isAuthenticationRequired(message: string): boolean;
5
3
  export interface RestoreOrCreateSessionInput {
6
4
  /** SDK 调用源:(method, params) => agent.request(method, params)(超时由 sdk-client 显式透传) */
7
5
  request: AcpRpcRequest;
@@ -9,11 +7,18 @@ export interface RestoreOrCreateSessionInput {
9
7
  resumeSessionId: string | null;
10
8
  resumeSupported: boolean;
11
9
  loadSupported: boolean;
12
- /** 客户端自带的窗口 MCP stdio 配置 */
13
- mcpServers?: McpServer[];
14
- /** Keep the same tools on retry; hosts requiring reader tools should enable this. */
10
+ /** 客户端自带的 MCP server(Inkdown 工具);Agent 不支持 HTTP 传输时传空数组 */
11
+ mcpServers?: unknown[];
12
+ /** Default true: never silently remove tools after a failed session/new. */
15
13
  preserveMcpOnRetry?: boolean;
14
+ /** Runtime-specific native options; not a standard ACP system prompt field. */
16
15
  sessionMeta?: Record<string, unknown>;
16
+ /**
17
+ * Ask the runtime for its code-mode (PTC) presentation on this session.
18
+ * Callers must gate this on `supportsCodeMode(agentCapabilities, runtimeId)`;
19
+ * the helper only applies it to new|load|resume requests.
20
+ */
21
+ codeMode?: boolean;
17
22
  /** session/load 回放期间回调(主进程用来压制 UI 更新) */
18
23
  onSuppressUpdates?: (suppress: boolean) => void;
19
24
  /** 测试可设为 0 */
@@ -21,6 +26,7 @@ export interface RestoreOrCreateSessionInput {
21
26
  log?: (level: 'info' | 'warn', message: string, data?: Record<string, unknown>) => void;
22
27
  }
23
28
  export interface RestoreOrCreateSessionResult {
29
+ /** Agent accepted the supplied MCP descriptors; not proof of tool execution. */
24
30
  mcpServersAccepted: boolean;
25
31
  recoveredToolOutputs?: Array<{
26
32
  toolCallId: string;
@@ -34,6 +40,7 @@ export interface RestoreOrCreateSessionResult {
34
40
  requestedSessionId?: string;
35
41
  restoreAttempts: AcpSessionRestoreAttempt[];
36
42
  }
43
+ export declare function isAuthenticationRequired(message: string): boolean;
37
44
  /**
38
45
  * SDK 瞬时错误判定:连接层故障(关闭/中断/超时/管道)可重试 1 次;
39
46
  * 协议层拒绝(cancelled / method-not-found / invalid-params / 业务 not-found)
@@ -48,7 +55,7 @@ export declare function isTransientAcpTransportError(error: unknown): boolean;
48
55
  * resume/load 对瞬时传输错误最多再试 1 次;失败明细写入 restoreAttempts。
49
56
  */
50
57
  export declare function restoreOrCreateAcpSession(input: RestoreOrCreateSessionInput): Promise<RestoreOrCreateSessionResult>;
51
- /** Preserve MCP when a bridge rejects only its optional native resource extension. */
58
+ /** Retry rejected native extensions without changing the MCP descriptors. */
52
59
  export declare function requestSessionWithResources(request: AcpRpcRequest, method: string, params: Record<string, unknown>, sessionMeta?: Record<string, unknown>): Promise<{
53
60
  result: Record<string, unknown>;
54
61
  nativeSessionAccepted: boolean;
@@ -119,11 +119,6 @@ export interface AcpConfigOptionValue {
119
119
  value: string;
120
120
  name: string;
121
121
  description?: string;
122
- /**
123
- * 分组名(ACP 允许 select 选项嵌套 `{group, name, options}`)。
124
- * 解析时拍平为一维列表并保留分组标签,value 保持 agent 原始编码不变。
125
- */
126
- group?: string;
127
122
  }
128
123
  export interface AcpConfigOption {
129
124
  configId: string;
@@ -272,28 +267,6 @@ export interface AcpProxySettings {
272
267
  host: string;
273
268
  port: number;
274
269
  }
275
- /**
276
- * DeepSeek(dsh)自定义端点/凭证:宿主表单「URL + Token」的落库形状。
277
- * 落库后由 SDK 在 spawn 时转成 `DEEPSEEK_BASE_URL` / `DEEPSEEK_API_KEY`,
278
- * 不写 harness 自己的 `$DSH_HOME/.credentials.yaml`(留在官方位置)。
279
- */
280
- export interface AcpDeepseekProviderStatus {
281
- configured: boolean;
282
- /** 已落库的端点;未配置时不返回 */
283
- baseUrl?: string;
284
- /**
285
- * 是否使用官方默认端点(未配置或配置值等于官方地址)。
286
- * 宿主据此渲染「官方 / 自定义」二选一。
287
- */
288
- isOfficial: boolean;
289
- hasApiKey: boolean;
290
- }
291
- export interface AcpDeepseekProviderSavePayload {
292
- /** 空串/未填时回落官方端点 */
293
- baseUrl?: string;
294
- /** 空串时保留已存的 Key(只改端点不重填 Token 的常见操作) */
295
- apiKey?: string;
296
- }
297
270
  export declare const CODEX_ACP_NPM_PACKAGE: '@agentclientprotocol/codex-acp';
298
271
  export declare const CLAUDE_ACP_NPM_PACKAGE: '@agentclientprotocol/claude-agent-acp';
299
272
  export declare const DEEPSEEK_DSH_NPM_PACKAGE: '@deepseek-ai/dsh';