@1agents/acp-service 0.1.4 → 0.2.0

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
@@ -1,155 +1,130 @@
1
1
  # @1agents/acp-service
2
2
 
3
- > DreamMate Network 的 **ACP Agent Runtime Service**:为 Claude Code、Grok、Codex 等 ACP 智能体提供统一的持久化执行、会话重绑与全双工 WebSocket 桥接服务。
4
- > 默认监听 **36812** 端口,向本机 `dreammate-node`(固定 36908)自动报备与接受探活。
3
+ ACP Agent Runtime Service for Codex, Grok Build, Claude Code and other Agents supported by `@scottzx/1acp`. Version 0.2 uses **ACP v1 JSON-RPC 2.0 over WebSocket**. Each connection selects one Agent; each session keeps that Agent and its workspace when reconnected.
5
4
 
6
- ---
5
+ ## Run
7
6
 
8
- ## 架构定位
7
+ Requires Node.js 22.13 or later and `@scottzx/1acp ^0.15.1`. The runtime's per-session launch argv and transient credentials APIs are required by Provider Profiles. Local development uses the runtime workspace package directly; no manual tarball installation is needed. Published service installations require the matching runtime version to be available in the registry.
9
8
 
10
- 在 DreamMate Network 四层体系中,`acp-service` 作为平级的执行平面(L1/L2 运行时服务)存在:
9
+ Run from the monorepo root:
11
10
 
11
+ ```sh
12
+ pnpm install --frozen-lockfile
13
+ pnpm --filter @scottzx/1acp build
14
+ pnpm --filter @1agents/acp-service build
15
+ pnpm start:service serve --host 127.0.0.1 --port 36812 --no-report
12
16
  ```
13
- Control Plane / Web 客户端 / IM 网关
14
- │
15
- ├─ 1. 探 36908 发现服务与端口
16
- ▼
17
- ┌───────────────────────┐
18
- │ dreammate-node │ ◄── 固定 36908 (L0.5 基础设施)
19
- └───────────▲───────────┘
20
- │ 2. 报备 & /health 周期探活
21
- ┌───────────┴───────────┐
22
- │ acp-service │ ◄── 3. 直连 36812 执行 ACP 全双工会话
23
- │ (默认 36812) │
24
- ├───────────────────────┤
25
- │ 底座依赖: │
26
- │ - @scottzx/1acp │ (携带 Grok _x.ai/* 与 Claude Auth-Env 治理)
27
- │ - dreammate-network │ (L0 协议契约)
28
- │ - dreammate-node │ (节点身份与客户端报备)
29
- └───────────────────────┘
30
- ```
31
17
 
32
- - **单端口复用**:
33
- - `GET /health`:存活探针,报告 node_id、当前活跃会话数与后台任务数。
34
- - `GET /manifest`:DreamMate Network 标准节点清单。
35
- - `WebSocket ws://<host>:36812/`:升级并接管 ACP JSON-RPC 消息流。
18
+ The default port is 36812. Without `--no-report`, the service reports to the local DreamMate node. Agent executables and their authentication must be available to the service process. `ACP_STATE_DIR` overrides the default `~/.1agents/acpx-state` directory for runtime records, turn journals and ACP replay data.
19
+
20
+ The standalone HTTP/WebSocket service does not read standard input and keeps running when it is closed or redirected from `/dev/null`. Stop the service with `SIGINT` or `SIGTERM`; both clean up managed Agent sessions before exiting.
36
21
 
37
- ---
22
+ ```ts
23
+ import { serveAcpService } from '@1agents/acp-service';
24
+ const service = await serveAcpService({ host: '127.0.0.1', port: 36812, report: false });
25
+ // Later: await service.close();
26
+ ```
38
27
 
39
- ## 安装与运行
28
+ HTTP endpoints:
40
29
 
41
- ### 1. 全局安装或作为 CLI 运行
30
+ - `GET /health`: service health and active session/task counts.
31
+ - `GET /manifest`: DreamMate service discovery, ACP version, custom transport and Agent endpoint paths. Profiles listed here describe registered launch configurations, not a successful installation/authentication probe.
32
+ - `GET /services`: current service/session counts.
42
33
 
43
- ```bash
44
- cd services/acp-service
45
- npm install
46
- npm run build
34
+ ## ACP connections
47
35
 
48
- # 启动服务(默认监听 0.0.0.0:36812,自动向 36908 报备)
49
- npm start
36
+ Connect to `ws://127.0.0.1:36812/agents/codex`, `/agents/grok-build`, `/agents/claude`, or another registered Agent name. `/` selects Codex. Each WebSocket text message contains one UTF-8 JSON-RPC object. Batch messages and the former `action/event` envelopes are rejected. WebSocket is a custom transport permitted by ACP, not the standard stdio transport.
50
37
 
51
- # 或使用 CLI 任意指定参数
52
- node dist/bin/acp-service.js --port 36812 --host 0.0.0.0
38
+ Initialize before sending session requests:
53
39
 
54
- # 单机调试(仅本地回环可见,不向 node-agent 报备)
55
- node dist/bin/acp-service.js --host 127.0.0.1 --no-report
40
+ ```json
41
+ {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}}
56
42
  ```
57
43
 
58
- ### 2. 作为库引入
44
+ Create a session using an absolute existing directory:
59
45
 
60
- ```ts
61
- import { serveAcpService } from '@1agents/acp-service';
46
+ ```json
47
+ {"jsonrpc":"2.0","id":2,"method":"session/new","params":{"cwd":"/absolute/project","mcpServers":[]}}
48
+ ```
62
49
 
63
- const { port, server, close } = await serveAcpService({
64
- port: 36812,
65
- host: '0.0.0.0',
66
- report: true, // 启动时自动向 dreammate-node (36908) 报备
67
- });
50
+ Use the **returned service session ID** for subsequent requests. Native Agent IDs are distinct and may appear in `_meta["1agents"].agentSessionId`; they must not replace the service ID.
68
51
 
69
- console.log(`ACP Service running on port ${port}`);
52
+ ```json
53
+ {"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":"returned-session-id","prompt":[{"type":"text","text":"Explain this project"}]}}
70
54
  ```
71
55
 
72
- ---
56
+ Output arrives as `session/update` notifications. The prompt request receives its response only when the turn settles, with a standard `stopReason`. Runtime failures return JSON-RPC errors. `session/cancel` is a notification; cancellation settles the original prompt request.
73
57
 
74
- ## 暴露的能力与接口
58
+ | Method | Behavior |
59
+ | --- | --- |
60
+ | `session/new` | Creates a new persistent session with a server-generated ID. |
61
+ | `session/load` | Attaches an existing session and replays its complete recorded ACP conversation before responding. |
62
+ | `session/resume` | Attaches without replaying conversation history. |
63
+ | `session/prompt` | Runs a turn; ordinary overlapping prompts are rejected as busy. |
64
+ | `session/cancel` | Cancels the current turn; has no RPC response. |
65
+ | `session/close` | Cancels work and releases live resources while retaining persistent history. |
66
+ | `session/list` | Lists this endpoint's bound, resumable sessions, optionally filtered by cwd. Returns the complete list without a next cursor. |
67
+ | `session/delete` | Closes live resources and tombstones the service session so it cannot be resumed or listed. Runtime history retention follows the runtime's deletion behavior. |
68
+ | `session/set_mode` | Selects an advertised native Agent mode. |
69
+ | `session/set_config_option` | Changes an advertised native option and returns the resulting configuration options. |
70
+ | `session/request_permission` | Server-to-client request; the client returns an advertised option ID or a cancelled outcome. |
75
71
 
76
- ### 1. HTTP 探测接口
72
+ Methods and content remain subject to the selected Agent's capabilities. The installed runtime supports text followed by image/audio attachments. Resource blocks and text interleaved after attachments are rejected explicitly rather than reordered. Modes/configuration are returned from the Agent, not synthesized as universal choices. Session creation and loading return the original ACP config options, including select tags and grouped choices; loading also republishes the current advertised slash commands even when the runtime emits no new command event.
77
73
 
78
- - `GET http://<host>:36812/health`
79
- ```json
80
- {
81
- "status": "ok",
82
- "node_id": "nigVtDS1s521CNTRL",
83
- "service": "acp-service",
84
- "kind": "agent_runtime",
85
- "sessions": 0,
86
- "background_tasks": 0,
87
- "uptime": 12.34
88
- }
89
- ```
74
+ The service currently advertises no connection authentication methods. Native Agent authentication remains owned by its runtime configuration and the negotiated session authentication extension.
90
75
 
91
- - `GET http://<host>:36812/manifest`
92
- 返回符合 `@1agents/dreammate-network` 规范的完整 Manifest。
76
+ ## Reconnection and history
93
77
 
94
- ### 2. WebSocket 动作接口(ACP 桥接)
78
+ A dropped WebSocket does not stop the Agent turn. Reinitialize the new connection and call `session/resume` or `session/load` with the same service ID and workspace. A live session has one controlling connection; a new owner displaces the old connection for that session only. SDK stream cancellation and socket closure may arrive in either order; transport cleanup closes the readable stream at most once.
95
79
 
96
- 客户端建立 `ws://<host>:36812/` 连接后,发送 JSON 消息:
80
+ Pending permissions, Grok questionnaires and plan confirmations stay with the session. They are sent as new RPC requests on the new connection, linked internally to the original one-shot operation. Their existing deadlines remain in effect. Late replies from old connections, duplicate replies, expired requests and already-cancelled operations cannot resolve them again.
97
81
 
98
- | 动作 (`action`) | 描述 | 关键参数 |
99
- | :--- | :--- | :--- |
100
- | `ensure_session` | 创建或恢复 ACP 会话 | `sessionId`, `workspacePath`, `agentType`, `permissionMode`, `responsePolicy` |
101
- | `prompt` | 发送用户提示词与附件 | `sessionId`, `text`, `attachments`, `responsePolicy` |
102
- | `respond_permission` | 响应工具调用的权限审批 | `sessionId`, `requestId`, `decision` |
103
- | `respond_ask_user_question` | 响应 Grok `_x.ai/ask_user_question` | `sessionId`, `requestId`, `answers` |
104
- | `respond_exit_plan_mode` | 响应 Grok `_x.ai/exit_plan_mode` | `sessionId`, `requestId`, `decision` |
105
- | `set_permission_mode` | 运行时调整权限等级 | `sessionId`, `mode` (`approve-reads`, `yolo` 等) |
106
- | `cancel_turn` | 取消当前正在执行的轮次 | `sessionId` |
107
- | `get_history` | 获取当前会话权威历史切片 | `sessionId` |
108
- | `close_session` | 结束并销毁会话 | `sessionId` |
82
+ A prompt RPC interrupted by a transport loss cannot receive its old response on a new connection. Standard clients reload history; 1agents clients additionally reconcile the persistent turn journal through negotiated notifications. Runtime turns continue writing the ACP replay log even while no socket is connected.
109
83
 
110
- ### 3. `responsePolicy`:人机流式 vs 智能体摘要
84
+ ACP bindings and append-only updates live under `ACP_STATE_DIR/acp`. A service restart restores runtime records and recorded history; it does not recreate vanished JavaScript approval promises. The existing turn journal records interrupted running/queued turns according to runtime recovery policy. An incomplete final log record is reported as an error rather than silently treated as complete history.
111
85
 
112
- `ensure_session` 与 `prompt` 都接受可选字段 `responsePolicy`:
86
+ Sessions imported from older/native records can resume and use the application history extension. They cannot claim complete `session/load` replay when no complete ACP log exists; that method returns an explicit error for those sessions.
113
87
 
114
- | 值 | 默认 | 适用 | 线上推送 |
115
- | :--- | :--- | :--- | :--- |
116
- | `stream` | 是 | 人类 UI(Web Chat、终端) | 全量 `text_delta` / `tool_call` / `turn_state` |
117
- | `summary` | 否 | 设备 B 上的调度 Agent | 轮次结束只推 `turn_complete` + `done`,附带 `sessionRef` |
88
+ ## Negotiated 1agents extensions
118
89
 
119
- ```json
120
- {
121
- "action": "prompt",
122
- "sessionId": "task-456",
123
- "text": "重构 backend/server.go 的鉴权逻辑",
124
- "responsePolicy": "summary"
125
- }
126
- ```
90
+ Clients opt in using `clientCapabilities._meta["1agents"] = { "version": 1 }` during initialization. The server advertises its extension version under `agentCapabilities._meta["1agents"]`. Plain ACP clients can create, prompt, approve tools, cancel and resume without these extensions.
127
91
 
128
- `summary` 结束时的收敛事件:
92
+ Custom launch/session options are carried only in `_meta["1agents"]`, including `systemContext`, `permissionMode`, `responsePolicy`, explicitly supplied child `env`, and the trusted provider-profile `launch` descriptor. Launch argv/environment validation and transient credential handling are preserved from the 1agents provider-profile integration. Credentials are not copied into ACP bindings or transcript metadata.
129
93
 
130
- ```json
131
- {
132
- "event": "turn_complete",
133
- "sessionId": "task-456",
134
- "status": "completed",
135
- "responsePolicy": "summary",
136
- "resultText": "已重构鉴权逻辑,修改了 2 个文件,测试通过。",
137
- "sessionRef": {
138
- "sessionId": "task-456",
139
- "turnId": 5,
140
- "sessionReaderUrl": "http://<device-A>:7777"
141
- }
142
- }
94
+ | Extension | Purpose |
95
+ | --- | --- |
96
+ | `_1agents/session/import` | Explicitly resumes a pre-migration native session ID and returns a new service session ID. |
97
+ | `_1agents/session/history` | Returns the runtime/native history projection used by existing chat views. |
98
+ | `_1agents/session/permission_mode` | Changes the service permission policy, independently of native Agent mode. |
99
+ | `_1agents/session/cancel_queued` | Cancels a queued managed request by its durable request ID. |
100
+ | `_1agents/session/fork` | Uses the runtime's optional fork capability. Imported/forked native history is not advertised as complete ACP replay. |
101
+ | `_1agents/session/authenticate`, `_1agents/session/logout` | Native session authentication controls. |
102
+ | `_1agents/sessions/close_all` | Closes all managed sessions. |
103
+ | `_1agents/session/meta` | Notification containing native models, modes and other UI capabilities. |
104
+ | `_1agents/events/<name>` | Application notifications such as `turn_sync`, `turn_state`, `turn_terminal`, `history_response`, `session_taken_over`, background tasks and interaction timeouts. |
105
+ | `_x.ai/ask_user_question`, `_x.ai/exit_plan_mode` | Server-to-client requests preserving Grok-specific questionnaire/plan semantics. Clients answer with the corresponding JSON-RPC result. |
106
+
107
+ Nonstandard metadata is namespaced; standard `session/update` content is still available without knowing the application view fields. `responsePolicy: "summary"` suppresses incremental conversation output while preserving the replay log and live permission/questions. The final prompt response carries the summary in `_meta["1agents"]`, and opted-in clients receive `turn_complete`. Managed turn IDs, idempotency keys and queue state are application extensions, not replacements for JSON-RPC request IDs.
108
+
109
+ ## Upgrade from 0.1
110
+
111
+ Upgrade the service and 1agents Go client together. Old `action/event` WebSocket clients are not supported by 0.2. The Go `internal/acpwire` client converts existing chat view messages to standard ACP and negotiated extensions; frontend view state can remain unchanged. It stores the returned service session ID for future reconnects and explicitly imports older native IDs when needed.
112
+
113
+ The npm `@1agents/acp-bridge` package is now a small launcher depending on `@1agents/acp-service ^0.2.0`. Release in order: `@scottzx/1acp 0.15.1`, `@1agents/acp-service 0.2.0`, then the dependent launcher. Install from the monorepo root with `pnpm install --frozen-lockfile`; the service uses `workspace:^` for the runtime, and pnpm converts it to a version range during packing. Development supervision locates `services/1acp/packages/service`; package filling must not overwrite the launcher with the former server implementation.
114
+
115
+ ## Verify
116
+
117
+ ```sh
118
+ npm run typecheck
119
+ npm test
143
120
  ```
144
121
 
145
- 权限审批、`ask_user_question`、`exit_plan_mode` 仍会实时下发——否则轮次会卡住。需要推理日志或工具细节时,用 `sessionRef.sessionReaderUrl` 走 `1session` / session-reader 按需下钻。
122
+ Tests use the official ACP SDK over real WebSockets, cover session lifecycle and permission reconnects, and drive the installed 1acp runtime through a deterministic external stdio Agent. They require no model API key. Existing real-provider smoke tests in the 1agents backend remain opt-in.
146
123
 
147
- Manifest 能力位:`agent.response_policy`。
124
+ ## Local harness discovery
148
125
 
149
- ---
126
+ `GET /agents` returns `{ "agents": [...] }`, a fresh local filesystem inventory shared by DSH and 1agents_app. Each entry includes the canonical ACP registry `id`, display `label`, native CLI `installed`, and `chat_ready`. Legacy app fields (`type`, capabilities, cc-connect transport, integration status and install guidance) remain available; `claude` uses the legacy app type `claudecode`.
150
127
 
151
- ## 协议与底层支持
128
+ Discovery checks PATH, `~/.local/bin`, `~/.grok/bin`, and installed adapter package launch files. A registered native ACP command is ready when its executable exists. Adapter-backed harnesses are ready when the adapter is installed, or when their native CLI and `npx` are installed; the latter uses the runtime's existing adapter download behavior when a session launches. Having `npx` or `uvx` alone does not expose uninstalled harnesses. Scanning neither executes agents nor downloads packages, and readiness does not verify credentials or model access. Detection-only frameworks remain in the inventory with `chat_ready: false`.
152
129
 
153
- - **Claude Code**:支持第三方 Anthropic 兼容端点,通过 `1acp` 的 `auth-env.ts` 自动清洗 `ANTHROPIC_AUTH_TOKEN` 与 `ANTHROPIC_API_KEY`,规避握手挂死。
154
- - **Grok Build**:原生支持 `_x.ai/ask_user_question` 问答扩展与 `_x.ai/exit_plan_mode` 退出计划模式扩展。
155
- - **Codex / Gemini / OpenClaw 等**:支持标准 ACP 子进程生命周期调度。
130
+ The service launcher uses the same local command resolution, including absolute paths to user-local binaries. The catalog originates from 1agents_app's former Go detector; consumers no longer probe their own host or maintain separate detection tables. `discoverAgents()` is also exported for embedded service consumers and includes local executable paths; the HTTP response omits these paths.
@@ -27,7 +27,7 @@ function getPackageVersion() {
27
27
  }
28
28
  }
29
29
  catch { }
30
- return '0.1.4';
30
+ return '0.2.0';
31
31
  }
32
32
  function printServeHelp(binName) {
33
33
  console.log(`用法: ${binName} serve [选项]
@@ -0,0 +1,26 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import { type Stream } from '@agentclientprotocol/sdk';
3
+ import type { WebSocket } from 'ws';
4
+ import { AcpState } from './acp-state.js';
5
+ type RecordValue = Record<string, any>;
6
+ export interface RuntimeBackend {
7
+ dispatch(peer: RuntimePeer, command: RecordValue): Promise<void>;
8
+ sessions: Map<string, RecordValue>;
9
+ record(id: string): Promise<RecordValue | undefined>;
10
+ status(id: string): Promise<RecordValue>;
11
+ history(id: string): Promise<RecordValue[]>;
12
+ }
13
+ /** Transport framing only; SDK owns method validation and RPC correlation. */
14
+ export declare function webSocketStream(ws: WebSocket): Stream;
15
+ /** A runtime subscriber owned by exactly one live ACP connection. */
16
+ export declare class RuntimePeer {
17
+ private readonly receive;
18
+ readyState: number;
19
+ _acpxReqHost?: string;
20
+ constructor(receive: (event: RecordValue) => void);
21
+ send(raw: string): void;
22
+ command(backend: RuntimeBackend, payload: RecordValue): Promise<RecordValue[]>;
23
+ }
24
+ /** Each endpoint binds the connection to one Agent, including session reloads. */
25
+ export declare function attachAcpConnection(ws: WebSocket, req?: IncomingMessage, backend?: RuntimeBackend, state?: AcpState): import("@agentclientprotocol/sdk").AgentConnection | undefined;
26
+ export {};