@dmall-inc/wd-cli 0.1.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,96 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 审批代理(design D6):执行器遇到工具调用审批时调用 request(),返回所选 optionId(或 null 表示拒绝/超时)。
5
+ *
6
+ * - 只读类(kind 为 read / search / think / fetch,或工具名在 autoApprove 里)直接按「允许一次」放行;
7
+ * - 其余上送 local_agent.permission_request,等页面决定;超时自动拒绝,并上送 local_agent.permission_resolved。
8
+ */
9
+
10
+ const { agui } = require('./agui');
11
+
12
+ const AUTO_KINDS = new Set(['read', 'search', 'think', 'fetch']);
13
+
14
+ class PermissionBroker {
15
+ constructor({ emit, timeoutMs = 600_000, autoApprove = [], log } = {}) {
16
+ this.emit = emit;
17
+ this.timeoutMs = timeoutMs;
18
+ this.autoApprove = new Set(autoApprove);
19
+ this.log = log || (() => {});
20
+ this.waiting = new Map();
21
+ }
22
+
23
+ setTimeout(ms) {
24
+ if (Number.isFinite(ms) && ms > 0) this.timeoutMs = ms;
25
+ }
26
+
27
+ /**
28
+ * @param ctx {sessionId, threadId, runId}
29
+ * @param req {toolCallId, title, kind, toolName, input, options:[{optionId,name,kind}]}
30
+ * @returns Promise<{optionId|null, outcome:'selected'|'rejected'|'timeout'|'cancelled', auto:boolean}>
31
+ */
32
+ async request(ctx, req) {
33
+ const options = Array.isArray(req.options) && req.options.length ? req.options : defaultOptions();
34
+ const allowOnce = options.find((o) => o.kind === 'allow_once') || options.find((o) => String(o.kind).startsWith('allow'));
35
+ if (allowOnce && (AUTO_KINDS.has(req.kind) || (req.toolName && this.autoApprove.has(req.toolName)))) {
36
+ return { optionId: allowOnce.optionId, outcome: 'selected', auto: true };
37
+ }
38
+ const requestId = agui.newId('perm');
39
+ const expiresAt = Date.now() + this.timeoutMs;
40
+ this.emit(ctx, agui.custom(ctx, 'local_agent.permission_request', {
41
+ requestId,
42
+ toolCallId: req.toolCallId,
43
+ title: req.title,
44
+ kind: req.kind,
45
+ toolName: req.toolName,
46
+ input: req.input,
47
+ options,
48
+ expiresAt,
49
+ }));
50
+ return new Promise((resolve) => {
51
+ const timer = setTimeout(() => this.settle(requestId, null, 'timeout'), this.timeoutMs);
52
+ this.waiting.set(requestId, { ctx, options, resolve, timer });
53
+ });
54
+ }
55
+
56
+ /** 页面决定到达。approved=false 或 optionId 是 reject 类都视为拒绝。 */
57
+ decide(requestId, { optionId, approved } = {}) {
58
+ const entry = this.waiting.get(requestId);
59
+ if (!entry) return false;
60
+ let chosen = optionId ? entry.options.find((o) => o.optionId === optionId) : null;
61
+ if (!chosen && approved === true) {
62
+ chosen = entry.options.find((o) => o.kind === 'allow_once') || entry.options.find((o) => String(o.kind).startsWith('allow'));
63
+ }
64
+ if (!chosen && approved === false) {
65
+ chosen = entry.options.find((o) => o.kind === 'reject_once') || entry.options.find((o) => String(o.kind).startsWith('reject'));
66
+ }
67
+ if (!chosen) return false;
68
+ this.settle(requestId, chosen.optionId, String(chosen.kind).startsWith('reject') ? 'rejected' : 'selected');
69
+ return true;
70
+ }
71
+
72
+ /** 本会话(或全部)的未决审批一律取消(运行被取消 / 会话关闭)。 */
73
+ cancelAll(sessionId) {
74
+ for (const [requestId, entry] of this.waiting) {
75
+ if (!sessionId || entry.ctx.sessionId === sessionId) this.settle(requestId, null, 'cancelled');
76
+ }
77
+ }
78
+
79
+ settle(requestId, optionId, outcome) {
80
+ const entry = this.waiting.get(requestId);
81
+ if (!entry) return;
82
+ this.waiting.delete(requestId);
83
+ clearTimeout(entry.timer);
84
+ this.emit(entry.ctx, agui.custom(entry.ctx, 'local_agent.permission_resolved', { requestId, optionId, outcome }));
85
+ entry.resolve({ optionId, outcome, auto: false });
86
+ }
87
+ }
88
+
89
+ function defaultOptions() {
90
+ return [
91
+ { optionId: 'allow_once', name: '允许一次', kind: 'allow_once' },
92
+ { optionId: 'reject_once', name: '拒绝', kind: 'reject_once' },
93
+ ];
94
+ }
95
+
96
+ module.exports = { PermissionBroker, defaultOptions, AUTO_KINDS };
@@ -0,0 +1,161 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 白名单目录判定(design D7):一律按 realpath 比较,防符号链接逃逸。
5
+ *
6
+ * - 会话 cwd 必须是某个允许根本身或其子目录;
7
+ * - Agent 经 ACP fs 读写的文件必须落在会话 cwd 内。对尚不存在的文件(新建),取其最近的已存在祖先做 realpath。
8
+ */
9
+
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+
13
+ function realpathOrNull(p) {
14
+ try {
15
+ return fs.realpathSync.native(p);
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+
21
+ /** 对可能不存在的路径求「真实路径」:最近存在祖先的 realpath + 剩余段。 */
22
+ function resolveReal(target) {
23
+ let current = path.resolve(target);
24
+ const rest = [];
25
+ for (;;) {
26
+ const real = realpathOrNull(current);
27
+ if (real) return rest.length ? path.join(real, ...rest.reverse()) : real;
28
+ const parent = path.dirname(current);
29
+ if (parent === current) return null;
30
+ rest.push(path.basename(current));
31
+ current = parent;
32
+ }
33
+ }
34
+
35
+ function isInside(child, parent) {
36
+ if (!child || !parent) return false;
37
+ if (child === parent) return true;
38
+ const rel = path.relative(parent, child);
39
+ return Boolean(rel) && !rel.startsWith('..') && !path.isAbsolute(rel);
40
+ }
41
+
42
+ /** cwd 是否在允许根内;返回真实路径或 null。 */
43
+ function resolveAllowedCwd(cwd, allowedRoots) {
44
+ if (!cwd || !Array.isArray(allowedRoots) || allowedRoots.length === 0) return null;
45
+ const real = realpathOrNull(cwd);
46
+ if (!real) return null;
47
+ try {
48
+ if (!fs.statSync(real).isDirectory()) return null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ for (const root of allowedRoots) {
53
+ const rootReal = realpathOrNull(root);
54
+ if (rootReal && isInside(real, rootReal)) return real;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** 文件路径是否在会话目录内(相对路径按 cwd 解析)。返回真实路径或 null。 */
60
+ function resolveInside(file, cwdReal) {
61
+ if (!file || !cwdReal) return null;
62
+ const absolute = path.isAbsolute(file) ? file : path.join(cwdReal, file);
63
+ const real = resolveReal(absolute);
64
+ return real && isInside(real, cwdReal) ? real : null;
65
+ }
66
+
67
+ /** 规范化后加入白名单(目录须存在),返回新列表。 */
68
+ function addRoot(roots, dir) {
69
+ const real = realpathOrNull(path.resolve(dir));
70
+ if (!real) throw new Error(`目录不存在:${dir}`);
71
+ if (!fs.statSync(real).isDirectory()) throw new Error(`不是目录:${dir}`);
72
+ const next = roots.filter((r) => r !== real);
73
+ next.push(real);
74
+ return { roots: next, added: real };
75
+ }
76
+
77
+ function removeRoot(roots, dir) {
78
+ const real = realpathOrNull(path.resolve(dir)) || path.resolve(dir);
79
+ return roots.filter((r) => r !== real && r !== dir);
80
+ }
81
+
82
+ /** 真实路径所在的允许根(realpath),不在任何根内返回 null。 */
83
+ function rootOf(real, allowedRoots) {
84
+ for (const root of allowedRoots || []) {
85
+ const rootReal = realpathOrNull(root);
86
+ if (rootReal && isInside(real, rootReal)) return rootReal;
87
+ }
88
+ return null;
89
+ }
90
+
91
+ /** 目录浏览缺省跳过的目录名(点号开头的另由 showHidden 控制)。 */
92
+ const SKIPPED_DIRS = new Set(['node_modules']);
93
+ const LIST_LIMIT = 500;
94
+
95
+ /**
96
+ * 列出白名单内某目录的子目录(add-local-agent-projects,design D5)。
97
+ *
98
+ * - dir 为空:返回各允许根本身(realpath,存在的才列),parent 为 null;
99
+ * - 否则 dir 须经 realpath 落在某个允许根内,只返回子目录(符号链接目录解析后仍须在根内),
100
+ * 缺省跳过点号开头与 node_modules,按名称排序,最多 500 项;
101
+ * - parent:上级目录仍在同一根内时给出,在根目录上时为 null(页面回到根列表)。
102
+ *
103
+ * @returns {{ path: string|null, parent: string|null, entries: {name,path,git}[], truncated: boolean }}
104
+ */
105
+ function listDirs(dir, allowedRoots, { showHidden = false } = {}) {
106
+ const roots = Array.isArray(allowedRoots) ? allowedRoots : [];
107
+ if (!dir) {
108
+ const entries = [];
109
+ const seen = new Set();
110
+ for (const root of roots) {
111
+ const real = realpathOrNull(root);
112
+ if (!real || seen.has(real)) continue;
113
+ seen.add(real);
114
+ entries.push({ name: path.basename(real) || real, path: real, git: isGitRepo(real) });
115
+ }
116
+ return { path: null, parent: null, entries, truncated: false };
117
+ }
118
+ const real = resolveAllowedCwd(dir, roots);
119
+ if (!real) throw new Error(`目录不在本机白名单内:${dir}`);
120
+ const root = rootOf(real, roots);
121
+ let dirents;
122
+ try {
123
+ dirents = fs.readdirSync(real, { withFileTypes: true });
124
+ } catch (error) {
125
+ throw new Error(`无法读取目录:${dir}(${error.code || error.message})`);
126
+ }
127
+ const entries = [];
128
+ for (const d of dirents) {
129
+ if (!showHidden && d.name.startsWith('.')) continue;
130
+ if (SKIPPED_DIRS.has(d.name)) continue;
131
+ const full = path.join(real, d.name);
132
+ let childReal = full;
133
+ if (d.isSymbolicLink()) {
134
+ childReal = realpathOrNull(full);
135
+ if (!childReal || !isInside(childReal, root)) continue;
136
+ try {
137
+ if (!fs.statSync(childReal).isDirectory()) continue;
138
+ } catch {
139
+ continue;
140
+ }
141
+ } else if (!d.isDirectory()) {
142
+ continue;
143
+ }
144
+ entries.push({ name: d.name, path: childReal, git: isGitRepo(childReal) });
145
+ }
146
+ entries.sort((a, b) => a.name.localeCompare(b.name));
147
+ const truncated = entries.length > LIST_LIMIT;
148
+ const parentDir = path.dirname(real);
149
+ const parent = real !== root && parentDir !== real && isInside(parentDir, root) ? parentDir : null;
150
+ return { path: real, parent, entries: truncated ? entries.slice(0, LIST_LIMIT) : entries, truncated };
151
+ }
152
+
153
+ function isGitRepo(dir) {
154
+ try {
155
+ return fs.existsSync(path.join(dir, '.git'));
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+
161
+ module.exports = { resolveAllowedCwd, resolveInside, resolveReal, isInside, addRoot, removeRoot, rootOf, listDirs };
@@ -0,0 +1,238 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 运行时探测与执行器装配(design D8)。
5
+ *
6
+ * claude ACP 执行器;可用 = PATH 上有 claude,或 daemon.json 覆盖了命令。适配器缺省 claude-agent-acp,
7
+ * PATH 上没有时回落 `npx -y <manifest 包>@<版本>`。
8
+ * codex ACP 执行器;可用 = PATH 上有 codex(或覆盖命令)。适配器缺省 codex-acp,同上回落。
9
+ * pi RPC 执行器;可用 = PATH 上有 pi(或覆盖命令)。
10
+ * 其它 执行器包:~/.config/wd-cli/executors/node_modules 下声明了 wdCliExecutor 的包,
11
+ * 导出 { id, name?, detect?(), createSession(opts) },经 `wd-cli daemon executor add <包>` 安装。
12
+ */
13
+
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const { execFileSync, execFile } = require('node:child_process');
17
+
18
+ const { createAcpExecutor } = require('./executors/acp');
19
+ const { createPiExecutor } = require('./executors/pi');
20
+
21
+ const DEFAULT_ADAPTERS = {
22
+ claude: { package: '@zed-industries/claude-agent-acp', bin: 'claude-agent-acp', version: 'latest' },
23
+ codex: { package: '@zed-industries/codex-acp', bin: 'codex-acp', version: 'latest' },
24
+ };
25
+
26
+ const NAMES = { claude: 'Claude Code', codex: 'Codex', pi: 'Pi' };
27
+
28
+ function which(bin, env = process.env) {
29
+ if (!bin) return null;
30
+ if (bin.includes('/') || bin.includes('\\')) return fs.existsSync(bin) ? bin : null;
31
+ const exts = process.platform === 'win32' ? (env.PATHEXT || '.EXE;.CMD;.BAT').split(';') : [''];
32
+ for (const dir of String(env.PATH || '').split(path.delimiter)) {
33
+ if (!dir) continue;
34
+ for (const ext of exts) {
35
+ const candidate = path.join(dir, bin + ext);
36
+ try {
37
+ fs.accessSync(candidate, fs.constants.X_OK);
38
+ return candidate;
39
+ } catch {
40
+ // 继续找
41
+ }
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+
47
+ function versionOf(bin) {
48
+ try {
49
+ const out = execFileSync(bin, ['--version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
50
+ const m = out.match(/\d+\.\d+(?:\.\d+)?(?:[-.\w]*)?/);
51
+ return m ? m[0] : out.trim().slice(0, 32) || null;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * 异步版 --version(daemon 周期复检用,不阻塞事件循环)。成功结果按「路径 + mtime + size」缓存:
59
+ * 二进制没变就不再起进程;失败不缓存,下一轮重试——开机时 PATH / 网络未就绪、claude 自更新中途
60
+ * 导致的一次失败,不会让运行时一直停在不可用。
61
+ */
62
+ function versionOfAsync(bin, cache) {
63
+ let key = null;
64
+ try {
65
+ const st = fs.statSync(bin);
66
+ key = `${bin}|${st.mtimeMs}|${st.size}`;
67
+ } catch {
68
+ return Promise.resolve(null);
69
+ }
70
+ if (cache && cache.has(key)) return Promise.resolve(cache.get(key));
71
+ return new Promise((resolve) => {
72
+ execFile(bin, ['--version'], { encoding: 'utf8', timeout: 15000 }, (error, stdout) => {
73
+ if (error) return resolve(null);
74
+ const out = String(stdout || '');
75
+ const m = out.match(/\d+\.\d+(?:\.\d+)?(?:[-.\w]*)?/);
76
+ const version = m ? m[0] : out.trim().slice(0, 32) || null;
77
+ if (version && cache) {
78
+ for (const k of cache.keys()) if (k.startsWith(`${bin}|`)) cache.delete(k);
79
+ cache.set(key, version);
80
+ }
81
+ resolve(version);
82
+ });
83
+ });
84
+ }
85
+
86
+ function asCommand(value) {
87
+ if (Array.isArray(value) && value.length && value.every((v) => typeof v === 'string')) return value;
88
+ if (typeof value === 'string' && value.trim()) return value.trim().split(/\s+/);
89
+ return null;
90
+ }
91
+
92
+ /** ACP 适配器命令:覆盖 > PATH 上的适配器 bin > npx 回落。 */
93
+ function adapterCommand(id, override, manifest) {
94
+ const explicit = asCommand(override && override.command);
95
+ if (explicit) return explicit;
96
+ const adapter = { ...DEFAULT_ADAPTERS[id], ...((manifest && manifest.adapters && manifest.adapters[id]) || {}) };
97
+ if (which(adapter.bin)) return [adapter.bin];
98
+ const version = adapter.version && adapter.version !== 'latest' ? `@${adapter.version}` : '';
99
+ return ['npx', '-y', `${adapter.package}${version}`];
100
+ }
101
+
102
+ /**
103
+ * 探测内置运行时。返回 [{id,name,version,available,reason,executor}]。
104
+ * versions:可选的「bin → 版本」预探测结果(异步复检时传入),缺省同步执行 --version。
105
+ */
106
+ function detectBuiltin({ daemonConfig, manifest, log, versions }) {
107
+ const versionFor = (bin) => (versions && Object.prototype.hasOwnProperty.call(versions, bin) ? versions[bin] : versionOf(bin));
108
+ const overrides = daemonConfig.runtimes || {};
109
+ const out = [];
110
+ for (const id of ['claude', 'codex']) {
111
+ const override = overrides[id] || {};
112
+ const cli = which(id);
113
+ const hasOverride = Boolean(asCommand(override.command));
114
+ // 只认能正常回答 --version 的 CLI:PATH 上同名的占位脚本 / shim 不算安装
115
+ const version = cli ? versionFor(cli) : null;
116
+ const available = override.enabled !== false && Boolean(version || hasOverride);
117
+ const command = adapterCommand(id, override, manifest);
118
+ out.push({
119
+ id,
120
+ name: NAMES[id],
121
+ version,
122
+ available,
123
+ reason: available ? undefined : override.enabled === false ? '已在 daemon.json 中停用'
124
+ : cli ? `${id} --version 执行失败` : `未找到 ${id} 命令`,
125
+ executor: createAcpExecutor({
126
+ runtimeId: id,
127
+ command,
128
+ installHint: id === 'claude' ? '确认已安装 Claude Code 并登录' : '确认已安装 Codex CLI 并登录',
129
+ log,
130
+ }),
131
+ });
132
+ }
133
+ const piOverride = overrides.pi || {};
134
+ const piCommand = asCommand(piOverride.command) || ['pi'];
135
+ const piBin = which(piCommand[0]);
136
+ const piVersion = piBin ? versionFor(piBin) : null;
137
+ const piAvailable = piOverride.enabled !== false && Boolean(piVersion || asCommand(piOverride.command));
138
+ out.push({
139
+ id: 'pi',
140
+ name: NAMES.pi,
141
+ version: piVersion,
142
+ available: piAvailable,
143
+ reason: piAvailable ? undefined : piOverride.enabled === false ? '已在 daemon.json 中停用'
144
+ : piBin ? 'pi --version 执行失败(可能不是 Pi Coding Agent)' : '未找到 pi 命令(npm i -g @earendil-works/pi-coding-agent)',
145
+ executor: createPiExecutor({ command: piCommand, log }),
146
+ });
147
+ return out;
148
+ }
149
+
150
+ /** 已安装的执行器包(声明 package.json 的 wdCliExecutor 字段)。加载失败的包标记不可用,不影响其它运行时。 */
151
+ function detectPacks({ executorsDir, log }) {
152
+ const out = [];
153
+ const nodeModules = path.join(executorsDir, 'node_modules');
154
+ if (!fs.existsSync(nodeModules)) return out;
155
+ const candidates = [];
156
+ for (const entry of fs.readdirSync(nodeModules)) {
157
+ if (entry.startsWith('.')) continue;
158
+ if (entry.startsWith('@')) {
159
+ for (const sub of fs.readdirSync(path.join(nodeModules, entry))) candidates.push(path.join(nodeModules, entry, sub));
160
+ } else {
161
+ candidates.push(path.join(nodeModules, entry));
162
+ }
163
+ }
164
+ for (const dir of candidates) {
165
+ let pkg;
166
+ try {
167
+ pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
168
+ } catch {
169
+ continue;
170
+ }
171
+ if (!pkg.wdCliExecutor) continue;
172
+ try {
173
+ const mod = require(dir);
174
+ const executor = mod && (mod.default || mod);
175
+ if (!executor || typeof executor.createSession !== 'function' || !executor.id) throw new Error('未导出 { id, createSession }');
176
+ const detected = typeof executor.detect === 'function' ? executor.detect() || {} : {};
177
+ out.push({
178
+ id: executor.id,
179
+ name: executor.name || pkg.name,
180
+ version: detected.version || pkg.version,
181
+ available: detected.available !== false,
182
+ reason: detected.reason,
183
+ packageName: pkg.name,
184
+ packageVersion: pkg.version,
185
+ executor,
186
+ });
187
+ } catch (error) {
188
+ log(`执行器包加载失败:${pkg.name} ${error.message}`);
189
+ out.push({ id: String(pkg.wdCliExecutor.id || pkg.name), name: pkg.name, version: pkg.version, available: false, reason: `加载失败:${error.message}`, packageName: pkg.name, packageVersion: pkg.version });
190
+ }
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /** 全部运行时:内置在前,执行器包可覆盖同 id 的内置项。 */
196
+ function detectAll(opts) {
197
+ const map = new Map();
198
+ for (const r of detectBuiltin(opts)) map.set(r.id, r);
199
+ for (const r of detectPacks(opts)) map.set(r.id, r);
200
+ return [...map.values()];
201
+ }
202
+
203
+ /** 内置运行时要探测版本的二进制(与 detectBuiltin 的查找口径一致)。 */
204
+ function builtinBins(daemonConfig) {
205
+ const overrides = (daemonConfig && daemonConfig.runtimes) || {};
206
+ const bins = [which('claude'), which('codex'), which((asCommand((overrides.pi || {}).command) || ['pi'])[0])];
207
+ return [...new Set(bins.filter(Boolean))];
208
+ }
209
+
210
+ /** 异步全量探测(daemon 运行中复检用):版本探测并行、走缓存,不阻塞通道收发。 */
211
+ async function detectAllAsync(opts, cache) {
212
+ const bins = builtinBins(opts.daemonConfig);
213
+ const results = await Promise.all(bins.map((bin) => versionOfAsync(bin, cache)));
214
+ const versions = {};
215
+ bins.forEach((bin, i) => { versions[bin] = results[i]; });
216
+ const map = new Map();
217
+ for (const r of detectBuiltin({ ...opts, versions })) map.set(r.id, r);
218
+ for (const r of detectPacks(opts)) map.set(r.id, r);
219
+ return [...map.values()];
220
+ }
221
+
222
+ /** 两次探测的清单是否有差异(只比较上报给平台的字段)。 */
223
+ function inventoryChanged(a, b) {
224
+ return JSON.stringify(toInventory(a || [])) !== JSON.stringify(toInventory(b || []));
225
+ }
226
+
227
+ /** 上报给平台的形态(去掉执行器对象)。 */
228
+ function toInventory(runtimes) {
229
+ return runtimes.map((r) => ({ id: r.id, name: r.name, version: r.version || null, available: Boolean(r.available), reason: r.reason }));
230
+ }
231
+
232
+ function executorVersions(runtimes) {
233
+ const out = {};
234
+ for (const r of runtimes) if (r.packageName) out[r.id] = `${r.packageName}@${r.packageVersion}`;
235
+ return out;
236
+ }
237
+
238
+ module.exports = { detectAll, detectAllAsync, inventoryChanged, versionOfAsync, detectBuiltin, detectPacks, toInventory, executorVersions, adapterCommand, which, DEFAULT_ADAPTERS };
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 开机自启(design:wd-cli daemon service install|uninstall)。
5
+ * macOS ~/Library/LaunchAgents/com.dmall.wd-cli.daemon.plist(launchctl bootstrap gui/<uid>)
6
+ * Linux ~/.config/systemd/user/wd-cli-daemon.service(systemctl --user enable --now)
7
+ * 服务以前台模式运行 daemon,PATH 取安装时的 PATH,保证能找到 claude / codex / pi。
8
+ */
9
+
10
+ const fs = require('node:fs');
11
+ const os = require('node:os');
12
+ const path = require('node:path');
13
+ const { execFileSync } = require('node:child_process');
14
+
15
+ const LABEL = 'com.dmall.wd-cli.daemon';
16
+ const UNIT = 'wd-cli-daemon.service';
17
+
18
+ function cliEntry() {
19
+ return path.resolve(__dirname, '..', '..', 'bin', 'wd-cli.js');
20
+ }
21
+
22
+ function programArgs(profileName) {
23
+ const args = [process.execPath, cliEntry(), 'daemon', 'start', '--foreground'];
24
+ if (profileName) args.push('--profile', profileName);
25
+ return args;
26
+ }
27
+
28
+ function xmlEscape(s) {
29
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
30
+ }
31
+
32
+ function launchdPlist({ profileName, logPath, env }) {
33
+ const args = programArgs(profileName).map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
34
+ const envEntries = { PATH: env.PATH || '/usr/local/bin:/usr/bin:/bin', HOME: os.homedir() };
35
+ if (env.WD_CLI_CONFIG_DIR) envEntries.WD_CLI_CONFIG_DIR = env.WD_CLI_CONFIG_DIR;
36
+ const envXml = Object.entries(envEntries)
37
+ .map(([k, v]) => ` <key>${xmlEscape(k)}</key>\n <string>${xmlEscape(v)}</string>`)
38
+ .join('\n');
39
+ return `<?xml version="1.0" encoding="UTF-8"?>
40
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
41
+ <plist version="1.0">
42
+ <dict>
43
+ <key>Label</key>
44
+ <string>${LABEL}</string>
45
+ <key>ProgramArguments</key>
46
+ <array>
47
+ ${args}
48
+ </array>
49
+ <key>EnvironmentVariables</key>
50
+ <dict>
51
+ ${envXml}
52
+ </dict>
53
+ <key>RunAtLoad</key>
54
+ <true/>
55
+ <key>KeepAlive</key>
56
+ <true/>
57
+ <key>StandardOutPath</key>
58
+ <string>${xmlEscape(logPath)}</string>
59
+ <key>StandardErrorPath</key>
60
+ <string>${xmlEscape(logPath)}</string>
61
+ </dict>
62
+ </plist>
63
+ `;
64
+ }
65
+
66
+ function systemdUnit({ profileName, env }) {
67
+ const exec = programArgs(profileName).map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(' ');
68
+ const lines = [
69
+ '[Unit]',
70
+ 'Description=wd-cli daemon(水滴平台运行时纳管)',
71
+ 'After=network-online.target',
72
+ '',
73
+ '[Service]',
74
+ `ExecStart=${exec}`,
75
+ 'Restart=always',
76
+ 'RestartSec=5',
77
+ `Environment=PATH=${env.PATH || '/usr/local/bin:/usr/bin:/bin'}`,
78
+ ];
79
+ if (env.WD_CLI_CONFIG_DIR) lines.push(`Environment=WD_CLI_CONFIG_DIR=${env.WD_CLI_CONFIG_DIR}`);
80
+ lines.push('', '[Install]', 'WantedBy=default.target', '');
81
+ return lines.join('\n');
82
+ }
83
+
84
+ function targetPath() {
85
+ if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
86
+ if (process.platform === 'linux') return path.join(os.homedir(), '.config', 'systemd', 'user', UNIT);
87
+ return null;
88
+ }
89
+
90
+ function install({ profileName, logPath, env = process.env, dryRun = false }) {
91
+ const file = targetPath();
92
+ if (!file) throw new Error('当前系统不支持自动安装服务(仅 macOS launchd / Linux systemd)');
93
+ const content = process.platform === 'darwin' ? launchdPlist({ profileName, logPath, env }) : systemdUnit({ profileName, env });
94
+ if (dryRun) return { file, content, loaded: false };
95
+ fs.mkdirSync(path.dirname(file), { recursive: true });
96
+ fs.writeFileSync(file, content, { mode: 0o644 });
97
+ let loaded = false;
98
+ try {
99
+ if (process.platform === 'darwin') {
100
+ const domain = `gui/${process.getuid()}`;
101
+ try {
102
+ execFileSync('launchctl', ['bootout', domain, file], { stdio: 'ignore' });
103
+ } catch {
104
+ // 未加载过
105
+ }
106
+ execFileSync('launchctl', ['bootstrap', domain, file], { stdio: 'ignore' });
107
+ } else {
108
+ execFileSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' });
109
+ execFileSync('systemctl', ['--user', 'enable', '--now', UNIT], { stdio: 'ignore' });
110
+ }
111
+ loaded = true;
112
+ } catch {
113
+ loaded = false;
114
+ }
115
+ return { file, content, loaded };
116
+ }
117
+
118
+ function uninstall() {
119
+ const file = targetPath();
120
+ if (!file) throw new Error('当前系统不支持自动安装服务');
121
+ try {
122
+ if (process.platform === 'darwin') {
123
+ execFileSync('launchctl', ['bootout', `gui/${process.getuid()}`, file], { stdio: 'ignore' });
124
+ } else {
125
+ execFileSync('systemctl', ['--user', 'disable', '--now', UNIT], { stdio: 'ignore' });
126
+ }
127
+ } catch {
128
+ // 未加载
129
+ }
130
+ const existed = fs.existsSync(file);
131
+ if (existed) fs.unlinkSync(file);
132
+ return { file, existed };
133
+ }
134
+
135
+ module.exports = { install, uninstall, launchdPlist, systemdUnit, targetPath, LABEL, UNIT };