@xiaozhi-pro/connector 0.0.0-stage → 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 qwen-audio-agent contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # XiaozhiPro Connector (Node)
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
+ Node 版实现,发布为 npm 包 `@xiaozhi-pro/connector`。
4
+
5
+ 安装、运行、API Key、自动探测和通信接口见 [../README.md](../README.md)。
6
+
7
+ ## 目录结构
8
+
9
+ ```text
10
+ node-connector/
11
+ ├── package.json
12
+ ├── README.md
13
+ ├── publish.md
14
+ ├── LICENSE
15
+ ├── bin/
16
+ │ └── xiaozhi-pro-connector.js
17
+ ├── src/
18
+ │ ├── cli.js
19
+ │ ├── connector.js
20
+ │ ├── acp.js
21
+ │ ├── detection.js
22
+ │ └── log.js
23
+ └── test/
24
+ ├── acp.test.js
25
+ ├── connector.test.js
26
+ └── detection.test.js
27
+ ```
28
+
29
+ ## 文件说明
30
+
31
+ | 文件 | 作用 |
32
+ | --- | --- |
33
+ | `package.json` | npm 包配置、依赖、`bin` 命令、发布文件白名单 |
34
+ | `publish.md` | npm 发布流程 |
35
+ | `bin/xiaozhi-pro-connector.js` | CLI 入口,调用 `src/cli.js` |
36
+ | `src/cli.js` | 参数解析、自动探测、启动多个 Connector |
37
+ | `src/detection.js` | 探测本地 Agent,组装启动命令、参数和环境变量 |
38
+ | `src/acp.js` | 本地 ACP 子进程:stdio 读写、JSON-RPC、session、权限 |
39
+ | `src/connector.js` | SaaS WebSocket 与本地 ACP 的桥接、消息队列、重连 |
40
+ | `src/log.js` | 统一日志输出 |
41
+ | `test/acp.test.js` | ACP 子进程测试:initialize / session / prompt |
42
+ | `test/connector.test.js` | WS 网关与 ACP 桥接测试 |
43
+ | `test/detection.test.js` | Agent 探测测试 |
44
+ | `LICENSE` | Apache-2.0 |
45
+
46
+ ## npm 包文件
47
+
48
+ `package.json` 中 `files` 只发布:
49
+
50
+ ```text
51
+ bin/
52
+ src/
53
+ README.md
54
+ LICENSE
55
+ ```
56
+
57
+ `test/` 不进入 npm 包。
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../src/cli.js';
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@xiaozhi-pro/connector",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "XiaozhiPro Agent Connector: bridge local ACP agents to XiaozhiPro Agent Gateway",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "bin": {
8
+ "xiaozhi-pro-connector": "bin/xiaozhi-pro-connector.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "start": "node ./bin/xiaozhi-pro-connector.js",
18
+ "test": "node --test test/*.test.js"
19
+ },
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "dependencies": {
24
+ "ws": "^8.18.0"
25
+ }
26
+ }
package/src/acp.js ADDED
@@ -0,0 +1,256 @@
1
+ import { spawn } from 'node:child_process';
2
+ import readline from 'node:readline';
3
+ import { log } from './log.js';
4
+
5
+ const PROTOCOL_VERSION = 1;
6
+ const STDERR_LIMIT = 12000;
7
+ const SESSION_TIMEOUT = 60000;
8
+ const DEBUG_AGENT = process.env.XIAOZHI_CONNECTOR_DEBUG_AGENT === '1';
9
+
10
+ function sleep(ms) {
11
+ return new Promise((resolve) => setTimeout(resolve, ms));
12
+ }
13
+
14
+ export class ACPProcess {
15
+ constructor(command, args, cwd, permissionMode, env = {}) {
16
+ this.command = command;
17
+ this.args = args || [];
18
+ this.cwd = cwd;
19
+ this.permissionMode = permissionMode || 'native';
20
+ this.env = env || {};
21
+ this.proc = null;
22
+ this.rl = null;
23
+ this.pending = new Map();
24
+ this.nextId = 1;
25
+ this.onNotification = null;
26
+ this.sessionId = null;
27
+ this.activeMessageId = null;
28
+ this.activeDeviceId = '';
29
+ this.currentText = [];
30
+ this.stderrTail = '';
31
+ }
32
+
33
+ async start() {
34
+ if (this.proc && this.proc.exitCode === null && this.proc.signalCode === null) {
35
+ return;
36
+ }
37
+ log(`启动 ACP Agent: ${this.command} ${this.args.join(' ')}`.trim());
38
+ const env = { ...process.env, ...this.env };
39
+ const childArgs = [...this.args];
40
+ const options = {
41
+ cwd: this.cwd,
42
+ env,
43
+ stdio: ['pipe', 'pipe', 'pipe'],
44
+ };
45
+ if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(this.command)) {
46
+ options.shell = true;
47
+ options.windowsVerbatimArguments = true;
48
+ }
49
+ this.proc = spawn(this.command, childArgs, options);
50
+ this.proc.on('exit', () => {
51
+ this.rejectPending(new Error(`ACP Agent 已退出: ${this.stderrTail.slice(-500) || 'unknown'}`));
52
+ try {
53
+ this.rl?.close();
54
+ } catch {
55
+ // ignore
56
+ }
57
+ this.rl = null;
58
+ this.proc = null;
59
+ });
60
+ this.rl = readline.createInterface({ input: this.proc.stdout, crlfDelay: Infinity });
61
+ this.rl.on('line', (line) => this._handleLine(line));
62
+ this.proc.stderr.on('data', (chunk) => {
63
+ const text = chunk.toString('utf8');
64
+ this.stderrTail = (this.stderrTail + text).slice(-STDERR_LIMIT);
65
+ if (DEBUG_AGENT) {
66
+ for (const line of text.split(/\r?\n/).filter(Boolean)) log(`agent: ${line}`);
67
+ }
68
+ });
69
+
70
+ const result = await this.request(
71
+ 'initialize',
72
+ {
73
+ protocolVersion: PROTOCOL_VERSION,
74
+ clientCapabilities: { elicitation: { form: {} } },
75
+ clientInfo: { name: 'xiaozhi-pro-connector', version: '1.0.0' },
76
+ },
77
+ 15000,
78
+ );
79
+ if (result?.protocolVersion !== PROTOCOL_VERSION) {
80
+ throw new Error(`ACP 协议版本不兼容: ${result?.protocolVersion}`);
81
+ }
82
+ log('ACP initialize 完成');
83
+ }
84
+
85
+ async ensureSession() {
86
+ if (!this.sessionId) {
87
+ const session = await this.request('session/new', { cwd: this.cwd, mcpServers: [] }, SESSION_TIMEOUT);
88
+ this.sessionId = session.sessionId;
89
+ log(`ACP session 创建完成: ${this.sessionId}`);
90
+ }
91
+ return this.sessionId;
92
+ }
93
+
94
+ async request(method, params, timeout) {
95
+ const id = this.nextId++;
96
+ const key = String(id);
97
+ const promise = new Promise((resolve, reject) => {
98
+ if (timeout) {
99
+ const timer = setTimeout(() => {
100
+ this.pending.delete(key);
101
+ reject(new Error(`ACP 请求超时: ${method}`));
102
+ }, timeout);
103
+ this.pending.set(key, { resolve, reject, timer });
104
+ } else {
105
+ // 不传 timeout 表示无限等待(如 session/prompt),进程退出时由 rejectPending 兜底
106
+ this.pending.set(key, { resolve, reject, timer: null });
107
+ }
108
+ });
109
+
110
+ try {
111
+ this._write({ jsonrpc: '2.0', id, method, params: params || {} });
112
+ return await promise;
113
+ } finally {
114
+ const pending = this.pending.get(key);
115
+ if (pending) {
116
+ if (pending.timer) clearTimeout(pending.timer);
117
+ this.pending.delete(key);
118
+ }
119
+ }
120
+ }
121
+
122
+ async notify(method, params) {
123
+ this._write({ jsonrpc: '2.0', method, params: params || {} });
124
+ }
125
+
126
+ async respond(id, result) {
127
+ this._write({ jsonrpc: '2.0', id, result });
128
+ }
129
+
130
+ async cancelSession() {
131
+ if (!this.sessionId) return;
132
+ await this.notify('session/cancel', { sessionId: this.sessionId });
133
+ }
134
+
135
+ async stop() {
136
+ const proc = this.proc;
137
+ if (!proc) return;
138
+ const exit = new Promise((resolve) => proc.once('exit', resolve));
139
+ if (proc.exitCode === null && proc.signalCode === null) {
140
+ proc.kill('SIGTERM');
141
+ }
142
+ const raced = await Promise.race([exit, sleep(3000)]);
143
+ if (raced === undefined && proc.exitCode === null && proc.signalCode === null) {
144
+ proc.kill('SIGKILL');
145
+ }
146
+ await exit;
147
+ try {
148
+ this.rl?.close();
149
+ } catch {
150
+ // ignore
151
+ }
152
+ this.rl = null;
153
+ this.proc = null;
154
+ this.rejectPending(new Error('ACP Agent 已停止'));
155
+ }
156
+
157
+ _write(message) {
158
+ if (!this.proc?.stdin?.writable) {
159
+ throw new Error('ACP Agent 未启动');
160
+ }
161
+ this.proc.stdin.write(`${JSON.stringify(message)}\n`);
162
+ }
163
+
164
+ _handleLine(line) {
165
+ let message;
166
+ try {
167
+ message = JSON.parse(line);
168
+ } catch {
169
+ return;
170
+ }
171
+ try {
172
+ this._handleMessage(message);
173
+ } catch (err) {
174
+ // Agent 回的消息格式意外时只记日志,绝不能让进程崩掉
175
+ log(`${DEBUG_AGENT ? 'agent' : 'ACP'} 消息处理异常: ${err.message}`);
176
+ }
177
+ }
178
+
179
+ _handleMessage(message) {
180
+ const id = message.id === undefined || message.id === null ? null : String(message.id);
181
+ if (id && (Object.prototype.hasOwnProperty.call(message, 'result') || Object.prototype.hasOwnProperty.call(message, 'error'))) {
182
+ const pending = this.pending.get(id);
183
+ if (!pending) return;
184
+ clearTimeout(pending.timer);
185
+ this.pending.delete(id);
186
+ if (message.error) {
187
+ pending.reject(new Error(message.error.message || 'ACP 请求失败'));
188
+ } else {
189
+ pending.resolve(message.result || {});
190
+ }
191
+ return;
192
+ }
193
+
194
+ if (message.method === 'session/update') {
195
+ this._handleUpdate(message.params || {});
196
+ } else if (message.method === 'session/request_permission') {
197
+ this._handlePermission(message.id, message.params || {}).catch((err) => {
198
+ log(`权限响应失败: ${err.message}`);
199
+ });
200
+ }
201
+ }
202
+
203
+ _extractText(update) {
204
+ const type = update.sessionUpdate;
205
+ if (type !== 'agent_message_chunk' && type !== 'agent_thought_chunk') return '';
206
+ // ACP 协议中 content 是单个 ContentBlock,兼容个别 Agent 发数组的情况
207
+ const blocks = Array.isArray(update.content) ? update.content : [update.content];
208
+ const parts = [];
209
+ for (const block of blocks) {
210
+ if (block && block.type === 'text') parts.push(String(block.text || ''));
211
+ }
212
+ const text = parts.join('');
213
+ if (type === 'agent_message_chunk') this.currentText.push(text);
214
+ return text;
215
+ }
216
+
217
+ _handleUpdate(params) {
218
+ if (!this.onNotification) return;
219
+ const update = params.update || {};
220
+ const text = this._extractText(update);
221
+ if (!text) return;
222
+ Promise.resolve(
223
+ this.onNotification({
224
+ type: 'update',
225
+ text,
226
+ role: 'agent',
227
+ device_id: this.activeDeviceId,
228
+ message_id: this.activeMessageId,
229
+ }),
230
+ ).catch((err) => log(`发送 update 失败: ${err.message}`));
231
+ }
232
+
233
+ async _handlePermission(id, params) {
234
+ if (id === undefined || id === null) return;
235
+ const options = params.options || [];
236
+ if (this.permissionMode === 'full') {
237
+ for (const option of options) {
238
+ if (option && (option.kind === 'allow_once' || option.kind === 'allow_always')) {
239
+ log(`自动允许权限: ${option.optionId}`);
240
+ await this.respond(id, { outcome: { outcome: 'selected', optionId: option.optionId } });
241
+ return;
242
+ }
243
+ }
244
+ }
245
+ log('拒绝权限请求');
246
+ await this.respond(id, { outcome: { outcome: 'rejected' } });
247
+ }
248
+
249
+ rejectPending(error) {
250
+ for (const pending of this.pending.values()) {
251
+ clearTimeout(pending.timer);
252
+ pending.reject(error);
253
+ }
254
+ this.pending.clear();
255
+ }
256
+ }
package/src/cli.js ADDED
@@ -0,0 +1,119 @@
1
+ import { AGENT_LABELS, AGENT_ORDER, collectTargets } from './detection.js';
2
+ import { Connector } from './connector.js';
3
+ import { log } from './log.js';
4
+
5
+ const VERSION = '1.0.1';
6
+ const SERVER = 'wss://api.qlcloud.top/xzp';
7
+
8
+ const HELP = `Usage: xiaozhi-pro-connector [options]
9
+
10
+ Options:
11
+ --token <token> 小智Pro API Key,也可用 XIAOZHI_PRO_TOKEN
12
+ -h, --help 显示帮助
13
+ -v, --version 显示版本
14
+ `;
15
+
16
+ function parseArgs(argv) {
17
+ const opts = {
18
+ server: SERVER,
19
+ token: process.env.XIAOZHI_PRO_TOKEN || '',
20
+ cwd: process.cwd(),
21
+ permission_mode: 'native',
22
+ command: '',
23
+ agentArgs: [],
24
+ help: false,
25
+ version: false,
26
+ };
27
+
28
+ for (let i = 0; i < argv.length; i++) {
29
+ const arg = argv[i];
30
+ if (arg === '--') {
31
+ opts.agentArgs.push(...argv.slice(i + 1));
32
+ break;
33
+ }
34
+ if (arg === '-h' || arg === '--help') {
35
+ opts.help = true;
36
+ continue;
37
+ }
38
+ if (arg === '-v' || arg === '--version') {
39
+ opts.version = true;
40
+ continue;
41
+ }
42
+ if (arg.startsWith('--')) {
43
+ let [key, value] = arg.slice(2).split('=', 2);
44
+ if (value === undefined) {
45
+ value = argv[++i];
46
+ }
47
+ switch (key) {
48
+ case 'token': opts.token = value; break;
49
+ case 'cwd': opts.cwd = value; break;
50
+ case 'permission-mode': opts.permission_mode = value; break;
51
+ case 'command': opts.command = value; break;
52
+ default:
53
+ if (value !== undefined) i--;
54
+ opts.agentArgs.push(arg);
55
+ if (value !== undefined) opts.agentArgs.push(value);
56
+ }
57
+ continue;
58
+ }
59
+ opts.agentArgs.push(arg);
60
+ }
61
+ return opts;
62
+ }
63
+
64
+ function buildTargets(opts) {
65
+ if (opts.command) {
66
+ return [{
67
+ agent_id: 'acp',
68
+ name: AGENT_LABELS.acp,
69
+ command: opts.command,
70
+ agent_args: [...opts.agentArgs],
71
+ agent_env: {},
72
+ }];
73
+ }
74
+ return collectTargets(opts.permission_mode, opts.agentArgs);
75
+ }
76
+
77
+ async function main() {
78
+ const opts = parseArgs(process.argv.slice(2));
79
+ if (opts.help) {
80
+ console.log(HELP);
81
+ return 0;
82
+ }
83
+ if (opts.version) {
84
+ console.log(VERSION);
85
+ return 0;
86
+ }
87
+ if (!opts.token) {
88
+ console.error('缺少 --token 或环境变量 XIAOZHI_PRO_TOKEN');
89
+ return 1;
90
+ }
91
+
92
+ const targets = buildTargets(opts);
93
+ if (!targets.length) {
94
+ const supported = AGENT_ORDER.filter((x) => x !== 'acp').map((x) => AGENT_LABELS[x]).join(' / ');
95
+ console.error(`未检测到可用 Agent,请先安装:${supported}`);
96
+ return 1;
97
+ }
98
+
99
+ if (targets.length === 1) {
100
+ log(`自动探测到 ACP Agent: ${targets[0].name} (${targets[0].command})`);
101
+ } else {
102
+ log(`自动探测到 ${targets.length} 个 ACP Agent: ${targets.map((t) => t.name).join(', ')}`);
103
+ }
104
+
105
+ const connectors = targets.map((target) => new Connector({ ...opts, ...target }));
106
+ const stop = () => connectors.forEach((connector) => connector.stop());
107
+ process.on('SIGINT', stop);
108
+ process.on('SIGTERM', stop);
109
+
110
+ await Promise.allSettled(connectors.map((connector) => connector.run()));
111
+ return 0;
112
+ }
113
+
114
+ main().then((code) => {
115
+ process.exitCode = code;
116
+ }).catch((err) => {
117
+ console.error(err.stack || err.message);
118
+ process.exitCode = 1;
119
+ });
@@ -0,0 +1,261 @@
1
+ import WebSocket from 'ws';
2
+ import { ACPProcess } from './acp.js';
3
+ import { log } from './log.js';
4
+
5
+ function sleep(ms) {
6
+ return new Promise((resolve) => setTimeout(resolve, ms));
7
+ }
8
+
9
+ export class Connector {
10
+ constructor(options) {
11
+ this.server = options.server;
12
+ this.token = options.token;
13
+ this.agentId = options.agent_id;
14
+ this.name = options.name || options.agent_id;
15
+ this.permissionMode = options.permission_mode || 'native';
16
+ this.reconnectDelay = options.reconnect_delay || 5000;
17
+ this.agent = new ACPProcess(options.command, options.agent_args, options.cwd, this.permissionMode, options.agent_env);
18
+ this.agent.onNotification = (payload) => this.send(payload);
19
+ this.ws = null;
20
+ this.queue = [];
21
+ this.messageResolver = null;
22
+ this.promptAbort = null;
23
+ this.stopped = false;
24
+ }
25
+
26
+ async run() {
27
+ while (!this.stopped) {
28
+ try {
29
+ await this.agent.start();
30
+ await this._connect();
31
+ } catch (err) {
32
+ if (this.stopped) break;
33
+ log(`${this.agentId} 连接异常: ${err.message}`);
34
+ } finally {
35
+ await this.agent.stop().catch(() => {});
36
+ }
37
+ if (!this.stopped) await sleep(this.reconnectDelay);
38
+ }
39
+ }
40
+
41
+ async _connect() {
42
+ const url = new URL(`${String(this.server).replace(/\/$/, '')}/api/v1/agent/ws`);
43
+ url.searchParams.set('token', this.token);
44
+ url.searchParams.set('agent_id', this.agentId);
45
+ const ws = new WebSocket(url.toString(), { handshakeTimeout: 10000 });
46
+ this.ws = ws;
47
+ const abort = new AbortController();
48
+ this.promptAbort = abort;
49
+ log(`连接 Agent Gateway: ${this.server} agent_id=${this.agentId}`);
50
+
51
+ try {
52
+ await new Promise((resolve, reject) => {
53
+ const cleanup = () => {
54
+ ws.off('open', onOpen);
55
+ ws.off('error', onError);
56
+ ws.off('close', onClose);
57
+ };
58
+ const onOpen = () => {
59
+ cleanup();
60
+ resolve();
61
+ };
62
+ const onError = (err) => {
63
+ cleanup();
64
+ reject(err);
65
+ };
66
+ const onClose = () => {
67
+ cleanup();
68
+ reject(new Error('WebSocket 连接失败'));
69
+ };
70
+ ws.once('open', onOpen);
71
+ ws.once('error', onError);
72
+ ws.once('close', onClose);
73
+ });
74
+ log(`${this.agentId} 连接成功`);
75
+
76
+ await this.send({
77
+ type: 'register',
78
+ name: this.name,
79
+ agent_id: this.agentId,
80
+ capabilities: { delegation: false, permissions: true, nativeSessionHistory: false },
81
+ });
82
+
83
+ this._startPromptWorker(abort.signal);
84
+
85
+ await new Promise((resolve, reject) => {
86
+ const onMessage = (raw) => {
87
+ this._onMessage(raw.toString()).catch(reject);
88
+ };
89
+ const onClose = () => {
90
+ ws.off('message', onMessage);
91
+ ws.off('error', onError);
92
+ resolve();
93
+ };
94
+ const onError = (err) => {
95
+ ws.off('message', onMessage);
96
+ ws.off('close', onClose);
97
+ reject(err);
98
+ };
99
+ ws.on('message', onMessage);
100
+ ws.on('close', onClose);
101
+ ws.on('error', onError);
102
+ if (this.stopped) ws.close();
103
+ });
104
+ log(`${this.agentId} 连接断开`);
105
+ } finally {
106
+ abort.abort();
107
+ this.queue = [];
108
+ if (this.messageResolver) {
109
+ this.messageResolver(undefined);
110
+ this.messageResolver = null;
111
+ }
112
+ this.promptAbort = null;
113
+ if (this.ws) {
114
+ this.ws.close();
115
+ this.ws = null;
116
+ }
117
+ }
118
+ }
119
+
120
+ async _onMessage(raw) {
121
+ let data;
122
+ try {
123
+ data = JSON.parse(raw);
124
+ } catch {
125
+ return;
126
+ }
127
+ if (!data || typeof data !== 'object') return;
128
+ const type = data.type;
129
+ if (type === 'auth_ok') return;
130
+ if (type === 'auth_fail') throw new Error(data.message || '鉴权失败');
131
+ if (type === 'ping') {
132
+ await this.send({ type: 'pong' });
133
+ return;
134
+ }
135
+ if (type === 'message') {
136
+ this._enqueue(data);
137
+ return;
138
+ }
139
+ if (type === 'cancel') {
140
+ await this.agent.cancelSession();
141
+ return;
142
+ }
143
+ log(`忽略服务端消息: ${type}`);
144
+ }
145
+
146
+ async send(payload) {
147
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
148
+ this.ws.send(JSON.stringify(payload));
149
+ }
150
+
151
+ _enqueue(message) {
152
+ this.queue.push(message);
153
+ if (this.messageResolver) {
154
+ const resolve = this.messageResolver;
155
+ this.messageResolver = null;
156
+ resolve(this.queue.shift());
157
+ }
158
+ }
159
+
160
+ async _waitForMessage(signal) {
161
+ if (this.queue.length) return this.queue.shift();
162
+ return new Promise((resolve) => {
163
+ const cleanup = () => {
164
+ signal.removeEventListener('abort', onAbort);
165
+ if (this.messageResolver === wrapped) this.messageResolver = null;
166
+ };
167
+ const onAbort = () => {
168
+ cleanup();
169
+ resolve(undefined);
170
+ };
171
+ const wrapped = (item) => {
172
+ cleanup();
173
+ resolve(item);
174
+ };
175
+ signal.addEventListener('abort', onAbort, { once: true });
176
+ this.messageResolver = wrapped;
177
+ });
178
+ }
179
+
180
+ async _startPromptWorker(signal) {
181
+ while (!signal.aborted && !this.stopped) {
182
+ const message = await this._waitForMessage(signal);
183
+ if (!message) continue;
184
+ try {
185
+ await this._handlePrompt(message);
186
+ } catch (err) {
187
+ log(`${this.agentId} 任务失败: ${err.message}`);
188
+ await this.send({
189
+ type: 'error',
190
+ text: err.message || 'Agent 执行失败',
191
+ role: 'error',
192
+ device_id: message.device_id || '',
193
+ message_id: message.message_id,
194
+ }).catch(() => {});
195
+ }
196
+ }
197
+ }
198
+
199
+ async _handlePrompt(message) {
200
+ const text = String(message.text || '');
201
+ if (!text) return;
202
+ const sessionId = await this.agent.ensureSession();
203
+ const messageId = message.message_id ?? Date.now();
204
+ const deviceId = String(message.device_id || '');
205
+ this.agent.activeMessageId = messageId;
206
+ this.agent.activeDeviceId = deviceId;
207
+ this.agent.currentText = [];
208
+ log(`${this.agentId} 收到任务: message_id=${messageId} device_id=${deviceId || '-'}`);
209
+
210
+ const result = await this.agent.request('session/prompt', {
211
+ sessionId,
212
+ prompt: [{ type: 'text', text }],
213
+ });
214
+
215
+ let finalText = this.agent.currentText.join('').trim();
216
+ if (!finalText) {
217
+ const blocks = Array.isArray(result?.content) ? result.content : result?.content ? [result.content] : [];
218
+ for (const block of blocks) {
219
+ if (block && block.type === 'text') finalText += String(block.text || '');
220
+ }
221
+ finalText = finalText.trim();
222
+ }
223
+ const stopReason = result?.stopReason || 'end_turn';
224
+ if (stopReason !== 'end_turn') {
225
+ log(`${this.agentId} 任务未完成: message_id=${messageId} stopReason=${stopReason}`);
226
+ await this.send({
227
+ type: 'error',
228
+ text: `Agent 未完成: ${stopReason}`,
229
+ role: 'error',
230
+ device_id: deviceId,
231
+ message_id: messageId,
232
+ });
233
+ return;
234
+ }
235
+ const preview = finalText.replace(/\s+/g, ' ').slice(0, 10);
236
+ log(`${this.agentId} 回复完成: message_id=${messageId} response=${preview}...`);
237
+ await this.send({
238
+ type: 'response',
239
+ text: finalText,
240
+ role: 'agent',
241
+ device_id: deviceId,
242
+ message_id: messageId,
243
+ });
244
+ }
245
+
246
+ stop() {
247
+ if (this.stopped) return;
248
+ this.stopped = true;
249
+ log(`${this.agentId} 收到停止信号`);
250
+ if (this.promptAbort) this.promptAbort.abort();
251
+ if (this.messageResolver) {
252
+ const resolve = this.messageResolver;
253
+ this.messageResolver = null;
254
+ resolve(undefined);
255
+ }
256
+ if (this.ws) {
257
+ this.ws.close();
258
+ this.ws = null;
259
+ }
260
+ }
261
+ }
@@ -0,0 +1,244 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
5
+
6
+ const IS_WIN = process.platform === 'win32';
7
+
8
+ export const AGENT_ORDER = [
9
+ 'openclaw',
10
+ 'hermes',
11
+ 'codex',
12
+ 'qwen',
13
+ 'opencode',
14
+ 'qoder',
15
+ 'minimax',
16
+ 'kimi',
17
+ 'codebuddy',
18
+ 'claude',
19
+ 'deepseek',
20
+ 'pi',
21
+ 'acp',
22
+ ];
23
+
24
+ export const AGENT_LABELS = {
25
+ acp: 'ACP',
26
+ claude: 'Claude Code',
27
+ codebuddy: 'CodeBuddy',
28
+ codex: 'Codex',
29
+ deepseek: 'DeepSeek',
30
+ hermes: 'Hermes',
31
+ kimi: 'Kimi Code',
32
+ minimax: 'MiniMax Code',
33
+ opencode: 'OpenCode',
34
+ openclaw: 'OpenClaw',
35
+ pi: 'Pi',
36
+ qoder: 'Qoder',
37
+ qwen: 'Qwen Code',
38
+ };
39
+
40
+ function isExecutable(file) {
41
+ if (!file) return false;
42
+ try {
43
+ const st = fs.statSync(file);
44
+ if (!st.isFile()) return false;
45
+ if (IS_WIN) return true;
46
+ fs.accessSync(file, fs.constants.X_OK);
47
+ return true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ function exeCandidates(command) {
54
+ if (command.includes('/') || command.includes('\\')) return [command];
55
+ if (IS_WIN) return [command, `${command}.exe`, `${command}.cmd`, `${command}.bat`];
56
+ return [command];
57
+ }
58
+
59
+ function unique(values) {
60
+ return Array.from(new Set(values.filter(Boolean)));
61
+ }
62
+
63
+ function nvmDirs() {
64
+ const root = process.env.NVM_DIR || path.join(os.homedir(), '.nvm');
65
+ const versions = path.join(root, 'versions', 'node');
66
+ try {
67
+ return fs
68
+ .readdirSync(versions)
69
+ .sort()
70
+ .reverse()
71
+ .map((name) => path.join(versions, name, 'bin'));
72
+ } catch {
73
+ return [];
74
+ }
75
+ }
76
+
77
+ function searchDirs() {
78
+ const home = os.homedir();
79
+ const dirs = (process.env.PATH || '').split(path.delimiter).filter(Boolean);
80
+ if (IS_WIN) {
81
+ return unique([
82
+ process.env.APPDATA ? path.join(process.env.APPDATA, 'npm') : '',
83
+ process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, 'npm') : '',
84
+ process.env.ProgramFiles ? path.join(process.env.ProgramFiles, 'nodejs') : '',
85
+ process.env['ProgramFiles(x86)'] ? path.join(process.env['ProgramFiles(x86)'], 'nodejs') : '',
86
+ ...dirs,
87
+ ]);
88
+ }
89
+ return unique([
90
+ ...nvmDirs(),
91
+ path.join(home, '.npm-global', 'bin'),
92
+ path.join(home, '.bun', 'bin'),
93
+ path.join(home, '.local', 'bin'),
94
+ '/opt/homebrew/bin',
95
+ '/usr/local/bin',
96
+ ...dirs,
97
+ ]);
98
+ }
99
+
100
+ function commandFallback(command) {
101
+ try {
102
+ const out = execFileSync(IS_WIN ? 'where' : 'which', [command], {
103
+ encoding: 'utf8',
104
+ stdio: ['ignore', 'pipe', 'ignore'],
105
+ });
106
+ const first = out.split(/\r?\n/).find(Boolean);
107
+ return first && isExecutable(first) ? first : '';
108
+ } catch {
109
+ return '';
110
+ }
111
+ }
112
+
113
+ function findExecutable(command, envNames = []) {
114
+ const envList = Array.isArray(envNames) ? envNames : [envNames].filter(Boolean);
115
+ for (const envName of envList) {
116
+ const envPath = process.env[envName];
117
+ if (isExecutable(envPath)) return envPath;
118
+ }
119
+ for (const dir of searchDirs()) {
120
+ for (const candidate of exeCandidates(command)) {
121
+ const full = path.join(dir, candidate);
122
+ if (isExecutable(full)) return full;
123
+ }
124
+ }
125
+ if (!command.includes('/') && !command.includes('\\')) {
126
+ return commandFallback(command);
127
+ }
128
+ return '';
129
+ }
130
+
131
+ function makeTarget(key, command, agentArgs, env, extraArgs) {
132
+ return {
133
+ agent_id: key,
134
+ name: AGENT_LABELS[key] || key,
135
+ command,
136
+ agent_args: [...agentArgs, ...(extraArgs || [])],
137
+ agent_env: env || {},
138
+ };
139
+ }
140
+
141
+ function localAgent(command, envNames, baseArgs, permissionMode, fullArgs = []) {
142
+ const file = findExecutable(command, envNames);
143
+ if (!file) return null;
144
+ const args = [...baseArgs];
145
+ if (permissionMode === 'full' && fullArgs.length) args.push(...fullArgs);
146
+ return { command: file, args, env: {} };
147
+ }
148
+
149
+ function adapterAgent(parentCommand, parentEnv, adapterCommand, adapterEnv, pkg, parentEnvKeys = []) {
150
+ const parent = findExecutable(parentCommand, parentEnv);
151
+ const env = {};
152
+ if (parent) {
153
+ for (const key of parentEnvKeys) env[key] = parent;
154
+ }
155
+ const adapter = findExecutable(adapterCommand, adapterEnv);
156
+ if (adapter) return { command: adapter, args: [], env };
157
+ const npx = findExecutable('npx', ['NPX_BIN']);
158
+ if (parent && npx) return { command: npx, args: ['-y', pkg], env };
159
+ return null;
160
+ }
161
+
162
+ function toWsUrl(rawUrl) {
163
+ if (rawUrl.startsWith('https://')) return `wss://${rawUrl.slice('https://'.length)}`;
164
+ if (rawUrl.startsWith('http://')) return `ws://${rawUrl.slice('http://'.length)}`;
165
+ return rawUrl;
166
+ }
167
+
168
+ function openclawAgent() {
169
+ const file = findExecutable('openclaw', ['OPENCLAW_ACP_BIN', 'OPENCLAW_BIN', 'OPENCLAW_PATH']);
170
+ if (!file) return null;
171
+ const args = ['acp', '--verbose'];
172
+ const rawUrl = process.env.OPENCLAW_GATEWAY_URL || process.env.OPENCLAW_WS_URL || process.env.OPENCLAW_BASE_URL || '';
173
+ if (rawUrl) args.push('--url', toWsUrl(rawUrl));
174
+ const token = process.env.OPENCLAW_GATEWAY_TOKEN || process.env.OPENCLAW_TOKEN || '';
175
+ if (token) args.push('--token', token);
176
+ return { command: file, args, env: {} };
177
+ }
178
+
179
+ export function buildAgent(key, permissionMode) {
180
+ if (key === 'openclaw') return openclawAgent();
181
+ if (key === 'hermes') return localAgent('hermes', ['HERMES_BIN'], ['acp', '--accept-hooks'], permissionMode);
182
+ if (key === 'qwen') return localAgent('qwen', ['QWEN_CODE_BIN', 'QWEN_BIN'], ['--acp'], permissionMode);
183
+ if (key === 'opencode') return localAgent('opencode', ['OPENCODE_BIN', 'OPENCODE_PATH'], ['acp'], permissionMode);
184
+ if (key === 'qoder') {
185
+ return localAgent(
186
+ 'qodercli',
187
+ ['QODERCLI_PATH', 'QODER_CLI_PATH'],
188
+ ['--acp'],
189
+ permissionMode,
190
+ ['--dangerously-skip-permissions'],
191
+ );
192
+ }
193
+ if (key === 'minimax') return localAgent('mcode', ['MINIMAX_CODE_BIN', 'MINIMAX_BIN'], ['acp'], permissionMode);
194
+ if (key === 'kimi') return localAgent('kimi', ['KIMI_CODE_BIN', 'KIMI_BIN'], ['acp'], permissionMode);
195
+ if (key === 'codebuddy') {
196
+ return localAgent(
197
+ 'codebuddy',
198
+ ['CODEBUDDY_BIN', 'CODEBUDDY_PATH'],
199
+ ['--acp'],
200
+ permissionMode,
201
+ ['--dangerously-skip-permissions'],
202
+ );
203
+ }
204
+ if (key === 'deepseek') {
205
+ return localAgent('dsh', ['DEEPSEEK_HARNESS_BIN', 'DSH_BIN'], ['--profile', 'acp'], permissionMode);
206
+ }
207
+ if (key === 'codex') {
208
+ return adapterAgent(
209
+ 'codex',
210
+ ['CODEX_PATH', 'CODEX_BIN'],
211
+ 'codex-acp',
212
+ ['CODEX_ACP_BIN', 'CODEX_ACP_PATH'],
213
+ '@agentclientprotocol/codex-acp@latest',
214
+ ['CODEX_PATH'],
215
+ );
216
+ }
217
+ if (key === 'claude') {
218
+ return adapterAgent(
219
+ 'claude',
220
+ ['CLAUDE_CODE_EXECUTABLE', 'CLAUDE_BIN'],
221
+ 'claude-agent-acp',
222
+ ['CLAUDE_CODE_ACP_BIN', 'CLAUDE_AGENT_ACP_BIN'],
223
+ '@agentclientprotocol/claude-agent-acp@latest',
224
+ ['CLAUDE_CODE_EXECUTABLE'],
225
+ );
226
+ }
227
+ if (key === 'pi') {
228
+ return adapterAgent('pi', ['PI_BIN', 'PI_COMMAND'], 'pi-acp', ['PI_ACP_BIN'], 'pi-acp@latest', ['PI_COMMAND', 'PI_BIN']);
229
+ }
230
+ if (key === 'acp') {
231
+ const command = process.env.ACP_COMMAND;
232
+ if (!command) return null;
233
+ const args = process.env.ACP_ARGS ? process.env.ACP_ARGS.match(/(?:[^\s"]+|"[^"]*")+/g)?.map((x) => x.replace(/^"|"$/g, '')) || [] : [];
234
+ return { command, args, env: {} };
235
+ }
236
+ return null;
237
+ }
238
+
239
+ export function collectTargets(permissionMode = 'native', extraArgs = []) {
240
+ return AGENT_ORDER.map((key) => {
241
+ const built = buildAgent(key, permissionMode);
242
+ return built ? makeTarget(key, built.command, built.args, built.env, extraArgs) : null;
243
+ }).filter(Boolean);
244
+ }
package/src/log.js ADDED
@@ -0,0 +1,6 @@
1
+ export function log(message) {
2
+ const d = new Date();
3
+ const pad = (n) => String(n).padStart(2, '0');
4
+ const ts = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
5
+ console.log(`[${ts}] [connector] ${message}`);
6
+ }