@dmall-inc/wd-cli 0.2.0 → 0.4.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.
@@ -0,0 +1,360 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Pi 执行器(design D8 修订):驱动本机已安装的 `pi` CLI 的 RPC 模式(JSONL over stdio),零依赖。
5
+ *
6
+ * pi --mode rpc --session-id <平台会话 id> -e <审批扩展>
7
+ *
8
+ * - `--session-id` 让同一平台会话在 daemon 重启后续接同一个 Pi 会话(会话文件存在 Pi 自己的目录);
9
+ * - 审批:注入的扩展在 tool_call 钩子里调 ctx.ui.confirm,RPC 模式下变成 extension_ui_request,
10
+ * 这里转给 PermissionBroker,再以 extension_ui_response 回填;
11
+ * - 事件映射:message_update(text_delta/thinking_delta) → 文本/思考;tool_execution_* → 工具卡;
12
+ * agent_settled → RUN_FINISHED。
13
+ */
14
+
15
+ const path = require('node:path');
16
+ const { spawn } = require('node:child_process');
17
+
18
+ const { agui, contentToText, clip } = require('../agui');
19
+
20
+ const EXTENSION_PATH = path.join(__dirname, 'pi-approval-extension.ts');
21
+ const PERMISSION_TITLE_PREFIX = 'WDCLI_PERMISSION:';
22
+
23
+ /** Pi 内置工具 → ACP 风格的 kind,页面据此选图标。 */
24
+ const TOOL_KIND = { read: 'read', grep: 'search', find: 'search', ls: 'search', bash: 'execute', write: 'edit', edit: 'edit' };
25
+
26
+ class PiSession {
27
+ constructor(opts) {
28
+ this.opts = opts;
29
+ this.log = opts.log || (() => {});
30
+ this.child = null;
31
+ this.ready = null;
32
+ this.nextId = 1;
33
+ this.pending = new Map();
34
+ this.ctx = null;
35
+ this.run = null;
36
+ }
37
+
38
+ start() {
39
+ if (this.ready) return this.ready;
40
+ this.ready = new Promise((resolve, reject) => {
41
+ const [cmd, ...baseArgs] = this.opts.command;
42
+ const args = [...baseArgs, '--mode', 'rpc', '--session-id', this.opts.platformSessionId, '-e', EXTENSION_PATH];
43
+ this.log(`启动 Pi:${[cmd, ...args].join(' ')}(cwd=${this.opts.cwd})`);
44
+ const child = spawn(cmd, args, {
45
+ cwd: this.opts.cwd,
46
+ env: { ...process.env, WDCLI_ALLOWED_ROOT: this.opts.cwd },
47
+ stdio: ['pipe', 'pipe', 'pipe'],
48
+ });
49
+ this.child = child;
50
+ let settled = false;
51
+ child.once('error', (error) => {
52
+ if (!settled) {
53
+ settled = true;
54
+ reject(Object.assign(new Error(`Pi 启动失败:${error.message}`), { code: 'RUNTIME_UNAVAILABLE' }));
55
+ }
56
+ });
57
+ child.once('spawn', () => {
58
+ if (!settled) {
59
+ settled = true;
60
+ resolve();
61
+ }
62
+ });
63
+ child.stderr.setEncoding('utf8');
64
+ child.stderr.on('data', (chunk) => this.log(`[pi] ${String(chunk).trimEnd()}`));
65
+ child.on('exit', (code, signal) => {
66
+ this.log(`Pi 退出:code=${code} signal=${signal}`);
67
+ for (const waiter of this.pending.values()) waiter.reject(new Error('Pi 已退出'));
68
+ this.pending.clear();
69
+ if (this.run) this.failRun('RUNTIME_EXITED', `Pi 进程已退出(code=${code})`);
70
+ this.ready = null;
71
+ });
72
+ // 严格按 LF 切分(不能用 readline:它会在 U+2028/2029 处断行)
73
+ let buffer = '';
74
+ child.stdout.setEncoding('utf8');
75
+ child.stdout.on('data', (chunk) => {
76
+ buffer += chunk;
77
+ let nl;
78
+ while ((nl = buffer.indexOf('\n')) >= 0) {
79
+ const line = buffer.slice(0, nl).replace(/\r$/, '');
80
+ buffer = buffer.slice(nl + 1);
81
+ if (line.trim()) this.onRecord(line);
82
+ }
83
+ });
84
+ });
85
+ this.ready.catch(() => {
86
+ this.ready = null;
87
+ });
88
+ return this.ready;
89
+ }
90
+
91
+ send(record) {
92
+ if (!this.child || this.child.exitCode !== null) return;
93
+ this.child.stdin.write(`${JSON.stringify(record)}\n`);
94
+ }
95
+
96
+ command(type, extra = {}) {
97
+ const id = `wd-${this.nextId++}`;
98
+ return new Promise((resolve, reject) => {
99
+ this.pending.set(id, { resolve, reject });
100
+ this.send({ id, type, ...extra });
101
+ });
102
+ }
103
+
104
+ /** images:[{mimeType, data(base64)}] → Pi RPC prompt 的 images 字段 */
105
+ async prompt(ctx, text, images = []) {
106
+ this.ctx = ctx;
107
+ this.run = { messageId: null, thinking: '', tools: new Map(), ended: false };
108
+ this.emit(agui.runStarted(ctx));
109
+ try {
110
+ await this.start();
111
+ } catch (error) {
112
+ this.failRun('RUNTIME_UNAVAILABLE', `${error.message};请先安装 Pi(npm i -g @earendil-works/pi-coding-agent)`);
113
+ return;
114
+ }
115
+ const finished = new Promise((resolve) => {
116
+ this.run.resolve = resolve;
117
+ });
118
+ try {
119
+ const payload = { message: text };
120
+ if (images.length) payload.images = images.map((i) => ({ type: 'image', data: i.data, mimeType: i.mimeType }));
121
+ const response = await this.command('prompt', payload);
122
+ if (!response.success) {
123
+ this.failRun('RUNTIME_ERROR', response.error || 'Pi 拒绝了这条消息');
124
+ return;
125
+ }
126
+ if (response.data && response.data.disposition === 'handled') {
127
+ this.finishRun({ stopReason: 'handled' });
128
+ return;
129
+ }
130
+ } catch (error) {
131
+ this.failRun('RUNTIME_ERROR', error.message);
132
+ return;
133
+ }
134
+ await finished;
135
+ }
136
+
137
+ cancel() {
138
+ if (this.child && this.run) this.command('abort').catch(() => {});
139
+ if (this.opts.permission) this.opts.permission.cancelAll(this.opts.platformSessionId);
140
+ }
141
+
142
+ close() {
143
+ this.cancel();
144
+ if (this.child && this.child.exitCode === null) {
145
+ try {
146
+ this.child.stdin.end();
147
+ const child = this.child;
148
+ setTimeout(() => {
149
+ if (child.exitCode === null) child.kill('SIGTERM');
150
+ }, 3000).unref();
151
+ } catch {
152
+ // 已退出
153
+ }
154
+ }
155
+ }
156
+
157
+ // ------------------------------------------------------------ 事件
158
+
159
+ emit(event) {
160
+ this.opts.emit(this.ctx, event);
161
+ }
162
+
163
+ /** 推理增量:映射为标准 REASONING_MESSAGE_*(与 work 同一套),DiWork 的推理折叠块直接渲染 */
164
+ reason(delta) {
165
+ if (!this.run) return;
166
+ if (this.run.messageId) {
167
+ this.emit(agui.textEnd(this.ctx, this.run.messageId));
168
+ this.run.messageId = null;
169
+ }
170
+ if (!this.run.reasoningId) {
171
+ this.run.reasoningId = agui.newId('rsn');
172
+ this.emit(agui.reasoningStart(this.ctx, this.run.reasoningId));
173
+ }
174
+ this.emit(agui.reasoningContent(this.ctx, this.run.reasoningId, delta));
175
+ }
176
+
177
+ closeReasoning() {
178
+ if (this.run && this.run.reasoningId) {
179
+ this.emit(agui.reasoningEnd(this.ctx, this.run.reasoningId));
180
+ this.run.reasoningId = null;
181
+ }
182
+ }
183
+
184
+ closeText() {
185
+ this.closeReasoning();
186
+ if (this.run && this.run.messageId) {
187
+ this.emit(agui.textEnd(this.ctx, this.run.messageId));
188
+ this.run.messageId = null;
189
+ }
190
+ }
191
+
192
+ finishRun(result) {
193
+ if (!this.run || this.run.ended) return;
194
+ this.closeText();
195
+ this.run.ended = true;
196
+ const resolve = this.run.resolve;
197
+ this.emit(agui.runFinished(this.ctx, result));
198
+ this.run = null;
199
+ if (resolve) resolve();
200
+ }
201
+
202
+ failRun(code, message) {
203
+ if (!this.run || this.run.ended) return;
204
+ this.closeText();
205
+ this.run.ended = true;
206
+ const resolve = this.run.resolve;
207
+ this.emit(agui.runError(this.ctx, code, message));
208
+ this.run = null;
209
+ if (resolve) resolve();
210
+ }
211
+
212
+ onRecord(line) {
213
+ let rec;
214
+ try {
215
+ rec = JSON.parse(line);
216
+ } catch {
217
+ this.log(`忽略非 JSON 输出:${line.slice(0, 200)}`);
218
+ return;
219
+ }
220
+ if (rec.type === 'response') {
221
+ const waiter = rec.id && this.pending.get(rec.id);
222
+ if (waiter) {
223
+ this.pending.delete(rec.id);
224
+ waiter.resolve(rec);
225
+ }
226
+ return;
227
+ }
228
+ if (rec.type === 'extension_ui_request') {
229
+ this.onUiRequest(rec);
230
+ return;
231
+ }
232
+ if (!this.run) return;
233
+ switch (rec.type) {
234
+ case 'message_update': {
235
+ const ev = rec.assistantMessageEvent || {};
236
+ if (ev.type === 'text_delta' && ev.delta) {
237
+ this.closeReasoning();
238
+ if (!this.run.messageId) {
239
+ this.run.messageId = agui.newId('msg');
240
+ this.emit(agui.textStart(this.ctx, this.run.messageId));
241
+ }
242
+ this.emit(agui.textContent(this.ctx, this.run.messageId, ev.delta));
243
+ } else if (ev.type === 'thinking_delta' && ev.delta) {
244
+ this.reason(ev.delta);
245
+ }
246
+ return;
247
+ }
248
+ case 'message_end':
249
+ if (rec.message && rec.message.role === 'assistant') this.closeText();
250
+ return;
251
+ case 'tool_execution_start':
252
+ this.onToolStart(rec);
253
+ return;
254
+ case 'tool_execution_update':
255
+ this.onToolUpdate(rec.toolCallId, 'in_progress', rec.partialResult);
256
+ return;
257
+ case 'tool_execution_end':
258
+ this.onToolEnd(rec);
259
+ return;
260
+ case 'agent_settled':
261
+ this.finishRun({ stopReason: rec.aborted ? 'cancelled' : 'end_turn' });
262
+ return;
263
+ case 'extension_error':
264
+ this.log(`Pi 扩展错误:${rec.error}`);
265
+ return;
266
+ default:
267
+ }
268
+ }
269
+
270
+ onToolStart(rec) {
271
+ this.closeText();
272
+ const tool = { name: rec.toolName, kind: TOOL_KIND[rec.toolName] || 'other', input: rec.args, ended: false };
273
+ this.run.tools.set(rec.toolCallId, tool);
274
+ this.emit(agui.toolStart(this.ctx, rec.toolCallId, rec.toolName, null));
275
+ if (rec.args !== undefined) this.emit(agui.toolArgs(this.ctx, rec.toolCallId, JSON.stringify(rec.args)));
276
+ this.emitToolUpdate(rec.toolCallId, 'pending');
277
+ }
278
+
279
+ onToolUpdate(toolCallId, status, partial) {
280
+ if (!this.run || !this.run.tools.has(toolCallId)) return;
281
+ const tool = this.run.tools.get(toolCallId);
282
+ if (partial) tool.output = clip(contentToText(partial.content));
283
+ this.emitToolUpdate(toolCallId, status);
284
+ }
285
+
286
+ onToolEnd(rec) {
287
+ if (!this.run.tools.has(rec.toolCallId)) this.onToolStart({ ...rec, args: rec.args });
288
+ const tool = this.run.tools.get(rec.toolCallId);
289
+ if (tool.ended) return;
290
+ tool.ended = true;
291
+ tool.output = clip(contentToText(rec.result && rec.result.content));
292
+ const status = rec.isError ? 'failed' : 'completed';
293
+ this.emitToolUpdate(rec.toolCallId, status);
294
+ this.emit(agui.toolEnd(this.ctx, rec.toolCallId));
295
+ this.emit(agui.toolResult(this.ctx, rec.toolCallId, tool.output || (rec.isError ? '执行失败' : '完成')));
296
+ }
297
+
298
+ emitToolUpdate(toolCallId, status) {
299
+ const tool = this.run.tools.get(toolCallId);
300
+ const input = tool.input || {};
301
+ const diffs = [];
302
+ if (tool.name === 'write' && typeof input.path === 'string') {
303
+ diffs.push({ path: input.path, oldText: null, newText: clip(input.content || '') });
304
+ } else if (tool.name === 'edit' && typeof input.path === 'string' && Array.isArray(input.edits)) {
305
+ for (const e of input.edits) diffs.push({ path: input.path, oldText: clip(e.oldText || ''), newText: clip(e.newText || '') });
306
+ } else if (tool.name === 'edit' && typeof input.path === 'string' && (input.oldText !== undefined || input.newText !== undefined)) {
307
+ diffs.push({ path: input.path, oldText: clip(input.oldText || ''), newText: clip(input.newText || '') });
308
+ }
309
+ this.emit(agui.custom(this.ctx, 'local_agent.tool_update', {
310
+ toolCallId,
311
+ title: tool.name,
312
+ kind: tool.kind,
313
+ status,
314
+ input,
315
+ locations: typeof input.path === 'string' ? [{ path: input.path }] : [],
316
+ diffs,
317
+ output: tool.output || undefined,
318
+ }));
319
+ }
320
+
321
+ async onUiRequest(rec) {
322
+ const dialog = ['select', 'confirm', 'input', 'editor'].includes(rec.method);
323
+ if (!dialog) return; // notify / setStatus 等无需应答
324
+ if (rec.method !== 'confirm' || !String(rec.title || '').startsWith(PERMISSION_TITLE_PREFIX) || !this.run) {
325
+ this.send({ type: 'extension_ui_response', id: rec.id, cancelled: true });
326
+ return;
327
+ }
328
+ const toolCallId = String(rec.title).slice(PERMISSION_TITLE_PREFIX.length);
329
+ let detail = {};
330
+ try {
331
+ detail = JSON.parse(rec.message || '{}');
332
+ } catch {
333
+ // 保持空对象
334
+ }
335
+ const decision = await this.opts.permission.request(this.ctx, {
336
+ toolCallId,
337
+ title: detail.toolName,
338
+ kind: TOOL_KIND[detail.toolName] || 'other',
339
+ toolName: detail.toolName,
340
+ input: detail.input,
341
+ options: [
342
+ { optionId: 'allow_once', name: '允许一次', kind: 'allow_once' },
343
+ { optionId: 'reject_once', name: '拒绝', kind: 'reject_once' },
344
+ ],
345
+ });
346
+ this.send({ type: 'extension_ui_response', id: rec.id, confirmed: decision.optionId === 'allow_once' });
347
+ }
348
+ }
349
+
350
+ function createPiExecutor({ command, log }) {
351
+ return {
352
+ id: 'pi',
353
+ kind: 'rpc',
354
+ createSession(opts) {
355
+ return new PiSession({ ...opts, command, log });
356
+ },
357
+ };
358
+ }
359
+
360
+ module.exports = { createPiExecutor, PiSession, EXTENSION_PATH, PERMISSION_TITLE_PREFIX };
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * daemon 主循环(前台运行):登记 → 拉清单 → 探测运行时 → 外连 bridge → 分派命令。
5
+ * `wd-cli daemon start` 缺省以 detached 子进程跑本函数(--foreground 时直接在当前进程跑)。
6
+ */
7
+
8
+ const fs = require('node:fs');
9
+
10
+ const state = require('./state');
11
+ const enrollLib = require('./enroll');
12
+ const runtimesLib = require('./runtimes');
13
+ const { BridgeChannel } = require('./channel');
14
+ const { Supervisor } = require('./supervisor');
15
+
16
+ /** 运行时周期复检间隔:--version 结果按二进制缓存,复检本身很轻 */
17
+ const RUNTIME_CHECK_INTERVAL_MS = 60_000;
18
+
19
+ async function runDaemon(ctx, { log }) {
20
+ const env = ctx.env;
21
+ const paths = state.paths(env);
22
+
23
+ let deviceToken = await enrollLib.ensureDeviceToken(ctx);
24
+ const manifestResp = await enrollLib.fetchManifest(ctx, (error) =>
25
+ log(`读取平台清单失败(${error.message}):bridge 地址将回落到本地配置或平台基址,如连不上请先修复登录态(wd-cli auth status)后重启 daemon`));
26
+ if (manifestResp && manifestResp.enabled === false) {
27
+ log('平台未开启运行时纳管(local-agent.enabled=false),仍会保持连接等待开启');
28
+ }
29
+ const manifest = (manifestResp && manifestResp.manifest) || {};
30
+ const bridgeUrl = enrollLib.resolveBridgeUrl(ctx, manifestResp);
31
+ if (!bridgeUrl) throw new Error('无法确定 bridge 地址:请用 --bridge-url 或 WD_CLI_BRIDGE_URL 指定');
32
+ if (!manifestResp) log(`bridge 地址回落为 ${bridgeUrl}`);
33
+
34
+ let daemonConfig = state.loadDaemonConfig(env);
35
+ const detect = () => runtimesLib.detectAll({ daemonConfig, manifest, executorsDir: paths.executors, log });
36
+ let runtimes = detect();
37
+ const versionCache = new Map();
38
+
39
+ let channel = null;
40
+ const snapshot = () =>
41
+ state.writeStatus({
42
+ pid: process.pid,
43
+ deviceId: state.deviceId(env),
44
+ bridgeUrl,
45
+ connection: channel ? channel.state : 'idle',
46
+ runtimes: runtimesLib.toInventory(runtimes),
47
+ roots: daemonConfig.allowedRoots,
48
+ activeRuns: supervisor.activeRuns(),
49
+ }, env);
50
+
51
+ const supervisor = new Supervisor({
52
+ send: (frame) => channel && channel.send(frame),
53
+ getRuntimes: () => runtimes,
54
+ getDaemonConfig: () => daemonConfig,
55
+ refreshRuntimes: (reason) => refreshRuntimes(reason),
56
+ host: state.hostInfo(),
57
+ cliVersion: enrollLib.cliVersion(),
58
+ log,
59
+ });
60
+
61
+ channel = new BridgeChannel({
62
+ bridgeUrl,
63
+ log,
64
+ getToken: async () => deviceToken,
65
+ onCommand: (cmd) => supervisor.handle(cmd),
66
+ onUnauthorized: async () => {
67
+ log('设备令牌被拒,尝试用登录身份重新登记');
68
+ try {
69
+ deviceToken = (await enrollLib.enroll(ctx)).deviceToken;
70
+ return true;
71
+ } catch (error) {
72
+ log(`重新登记失败:${error.message}`);
73
+ return false;
74
+ }
75
+ },
76
+ });
77
+ channel.on('state', (s) => {
78
+ log(`通道状态:${s}`);
79
+ snapshot();
80
+ });
81
+
82
+ // 自动恢复:运行时可用性会在 daemon 运行中变化(开机时 PATH / 网络未就绪致 --version 失败、
83
+ // 之后才安装或登录、自更新替换了二进制),周期 + 失败触发复检,有变化即重报清单,无需重启 daemon
84
+ let refreshing = null;
85
+ const refreshRuntimes = (reason) => {
86
+ if (refreshing) return refreshing;
87
+ refreshing = (async () => {
88
+ const next = await runtimesLib.detectAllAsync(
89
+ { daemonConfig, manifest, executorsDir: paths.executors, log }, versionCache);
90
+ if (!runtimesLib.inventoryChanged(runtimes, next)) return;
91
+ const was = new Map(runtimes.map((r) => [r.id, r.available]));
92
+ runtimes = next;
93
+ const diff = next.filter((r) => was.get(r.id) !== r.available)
94
+ .map((r) => `${r.id}${r.available ? ' 恢复可用' : ` 不可用(${r.reason || '未知原因'})`}`);
95
+ log(`运行时变化${reason ? `(${reason})` : ''}:${diff.join(',') || '版本或说明更新'}`);
96
+ if (channel.state === 'connected') supervisor.runtimesChanged();
97
+ snapshot();
98
+ })().finally(() => {
99
+ refreshing = null;
100
+ });
101
+ return refreshing;
102
+ };
103
+ const checkTimer = setInterval(() => {
104
+ refreshRuntimes().catch((error) => log(`复检运行时失败:${error.message}`));
105
+ }, RUNTIME_CHECK_INTERVAL_MS);
106
+ checkTimer.unref();
107
+
108
+ // daemon.json 变化(roots add/remove、命令覆盖)即时生效并重报清单
109
+ const onConfigChange = () => {
110
+ daemonConfig = state.loadDaemonConfig(env);
111
+ runtimes = detect();
112
+ if (channel.state === 'connected') channel.send(supervisor.inventory());
113
+ snapshot();
114
+ log('daemon.json 已变更,重新上报清单');
115
+ };
116
+ fs.watchFile(paths.daemonConfig, { interval: 3000 }, onConfigChange);
117
+
118
+ const stopped = new Promise((resolve, reject) => {
119
+ channel.on('fatal', (error) => reject(error));
120
+ const shutdown = async (signal) => {
121
+ log(`收到 ${signal},停止 daemon`);
122
+ clearInterval(checkTimer);
123
+ fs.unwatchFile(paths.daemonConfig, onConfigChange);
124
+ supervisor.shutdown();
125
+ await channel.drain(3000);
126
+ channel.stop();
127
+ resolve();
128
+ };
129
+ process.once('SIGTERM', () => shutdown('SIGTERM'));
130
+ process.once('SIGINT', () => shutdown('SIGINT'));
131
+ });
132
+
133
+ log(`daemon 启动:deviceId=${state.deviceId(env)} bridge=${bridgeUrl} 运行时=${runtimes.filter((r) => r.available).map((r) => r.id).join(',') || '无'}`);
134
+ channel.start();
135
+ snapshot();
136
+ const timer = setInterval(snapshot, 15_000);
137
+ timer.unref();
138
+ try {
139
+ await stopped;
140
+ } finally {
141
+ clearInterval(timer);
142
+ clearInterval(checkTimer);
143
+ }
144
+ }
145
+
146
+ module.exports = { runDaemon };
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 换行分隔的 JSON-RPC 2.0 对端(ACP 的 stdio 传输)。零依赖。
5
+ *
6
+ * - request(method, params):发请求,返回 Promise(按 id 关联响应);
7
+ * - notify(method, params):发通知;
8
+ * - onRequest(handler):对端发来的请求(如 session/request_permission、fs/read_text_file),handler 返回结果或抛错;
9
+ * - onNotification(handler):对端发来的通知(如 session/update)。
10
+ */
11
+
12
+ const { EventEmitter } = require('node:events');
13
+
14
+ class JsonRpcPeer extends EventEmitter {
15
+ constructor(readable, writable, { log } = {}) {
16
+ super();
17
+ this.writable = writable;
18
+ this.log = log || (() => {});
19
+ this.nextId = 1;
20
+ this.pending = new Map();
21
+ this.requestHandler = null;
22
+ this.notificationHandler = null;
23
+ this.closed = false;
24
+ let buffer = '';
25
+ readable.setEncoding('utf8');
26
+ readable.on('data', (chunk) => {
27
+ buffer += chunk;
28
+ let nl;
29
+ while ((nl = buffer.indexOf('\n')) >= 0) {
30
+ const line = buffer.slice(0, nl).trim();
31
+ buffer = buffer.slice(nl + 1);
32
+ if (line) this.handleLine(line);
33
+ }
34
+ });
35
+ readable.on('end', () => this.close(new Error('对端已关闭')));
36
+ readable.on('error', (error) => this.close(error));
37
+ }
38
+
39
+ onRequest(handler) {
40
+ this.requestHandler = handler;
41
+ }
42
+
43
+ onNotification(handler) {
44
+ this.notificationHandler = handler;
45
+ }
46
+
47
+ handleLine(line) {
48
+ let msg;
49
+ try {
50
+ msg = JSON.parse(line);
51
+ } catch {
52
+ this.log(`忽略非 JSON 输出:${line.slice(0, 200)}`);
53
+ return;
54
+ }
55
+ if (msg && Object.prototype.hasOwnProperty.call(msg, 'id') && (msg.result !== undefined || msg.error !== undefined) && !msg.method) {
56
+ const waiter = this.pending.get(msg.id);
57
+ if (!waiter) return;
58
+ this.pending.delete(msg.id);
59
+ if (msg.error) {
60
+ const error = new Error(msg.error.message || 'JSON-RPC 错误');
61
+ error.code = msg.error.code;
62
+ error.data = msg.error.data;
63
+ waiter.reject(error);
64
+ } else {
65
+ waiter.resolve(msg.result);
66
+ }
67
+ return;
68
+ }
69
+ if (msg && msg.method && Object.prototype.hasOwnProperty.call(msg, 'id')) {
70
+ this.dispatchRequest(msg);
71
+ return;
72
+ }
73
+ if (msg && msg.method) {
74
+ try {
75
+ if (this.notificationHandler) this.notificationHandler(msg.method, msg.params || {});
76
+ } catch (error) {
77
+ this.log(`处理通知失败:${msg.method} ${error.message}`);
78
+ }
79
+ }
80
+ }
81
+
82
+ async dispatchRequest(msg) {
83
+ try {
84
+ if (!this.requestHandler) throw Object.assign(new Error(`未实现:${msg.method}`), { code: -32601 });
85
+ const result = await this.requestHandler(msg.method, msg.params || {});
86
+ this.send({ jsonrpc: '2.0', id: msg.id, result: result === undefined ? null : result });
87
+ } catch (error) {
88
+ this.send({
89
+ jsonrpc: '2.0',
90
+ id: msg.id,
91
+ error: { code: typeof error.code === 'number' ? error.code : -32603, message: error.message || '内部错误' },
92
+ });
93
+ }
94
+ }
95
+
96
+ send(obj) {
97
+ if (this.closed) return;
98
+ try {
99
+ this.writable.write(`${JSON.stringify(obj)}\n`);
100
+ } catch (error) {
101
+ this.close(error);
102
+ }
103
+ }
104
+
105
+ request(method, params) {
106
+ if (this.closed) return Promise.reject(new Error('连接已关闭'));
107
+ const id = this.nextId++;
108
+ return new Promise((resolve, reject) => {
109
+ this.pending.set(id, { resolve, reject });
110
+ this.send({ jsonrpc: '2.0', id, method, params });
111
+ });
112
+ }
113
+
114
+ notify(method, params) {
115
+ this.send({ jsonrpc: '2.0', method, params });
116
+ }
117
+
118
+ close(error) {
119
+ if (this.closed) return;
120
+ this.closed = true;
121
+ for (const waiter of this.pending.values()) waiter.reject(error || new Error('连接已关闭'));
122
+ this.pending.clear();
123
+ this.emit('close', error);
124
+ }
125
+ }
126
+
127
+ module.exports = { JsonRpcPeer };