agent-bridge-aun 1.0.20 → 1.0.21
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
CHANGED
|
@@ -4,6 +4,10 @@
|
|
|
4
4
|
|
|
5
5
|
安装后在 ABWeb 的插件管理中启动 AUN 通道。配置 `aid` 和可选的 `agent_plugin`;默认 Agent 插件为 `qwenwork`。AID 创建接口为 `POST /api/plugins/aun/aid`,请求内容为 `{"aid":"新AID.agentid.cn","owner_aid":"所有者AID.agentid.cn"}`。
|
|
6
6
|
|
|
7
|
+
创建使用 SDK 的兼容注册流程;Owner AID 只保存为本地归属配置,不代表 AUN 协议 Owner 关系已签名或激活。Gateway 信任根使用随插件提供并校验指纹的 AUN 根证书,不从 Gateway 下载未经验证的 CA 链。
|
|
8
|
+
|
|
9
|
+
核心支持插件命令后,可运行 `mab aun status`、`mab aun list`、`mab aun agents`、`mab aun create <aid> --owner <owner-aid> [--agent <plugin-id>]`、`mab aun bind <aid> <plugin-id>` 和 `mab aun unbind <plugin-id>`。Agent 从当前已就绪的插件动态发现。创建后连接或关联失败时,响应会标明 AID 已创建;先用 `mab aun list` 检查,不要重试创建。命令不会记录原始参数或 Owner AID。
|
|
10
|
+
|
|
7
11
|
该插件依赖 `@agentunion/fastaun`,要求 Node.js 22.16 或更高版本。
|
|
8
12
|
|
|
9
13
|
ABWeb 的 AUN 设置只展示已连接 AID,并按来源分组。插件通过 SDK 密钥库枚举 AID,再逐个建立连接;只有连接成功的身份才会显示。EvolCore 来源身份只用于连接状态检测,不订阅消息,避免重复收信;本工程创建的身份负责消息收发。连接状态检测不调用 `ec agent list/show`。将 EvolCore 身份关联到 Agent 时仍使用既有 `ec agent set/reload` 路由配置,该配置不参与连接状态检测。列表先显示已关联 Agent 的身份,各组按最近成功关联的时间倒序排列,时间相同或旧记录没有时间时按 AID 名称排序。关联时间保存在插件配置的 `binding_times` 中,刷新或重启后保留;旧记录不补造时间,再次关联成功后开始记录。
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
-----BEGIN CERTIFICATE-----
|
|
2
|
+
MIIB/TCCAYOgAwIBAgIUI/WLfQXFR9KpvBlhnvJFIAtylNQwCgYIKoZIzj0EAwMw
|
|
3
|
+
KzEUMBIGA1UEAwwLQVVOIFJvb3QgQ0ExEzARBgNVBAoMCkFnZW50VW5pb24wIBcN
|
|
4
|
+
MjYwMzE3MDE1NDUyWhgPMjA1NjAzMDkwMTU5NTJaMCsxFDASBgNVBAMMC0FVTiBS
|
|
5
|
+
b290IENBMRMwEQYDVQQKDApBZ2VudFVuaW9uMHYwEAYHKoZIzj0CAQYFK4EEACID
|
|
6
|
+
YgAEbuQMkmsHjhtwsgoFhfgC4514k2IMQVECNeBtxiwiEe5OTY0D7MvqwtEzz67r
|
|
7
|
+
1jo2OXOuA+BajSW/ZOw89HH2zrWIshw2qVo5WP4ELnrKk/dipfiJBm9IrJXsO0kN
|
|
8
|
+
ope4o2YwZDASBgNVHRMBAf8ECDAGAQH/AgECMA4GA1UdDwEB/wQEAwIBhjAdBgNV
|
|
9
|
+
HQ4EFgQULmOUMJCtK8VatDpoo/iigMIu3hwwHwYDVR0jBBgwFoAULmOUMJCtK8Va
|
|
10
|
+
tDpoo/iigMIu3hwwCgYIKoZIzj0EAwMDaAAwZQIwPcby4jt32sKANZhUuFaOcWiy
|
|
11
|
+
V8rgbF0pF+ROrlg+9JdQ3yRyGWTU2VRNyzd+FlNbAjEAgVKYzN6mpxnVfjk8dHYH
|
|
12
|
+
vh6o6LY9oqw8rdZ/2Q1k1eUSaFxykTZQ9ipR84GIGXrc
|
|
13
|
+
-----END CERTIFICATE-----
|
|
@@ -3,16 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.AunPlugin = void 0;
|
|
4
4
|
const promises_1 = require("node:fs/promises");
|
|
5
5
|
const node_fs_1 = require("node:fs");
|
|
6
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
7
|
const node_module_1 = require("node:module");
|
|
7
8
|
const node_path_1 = require("node:path");
|
|
8
9
|
const node_os_1 = require("node:os");
|
|
9
10
|
const node_url_1 = require("node:url");
|
|
10
11
|
const messages_1 = require("./messages");
|
|
11
|
-
const evolcore_1 = require("./evolcore");
|
|
12
12
|
const manifest = {
|
|
13
|
-
id: "aun", version: "1.0.
|
|
13
|
+
id: "aun", version: "1.0.21", type: "channel", displayName: "AUN 通道",
|
|
14
14
|
entry: "dist/src-ts/plugins/aun/index.js", apiVersion: "1", process: "in-process",
|
|
15
|
-
capabilities: ["channel", "channel.identity.create", "channel.receive", "channel.send", "health"],
|
|
15
|
+
capabilities: ["channel", "channel.identity.create", "channel.receive", "channel.send", "health", "cli"],
|
|
16
16
|
configSchema: "config.schema.json",
|
|
17
17
|
managementPage: "/abweb/channels/aun",
|
|
18
18
|
};
|
|
@@ -31,6 +31,24 @@ async function loadSdk() {
|
|
|
31
31
|
throw new Error("未找到 @agentunion/fastaun,请确认 AUN 插件依赖已安装");
|
|
32
32
|
}
|
|
33
33
|
const aidPattern = /^[a-z0-9][a-z0-9_-]{2,63}\.[a-z0-9-]+(?:\.[a-z0-9-]+)+$/;
|
|
34
|
+
const aunRootFingerprint = "DD:09:E9:FD:31:6C:42:DC:7D:F3:5C:98:9C:2C:76:3A:A1:88:D8:4C:9C:C9:FC:D4:2E:A3:10:A2:62:1E:C5:45";
|
|
35
|
+
const cliCommands = [
|
|
36
|
+
{ name: "status", summary: "查看 AUN 通道状态", usage: "mab aun status" },
|
|
37
|
+
{ name: "list", summary: "查看已连接 AID 和 Agent 关联", usage: "mab aun list" },
|
|
38
|
+
{ name: "agents", summary: "列出当前已就绪的 Agent 插件", usage: "mab aun agents" },
|
|
39
|
+
{ name: "create", summary: "创建并连接 AID,可选关联 Agent", usage: "mab aun create <aid> --owner <owner-aid> [--agent <plugin-id>]", examples: ["mab aun create new.agentid.cn --owner owner.agentid.cn --agent qwenwork"] },
|
|
40
|
+
{ name: "bind", summary: "将 AID 关联到 Agent", usage: "mab aun bind <aid> <plugin-id>", examples: ["mab aun bind new.agentid.cn qwenwork"] },
|
|
41
|
+
{ name: "unbind", summary: "解除 Agent 与 AID 的关联", usage: "mab aun unbind <plugin-id>", examples: ["mab aun unbind qwenwork"] },
|
|
42
|
+
];
|
|
43
|
+
class AunCommandError extends Error {
|
|
44
|
+
statusCode;
|
|
45
|
+
data;
|
|
46
|
+
constructor(message, statusCode = 400, data) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.statusCode = statusCode;
|
|
49
|
+
this.data = data;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
34
52
|
class AunPlugin {
|
|
35
53
|
options;
|
|
36
54
|
manifest = manifest;
|
|
@@ -57,10 +75,9 @@ class AunPlugin {
|
|
|
57
75
|
}
|
|
58
76
|
identity = {
|
|
59
77
|
list: async () => {
|
|
60
|
-
const connected = [...this.clients.keys()];
|
|
61
78
|
return {
|
|
62
|
-
evolcore:
|
|
63
|
-
muAgentBridge:
|
|
79
|
+
evolcore: [],
|
|
80
|
+
muAgentBridge: [...this.clients.keys()].sort(),
|
|
64
81
|
localMuAgentBridge: [...this.identities].filter((aid) => !this.clients.has(aid)).sort(),
|
|
65
82
|
};
|
|
66
83
|
},
|
|
@@ -72,11 +89,13 @@ class AunPlugin {
|
|
|
72
89
|
this.creating = true;
|
|
73
90
|
try {
|
|
74
91
|
if (!this.identities.has(aid)) {
|
|
75
|
-
//
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
92
|
+
// Owner AID 是本地归属配置;身份签发沿用 EvolCore 的兼容注册流程。
|
|
93
|
+
if (!this.listStoreAids().includes(aid)) {
|
|
94
|
+
await this.prepareTrustRoots(aid);
|
|
95
|
+
const result = await this.store.register(aid);
|
|
96
|
+
if (!result.ok)
|
|
97
|
+
throw new Error(redact(result.error?.message ?? result.error?.code ?? "AID 注册失败"));
|
|
98
|
+
}
|
|
80
99
|
const loaded = this.store.load(aid);
|
|
81
100
|
if (!loaded.ok || !loaded.data)
|
|
82
101
|
throw new Error(loaded.error?.message ?? "注册后未能加载本地身份");
|
|
@@ -85,7 +104,7 @@ class AunPlugin {
|
|
|
85
104
|
this.config.owner_aid = owner;
|
|
86
105
|
this.config.aun_path = this.path();
|
|
87
106
|
await this.persist();
|
|
88
|
-
this.context?.logger.info("AUN 身份已创建", { aid
|
|
107
|
+
this.context?.logger.info("AUN 身份已创建", { aid });
|
|
89
108
|
}
|
|
90
109
|
const connectionError = !this.clients.has(aid) ? await this.connectAid(aid) : undefined;
|
|
91
110
|
return { aid, status: "已创建", connection: this.clients.has(aid) ? "ready" : "degraded", ...(connectionError ? { connectionError } : {}) };
|
|
@@ -94,7 +113,7 @@ class AunPlugin {
|
|
|
94
113
|
this.creating = false;
|
|
95
114
|
}
|
|
96
115
|
},
|
|
97
|
-
bind: async (pluginId, aid,
|
|
116
|
+
bind: async (pluginId, aid, _port) => {
|
|
98
117
|
if (pluginId === "aun" || pluginId === "abweb")
|
|
99
118
|
throw new Error("只能关联 Agent 插件");
|
|
100
119
|
const previous = this.bindings;
|
|
@@ -120,15 +139,21 @@ class AunPlugin {
|
|
|
120
139
|
this.bindings[aid] = pluginId;
|
|
121
140
|
}
|
|
122
141
|
else {
|
|
123
|
-
|
|
124
|
-
|
|
142
|
+
// 本地身份由插件直接接管,不再通过 ec 配置路由。
|
|
143
|
+
const loaded = this.store.load(aid);
|
|
144
|
+
if (!loaded.ok || !loaded.data)
|
|
145
|
+
throw new Error("AID 不在本地密钥库中,无法关联");
|
|
146
|
+
this.identities.add(aid);
|
|
147
|
+
if (!this.clients.has(aid))
|
|
148
|
+
await this.connectAid(aid);
|
|
149
|
+
if (!this.clients.has(aid))
|
|
125
150
|
throw new Error("AID 当前未连接");
|
|
126
|
-
await (0, evolcore_1.configureAidForPlugin)(pluginId, aid, port);
|
|
127
151
|
for (const [identity, target] of Object.entries(this.bindings))
|
|
128
152
|
if (target === pluginId) {
|
|
129
153
|
delete this.bindings[identity];
|
|
130
154
|
delete this.bindingTimes[identity];
|
|
131
155
|
}
|
|
156
|
+
this.bindings[aid] = pluginId;
|
|
132
157
|
}
|
|
133
158
|
}
|
|
134
159
|
else {
|
|
@@ -197,6 +222,8 @@ class AunPlugin {
|
|
|
197
222
|
["GET", "/api/plugins/aun/identities", this.listIdentities],
|
|
198
223
|
["POST", "/api/plugins/aun/bind", this.bindAgent],
|
|
199
224
|
["POST", "/api/plugins/aun/settings", this.saveSettings],
|
|
225
|
+
["GET", "/api/plugins/aun/commands", this.listCommands],
|
|
226
|
+
["POST", "/api/plugins/aun/commands", this.runCommand],
|
|
200
227
|
...(["", "/app.js", "/style.css"].map((suffix) => ["GET", `/abweb/channels/aun${suffix}`, this.servePage])),
|
|
201
228
|
]) {
|
|
202
229
|
const dispose = context.http.register({ method, path, handler });
|
|
@@ -214,13 +241,16 @@ class AunPlugin {
|
|
|
214
241
|
this.identities.add(this.aid);
|
|
215
242
|
for (const aid of this.identities)
|
|
216
243
|
await this.connectAid(aid);
|
|
217
|
-
//
|
|
218
|
-
for (const aid of this.listStoreAids())
|
|
244
|
+
// 密钥库中的其余 AID 也自动连接:不再依赖 ec 或 EvolCore 进程
|
|
245
|
+
for (const aid of this.listStoreAids()) {
|
|
246
|
+
this.identities.add(aid);
|
|
219
247
|
if (!this.clients.has(aid))
|
|
220
248
|
await this.connectAid(aid);
|
|
249
|
+
}
|
|
221
250
|
}
|
|
222
251
|
async connectAid(aid) {
|
|
223
252
|
try {
|
|
253
|
+
await this.prepareTrustRoots(aid);
|
|
224
254
|
const loaded = this.store.load(aid);
|
|
225
255
|
if (!loaded.ok || !loaded.data)
|
|
226
256
|
throw new Error(loaded.error?.message ?? "本地密钥库中不存在该 AID");
|
|
@@ -272,9 +302,49 @@ class AunPlugin {
|
|
|
272
302
|
return (0, node_path_1.resolve)(process.env.AUN_HOME ?? process.env.EVOLCORE_HOME ?? (0, node_path_1.join)((0, node_os_1.homedir)(), ".evolcore"));
|
|
273
303
|
}
|
|
274
304
|
newStore() {
|
|
275
|
-
const rootCaPath =
|
|
305
|
+
const rootCaPath = this.rootCaPath();
|
|
276
306
|
return new this.sdk.AIDStore({ aunPath: this.path(), encryptionSeed: typeof this.config.encryption_seed === "string" && this.config.encryption_seed ? this.config.encryption_seed : "evol", verifySsl: typeof this.config.verify_ssl === "boolean" ? this.config.verify_ssl : true, rootCaPath: (0, node_fs_1.existsSync)(rootCaPath) ? rootCaPath : undefined });
|
|
277
307
|
}
|
|
308
|
+
rootCaPath() {
|
|
309
|
+
return typeof this.config.root_ca_path === "string" && this.config.root_ca_path
|
|
310
|
+
? this.config.root_ca_path
|
|
311
|
+
: (0, node_path_1.join)(this.context.dataDir, "CA", "root", "root.crt");
|
|
312
|
+
}
|
|
313
|
+
async prepareTrustRoots(aid) {
|
|
314
|
+
const rootCaPath = this.rootCaPath();
|
|
315
|
+
const customPath = typeof this.config.root_ca_path === "string" && this.config.root_ca_path.trim();
|
|
316
|
+
if ((0, node_fs_1.existsSync)(rootCaPath)) {
|
|
317
|
+
if (customPath)
|
|
318
|
+
return;
|
|
319
|
+
const existing = new node_crypto_1.X509Certificate(await (0, promises_1.readFile)(rootCaPath, "utf8"));
|
|
320
|
+
if (existing.fingerprint256 !== aunRootFingerprint)
|
|
321
|
+
throw new Error("AUN 插件根证书指纹校验失败");
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (customPath)
|
|
325
|
+
throw new Error("配置的 AUN 根证书文件不存在");
|
|
326
|
+
try {
|
|
327
|
+
const cert = new node_crypto_1.X509Certificate(await (0, promises_1.readFile)((0, node_path_1.join)(__dirname, "certs", "root.crt"), "utf8"));
|
|
328
|
+
if (cert.fingerprint256 !== aunRootFingerprint)
|
|
329
|
+
throw new Error("内置 AUN 根证书指纹校验失败");
|
|
330
|
+
await (0, promises_1.mkdir)((0, node_path_1.dirname)(rootCaPath), { recursive: true });
|
|
331
|
+
await (0, promises_1.writeFile)(rootCaPath, cert.toString(), { mode: 0o600, flag: "wx" });
|
|
332
|
+
const oldStore = this.store;
|
|
333
|
+
const newStore = this.newStore();
|
|
334
|
+
this.store = newStore;
|
|
335
|
+
try {
|
|
336
|
+
await oldStore?.close();
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
this.context?.logger.warn("关闭旧 AUN Store 失败", { error: safeError(error) });
|
|
340
|
+
}
|
|
341
|
+
this.context?.logger.info("AUN 固定信任根证书已安装", { aid });
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
this.context?.logger.warn("AUN Gateway 信任根证书初始化失败", { aid, error: safeError(error) });
|
|
345
|
+
throw new Error(`AUN Gateway 信任根证书初始化失败:${safeError(error)}`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
278
348
|
createAid = async (request, response) => {
|
|
279
349
|
let input;
|
|
280
350
|
try {
|
|
@@ -367,6 +437,254 @@ class AunPlugin {
|
|
|
367
437
|
this.json(response, 400, { error: safeError(error) });
|
|
368
438
|
}
|
|
369
439
|
};
|
|
440
|
+
listCommands = async (_request, response) => {
|
|
441
|
+
response.setHeader("cache-control", "no-store");
|
|
442
|
+
this.json(response, 200, { protocolVersion: 1, plugin: "aun", version: manifest.version, commands: cliCommands });
|
|
443
|
+
};
|
|
444
|
+
runCommand = async (request, response) => {
|
|
445
|
+
try {
|
|
446
|
+
const chunks = [];
|
|
447
|
+
let size = 0;
|
|
448
|
+
for await (const chunk of request) {
|
|
449
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
450
|
+
size += buffer.length;
|
|
451
|
+
if (size > 65536)
|
|
452
|
+
throw new AunCommandError("请求内容过大");
|
|
453
|
+
chunks.push(buffer);
|
|
454
|
+
}
|
|
455
|
+
let input;
|
|
456
|
+
try {
|
|
457
|
+
input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
458
|
+
}
|
|
459
|
+
catch {
|
|
460
|
+
throw new AunCommandError("命令请求 JSON 格式无效");
|
|
461
|
+
}
|
|
462
|
+
if (!input || typeof input !== "object" || input.protocolVersion !== 1 || !Array.isArray(input.argv) || !input.argv.every((arg) => typeof arg === "string")) {
|
|
463
|
+
throw new AunCommandError("命令请求格式无效");
|
|
464
|
+
}
|
|
465
|
+
const result = await this.executeCommand(input.argv);
|
|
466
|
+
this.commandResult(response, 200, true, result.message, result.data);
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
const failure = error instanceof AunCommandError ? error : new AunCommandError(safeError(error), 502);
|
|
470
|
+
this.commandResult(response, failure.statusCode, false, failure.message, failure.data);
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
async executeCommand(argv) {
|
|
474
|
+
const [command, ...args] = argv;
|
|
475
|
+
if (command === "status" && !args.length)
|
|
476
|
+
return { message: this.healthMessage, data: await this.health() };
|
|
477
|
+
if (command === "list" && !args.length) {
|
|
478
|
+
const groups = await this.identity.list();
|
|
479
|
+
const aids = [...new Set([...groups.evolcore, ...groups.muAgentBridge, ...(groups.localMuAgentBridge ?? []), ...this.listStoreAids()])].sort();
|
|
480
|
+
return { message: aids.length ? `AID 列表:\n${aids.join("\n")}` : "暂无本地 AID", data: {
|
|
481
|
+
aids,
|
|
482
|
+
bindings: this.bindings,
|
|
483
|
+
bindingTimes: this.bindingTimes,
|
|
484
|
+
} };
|
|
485
|
+
}
|
|
486
|
+
if (command === "agents" && !args.length) {
|
|
487
|
+
const agents = await this.agents();
|
|
488
|
+
return { message: agents.length ? `当前已就绪的 Agent 插件:\n${agents.map((agent) => `${agent.id}(${agent.displayName})`).join("\n")}` : "暂无已就绪的 Agent 插件", data: agents };
|
|
489
|
+
}
|
|
490
|
+
if (command === "create")
|
|
491
|
+
return this.createCommand(args);
|
|
492
|
+
if (command === "bind" && args.length === 2) {
|
|
493
|
+
const [aid, pluginId] = args;
|
|
494
|
+
if (!aidPattern.test(aid))
|
|
495
|
+
throw new AunCommandError("AID 格式无效");
|
|
496
|
+
this.validatePluginId(pluginId);
|
|
497
|
+
await this.requireAgent(pluginId);
|
|
498
|
+
const replacedAids = (await this.agentBindings(pluginId)).filter((previousAid) => previousAid !== aid);
|
|
499
|
+
try {
|
|
500
|
+
await this.patchAgentAid(pluginId, aid);
|
|
501
|
+
}
|
|
502
|
+
catch (error) {
|
|
503
|
+
const bindingState = await this.bindingState(pluginId).catch(() => undefined);
|
|
504
|
+
throw new AunCommandError(`AID 关联请求失败,已回读当前状态:${safeError(error)}`, error instanceof AunCommandError ? error.statusCode : 502, { aid, agent: pluginId, ...(bindingState ? { bindingState } : { bindingState: "unknown" }) });
|
|
505
|
+
}
|
|
506
|
+
return {
|
|
507
|
+
message: replacedAids.length ? `AID ${replacedAids.join("、")} 已替换为 ${aid} 并关联到 ${pluginId}` : `AID 已关联到 ${pluginId}`,
|
|
508
|
+
data: { aid, agent: pluginId, replacedAids },
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
if (command === "unbind" && args.length === 1) {
|
|
512
|
+
const [pluginId] = args;
|
|
513
|
+
this.validatePluginId(pluginId);
|
|
514
|
+
await this.requireAgent(pluginId, false);
|
|
515
|
+
const unboundAids = await this.agentBindings(pluginId);
|
|
516
|
+
try {
|
|
517
|
+
await this.patchAgentAid(pluginId, "");
|
|
518
|
+
}
|
|
519
|
+
catch (error) {
|
|
520
|
+
const bindingState = await this.bindingState(pluginId).catch(() => undefined);
|
|
521
|
+
throw new AunCommandError(`解除关联请求失败,已回读当前状态:${safeError(error)}`, error instanceof AunCommandError ? error.statusCode : 502, { agent: pluginId, ...(bindingState ? { bindingState } : { bindingState: "unknown" }) });
|
|
522
|
+
}
|
|
523
|
+
return { message: `已解除 ${pluginId} 的 AID 关联`, data: { agent: pluginId, unboundAids } };
|
|
524
|
+
}
|
|
525
|
+
if (!["status", "list", "agents", "create", "bind", "unbind"].includes(command ?? ""))
|
|
526
|
+
throw new AunCommandError(`未知 AUN 命令:${command ?? ""}`);
|
|
527
|
+
throw new AunCommandError(`AUN 命令参数无效:${command}`);
|
|
528
|
+
}
|
|
529
|
+
async createCommand(args) {
|
|
530
|
+
const aid = args[0] ?? "";
|
|
531
|
+
if (!aidPattern.test(aid))
|
|
532
|
+
throw new AunCommandError("AID 格式无效");
|
|
533
|
+
let owner = "";
|
|
534
|
+
let agent = "";
|
|
535
|
+
for (let index = 1; index < args.length; index++) {
|
|
536
|
+
const option = args[index];
|
|
537
|
+
const value = args[++index];
|
|
538
|
+
if (!value || value.startsWith("--"))
|
|
539
|
+
throw new AunCommandError(`${option} 需要参数`);
|
|
540
|
+
if (option === "--owner" && !owner)
|
|
541
|
+
owner = value;
|
|
542
|
+
else if (option === "--agent" && !agent)
|
|
543
|
+
agent = value;
|
|
544
|
+
else
|
|
545
|
+
throw new AunCommandError(`不支持的创建参数:${option}`);
|
|
546
|
+
}
|
|
547
|
+
if (!owner || !aidPattern.test(owner))
|
|
548
|
+
throw new AunCommandError("需要有效的 --owner AID");
|
|
549
|
+
if (agent) {
|
|
550
|
+
this.validatePluginId(agent);
|
|
551
|
+
await this.requireAgent(agent);
|
|
552
|
+
}
|
|
553
|
+
let created;
|
|
554
|
+
try {
|
|
555
|
+
created = await this.identity.create(aid, owner);
|
|
556
|
+
}
|
|
557
|
+
catch (error) {
|
|
558
|
+
const exists = this.identities.has(aid) || this.listStoreAids().includes(aid);
|
|
559
|
+
if (exists)
|
|
560
|
+
throw new AunCommandError("AID 可能已创建,但后续连接或保存失败;请先执行 mab aun list 确认,不要重试创建", 502, { created: true, aid });
|
|
561
|
+
throw new AunCommandError(`AID 创建失败:${safeError(error).replaceAll(owner, "[已隐藏]")}`, 502);
|
|
562
|
+
}
|
|
563
|
+
const data = { created: true, aid, connection: created.connection ?? "ready" };
|
|
564
|
+
if (created.connection !== "ready")
|
|
565
|
+
throw new AunCommandError("AID 已创建,但连接失败;请先执行 mab aun list 确认,不要重试创建", 502, { ...data, connectionError: created.connectionError });
|
|
566
|
+
let replacedAids = [];
|
|
567
|
+
if (agent) {
|
|
568
|
+
try {
|
|
569
|
+
replacedAids = (await this.agentBindings(agent)).filter((previousAid) => previousAid !== aid);
|
|
570
|
+
await this.patchAgentAid(agent, aid);
|
|
571
|
+
}
|
|
572
|
+
catch (error) {
|
|
573
|
+
const bindingState = await this.bindingState(agent).catch(() => undefined);
|
|
574
|
+
throw new AunCommandError(`AID 已创建,但 Agent 关联失败,已回读当前状态:${safeError(error)}`, 502, { ...data, agent, ...(bindingState ? { bindingState } : { bindingState: "unknown" }) });
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return {
|
|
578
|
+
message: agent ? (replacedAids.length ? `AID ${replacedAids.join("、")} 已替换为 ${aid} 并关联到 ${agent}` : `AID 已创建并关联到 ${agent}`) : "AID 已创建并连接",
|
|
579
|
+
data: { ...data, ...(agent ? { agent, replacedAids } : {}) },
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
async agents(readyOnly = true) {
|
|
583
|
+
const payload = await this.controlRequest("/api/plugins");
|
|
584
|
+
if (!Array.isArray(payload.plugins))
|
|
585
|
+
throw new AunCommandError("控制 API 插件列表格式无效", 502);
|
|
586
|
+
return payload.plugins.filter((plugin) => !!plugin && typeof plugin === "object" && !Array.isArray(plugin))
|
|
587
|
+
.filter((plugin) => plugin.type === "agent" && (!readyOnly || plugin.status === "ready") && typeof plugin.id === "string" && /^[a-z][a-z0-9-]{1,63}$/.test(plugin.id))
|
|
588
|
+
.map((plugin) => ({ id: plugin.id, displayName: typeof plugin.displayName === "string" ? plugin.displayName : plugin.id }))
|
|
589
|
+
.sort((left, right) => left.id.localeCompare(right.id));
|
|
590
|
+
}
|
|
591
|
+
async requireAgent(pluginId, readyOnly = true) {
|
|
592
|
+
if (!(await this.agents(readyOnly)).some((agent) => agent.id === pluginId))
|
|
593
|
+
throw new AunCommandError(readyOnly ? "目标 Agent 不存在或尚未就绪" : "目标插件不存在或不是 Agent 插件");
|
|
594
|
+
}
|
|
595
|
+
validatePluginId(pluginId) {
|
|
596
|
+
if (!/^[a-z][a-z0-9-]{1,63}$/.test(pluginId) || pluginId === "aun" || pluginId === "abweb")
|
|
597
|
+
throw new AunCommandError("Agent 插件 ID 无效");
|
|
598
|
+
}
|
|
599
|
+
async patchAgentAid(pluginId, aid) {
|
|
600
|
+
await this.controlRequest(`/api/plugins/${encodeURIComponent(pluginId)}/aid`, "PATCH", { aid });
|
|
601
|
+
}
|
|
602
|
+
async agentBindings(pluginId) {
|
|
603
|
+
const aun = await this.controlPayload("/api/plugins/aun/identities");
|
|
604
|
+
if (!aun.bindings || typeof aun.bindings !== "object" || Array.isArray(aun.bindings))
|
|
605
|
+
throw new AunCommandError("AUN 身份列表格式无效", 502);
|
|
606
|
+
const bindings = aun.bindings;
|
|
607
|
+
return Object.entries(bindings).filter(([, target]) => target === pluginId).map(([aid]) => aid).sort();
|
|
608
|
+
}
|
|
609
|
+
async bindingState(pluginId) {
|
|
610
|
+
const [aun, agent] = await Promise.all([
|
|
611
|
+
this.agentBindings(pluginId),
|
|
612
|
+
this.controlPayload(`/api/plugins/${encodeURIComponent(pluginId)}/config`),
|
|
613
|
+
]);
|
|
614
|
+
return {
|
|
615
|
+
aunAids: aun,
|
|
616
|
+
agentAid: typeof agent.aid === "string" ? agent.aid : "",
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
async controlRequest(path, method = "GET", body) {
|
|
620
|
+
const result = await this.controlPayload(path, method, body);
|
|
621
|
+
if (result.ok !== true)
|
|
622
|
+
throw new AunCommandError("本机控制 API 响应未确认操作成功", 502);
|
|
623
|
+
return result;
|
|
624
|
+
}
|
|
625
|
+
async controlPayload(path, method = "GET", body) {
|
|
626
|
+
const base = this.controlUrl();
|
|
627
|
+
let response;
|
|
628
|
+
try {
|
|
629
|
+
response = await fetch(new URL(path, base), {
|
|
630
|
+
method,
|
|
631
|
+
headers: { accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }) },
|
|
632
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
633
|
+
signal: AbortSignal.timeout(5000),
|
|
634
|
+
redirect: "error",
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
catch (error) {
|
|
638
|
+
throw new AunCommandError(`本机控制 API 请求失败:${safeError(error)}`, 502);
|
|
639
|
+
}
|
|
640
|
+
let raw;
|
|
641
|
+
try {
|
|
642
|
+
raw = await readResponse(response, 65536);
|
|
643
|
+
}
|
|
644
|
+
catch (error) {
|
|
645
|
+
if (error instanceof AunCommandError)
|
|
646
|
+
throw error;
|
|
647
|
+
throw new AunCommandError(`本机控制 API 响应读取失败:${safeError(error)}`, 502);
|
|
648
|
+
}
|
|
649
|
+
let payload;
|
|
650
|
+
try {
|
|
651
|
+
payload = JSON.parse(raw);
|
|
652
|
+
}
|
|
653
|
+
catch {
|
|
654
|
+
throw new AunCommandError("本机控制 API 返回的 JSON 无效", 502);
|
|
655
|
+
}
|
|
656
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
657
|
+
throw new AunCommandError("本机控制 API 响应格式无效", 502);
|
|
658
|
+
const result = payload;
|
|
659
|
+
if (!response.ok) {
|
|
660
|
+
const message = typeof result.error === "string" ? result.error : `HTTP ${response.status}`;
|
|
661
|
+
throw new AunCommandError(`本机控制 API 操作失败:${message}`, response.status >= 400 && response.status < 500 ? response.status : 502);
|
|
662
|
+
}
|
|
663
|
+
return result;
|
|
664
|
+
}
|
|
665
|
+
controlUrl() {
|
|
666
|
+
const controlUrl = this.context?.runtime?.controlUrl;
|
|
667
|
+
if (!controlUrl)
|
|
668
|
+
throw new AunCommandError("运行时未提供 controlUrl,请更新核心服务", 502);
|
|
669
|
+
let url;
|
|
670
|
+
try {
|
|
671
|
+
url = new URL(controlUrl);
|
|
672
|
+
}
|
|
673
|
+
catch {
|
|
674
|
+
throw new AunCommandError("运行时 controlUrl 无效", 502);
|
|
675
|
+
}
|
|
676
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
|
677
|
+
if (url.protocol !== "http:" || !["127.0.0.1", "::1"].includes(hostname) || url.username || url.password || (url.pathname !== "/") || url.search || url.hash) {
|
|
678
|
+
throw new AunCommandError("运行时 controlUrl 必须指向本机回环地址", 502);
|
|
679
|
+
}
|
|
680
|
+
return url;
|
|
681
|
+
}
|
|
682
|
+
commandResult(response, status, ok, message, data) {
|
|
683
|
+
response.statusCode = status;
|
|
684
|
+
response.setHeader("content-type", "application/json; charset=utf-8");
|
|
685
|
+
response.setHeader("cache-control", "no-store");
|
|
686
|
+
response.end(JSON.stringify({ ok, message, ...(data === undefined ? {} : { data }) }));
|
|
687
|
+
}
|
|
370
688
|
servePage = async (request, response) => {
|
|
371
689
|
const path = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
372
690
|
const file = path.endsWith("/app.js") ? "app.js" : path.endsWith("/style.css") ? "style.css" : "index.html";
|
|
@@ -428,6 +746,34 @@ exports.default = AunPlugin;
|
|
|
428
746
|
function safeError(error) {
|
|
429
747
|
return redact(error instanceof Error ? error.message : String(error)).slice(0, 240);
|
|
430
748
|
}
|
|
749
|
+
async function readResponse(response, limit) {
|
|
750
|
+
if (!response.body) {
|
|
751
|
+
const raw = await response.text();
|
|
752
|
+
if (Buffer.byteLength(raw) > limit)
|
|
753
|
+
throw new AunCommandError("响应内容过大", 502);
|
|
754
|
+
return raw;
|
|
755
|
+
}
|
|
756
|
+
const reader = response.body.getReader();
|
|
757
|
+
const chunks = [];
|
|
758
|
+
let size = 0;
|
|
759
|
+
try {
|
|
760
|
+
while (true) {
|
|
761
|
+
const { done, value } = await reader.read();
|
|
762
|
+
if (done)
|
|
763
|
+
break;
|
|
764
|
+
size += value.byteLength;
|
|
765
|
+
if (size > limit) {
|
|
766
|
+
await reader.cancel();
|
|
767
|
+
throw new AunCommandError("响应内容过大", 502);
|
|
768
|
+
}
|
|
769
|
+
chunks.push(Buffer.from(value));
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
finally {
|
|
773
|
+
reader.releaseLock();
|
|
774
|
+
}
|
|
775
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
776
|
+
}
|
|
431
777
|
function redact(message) {
|
|
432
778
|
return message.replace(/(private[_ -]?key|seed|token|certificate)\s*[:=]\s*[^\s,;]+/gi, "$1=[已隐藏]");
|
|
433
779
|
}
|
|
@@ -37,8 +37,15 @@
|
|
|
37
37
|
configForm.elements.encryption_seed.value = "";
|
|
38
38
|
}
|
|
39
39
|
list.replaceChildren();
|
|
40
|
-
const entries = [
|
|
41
|
-
|
|
40
|
+
const entries = [];
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
for (const [group, label, values] of [[0, "本工程 · 已连接", identities.groups.muAgentBridge || []], [1, "EvolCore · 已连接", identities.groups.evolcore || []]]) {
|
|
43
|
+
for (const aid of values) {
|
|
44
|
+
if (seen.has(aid)) continue;
|
|
45
|
+
seen.add(aid);
|
|
46
|
+
entries.push({ aid, label, group, bound: identities.bindings?.[aid] || agents.find((agent) => agent.id && agent.configAid === aid)?.id || "", time: Date.parse(identities.bindingTimes?.[aid] || "") || 0 });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
42
49
|
entries.sort((a, b) => Number(Boolean(b.bound)) - Number(Boolean(a.bound)) || a.group - b.group || b.time - a.time || a.aid.localeCompare(b.aid));
|
|
43
50
|
for (const { aid, label, bound } of entries) {
|
|
44
51
|
const row = document.createElement("tr");
|
|
@@ -49,7 +56,7 @@
|
|
|
49
56
|
cell.append(select); row.append(cell); list.append(row);
|
|
50
57
|
}
|
|
51
58
|
if (!list.children.length) { const row = document.createElement("tr"); const cell = document.createElement("td"); cell.colSpan = 4; cell.textContent = "暂无已连接 AID"; row.append(cell); list.append(row); }
|
|
52
|
-
show(`${
|
|
59
|
+
show(`${entries.length} 个已连接 AID`);
|
|
53
60
|
} catch (error) { show(String(error), true); }
|
|
54
61
|
finally { loading = false; }
|
|
55
62
|
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
<header><h1>AUN 身份</h1><button id="refresh" type="button">刷新</button></header>
|
|
7
7
|
<p id="status" role="status"></p>
|
|
8
8
|
<div class="table-scroll"><table><thead><tr><th>AID</th><th>来源</th><th>已关联 Agent</th><th>操作</th></tr></thead><tbody id="identities"></tbody></table></div>
|
|
9
|
-
<form id="create-form"><h2>创建 AID</h2><div class="fields"><label>新 AID<input name="aid" required placeholder="例如:example.agentid.cn"></label><label>Owner AID<input name="ownerAid" required placeholder="例如:owner.agentid.cn(本地归属配置)"><small class="hint">Owner
|
|
9
|
+
<form id="create-form"><h2>创建 AID</h2><div class="fields"><label>新 AID<input name="aid" required placeholder="例如:example.agentid.cn"></label><label>Owner AID<input name="ownerAid" required placeholder="例如:owner.agentid.cn(本地归属配置)"><small class="hint">Owner 保存为本地归属配置;不代表 AUN 协议中的 Owner 关系已激活。</small></label></div><button type="submit">创建</button></form>
|
|
10
10
|
<form id="config-form"><h2>通道配置</h2><div class="fields"><label>默认 Agent<select name="agent_plugin"></select></label><label>允许的来源<input name="allow_from"></label><label>AUN 存储路径<input name="aun_path"></label><label>加密种子<input name="encryption_seed" type="password" autocomplete="new-password" placeholder="留空则不修改"></label></div><button type="submit">保存配置</button></form>
|
|
11
11
|
</main>
|
|
12
12
|
<script src="/abweb/channels/aun/app.js"></script>
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "aun",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.21",
|
|
4
4
|
"type": "channel",
|
|
5
5
|
"displayName": "AUN 通道",
|
|
6
6
|
"entry": "dist/src-ts/plugins/aun/index.js",
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
"channel.identity.create",
|
|
12
12
|
"channel.receive",
|
|
13
13
|
"channel.send",
|
|
14
|
-
"health"
|
|
14
|
+
"health",
|
|
15
|
+
"cli"
|
|
15
16
|
],
|
|
16
17
|
"configSchema": "config.schema.json",
|
|
17
18
|
"managementPage": "/abweb/channels/aun"
|