@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,480 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * ACP 执行器(design D8):每个平台会话起一个 ACP 适配器子进程(claude-agent-acp / codex-acp …),
5
+ * 经 stdio JSON-RPC 驱动,并把 session/update 映射成 AG-UI 事件。
6
+ *
7
+ * 映射表见 design D4。客户端能力只声明 fs 读写(限制在会话目录内),不声明 terminal——
8
+ * 适配器会退回自己执行命令,命令执行同样经 session/request_permission 走审批。
9
+ */
10
+
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+ const { spawn } = require('node:child_process');
14
+
15
+ const { JsonRpcPeer } = require('../jsonrpc');
16
+ const { agui, contentToText, clip } = require('../agui');
17
+ const { resolveInside } = require('../roots');
18
+
19
+ const ACP_PROTOCOL_VERSION = 1;
20
+ const CLIENT_INFO = { name: 'wd-cli-daemon', title: 'Waterdrop wd-cli daemon', version: '1' };
21
+ /** 适配器从拉起到建好会话的上限(含 npx 首次下载适配器);卡在登录 / 初始化时不再无限挂住会话 */
22
+ const START_TIMEOUT_MS = 120_000;
23
+ /** 取消后等适配器收口的上限:适配器假死不响应 session/cancel 时强杀,下一轮按续接重启 */
24
+ const CANCEL_GRACE_MS = 10_000;
25
+
26
+ class AcpSession {
27
+ /**
28
+ * @param opts.runtimeId claude / codex
29
+ * @param opts.command [cmd, ...args]
30
+ * @param opts.cwd 会话真实目录(已过白名单)
31
+ * @param opts.emit (ctx, event) => void
32
+ * @param opts.onRuntimeSession (runtimeSessionId) => void
33
+ * @param opts.permission PermissionBroker
34
+ * @param opts.platformSessionId
35
+ * @param opts.runtimeSessionId 上次绑定的 ACP 会话(支持 loadSession 时尝试续接)
36
+ */
37
+ constructor(opts) {
38
+ this.opts = opts;
39
+ this.log = opts.log || (() => {});
40
+ this.child = null;
41
+ this.peer = null;
42
+ this.acpSessionId = null;
43
+ this.ready = null;
44
+ this.ctx = null;
45
+ this.run = null;
46
+ this.startTimeoutMs = opts.startTimeoutMs || START_TIMEOUT_MS;
47
+ this.cancelGraceMs = opts.cancelGraceMs || CANCEL_GRACE_MS;
48
+ }
49
+
50
+ async start() {
51
+ if (this.ready) return this.ready;
52
+ this.ready = (async () => {
53
+ const [cmd, ...args] = this.opts.command;
54
+ this.log(`启动适配器:${[cmd, ...args].join(' ')}(cwd=${this.opts.cwd})`);
55
+ const child = spawn(cmd, args, {
56
+ cwd: this.opts.cwd,
57
+ env: { ...process.env, ...(this.opts.env || {}) },
58
+ stdio: ['pipe', 'pipe', 'pipe'],
59
+ });
60
+ this.child = child;
61
+ const startTimeout = new Promise((_, reject) => {
62
+ this.startTimer = setTimeout(() => reject(Object.assign(
63
+ new Error(`适配器 ${Math.round(this.startTimeoutMs / 1000)} 秒内未完成初始化(可能在等待登录或卡住)`),
64
+ { code: 'RUNTIME_START_TIMEOUT' })), this.startTimeoutMs);
65
+ });
66
+ startTimeout.catch(() => {});
67
+ const spawnError = new Promise((_, reject) => {
68
+ child.once('error', (error) => reject(Object.assign(new Error(`适配器启动失败:${error.message}`), { code: 'RUNTIME_UNAVAILABLE' })));
69
+ });
70
+ child.stderr.setEncoding('utf8');
71
+ child.stderr.on('data', (chunk) => this.log(`[${this.opts.runtimeId}] ${String(chunk).trimEnd()}`));
72
+ child.on('exit', (code, signal) => {
73
+ this.log(`适配器退出:code=${code} signal=${signal}`);
74
+ // 已被新进程替换(强杀后立即重启):旧进程的退出不能清掉新进程的状态
75
+ if (this.child !== child) return;
76
+ if (this.run) this.failRun('RUNTIME_EXITED', `运行时进程已退出(code=${code})`);
77
+ this.ready = null;
78
+ this.acpSessionId = null;
79
+ });
80
+
81
+ const peer = new JsonRpcPeer(child.stdout, child.stdin, { log: this.log });
82
+ this.peer = peer;
83
+ peer.onNotification((method, params) => this.onNotification(method, params));
84
+ peer.onRequest((method, params) => this.onRequest(method, params));
85
+
86
+ const init = await Promise.race([
87
+ startTimeout,
88
+ peer.request('initialize', {
89
+ protocolVersion: ACP_PROTOCOL_VERSION,
90
+ clientCapabilities: { fs: { readTextFile: true, writeTextFile: true }, terminal: false },
91
+ clientInfo: CLIENT_INFO,
92
+ }),
93
+ spawnError,
94
+ ]);
95
+ this.agentCapabilities = (init && init.agentCapabilities) || {};
96
+
97
+ if (this.opts.runtimeSessionId && this.agentCapabilities.loadSession) {
98
+ try {
99
+ this.loading = true;
100
+ await Promise.race([startTimeout, peer.request('session/load', { sessionId: this.opts.runtimeSessionId, cwd: this.opts.cwd, mcpServers: [] })]);
101
+ this.acpSessionId = this.opts.runtimeSessionId;
102
+ } catch (error) {
103
+ if (error.code === 'RUNTIME_START_TIMEOUT') throw error;
104
+ this.log(`续接运行时会话失败,改为新建:${error.message}`);
105
+ } finally {
106
+ this.loading = false;
107
+ }
108
+ }
109
+ if (!this.acpSessionId) {
110
+ const created = await Promise.race([startTimeout, peer.request('session/new', { cwd: this.opts.cwd, mcpServers: [] })]);
111
+ this.acpSessionId = created && created.sessionId;
112
+ if (!this.acpSessionId) throw new Error('适配器未返回 sessionId');
113
+ }
114
+ if (this.opts.onRuntimeSession) this.opts.onRuntimeSession(this.acpSessionId);
115
+ })();
116
+ try {
117
+ await this.ready;
118
+ } catch (error) {
119
+ this.ready = null;
120
+ this.kill(error.code === 'RUNTIME_START_TIMEOUT' ? 'SIGKILL' : 'SIGTERM');
121
+ throw error;
122
+ } finally {
123
+ clearTimeout(this.startTimer);
124
+ }
125
+ return this.ready;
126
+ }
127
+
128
+ /**
129
+ * 执行一轮:返回在 RUN_FINISHED / RUN_ERROR 发出后 resolve。
130
+ * images:[{mimeType, data(base64)}],适配器声明 promptCapabilities.image 时作为 ACP image 内容块发送。
131
+ */
132
+ async prompt(ctx, text, images = []) {
133
+ this.ctx = ctx;
134
+ this.run = { messageId: null, tools: new Map(), ended: false };
135
+ this.emit(agui.runStarted(ctx));
136
+ try {
137
+ await this.start();
138
+ } catch (error) {
139
+ this.failRun(error.code === 'RUNTIME_UNAVAILABLE' ? 'RUNTIME_UNAVAILABLE' : 'RUNTIME_START_FAILED',
140
+ `${error.message}${this.opts.installHint ? `;${this.opts.installHint}` : ''}`);
141
+ return;
142
+ }
143
+ const blocks = [];
144
+ if (images.length) {
145
+ const caps = (this.agentCapabilities && this.agentCapabilities.promptCapabilities) || {};
146
+ if (!caps.image) {
147
+ // 不悄悄丢图:用户以为模型看过图会被误导
148
+ this.failRun('IMAGE_UNSUPPORTED', `当前运行时(${this.opts.runtimeId})的 ACP 适配器不支持图片输入`);
149
+ return;
150
+ }
151
+ for (const img of images) blocks.push({ type: 'image', mimeType: img.mimeType, data: img.data });
152
+ }
153
+ if (text) blocks.push({ type: 'text', text });
154
+ try {
155
+ const result = await this.peer.request('session/prompt', {
156
+ sessionId: this.acpSessionId,
157
+ prompt: blocks,
158
+ });
159
+ this.finishRun({ stopReason: (result && result.stopReason) || 'end_turn' });
160
+ } catch (error) {
161
+ this.failRun('RUNTIME_ERROR', error.message || '运行时返回错误');
162
+ // 适配器报错(如上游超时)后进程内状态可能已坏,下一轮会空转直接 end_turn:
163
+ // 重启适配器,下一轮按 session/load 续接同一会话(不支持则新开)
164
+ if (this.acpSessionId) this.opts.runtimeSessionId = this.acpSessionId;
165
+ this.kill();
166
+ this.ready = null;
167
+ }
168
+ }
169
+
170
+ cancel() {
171
+ if (this.opts.permission) this.opts.permission.cancelAll(this.opts.platformSessionId);
172
+ if (!this.run) return;
173
+ if (!this.acpSessionId) {
174
+ // 还在启动(初始化卡住):直接结束进程,start() 随对端关闭失败收口
175
+ this.kill();
176
+ return;
177
+ }
178
+ if (this.peer) this.peer.notify('session/cancel', { sessionId: this.acpSessionId });
179
+ // 适配器假死不响应取消:宽限期后强杀,exit 处理收口本轮;下一轮按 session/load 续接
180
+ const run = this.run;
181
+ const timer = setTimeout(() => {
182
+ if (this.run !== run || run.ended) return;
183
+ this.log(`取消后 ${Math.round(this.cancelGraceMs / 1000)} 秒适配器仍未收口,强制重启`);
184
+ this.opts.runtimeSessionId = this.acpSessionId;
185
+ this.kill('SIGKILL');
186
+ }, this.cancelGraceMs);
187
+ timer.unref();
188
+ }
189
+
190
+ close() {
191
+ this.cancel();
192
+ this.kill();
193
+ }
194
+
195
+ kill(signal = 'SIGTERM') {
196
+ if (this.child && this.child.exitCode === null) {
197
+ try {
198
+ this.child.kill(signal);
199
+ } catch {
200
+ // 已退出
201
+ }
202
+ }
203
+ }
204
+
205
+ // ------------------------------------------------------------ 事件映射
206
+
207
+ emit(event) {
208
+ this.opts.emit(this.ctx, event);
209
+ }
210
+
211
+ /** 推理增量:映射为标准 REASONING_MESSAGE_*(与 work 同一套),DiWork 的推理折叠块直接渲染 */
212
+ reason(delta) {
213
+ if (!this.run) return;
214
+ if (this.run.messageId) {
215
+ this.emit(agui.textEnd(this.ctx, this.run.messageId));
216
+ this.run.messageId = null;
217
+ }
218
+ if (!this.run.reasoningId) {
219
+ this.run.reasoningId = agui.newId('rsn');
220
+ this.emit(agui.reasoningStart(this.ctx, this.run.reasoningId));
221
+ }
222
+ this.emit(agui.reasoningContent(this.ctx, this.run.reasoningId, delta));
223
+ }
224
+
225
+ closeReasoning() {
226
+ if (this.run && this.run.reasoningId) {
227
+ this.emit(agui.reasoningEnd(this.ctx, this.run.reasoningId));
228
+ this.run.reasoningId = null;
229
+ }
230
+ }
231
+
232
+ closeText() {
233
+ this.closeReasoning();
234
+ if (this.run && this.run.messageId) {
235
+ this.emit(agui.textEnd(this.ctx, this.run.messageId));
236
+ this.run.messageId = null;
237
+ }
238
+ }
239
+
240
+ finishRun(result) {
241
+ if (!this.run || this.run.ended) return;
242
+ this.closeText();
243
+ for (const [toolCallId, tool] of this.run.tools) {
244
+ if (tool.started && !tool.ended) {
245
+ if (!tool.argsSent) this.emit(agui.toolArgs(this.ctx, toolCallId, JSON.stringify(tool.rawInput === undefined ? {} : tool.rawInput)));
246
+ this.emit(agui.toolEnd(this.ctx, toolCallId));
247
+ }
248
+ }
249
+ this.run.ended = true;
250
+ this.emit(agui.runFinished(this.ctx, result));
251
+ this.run = null;
252
+ }
253
+
254
+ failRun(code, message) {
255
+ if (!this.run || this.run.ended) return;
256
+ this.closeText();
257
+ this.run.ended = true;
258
+ this.emit(agui.runError(this.ctx, code, message));
259
+ this.run = null;
260
+ }
261
+
262
+ onNotification(method, params) {
263
+ if (method !== 'session/update' || !params || !params.update) return;
264
+ const update = params.update;
265
+ // 可用斜杠命令(内置命令 + 技能 + 自定义命令)与是否在运行无关:会话建立后适配器会主动推一次
266
+ if (update.sessionUpdate === 'available_commands_update') {
267
+ this.availableCommands = normalizeCommands(update.availableCommands);
268
+ if (this.opts.onCommands) this.opts.onCommands(this.availableCommands);
269
+ return;
270
+ }
271
+ if (this.loading || !this.run) return; // session/load 时回放的历史不再上送
272
+ switch (update.sessionUpdate) {
273
+ case 'agent_message_chunk': {
274
+ const delta = contentToText(update.content);
275
+ if (!delta) return;
276
+ this.closeReasoning();
277
+ if (!this.run.messageId) {
278
+ this.run.messageId = agui.newId('msg');
279
+ this.emit(agui.textStart(this.ctx, this.run.messageId));
280
+ }
281
+ this.emit(agui.textContent(this.ctx, this.run.messageId, delta));
282
+ return;
283
+ }
284
+ case 'agent_thought_chunk': {
285
+ const text = contentToText(update.content);
286
+ if (text) this.reason(text);
287
+ return;
288
+ }
289
+ case 'tool_call':
290
+ this.onToolCall(update);
291
+ return;
292
+ case 'tool_call_update':
293
+ this.onToolCall(update);
294
+ return;
295
+ case 'plan':
296
+ this.emit(agui.custom(this.ctx, 'local_agent.plan', { entries: update.entries || [] }));
297
+ return;
298
+ default:
299
+ }
300
+ }
301
+
302
+ onToolCall(update) {
303
+ const toolCallId = update.toolCallId;
304
+ if (!toolCallId) return;
305
+ const tools = this.run.tools;
306
+ const tool = tools.get(toolCallId) || { started: false, ended: false, title: '', kind: 'other', status: 'pending' };
307
+ if (update.title) tool.title = update.title;
308
+ if (update.kind) tool.kind = update.kind;
309
+ if (update.status) tool.status = update.status;
310
+ if (update.rawInput !== undefined) tool.rawInput = update.rawInput;
311
+ if (update.rawOutput !== undefined) tool.rawOutput = update.rawOutput;
312
+ if (Array.isArray(update.content)) tool.content = update.content;
313
+ if (Array.isArray(update.locations)) tool.locations = update.locations;
314
+ tools.set(toolCallId, tool);
315
+
316
+ if (!tool.started) {
317
+ this.closeText();
318
+ tool.started = true;
319
+ this.emit(agui.toolStart(this.ctx, toolCallId, tool.title || tool.kind, null));
320
+ }
321
+ // 参数只发一次且要等它到齐:适配器(如 claude-agent-acp)先发 rawInput={} 的 tool_call,
322
+ // 真实参数在随后的 tool_call_update 里才流到。AG-UI 的 TOOL_CALL_ARGS 是增量拼接语义,
323
+ // 先发 "{}" 再发完整 JSON 会拼成非法串,页面卡片就停在空参数上
324
+ if (!tool.argsSent && hasInput(tool.rawInput)) {
325
+ tool.argsSent = true;
326
+ this.emit(agui.toolArgs(this.ctx, toolCallId, JSON.stringify(tool.rawInput)));
327
+ }
328
+
329
+ const diffs = (tool.content || [])
330
+ .filter((c) => c && c.type === 'diff')
331
+ .map((c) => ({ path: c.path, oldText: c.oldText == null ? null : clip(c.oldText), newText: clip(c.newText) }));
332
+ const outputText = clip(contentToText((tool.content || []).filter((c) => !c || c.type !== 'diff')));
333
+ this.emit(agui.custom(this.ctx, 'local_agent.tool_update', {
334
+ toolCallId,
335
+ title: tool.title,
336
+ kind: tool.kind,
337
+ status: tool.status,
338
+ input: tool.rawInput,
339
+ locations: tool.locations || [],
340
+ diffs,
341
+ output: outputText || undefined,
342
+ }));
343
+
344
+ if (!tool.ended && (tool.status === 'completed' || tool.status === 'failed')) {
345
+ if (!tool.argsSent) {
346
+ // 到终态仍没有非空参数(真无参工具):补发一次,保证 TOOL_CALL_ARGS 是合法 JSON
347
+ tool.argsSent = true;
348
+ this.emit(agui.toolArgs(this.ctx, toolCallId, JSON.stringify(tool.rawInput === undefined ? {} : tool.rawInput)));
349
+ }
350
+ tool.ended = true;
351
+ this.emit(agui.toolEnd(this.ctx, toolCallId));
352
+ let result = outputText;
353
+ if (!result && tool.rawOutput !== undefined) {
354
+ result = clip(typeof tool.rawOutput === 'string' ? tool.rawOutput : JSON.stringify(tool.rawOutput));
355
+ }
356
+ if (!result && diffs.length) result = diffs.map((d) => `已修改 ${d.path}`).join('\n');
357
+ this.emit(agui.toolResult(this.ctx, toolCallId, result || (tool.status === 'failed' ? '执行失败' : '完成')));
358
+ }
359
+ }
360
+
361
+ // ------------------------------------------------------------ 对端请求
362
+
363
+ async onRequest(method, params) {
364
+ switch (method) {
365
+ case 'session/request_permission':
366
+ return this.requestPermission(params);
367
+ case 'fs/read_text_file':
368
+ return this.readTextFile(params);
369
+ case 'fs/write_text_file':
370
+ return this.writeTextFile(params);
371
+ default:
372
+ throw Object.assign(new Error(`客户端未实现:${method}`), { code: -32601 });
373
+ }
374
+ }
375
+
376
+ async requestPermission(params) {
377
+ const call = params.toolCall || {};
378
+ const options = Array.isArray(params.options) ? params.options : [];
379
+ if (!this.run || !this.opts.permission) return { outcome: { outcome: 'cancelled' } };
380
+ const ctx = this.ctx;
381
+ const decision = await this.opts.permission.request(ctx, {
382
+ toolCallId: call.toolCallId,
383
+ title: call.title,
384
+ kind: call.kind,
385
+ toolName: call.title,
386
+ input: call.rawInput,
387
+ options,
388
+ });
389
+ if (decision.optionId) return { outcome: { outcome: 'selected', optionId: decision.optionId } };
390
+ if (decision.outcome === 'timeout') {
391
+ const reject = options.find((o) => o.kind === 'reject_once') || options.find((o) => String(o.kind).startsWith('reject'));
392
+ if (reject) return { outcome: { outcome: 'selected', optionId: reject.optionId } };
393
+ }
394
+ return { outcome: { outcome: 'cancelled' } };
395
+ }
396
+
397
+ readTextFile(params) {
398
+ const file = resolveInside(params.path, this.opts.cwd);
399
+ if (!file) throw Object.assign(new Error(`路径不在会话目录内:${params.path}`), { code: -32602 });
400
+ let text = fs.readFileSync(file, 'utf8');
401
+ if (params.line || params.limit) {
402
+ const lines = text.split('\n');
403
+ const start = Math.max(0, (Number(params.line) || 1) - 1);
404
+ const end = params.limit ? start + Number(params.limit) : lines.length;
405
+ text = lines.slice(start, end).join('\n');
406
+ }
407
+ return { content: text };
408
+ }
409
+
410
+ writeTextFile(params) {
411
+ const file = resolveInside(params.path, this.opts.cwd);
412
+ if (!file) throw Object.assign(new Error(`路径不在会话目录内:${params.path}`), { code: -32602 });
413
+ fs.mkdirSync(path.dirname(file), { recursive: true });
414
+ fs.writeFileSync(file, String(params.content == null ? '' : params.content));
415
+ return null;
416
+ }
417
+ }
418
+
419
+ /** 参数是否已有实际内容(空对象 / 空数组 / 空串视为未到齐) */
420
+ function hasInput(value) {
421
+ if (value === undefined || value === null) return false;
422
+ if (typeof value === 'string') return value.length > 0;
423
+ if (Array.isArray(value)) return value.length > 0;
424
+ if (typeof value === 'object') return Object.keys(value).length > 0;
425
+ return true;
426
+ }
427
+
428
+ /** ACP 执行器工厂:与 Pi 执行器包同构(id / detect 由 runtimes.js 负责,这里只建会话)。 */
429
+ /** ACP AvailableCommand[] → [{name, description, hint}](去重、去前导斜杠、限量)。 */
430
+ function normalizeCommands(list) {
431
+ const out = [];
432
+ const seen = new Set();
433
+ for (const c of Array.isArray(list) ? list : []) {
434
+ const name = c && typeof c.name === 'string' ? c.name.replace(/^\//, '').trim() : '';
435
+ if (!name || seen.has(name)) continue;
436
+ seen.add(name);
437
+ const hint = c.input && typeof c.input.hint === 'string' ? c.input.hint : undefined;
438
+ out.push({ name, description: typeof c.description === 'string' ? clip(c.description, 300) : undefined, hint });
439
+ if (out.length >= 200) break;
440
+ }
441
+ return out;
442
+ }
443
+
444
+ function createAcpExecutor({ runtimeId, command, installHint, log }) {
445
+ return {
446
+ id: runtimeId,
447
+ kind: 'acp',
448
+ createSession(opts) {
449
+ return new AcpSession({ ...opts, runtimeId, command, installHint, log });
450
+ },
451
+ /**
452
+ * 拉起一次适配器、建会话,等它推送可用命令后关闭——用户还没发过消息时,页面的「/」候选也有内容。
453
+ * 超时或失败返回 null(不影响正常会话)。
454
+ */
455
+ async probeCommands({ cwd, timeoutMs = 20000 }) {
456
+ let resolveCommands;
457
+ const got = new Promise((resolve) => { resolveCommands = resolve; });
458
+ const session = new AcpSession({
459
+ runtimeId, command, installHint, log: () => {}, cwd,
460
+ platformSessionId: `probe_${runtimeId}`,
461
+ emit: () => {},
462
+ onCommands: (commands) => resolveCommands(commands),
463
+ });
464
+ let timer;
465
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), timeoutMs); });
466
+ try {
467
+ await Promise.race([session.start(), timeout]);
468
+ return await Promise.race([got, timeout]);
469
+ } catch (error) {
470
+ if (log) log(`探测 ${runtimeId} 可用命令失败:${error.message}`);
471
+ return null;
472
+ } finally {
473
+ clearTimeout(timer);
474
+ session.kill();
475
+ }
476
+ },
477
+ };
478
+ }
479
+
480
+ module.exports = { createAcpExecutor, AcpSession, ACP_PROTOCOL_VERSION, normalizeCommands };
@@ -0,0 +1,57 @@
1
+ // wd-cli daemon 注入给 Pi 的审批扩展(add-local-agent-runtime)。
2
+ //
3
+ // Pi 以 RPC 模式运行时,ctx.ui.confirm 会变成 stdout 上的 extension_ui_request,由 wd-cli daemon 接住、
4
+ // 转给 DiWork 页面审批,再以 extension_ui_response 回填。标题前缀 WDCLI_PERMISSION: 是与 daemon 的约定。
5
+ //
6
+ // 规则:
7
+ // - 只读工具(read / grep / find / ls)直接放行;
8
+ // - 读写类工具的 path 必须落在 WDCLI_ALLOWED_ROOT(会话目录)内,越界直接拦截,不进审批;
9
+ // - 其余调用(bash / write / edit / 自定义工具)都要审批,被拒绝即拦截。
10
+ import * as path from "node:path";
11
+ import * as fs from "node:fs";
12
+
13
+ const READ_ONLY = new Set(["read", "grep", "find", "ls"]);
14
+ const PATH_TOOLS = new Set(["read", "write", "edit", "grep", "find", "ls"]);
15
+
16
+ function realish(p: string): string {
17
+ let current = path.resolve(p);
18
+ const rest: string[] = [];
19
+ for (;;) {
20
+ try {
21
+ const real = fs.realpathSync.native(current);
22
+ return rest.length ? path.join(real, ...rest.reverse()) : real;
23
+ } catch {
24
+ const parent = path.dirname(current);
25
+ if (parent === current) return path.resolve(p);
26
+ rest.push(path.basename(current));
27
+ current = parent;
28
+ }
29
+ }
30
+ }
31
+
32
+ function inside(child: string, parent: string): boolean {
33
+ if (child === parent) return true;
34
+ const rel = path.relative(parent, child);
35
+ return !!rel && !rel.startsWith("..") && !path.isAbsolute(rel);
36
+ }
37
+
38
+ export default function (pi: any) {
39
+ const root = process.env.WDCLI_ALLOWED_ROOT ? realish(process.env.WDCLI_ALLOWED_ROOT) : null;
40
+
41
+ pi.on("tool_call", async (event: any, ctx: any) => {
42
+ const name: string = event.toolName;
43
+ const input = event.input || {};
44
+ if (root && PATH_TOOLS.has(name) && typeof input.path === "string") {
45
+ const target = realish(path.isAbsolute(input.path) ? input.path : path.join(root, input.path));
46
+ if (!inside(target, root)) {
47
+ return { block: true, reason: `路径不在允许的工作目录内:${input.path}` };
48
+ }
49
+ }
50
+ if (READ_ONLY.has(name)) return;
51
+ const ok = await ctx.ui.confirm(
52
+ `WDCLI_PERMISSION:${event.toolCallId}`,
53
+ JSON.stringify({ toolName: name, input }),
54
+ );
55
+ if (!ok) return { block: true, reason: "用户拒绝了这次工具调用" };
56
+ });
57
+ }