@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.
- package/README.md +88 -0
- package/docs/design-references.md +2 -0
- package/lib/args.js +2 -1
- package/lib/auth.js +1 -1
- package/lib/commands/daemon.js +411 -0
- package/lib/commands/device.js +92 -0
- package/lib/commands/diwork.js +544 -0
- package/lib/commands/index.js +5 -0
- package/lib/commands/open.js +89 -0
- package/lib/commands/tool.js +327 -0
- package/lib/daemon/agui.js +63 -0
- package/lib/daemon/channel.js +183 -0
- package/lib/daemon/enroll.js +78 -0
- package/lib/daemon/executors/acp.js +480 -0
- package/lib/daemon/executors/pi-approval-extension.ts +57 -0
- package/lib/daemon/executors/pi.js +360 -0
- package/lib/daemon/index.js +146 -0
- package/lib/daemon/jsonrpc.js +127 -0
- package/lib/daemon/permission.js +96 -0
- package/lib/daemon/roots.js +161 -0
- package/lib/daemon/runtimes.js +238 -0
- package/lib/daemon/service.js +135 -0
- package/lib/daemon/state.js +188 -0
- package/lib/daemon/supervisor.js +244 -0
- package/package.json +1 -1
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 工具(/api/open/tools/**):管理 MCP / REST-API 工具,并按子工具直接调用。
|
|
5
|
+
*
|
|
6
|
+
* 调用直接打工具、不经过 Agent / LLM;连接地址与认证一律用平台上已保存的配置,
|
|
7
|
+
* CLI 只传「子工具名 + 入参」。入参组装借鉴 `gh api -F/-f` 与 `kubectl --set`:
|
|
8
|
+
* --args-file < --args < --arg(后者覆盖前者同名键),--arg 值先按 JSON 解析、失败当字符串,
|
|
9
|
+
* key 支持点号嵌套(filter.status=open)。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const fs = require('node:fs');
|
|
13
|
+
|
|
14
|
+
const http = require('../http');
|
|
15
|
+
const dataInput = require('../data');
|
|
16
|
+
const output = require('../output');
|
|
17
|
+
const { CliError, EXIT } = output;
|
|
18
|
+
|
|
19
|
+
/** 单次调用的服务端硬上限是 120s;客户端多留 10s 给建连与返回。 */
|
|
20
|
+
const INVOKE_HTTP_TIMEOUT_MS = 130_000;
|
|
21
|
+
const INVOKE_TIMEOUT_MARGIN_MS = 10_000;
|
|
22
|
+
|
|
23
|
+
const LIST_COLUMNS = [
|
|
24
|
+
{ key: 'id', label: 'ID' },
|
|
25
|
+
{ key: 'name', label: '名称' },
|
|
26
|
+
{ key: 'scope', label: '归属' },
|
|
27
|
+
{ key: 'source', label: '来源' },
|
|
28
|
+
{ key: 'type', label: '类型' },
|
|
29
|
+
{ key: 'status', label: '状态' },
|
|
30
|
+
{ key: 'publishStatus', label: '发布' },
|
|
31
|
+
{ key: 'companyApprovalStatus', label: '授权' },
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
const SUBTOOL_COLUMNS = [
|
|
35
|
+
{ key: 'name', label: '子工具' },
|
|
36
|
+
{ key: 'grantStatus', label: '授权' },
|
|
37
|
+
{ key: 'description', label: '描述' },
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
const toolArg = { name: 'toolId', required: true, summary: '工具 id' };
|
|
41
|
+
|
|
42
|
+
function toolPath(ctx, suffix = '') {
|
|
43
|
+
return `/tools/${encodeURIComponent(ctx.args[0])}${suffix}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 是否按机器可读输出(显式 -o json/raw、--json、--jq,或标准输出非 TTY 时的缺省 json)。 */
|
|
47
|
+
function wantsJson(flags) {
|
|
48
|
+
return output.resolveFormat(flags) !== 'table' || Boolean(flags.json || flags.jq);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 读 --file:路径或 `-`(标准输入),必须是 JSON 对象。 */
|
|
52
|
+
function readJsonObjectFile(value, label) {
|
|
53
|
+
const raw = String(value) === '-' ? dataInput.readStdin() : readFileOrFail(value, label);
|
|
54
|
+
return parseJsonObject(raw, label);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function readFileOrFail(file, label) {
|
|
58
|
+
if (!fs.existsSync(file)) throw new CliError(`${label} 指定的文件不存在:${file}`, EXIT.USAGE);
|
|
59
|
+
return fs.readFileSync(file, 'utf8');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function parseJsonObject(text, label) {
|
|
63
|
+
let value;
|
|
64
|
+
try {
|
|
65
|
+
value = JSON.parse(text);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
throw new CliError(`${label} 不是合法 JSON:${error.message}`, EXIT.USAGE);
|
|
68
|
+
}
|
|
69
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
70
|
+
throw new CliError(`${label} 须为 JSON 对象`, EXIT.USAGE, { hint: '形如 {"query":"报销","limit":5}' });
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** `--arg` 的值:能按 JSON 解析就取解析值(数字 / 布尔 / 对象 / 带引号字符串),否则取原字符串。 */
|
|
76
|
+
function parseArgValue(raw) {
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(raw);
|
|
79
|
+
} catch {
|
|
80
|
+
return raw;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 把 `a.b.c=v` 写进嵌套对象;中途撞到非对象值时以新对象覆盖(后写者赢)。 */
|
|
85
|
+
function setPath(target, dottedKey, value) {
|
|
86
|
+
const parts = dottedKey.split('.');
|
|
87
|
+
let node = target;
|
|
88
|
+
for (let i = 0; i < parts.length - 1; i += 1) {
|
|
89
|
+
const key = parts[i];
|
|
90
|
+
if (!node[key] || typeof node[key] !== 'object' || Array.isArray(node[key])) node[key] = {};
|
|
91
|
+
node = node[key];
|
|
92
|
+
}
|
|
93
|
+
node[parts[parts.length - 1]] = value;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 合并三种入参来源:--args-file < --args < --arg。导出供单测。 */
|
|
97
|
+
function buildArguments(flags) {
|
|
98
|
+
const merged = {};
|
|
99
|
+
if (flags.argsFile !== undefined) Object.assign(merged, readJsonObjectFile(flags.argsFile, '--args-file'));
|
|
100
|
+
if (flags.args !== undefined) Object.assign(merged, parseJsonObject(String(flags.args), '--args'));
|
|
101
|
+
for (const item of flags.arg || []) {
|
|
102
|
+
const text = String(item);
|
|
103
|
+
const eq = text.indexOf('=');
|
|
104
|
+
if (eq <= 0) throw new CliError(`--arg 需要 key=value 形式,收到:${text}`, EXIT.USAGE);
|
|
105
|
+
const key = text.slice(0, eq);
|
|
106
|
+
if (key.split('.').some((p) => !p)) throw new CliError(`--arg 的键不合法:${key}`, EXIT.USAGE);
|
|
107
|
+
setPath(merged, key, parseArgValue(text.slice(eq + 1)));
|
|
108
|
+
}
|
|
109
|
+
return merged;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** table 模式呈现调用结果:文本内容直出,其余结构化内容缩进 JSON。 */
|
|
113
|
+
function renderContent(content) {
|
|
114
|
+
if (content === null || content === undefined) return '';
|
|
115
|
+
if (typeof content === 'string') return content;
|
|
116
|
+
const items = Array.isArray(content) ? content : [content];
|
|
117
|
+
return items
|
|
118
|
+
.map((item) => {
|
|
119
|
+
if (item && typeof item === 'object' && item.type === 'text' && typeof item.text === 'string') return item.text;
|
|
120
|
+
return JSON.stringify(item, null, 2);
|
|
121
|
+
})
|
|
122
|
+
.join('\n');
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const list = {
|
|
126
|
+
name: 'list',
|
|
127
|
+
summary: '列出可见工具(分页)',
|
|
128
|
+
flags: {
|
|
129
|
+
scope: { type: 'string', summary: 'personal | team | company(缺省为全部可见)' },
|
|
130
|
+
source: { type: 'string', summary: '按来源过滤,如 mcp' },
|
|
131
|
+
keyword: { type: 'string', summary: '关键词,命中名称 / 副标题 / 描述' },
|
|
132
|
+
page: { type: 'number', summary: '页码,从 1 开始' },
|
|
133
|
+
'page-size': { type: 'number', summary: '每页条数(上限 100)' },
|
|
134
|
+
paginate: { type: 'boolean', summary: '自动翻页取全部' },
|
|
135
|
+
},
|
|
136
|
+
examples: ['wd-cli tool list', 'wd-cli tool list --scope company --source mcp', 'wd-cli tool list --keyword 工单 --paginate'],
|
|
137
|
+
async run(ctx) {
|
|
138
|
+
const options = {
|
|
139
|
+
path: '/tools',
|
|
140
|
+
query: {
|
|
141
|
+
scope: ctx.flags.scope,
|
|
142
|
+
source: ctx.flags.source,
|
|
143
|
+
keyword: ctx.flags.keyword,
|
|
144
|
+
pageNum: ctx.flags.page,
|
|
145
|
+
pageSize: ctx.flags.pageSize,
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
const result = ctx.flags.paginate ? await http.requestAllPages(ctx, options) : await http.request(ctx, options);
|
|
149
|
+
const rows = Array.isArray(result) ? result : result && result.list ? result.list : [];
|
|
150
|
+
output.print(wantsJson(ctx.flags) ? result : rows, { flags: ctx.flags, columns: LIST_COLUMNS, empty: '没有可见的工具' });
|
|
151
|
+
return EXIT.OK;
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const get = {
|
|
156
|
+
name: 'get',
|
|
157
|
+
summary: '查看工具详情(认证与自定义参数值已脱敏)',
|
|
158
|
+
args: [toolArg],
|
|
159
|
+
examples: ['wd-cli tool get 12', 'wd-cli tool get 12 -o json --jq .config'],
|
|
160
|
+
async run(ctx) {
|
|
161
|
+
output.print(await http.request(ctx, { path: toolPath(ctx) }), { flags: ctx.flags });
|
|
162
|
+
return EXIT.OK;
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const subtools = {
|
|
167
|
+
name: 'subtools',
|
|
168
|
+
summary: '列出子工具与授权状态;--name 查看单个子工具的入参结构',
|
|
169
|
+
args: [toolArg],
|
|
170
|
+
flags: { name: { type: 'string', summary: '子工具名:输出其完整定义(含 inputSchema)' } },
|
|
171
|
+
examples: ['wd-cli tool subtools 12', 'wd-cli tool subtools 12 --name search_docs -o json'],
|
|
172
|
+
async run(ctx) {
|
|
173
|
+
const result = (await http.request(ctx, { path: toolPath(ctx, '/subtools') })) || {};
|
|
174
|
+
const items = Array.isArray(result.tools) ? result.tools : [];
|
|
175
|
+
if (result.ok === false && result.message) output.warn(result.message, ctx.flags);
|
|
176
|
+
if (ctx.flags.name !== undefined) {
|
|
177
|
+
const wanted = String(ctx.flags.name);
|
|
178
|
+
const hit = items.find((item) => item && item.name === wanted);
|
|
179
|
+
if (!hit) {
|
|
180
|
+
const names = items.map((item) => item && item.name).filter(Boolean);
|
|
181
|
+
throw new CliError(`子工具不存在:${wanted}`, EXIT.BUSINESS, {
|
|
182
|
+
hint: names.length ? `可用子工具:${names.join(', ')}` : '该工具没有可用子工具',
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
output.print(hit, { flags: ctx.flags });
|
|
186
|
+
return EXIT.OK;
|
|
187
|
+
}
|
|
188
|
+
output.print(wantsJson(ctx.flags) ? result : items, { flags: ctx.flags, columns: SUBTOOL_COLUMNS, empty: '该工具没有子工具' });
|
|
189
|
+
return EXIT.OK;
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const create = {
|
|
194
|
+
name: 'create',
|
|
195
|
+
summary: '从 JSON 文件创建工具',
|
|
196
|
+
principals: ['user'],
|
|
197
|
+
flags: { file: { type: 'string', summary: '工具定义 JSON 文件路径,- 为标准输入(必填)' } },
|
|
198
|
+
examples: ['wd-cli tool create --file mcp-tool.json', 'cat tool.json | wd-cli tool create --file -'],
|
|
199
|
+
async run(ctx) {
|
|
200
|
+
if (ctx.flags.file === undefined) {
|
|
201
|
+
throw new CliError('缺少 --file', EXIT.USAGE, {
|
|
202
|
+
hint: '认证值建议用凭证引用:auth.valueSource=credential + auth.credentialKey,不要把明文写进文件',
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
const body = readJsonObjectFile(ctx.flags.file, '--file');
|
|
206
|
+
const created = await http.request(ctx, { method: 'POST', path: '/tools', body });
|
|
207
|
+
if (wantsJson(ctx.flags)) {
|
|
208
|
+
output.print(created, { flags: ctx.flags });
|
|
209
|
+
} else {
|
|
210
|
+
output.success(`已创建工具 ${created && created.id ? created.id : ''}`.trim(), ctx.flags);
|
|
211
|
+
if (created && created.id) output.print(created.id, { flags: ctx.flags });
|
|
212
|
+
}
|
|
213
|
+
return EXIT.OK;
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const update = {
|
|
218
|
+
name: 'update',
|
|
219
|
+
summary: '以 JSON 局部更新工具',
|
|
220
|
+
principals: ['user'],
|
|
221
|
+
args: [toolArg],
|
|
222
|
+
flags: { file: { type: 'string', summary: '更新内容 JSON 文件路径,- 为标准输入(必填)' } },
|
|
223
|
+
examples: ['wd-cli tool update 12 --file patch.json', 'echo \'{"description":"新描述"}\' | wd-cli tool update 12 --file -'],
|
|
224
|
+
async run(ctx) {
|
|
225
|
+
if (ctx.flags.file === undefined) throw new CliError('缺少 --file', EXIT.USAGE);
|
|
226
|
+
const body = readJsonObjectFile(ctx.flags.file, '--file');
|
|
227
|
+
await http.request(ctx, { method: 'PUT', path: toolPath(ctx), body });
|
|
228
|
+
output.success(`已更新工具 ${ctx.args[0]}`, ctx.flags);
|
|
229
|
+
return EXIT.OK;
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const remove = {
|
|
234
|
+
name: 'delete',
|
|
235
|
+
summary: '删除工具',
|
|
236
|
+
principals: ['user'],
|
|
237
|
+
args: [toolArg],
|
|
238
|
+
examples: ['wd-cli tool delete 12 --yes'],
|
|
239
|
+
async run(ctx) {
|
|
240
|
+
const ok = await dataInput.confirm(`确认删除工具 ${ctx.args[0]}?`, ctx.flags);
|
|
241
|
+
if (!ok) {
|
|
242
|
+
output.info('已取消', ctx.flags);
|
|
243
|
+
return EXIT.OK;
|
|
244
|
+
}
|
|
245
|
+
await http.request(ctx, { method: 'DELETE', path: toolPath(ctx) });
|
|
246
|
+
output.success('已删除', ctx.flags);
|
|
247
|
+
return EXIT.OK;
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
const testCommand = {
|
|
252
|
+
name: 'test',
|
|
253
|
+
summary: '按已保存配置探测连通性(MCP 拉子工具清单 / REST 探测服务地址)',
|
|
254
|
+
args: [toolArg],
|
|
255
|
+
examples: ['wd-cli tool test 12'],
|
|
256
|
+
async run(ctx) {
|
|
257
|
+
const result = (await http.request(ctx, { method: 'POST', path: toolPath(ctx, '/test') })) || {};
|
|
258
|
+
if (wantsJson(ctx.flags)) {
|
|
259
|
+
output.print(result, { flags: ctx.flags });
|
|
260
|
+
} else if (result.ok) {
|
|
261
|
+
const bits = [result.message || '连接成功'];
|
|
262
|
+
if (typeof result.latencyMs === 'number') bits.push(`${result.latencyMs}ms`);
|
|
263
|
+
output.success(bits.join(','), ctx.flags);
|
|
264
|
+
}
|
|
265
|
+
if (!result.ok) {
|
|
266
|
+
throw new CliError(result.message || '连通性探测失败', EXIT.BUSINESS, {
|
|
267
|
+
hint: result.credentialUnresolved ? '工具引用的平台凭证不可用,先在平台「凭证」页配置该标识' : undefined,
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
return EXIT.OK;
|
|
271
|
+
},
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
const invoke = {
|
|
275
|
+
name: 'invoke',
|
|
276
|
+
summary: '直接调用工具',
|
|
277
|
+
args: [toolArg, { name: 'subtool', required: true, summary: '子工具名(MCP 工具名 / REST 操作名)' }],
|
|
278
|
+
flags: {
|
|
279
|
+
arg: { type: 'string', repeat: true, summary: '入参 key=value,可重复;值按 JSON 解析(失败当字符串),key 支持 a.b 嵌套' },
|
|
280
|
+
args: { type: 'string', summary: '入参 JSON 对象,如 \'{"query":"x"}\'' },
|
|
281
|
+
'args-file': { type: 'string', summary: '入参 JSON 文件,- 为标准输入' },
|
|
282
|
+
},
|
|
283
|
+
examples: [
|
|
284
|
+
'wd-cli tool invoke 12 search_docs --arg query=报销 --arg limit=5',
|
|
285
|
+
'wd-cli tool invoke 30 getOrder --args \'{"orderId":"A1"}\'',
|
|
286
|
+
'echo \'{"orderId":"A1"}\' | wd-cli tool invoke 30 getOrder --args-file - -o json',
|
|
287
|
+
"wd-cli tool invoke 30 getOrder --arg 'orderId=\"007\"' # 保留前导零:值写成 JSON 字符串",
|
|
288
|
+
],
|
|
289
|
+
async run(ctx) {
|
|
290
|
+
const body = { subtool: ctx.args[1], arguments: buildArguments(ctx.flags) };
|
|
291
|
+
// --timeout-ms 同时约束服务端调用(透传)与本次 HTTP 等待(多留余量);缺省按服务端上限等待
|
|
292
|
+
if (ctx.flags.timeoutMs) {
|
|
293
|
+
body.timeoutMs = ctx.flags.timeoutMs;
|
|
294
|
+
ctx.flags.timeoutMs += INVOKE_TIMEOUT_MARGIN_MS;
|
|
295
|
+
} else {
|
|
296
|
+
ctx.flags.timeoutMs = INVOKE_HTTP_TIMEOUT_MS;
|
|
297
|
+
}
|
|
298
|
+
const result = (await http.request(ctx, { method: 'POST', path: toolPath(ctx, '/invoke'), body })) || {};
|
|
299
|
+
if (result.truncated) output.warn('返回内容过大,已被服务端截断', ctx.flags);
|
|
300
|
+
if (result.ok === false) {
|
|
301
|
+
if (wantsJson(ctx.flags)) output.print(result, { flags: ctx.flags });
|
|
302
|
+
throw new CliError(result.message || '调用失败', EXIT.BUSINESS);
|
|
303
|
+
}
|
|
304
|
+
if (wantsJson(ctx.flags)) {
|
|
305
|
+
output.print(result, { flags: ctx.flags });
|
|
306
|
+
} else {
|
|
307
|
+
output.print(renderContent(result.content), { flags: ctx.flags });
|
|
308
|
+
if (typeof result.latencyMs === 'number') output.info(`耗时 ${result.latencyMs}ms`, ctx.flags);
|
|
309
|
+
}
|
|
310
|
+
if (result.isError) {
|
|
311
|
+
output.warn(`工具返回错误${result.httpStatus ? `(HTTP ${result.httpStatus})` : ''}`, ctx.flags);
|
|
312
|
+
return EXIT.BUSINESS;
|
|
313
|
+
}
|
|
314
|
+
return EXIT.OK;
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
module.exports = {
|
|
319
|
+
id: 'tool',
|
|
320
|
+
summary: '工具:列出 / 详情 / 子工具 / 增删改 / 连通性测试 / 直接调用',
|
|
321
|
+
description:
|
|
322
|
+
'调用(invoke)直接打工具、会产生真实副作用;连接与认证取平台已保存配置。工作空间令牌(wat_)只能查看与调用本空间团队工具和免审批公司级工具,增删改需登录态。',
|
|
323
|
+
principals: ['workspace'],
|
|
324
|
+
commands: [list, get, subtools, create, update, remove, testCommand, invoke],
|
|
325
|
+
buildArguments,
|
|
326
|
+
renderContent,
|
|
327
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* AG-UI 事件构造(design D4)。执行器只用这里的函数产出事件,保证各运行时上送同一套形状。
|
|
5
|
+
* 自定义事件统一以 local_agent.* 命名,页面据此渲染思考、计划、工具详情(含 diff)与审批卡。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const crypto = require('node:crypto');
|
|
9
|
+
|
|
10
|
+
function id(prefix) {
|
|
11
|
+
return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function base(type, ctx, extra) {
|
|
15
|
+
return { type, threadId: ctx.threadId, runId: ctx.runId, timestamp: Date.now(), ...extra };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const agui = {
|
|
19
|
+
newId: id,
|
|
20
|
+
runStarted: (ctx) => base('RUN_STARTED', ctx, {}),
|
|
21
|
+
runFinished: (ctx, result) => base('RUN_FINISHED', ctx, result ? { result } : {}),
|
|
22
|
+
runError: (ctx, code, message) => base('RUN_ERROR', ctx, { code, message }),
|
|
23
|
+
textStart: (ctx, messageId) => base('TEXT_MESSAGE_START', ctx, { messageId, role: 'assistant' }),
|
|
24
|
+
textContent: (ctx, messageId, delta) => base('TEXT_MESSAGE_CONTENT', ctx, { messageId, delta }),
|
|
25
|
+
textEnd: (ctx, messageId) => base('TEXT_MESSAGE_END', ctx, { messageId }),
|
|
26
|
+
// parentMessageId 在 AG-UI schema 里是可选字符串:没有就省略,传 null 会被客户端校验拒绝
|
|
27
|
+
reasoningStart: (ctx, messageId) => base('REASONING_MESSAGE_START', ctx, { messageId, role: 'reasoning' }),
|
|
28
|
+
reasoningContent: (ctx, messageId, delta) => base('REASONING_MESSAGE_CONTENT', ctx, { messageId, delta }),
|
|
29
|
+
reasoningEnd: (ctx, messageId) => base('REASONING_MESSAGE_END', ctx, { messageId }),
|
|
30
|
+
toolStart: (ctx, toolCallId, toolCallName, parentMessageId) =>
|
|
31
|
+
base('TOOL_CALL_START', ctx, parentMessageId ? { toolCallId, toolCallName, parentMessageId } : { toolCallId, toolCallName }),
|
|
32
|
+
toolArgs: (ctx, toolCallId, delta) => base('TOOL_CALL_ARGS', ctx, { toolCallId, delta }),
|
|
33
|
+
toolEnd: (ctx, toolCallId) => base('TOOL_CALL_END', ctx, { toolCallId }),
|
|
34
|
+
toolResult: (ctx, toolCallId, content) =>
|
|
35
|
+
base('TOOL_CALL_RESULT', ctx, { messageId: id('tr'), toolCallId, content, role: 'tool' }),
|
|
36
|
+
custom: (ctx, name, value) => base('CUSTOM', ctx, { name, value }),
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** 把各种内容块(ACP ContentBlock / ToolCallContent)压成可读文本。 */
|
|
40
|
+
function contentToText(content) {
|
|
41
|
+
if (content === null || content === undefined) return '';
|
|
42
|
+
if (typeof content === 'string') return content;
|
|
43
|
+
if (Array.isArray(content)) return content.map(contentToText).filter(Boolean).join('\n');
|
|
44
|
+
if (typeof content !== 'object') return String(content);
|
|
45
|
+
if (content.type === 'text') return content.text || '';
|
|
46
|
+
if (content.type === 'content') return contentToText(content.content);
|
|
47
|
+
if (content.type === 'diff') return `diff ${content.path || ''}`;
|
|
48
|
+
if (content.type === 'terminal') return `[terminal ${content.terminalId || ''}]`;
|
|
49
|
+
if (content.type === 'resource_link') return content.uri || content.name || '';
|
|
50
|
+
if (content.type === 'resource') return (content.resource && (content.resource.text || content.resource.uri)) || '';
|
|
51
|
+
if (content.type === 'image') return '[image]';
|
|
52
|
+
return JSON.stringify(content);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 截断超长文本(工具输出可能很大),保留头尾。 */
|
|
56
|
+
function clip(text, max = 64 * 1024) {
|
|
57
|
+
const s = String(text || '');
|
|
58
|
+
if (s.length <= max) return s;
|
|
59
|
+
const half = Math.floor(max / 2);
|
|
60
|
+
return `${s.slice(0, half)}\n…(已截断 ${s.length - max} 字符)…\n${s.slice(-half)}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
module.exports = { agui, contentToText, clip };
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 设备通道客户端(design D2):SSE 下行 + POST 上行,纯 HTTP、零依赖、本机不监听端口。
|
|
5
|
+
*
|
|
6
|
+
* - 下行 `GET {bridge}/bridge/daemon/channel`:event=command 的帧交给 onCommand;30s 无任何字节视为断开;
|
|
7
|
+
* - 上行 `POST {bridge}/bridge/daemon/frames`:帧排队、单飞批量发送,失败退避重试且保序;
|
|
8
|
+
* - 断开后 1s 起、30s 封顶指数退避重连;401 先回调 onUnauthorized(重新登记),仍失败则停止。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const { EventEmitter } = require('node:events');
|
|
12
|
+
const { parseSseBlock } = require('../http');
|
|
13
|
+
|
|
14
|
+
const MAX_BATCH = 200;
|
|
15
|
+
const MAX_QUEUE = 20_000;
|
|
16
|
+
|
|
17
|
+
class BridgeChannel extends EventEmitter {
|
|
18
|
+
constructor({ bridgeUrl, getToken, onCommand, onUnauthorized, log, idleMs = 30_000 }) {
|
|
19
|
+
super();
|
|
20
|
+
this.bridgeUrl = String(bridgeUrl || '').replace(/\/+$/, '');
|
|
21
|
+
this.getToken = getToken;
|
|
22
|
+
this.onCommand = onCommand;
|
|
23
|
+
this.onUnauthorized = onUnauthorized || (async () => false);
|
|
24
|
+
this.log = log || (() => {});
|
|
25
|
+
this.idleMs = idleMs;
|
|
26
|
+
this.state = 'idle';
|
|
27
|
+
this.stopped = false;
|
|
28
|
+
this.backoffMs = 1000;
|
|
29
|
+
this.queue = [];
|
|
30
|
+
this.flushing = false;
|
|
31
|
+
this.abort = null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
start() {
|
|
35
|
+
this.stopped = false;
|
|
36
|
+
this.loop();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
stop() {
|
|
40
|
+
this.stopped = true;
|
|
41
|
+
if (this.abort) this.abort.abort();
|
|
42
|
+
this.setState('stopped');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
setState(state) {
|
|
46
|
+
if (this.state === state) return;
|
|
47
|
+
this.state = state;
|
|
48
|
+
this.emit('state', state);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async loop() {
|
|
52
|
+
while (!this.stopped) {
|
|
53
|
+
let unauthorized = false;
|
|
54
|
+
try {
|
|
55
|
+
unauthorized = await this.connectOnce();
|
|
56
|
+
} catch (error) {
|
|
57
|
+
this.log(`通道断开:${error.message}`);
|
|
58
|
+
}
|
|
59
|
+
if (this.stopped) break;
|
|
60
|
+
this.setState('disconnected');
|
|
61
|
+
if (unauthorized) {
|
|
62
|
+
const recovered = await this.onUnauthorized().catch(() => false);
|
|
63
|
+
if (!recovered) {
|
|
64
|
+
this.emit('fatal', new Error('设备令牌已失效且重新登记失败(设备可能已被撤销)'));
|
|
65
|
+
this.stop();
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
this.backoffMs = 1000;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const wait = this.backoffMs + Math.floor(Math.random() * 500);
|
|
72
|
+
this.backoffMs = Math.min(this.backoffMs * 2, 30_000);
|
|
73
|
+
await sleep(wait);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 建一次下行连接;返回 true 表示 401。 */
|
|
78
|
+
async connectOnce() {
|
|
79
|
+
this.setState('connecting');
|
|
80
|
+
const token = await this.getToken();
|
|
81
|
+
const controller = new AbortController();
|
|
82
|
+
this.abort = controller;
|
|
83
|
+
let idleTimer = null;
|
|
84
|
+
const resetIdle = () => {
|
|
85
|
+
clearTimeout(idleTimer);
|
|
86
|
+
idleTimer = setTimeout(() => controller.abort(), this.idleMs);
|
|
87
|
+
};
|
|
88
|
+
resetIdle();
|
|
89
|
+
try {
|
|
90
|
+
const response = await fetch(`${this.bridgeUrl}/bridge/daemon/channel`, {
|
|
91
|
+
headers: { Authorization: `Bearer ${token}`, Accept: 'text/event-stream' },
|
|
92
|
+
signal: controller.signal,
|
|
93
|
+
});
|
|
94
|
+
if (response.status === 401) return true;
|
|
95
|
+
if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);
|
|
96
|
+
this.setState('connected');
|
|
97
|
+
this.backoffMs = 1000;
|
|
98
|
+
this.emit('connected');
|
|
99
|
+
this.flush();
|
|
100
|
+
const decoder = new TextDecoder();
|
|
101
|
+
let buffer = '';
|
|
102
|
+
for await (const chunk of response.body) {
|
|
103
|
+
resetIdle();
|
|
104
|
+
buffer += decoder.decode(chunk, { stream: true }).replace(/\r\n/g, '\n');
|
|
105
|
+
let sep;
|
|
106
|
+
while ((sep = buffer.indexOf('\n\n')) >= 0) {
|
|
107
|
+
const block = buffer.slice(0, sep);
|
|
108
|
+
buffer = buffer.slice(sep + 2);
|
|
109
|
+
const parsed = parseSseBlock(block);
|
|
110
|
+
if (parsed && parsed.event === 'command' && parsed.data && typeof parsed.data === 'object') {
|
|
111
|
+
try {
|
|
112
|
+
this.onCommand(parsed.data);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
this.log(`处理命令失败:${error.message}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
throw new Error('下行流已结束');
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (error && error.name === 'AbortError') throw new Error(this.stopped ? '已停止' : `${this.idleMs}ms 无数据`);
|
|
122
|
+
throw error;
|
|
123
|
+
} finally {
|
|
124
|
+
clearTimeout(idleTimer);
|
|
125
|
+
this.abort = null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** 上行一帧(排队保序)。 */
|
|
130
|
+
send(frame) {
|
|
131
|
+
if (this.queue.length >= MAX_QUEUE) {
|
|
132
|
+
this.queue.shift();
|
|
133
|
+
this.log('上行队列已满,丢弃最旧的一帧');
|
|
134
|
+
}
|
|
135
|
+
this.queue.push(frame);
|
|
136
|
+
this.flush();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async flush() {
|
|
140
|
+
if (this.flushing || this.stopped) return;
|
|
141
|
+
this.flushing = true;
|
|
142
|
+
let retryMs = 500;
|
|
143
|
+
try {
|
|
144
|
+
while (this.queue.length && !this.stopped) {
|
|
145
|
+
const batch = this.queue.slice(0, MAX_BATCH);
|
|
146
|
+
try {
|
|
147
|
+
const token = await this.getToken();
|
|
148
|
+
const response = await fetch(`${this.bridgeUrl}/bridge/daemon/frames`, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
151
|
+
body: JSON.stringify({ frames: batch }),
|
|
152
|
+
});
|
|
153
|
+
if (response.status === 401) {
|
|
154
|
+
await response.text().catch(() => '');
|
|
155
|
+
throw new Error('上行鉴权失败');
|
|
156
|
+
}
|
|
157
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
158
|
+
await response.text().catch(() => '');
|
|
159
|
+
this.queue.splice(0, batch.length);
|
|
160
|
+
retryMs = 500;
|
|
161
|
+
} catch (error) {
|
|
162
|
+
this.log(`上行失败,${retryMs}ms 后重试:${error.message}`);
|
|
163
|
+
await sleep(retryMs);
|
|
164
|
+
retryMs = Math.min(retryMs * 2, 15_000);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
} finally {
|
|
168
|
+
this.flushing = false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 等上行队列发完(停止前尽量把终态事件送出去)。 */
|
|
173
|
+
async drain(timeoutMs = 5000) {
|
|
174
|
+
const deadline = Date.now() + timeoutMs;
|
|
175
|
+
while (this.queue.length && Date.now() < deadline) await sleep(100);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function sleep(ms) {
|
|
180
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
module.exports = { BridgeChannel };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 设备登记(design D3):用 wd-cli auth login 的用户身份调 open-server,换取 ldt_ 设备令牌并存入钥匙串。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const http = require('../http');
|
|
8
|
+
const { CliError, EXIT } = require('../output');
|
|
9
|
+
const state = require('./state');
|
|
10
|
+
|
|
11
|
+
function cliVersion() {
|
|
12
|
+
try {
|
|
13
|
+
return require('../../package.json').version;
|
|
14
|
+
} catch {
|
|
15
|
+
return '0.0.0';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 登记(或重登记轮换令牌),返回 { deviceId, name, deviceToken, storage }。 */
|
|
20
|
+
async function enroll(ctx, { name } = {}) {
|
|
21
|
+
if (ctx.principal !== 'user') {
|
|
22
|
+
throw new CliError('本机登记需要统一身份登录态', EXIT.USAGE, { hint: '先执行 wd-cli auth login(不要用 --token / WD_CLI_TOKEN)' });
|
|
23
|
+
}
|
|
24
|
+
const daemonConfig = state.loadDaemonConfig(ctx.env);
|
|
25
|
+
const host = state.hostInfo();
|
|
26
|
+
const result = await http.request(ctx, {
|
|
27
|
+
method: 'POST',
|
|
28
|
+
path: '/local-agents/devices/enroll',
|
|
29
|
+
body: {
|
|
30
|
+
deviceId: state.deviceId(ctx.env),
|
|
31
|
+
name: name || daemonConfig.deviceName || host.hostname,
|
|
32
|
+
hostname: host.hostname,
|
|
33
|
+
os: host.os,
|
|
34
|
+
arch: host.arch,
|
|
35
|
+
cliVersion: cliVersion(),
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
if (!result || !result.deviceToken) throw new CliError('登记响应缺少设备令牌', EXIT.BUSINESS);
|
|
39
|
+
const storage = state.saveDeviceToken(ctx.runtime.profileName, result.deviceToken, ctx.env);
|
|
40
|
+
return { ...result, storage };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 取本机设备令牌,没有就登记一次。 */
|
|
44
|
+
async function ensureDeviceToken(ctx) {
|
|
45
|
+
const existing = state.loadDeviceToken(ctx.runtime.profileName, ctx.env);
|
|
46
|
+
if (existing) return existing;
|
|
47
|
+
return (await enroll(ctx)).deviceToken;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 平台下发的清单与连接配置(失败时返回 null,daemon 用缺省值继续)。
|
|
52
|
+
* onError:失败原因的回调——daemon 据此写进日志(缺省只在 --verbose 下可见,曾让「bridge 地址悄悄回落」难以排查)。
|
|
53
|
+
*/
|
|
54
|
+
async function fetchManifest(ctx, onError) {
|
|
55
|
+
try {
|
|
56
|
+
return await http.request(ctx, { path: '/local-agents/manifest' });
|
|
57
|
+
} catch (error) {
|
|
58
|
+
ctx.log(`读取执行器清单失败:${error.message}`);
|
|
59
|
+
if (onError) onError(error);
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** bridge 基址:--bridge-url > WD_CLI_BRIDGE_URL > daemon.json bridgeUrl > 平台配置 > 平台基址。 */
|
|
65
|
+
function resolveBridgeUrl(ctx, manifest) {
|
|
66
|
+
const daemonConfig = state.loadDaemonConfig(ctx.env);
|
|
67
|
+
const candidates = [
|
|
68
|
+
ctx.flags.bridgeUrl,
|
|
69
|
+
ctx.env.WD_CLI_BRIDGE_URL,
|
|
70
|
+
daemonConfig.bridgeUrl,
|
|
71
|
+
manifest && manifest.bridgeBaseUrl,
|
|
72
|
+
ctx.runtime.baseUrl,
|
|
73
|
+
];
|
|
74
|
+
const hit = candidates.find((v) => typeof v === 'string' && v.trim());
|
|
75
|
+
return hit ? hit.trim().replace(/\/+$/, '') : '';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = { enroll, ensureDeviceToken, fetchManifest, resolveBridgeUrl, cliVersion };
|