@aalis/plugin-webui-server 0.12.0 → 0.14.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.
@@ -1,14 +1,74 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
+ import { isConfigSaveRefused } from '@aalis/api-host-config';
2
3
  import { parseInstanceId } from '@aalis/core';
3
4
  import { CORE_CONFIG_SCHEMA, cloneConfigObject, defaultsFrom, removeExtraFields, validateConfig, } from '@aalis/schema-config';
4
5
  function errorMessage(err) {
5
6
  return err instanceof Error ? err.message : String(err);
6
7
  }
8
+ /**
9
+ * 落盘被拒后运行态怎样与文件对齐:插件配置与新建的实例随配置文件热重载(文件里没有配置段的后缀实例会被卸载);
10
+ * 启停与服务偏好只在重启时按文件登记
11
+ */
12
+ const RECONCILE = {
13
+ reload: '修好配置文件后会按文件内容重载',
14
+ restart: '修好配置文件后,重启时以文件内容为准',
15
+ };
16
+ /**
17
+ * 管理动作改完运行态之后落盘;失败时回 `applied: true` 并返回 false:改动已在运行态生效、只是没写进文件,
18
+ * 调用方别当成「没改成」去重试。宿主拒写(配置文件有尚未生效的外部修改)回 409,之后以文件为准对账;
19
+ * 其它失败(权限、磁盘写满等)回 500,文件没变也不会触发重载,改动留在文档里,下一次成功保存时一并写入。
20
+ * `outcome` 是动作之后插件没有落在预期状态的说明(如激活失败转 error、仍在激活、保持禁用):落盘也失败时放在回执开头,
21
+ * 两件事一并说明。
22
+ */
23
+ export async function saveAfterApply(doc, res, reconcile, outcome) {
24
+ try {
25
+ await doc.save();
26
+ return true;
27
+ }
28
+ catch (err) {
29
+ const lead = outcome ? `${outcome};` : '';
30
+ if (isConfigSaveRefused(err)) {
31
+ res.status(409).json({
32
+ error: `${lead}已在运行态生效,但未写入配置文件(${errorMessage(err)});${RECONCILE[reconcile]}`,
33
+ applied: true,
34
+ });
35
+ }
36
+ else {
37
+ res.status(500).json({
38
+ error: `${lead}已在运行态生效,但写入配置文件失败(${errorMessage(err)});改动保留在文档里,下次保存成功时一并写入`,
39
+ applied: true,
40
+ });
41
+ }
42
+ return false;
43
+ }
44
+ }
45
+ /**
46
+ * 管理动作受理后等重算落定,再读实例状态写回执:动作撞上在飞的重算时只排队、立即返回,立即读到的还是 pending,
47
+ * 之后的激活失败就漏报了。idle 不等转入后台的慢激活:重算对单个激活至多等到慢激活阈值。
48
+ */
49
+ async function settledEntry(pm, instanceId) {
50
+ await pm.idle();
51
+ return pm.getPlugin(instanceId);
52
+ }
53
+ /** 落定后既没激活也没失败的说明:慢激活转入后台仍在进行,或在等 required 依赖满足;其余状态由各路由自己说明 */
54
+ function notYetActive(state) {
55
+ if (state === 'activating')
56
+ return '仍在激活(超过慢激活阈值,已转入后台),结果以插件列表为准';
57
+ if (state === 'pending')
58
+ return '尚未激活,正在等待 required 依赖满足';
59
+ return undefined;
60
+ }
7
61
  /** 注册插件管理 + 全局配置相关 REST 路由 */
8
62
  export function registerPluginRoutes(expressApp, caps, identify, gate, getAction) {
9
63
  const getApp = () => caps.app.current;
10
64
  const getPluginMgr = () => caps.plugins.current;
11
- const hostConfig = () => caps.hostConfig.require();
65
+ /** 配置文档由宿主提供;没有时读写文档的路由一律 503,与扫描、市场路由的缺席口径一致 */
66
+ const docOr503 = (res) => {
67
+ const doc = caps.hostConfig.current;
68
+ if (!doc)
69
+ res.status(503).json({ error: '宿主未提供配置文档(host-config),无法读写配置' });
70
+ return doc;
71
+ };
12
72
  // 获取插件列表及状态
13
73
  expressApp.get('/api/plugins', gate(), (_req, res) => {
14
74
  const app = getApp();
@@ -55,6 +115,7 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
55
115
  instanceId: p.instanceId,
56
116
  displayName: p.displayName,
57
117
  state: p.state,
118
+ slow: p.slow,
58
119
  provides: p.provides ?? [],
59
120
  // 完整能力声明含内置能力与 apply 别名;外部依赖闸与工具/指令可见性仍是各自独立的事实。
60
121
  uses: p.uses,
@@ -137,8 +198,10 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
137
198
  });
138
199
  // 获取当前全局配置
139
200
  expressApp.get('/api/config', gate(), (_req, res) => {
140
- const allConfig = hostConfig().getAll();
141
- res.json({ ...allConfig, _schema: CORE_CONFIG_SCHEMA });
201
+ const doc = docOr503(res);
202
+ if (!doc)
203
+ return;
204
+ res.json({ ...doc.getAll(), _schema: CORE_CONFIG_SCHEMA });
142
205
  });
143
206
  // 更新全局配置字段
144
207
  expressApp.put('/api/config', gate(), async (req, res) => {
@@ -148,17 +211,22 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
148
211
  return;
149
212
  }
150
213
  const app = getApp();
151
- const pm = getPluginMgr();
152
- if (!app || !pm) {
214
+ if (!app) {
153
215
  res.status(500).json({ error: 'App 不可用' });
154
216
  return;
155
217
  }
218
+ const doc = docOr503(res);
219
+ if (!doc)
220
+ return;
156
221
  // 可改的只有 CORE_CONFIG_SCHEMA 的键。内置前端(buildDraftFromSchema)会把 GET 到的整份配置连同
157
222
  // _schema 原样回传,其中 plugins 等还可能是过期快照(插件配置页保存后不刷新全局 config),
158
223
  // 所以不能按键报错:其余键一律不应用,但把真有改动的点名回给调用方——不静默吞掉却回复「已保存」。
159
224
  const allowed = Object.keys(CORE_CONFIG_SCHEMA);
160
- const current = hostConfig().getAll();
161
- const differs = (k) => !isDeepStrictEqual(updates[k], current[k]);
225
+ const current = doc.getAll();
226
+ // 文档里没写的核心键按 schema 默认值比较:内置前端把默认值回填进草稿后整份回传,不能据此判成改动(否则只改
227
+ // 名字也会把默认值写进文件并触发重启)
228
+ const currentOf = (k) => current[k] ?? CORE_CONFIG_SCHEMA[k]?.default;
229
+ const differs = (k) => !isDeepStrictEqual(updates[k], currentOf(k));
162
230
  const ignored = Object.keys(updates).filter(k => k !== '_schema' && !allowed.includes(k) && differs(k));
163
231
  const changed = allowed.filter(k => k in updates && differs(k));
164
232
  // 与插件配置路径同一把尺子:类型不符的值(如 name 传数字)不落盘。select 的取值范围 validateConfig
@@ -175,32 +243,53 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
175
243
  res.status(400).json({ error: invalid.join('; ') });
176
244
  return;
177
245
  }
246
+ const previous = Object.fromEntries(changed.map(k => [k, current[k]]));
178
247
  for (const key of changed)
179
- hostConfig().set(key, updates[key]);
180
- // name / logLevel 都要重启才生效;值没变就不重启
181
- const restartNeeded = changed.length > 0;
248
+ doc.set(key, updates[key]);
249
+ // logLevel 与 slowThresholdMs 只在启动时读取,改了才重启;name 由 /api/status 每次实时读文档(appName),保存即生效。
250
+ // 装有人设时聊天显示人设名,应用名称只在仪表盘上看得到
251
+ const restartNeeded = changed.some(k => k === 'logLevel' || k === 'slowThresholdMs');
182
252
  const note = ignored.length > 0 ? `(已忽略不可修改的字段: ${ignored.join(', ')})` : '';
183
253
  try {
184
- await app.saveConfig();
185
- if (restartNeeded) {
186
- res.json({ ok: true, message: `全局配置已更新,正在重启应用以生效…${note}`, restart: true, ignored });
187
- app.restart();
188
- }
189
- else {
190
- res.json({ ok: true, message: `全局配置已更新并保存${note}`, ignored });
191
- }
254
+ await doc.save();
192
255
  }
193
256
  catch (err) {
194
- const msg = err instanceof Error ? err.message : String(err);
195
- res.status(500).json({ error: msg });
257
+ // 拒写与写入失败都撤回文档里的改动,免得下一次任意保存把这次没存下的修改写进文件。
258
+ // logLevel / slowThresholdMs 要重启才生效,name 由状态接口读文档:撤回后都回到修改前,运行态不留改动
259
+ for (const key of changed)
260
+ doc.set(key, previous[key]);
261
+ res
262
+ .status(isConfigSaveRefused(err) ? 409 : 500)
263
+ .json({ error: `未写入配置文件(${errorMessage(err)}),本次修改已撤回` });
264
+ return;
196
265
  }
266
+ if (!restartNeeded) {
267
+ res.json({ ok: true, message: `全局配置已更新并保存${note}`, ignored });
268
+ return;
269
+ }
270
+ // 先发起重启再回复:宿主没注入重启策略时 restart() 同步抛错,据此回 restart:false,前端才不会进入等待重连
271
+ // 却永远等不到。发起之后的停机是异步的(core 先广播 app:restarting,何时停机由重启策略决定,Node 宿主延迟
272
+ // 500ms),这条回复来得及发出。已写进文件,重启失败不撤回:改动在下次启动时生效
273
+ try {
274
+ app.restart();
275
+ }
276
+ catch (err) {
277
+ const reason = `全局配置已保存,但重启失败(${errorMessage(err)}),改动在下次启动时生效`;
278
+ caps.logger?.error(reason);
279
+ res.json({ ok: true, message: `${reason}${note}`, restart: false, ignored });
280
+ return;
281
+ }
282
+ res.json({ ok: true, message: `全局配置已更新,正在重启应用以生效…${note}`, restart: true, ignored });
197
283
  });
198
284
  // 获取单个插件的原始配置(未脱敏,给编辑器回写用)。
199
285
  // 列表 GET /api/plugins 已把 schema.secret 换成固定掩码;本接口必须是原文,否则保存会把掩码写回。
200
286
  expressApp.get('/api/plugins/:name/config', gate(), (req, res) => {
201
287
  const pluginName = req.params.name;
288
+ const doc = docOr503(res);
289
+ if (!doc)
290
+ return;
202
291
  try {
203
- const pluginConfig = hostConfig().getPluginConfig(pluginName);
292
+ const pluginConfig = doc.getPluginConfig(pluginName);
204
293
  res.json({ name: pluginName, config: pluginConfig });
205
294
  }
206
295
  catch (err) {
@@ -215,34 +304,52 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
215
304
  res.status(400).json({ error: 'config 字段必须是对象' });
216
305
  return;
217
306
  }
218
- const app = getApp();
219
307
  const pm = getPluginMgr();
220
- if (!app || !pm) {
221
- res.status(500).json({ error: 'App 不可用' });
308
+ if (!pm) {
309
+ res.status(500).json({ error: '插件管理服务不可用' });
222
310
  return;
223
311
  }
312
+ const doc = docOr503(res);
313
+ if (!doc)
314
+ return;
224
315
  // 补默认值再交给 updateConfig:后者是**整体替换**语义(core 的 orchestration/plugin.ts 里
225
316
  // entry.config = newConfig 直接顶掉)。不补的话,PUT 一个部分对象就会把未列出的
226
317
  // 字段从内存态和 yaml 里一起抹掉。默认值从 configSchema 派生(唯一声明来源)。
227
- const schema = pm.getPlugin(pluginName)?.definition?.configSchema;
318
+ const entry = pm.getPlugin(pluginName);
319
+ const schema = entry?.definition?.configSchema;
228
320
  const defaults = defaultsFrom(schema);
229
321
  // 基线取「默认值叠已存值」而非裸默认值:defaultsFrom 只收录声明了 default 的键,
230
322
  // 而 apiKey / accessToken 这类 secret 多数**没有** default(deepseek、embedding-openai、
231
323
  // llm-openai、serper、onebot 皆是)。用裸 defaults 打底时,请求里没带 apiKey 就等于
232
324
  // merged 里根本没有这个键,整体替换后用户的密钥从内存态与 yaml 一起消失。
233
325
  // 叠上已存值后语义才是真正的部分更新:没提交的字段保持原样,要清空得显式传空串。
326
+ let docConfig;
234
327
  let stored;
235
328
  let merged;
329
+ const ignored = [];
330
+ const removed = [];
236
331
  try {
237
- stored = { ...defaults, ...hostConfig().getPluginConfig(pluginName) };
238
- merged = { ...stored, ...newConfig };
239
- // 与 runtime config-sync 同一政策:有 schema 就裁掉未知键并 warn,避免 WebUI 把
240
- // 手滑字段写进 stored,而 YAML watch 路径却会裁掉——两边政策必须一致。
241
- if (schema && Object.keys(schema).length > 0) {
242
- const removed = [];
243
- merged = removeExtraFields(merged, schema, removed);
244
- if (removed.length > 0) {
245
- caps.logger?.warn(`配置同步:${pluginName} 裁掉 schema 外字段 [${removed.join(', ')}]`);
332
+ docConfig = doc.getPluginConfig(pluginName);
333
+ // 先铺文档里的原配置、缺的默认键追加到末尾:写回时保留配置文件里原有的键序
334
+ stored = { ...docConfig };
335
+ for (const [key, value] of Object.entries(defaults)) {
336
+ if (!Object.hasOwn(stored, key))
337
+ stored[key] = value;
338
+ }
339
+ const submitted = newConfig;
340
+ merged = { ...stored, ...submitted };
341
+ // 与宿主的配置同步同一政策(host-config 的 trimUnknownFields):宿主裁剪且有 schema 时裁掉未知键并 warn,
342
+ // 避免 WebUI 把手滑字段写进 stored,而 YAML watch 路径却会裁掉;宿主保留未知字段时这里也不裁。
343
+ // 被裁的字段按来源回给调用方,不静默吞掉却回复「已更新」:本次提交里的记 ignored(与 PUT /api/config
344
+ // 同一口径);文档里原有、本次没提交的不是用户这次写的,随整份写回从配置文件删掉,记 removed
345
+ if (doc.trimUnknownFields !== false && schema && Object.keys(schema).length > 0) {
346
+ const shape = schema;
347
+ for (const [key, value] of Object.entries(merged)) {
348
+ removeExtraFields({ [key]: value }, shape, Object.hasOwn(submitted, key) ? ignored : removed);
349
+ }
350
+ merged = removeExtraFields(merged, shape);
351
+ if (ignored.length + removed.length > 0) {
352
+ caps.logger?.warn(`配置同步:${pluginName} 裁掉 schema 外字段 [${[...ignored, ...removed].join(', ')}]`);
246
353
  }
247
354
  }
248
355
  }
@@ -250,12 +357,13 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
250
357
  res.status(400).json({ error: errorMessage(err) });
251
358
  return;
252
359
  }
360
+ const note = (ignored.length > 0 ? `(已忽略未声明的配置字段: ${ignored.join(', ')})` : '') +
361
+ (removed.length > 0 ? `(已从配置文件移除未声明的字段: ${removed.join(', ')})` : '');
253
362
  // 保存前校验,拦新不追旧:只拒绝本次编辑**新引入**的 invalid(配错了)。
254
363
  // 存量问题放行——否则带着历史脏值(或 schema 表达不了的多态字段,如 mcp-client
255
364
  // 的 args 数组形态)的插件会在 WebUI 永久存不了任何字段;启动侧 config-sync
256
365
  // 对它们已有告警。missing(没配全)也放行:半成品配置是启用插件配到一半的
257
- // 正常中间态。禁用插件的 PUT 走下方 updateConfig 失败分支,在那里区分
258
- // 「已禁用」(409,提示先启用)与「真不存在」(404)。
366
+ // 正常中间态。
259
367
  const preExisting = new Set(validateConfig(schema, stored).map(i => `${i.path}|${i.message}`));
260
368
  const issues = validateConfig(schema, merged).filter(i => i.kind === 'invalid' && !preExisting.has(`${i.path}|${i.message}`));
261
369
  if (issues.length > 0) {
@@ -265,6 +373,15 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
265
373
  });
266
374
  return;
267
375
  }
376
+ // 运行态与文档都已是这份配置:不重建插件(updateConfig 即 bounce,会连带重启依赖它所提供服务的下游)。
377
+ // 仍照常落盘:上一次保存可能写文件失败(500),文档与运行态已是新配置而文件没变,原样重试要能补写;
378
+ // 自写回不会触发 watch 重载。只认 active:error 态插件靠原样保存来重试激活,照旧走 updateConfig
379
+ if (entry?.state === 'active' && isDeepStrictEqual(merged, entry.config) && isDeepStrictEqual(merged, docConfig)) {
380
+ if (!(await saveAfterApply(doc, res, 'reload')))
381
+ return;
382
+ res.json({ ok: true, message: `插件 ${pluginName} 配置无改动,已写回配置文件${note}`, ignored, removed });
383
+ return;
384
+ }
268
385
  let success;
269
386
  try {
270
387
  success = await pm.updateConfig(pluginName, merged);
@@ -274,34 +391,43 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
274
391
  return;
275
392
  }
276
393
  if (success) {
277
- await app.saveConfig();
278
- res.json({ ok: true, message: `插件 ${pluginName} 配置已更新` });
394
+ // 管理动作只改运行态;跨重启保留要本路由写文档并落盘
395
+ doc.setPluginConfig(pluginName, merged);
396
+ // 按新配置重新激活失败、转为 error:照样写入配置(原样再存即重试激活),但按实际状态回报。
397
+ // 禁用态只换上新配置、保持禁用,启用时按它激活
398
+ const after = await settledEntry(pm, pluginName);
399
+ const failure = after?.state === 'error'
400
+ ? `插件 ${pluginName} 按新配置重新激活失败,已转为 error 态(${after.error ?? '详见日志'})`
401
+ : undefined;
402
+ const aside = after?.state === 'disabled' ? '插件已禁用,启用时按新配置激活' : notYetActive(after?.state);
403
+ if (!(await saveAfterApply(doc, res, 'reload', failure ?? aside)))
404
+ return;
405
+ if (failure !== undefined) {
406
+ res.status(500).json({ error: `${failure};配置已写入配置文件${note}` });
407
+ return;
408
+ }
409
+ res.json({
410
+ ok: true,
411
+ message: `插件 ${pluginName} 配置已更新${note}${aside ? `;${aside}` : ''}`,
412
+ ignored,
413
+ removed,
414
+ });
279
415
  }
280
416
  else {
281
- // 插件被禁用时这里也会走到,但「不存在」会把用户引向错误方向——区分「禁用」与「真不存在」并给出下一步。
282
- try {
283
- const disabled = hostConfig().isPluginDisabled(pluginName);
284
- if (disabled) {
285
- res.status(409).json({ error: `插件 ${pluginName} 已禁用,配置未写入——先启用插件再修改配置` });
286
- }
287
- else {
288
- res.status(404).json({ error: `插件 ${pluginName} 不存在` });
289
- }
290
- }
291
- catch (err) {
292
- res.status(400).json({ error: errorMessage(err) });
293
- }
417
+ res.status(404).json({ error: `插件 ${pluginName} 不存在` });
294
418
  }
295
419
  });
296
420
  // 启用插件
297
421
  expressApp.post('/api/plugins/:name/enable', gate(), async (req, res) => {
298
422
  const pluginName = req.params.name;
299
- const app = getApp();
300
423
  const pm = getPluginMgr();
301
- if (!app || !pm) {
302
- res.status(500).json({ error: 'App 不可用' });
424
+ if (!pm) {
425
+ res.status(500).json({ error: '插件管理服务不可用' });
303
426
  return;
304
427
  }
428
+ const doc = docOr503(res);
429
+ if (!doc)
430
+ return;
305
431
  let success;
306
432
  try {
307
433
  success = await pm.enable(pluginName);
@@ -311,8 +437,20 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
311
437
  return;
312
438
  }
313
439
  if (success) {
314
- await app.saveConfig();
315
- res.json({ ok: true, message: `插件 ${pluginName} 已启用` });
440
+ doc.setPluginEnabled(pluginName, true);
441
+ // 激活失败、转为 error:照样记为启用(重启时再激活),但按实际状态回报
442
+ const after = await settledEntry(pm, pluginName);
443
+ const failure = after?.state === 'error'
444
+ ? `插件 ${pluginName} 激活失败,已转为 error 态(${after.error ?? '详见日志'})`
445
+ : undefined;
446
+ const aside = notYetActive(after?.state);
447
+ if (!(await saveAfterApply(doc, res, 'restart', failure ?? aside)))
448
+ return;
449
+ if (failure !== undefined) {
450
+ res.status(500).json({ error: `${failure};配置文件已记为启用` });
451
+ return;
452
+ }
453
+ res.json({ ok: true, message: `插件 ${pluginName} 已启用${aside ? `;${aside}` : ''}` });
316
454
  }
317
455
  else {
318
456
  res.status(404).json({ error: `插件 ${pluginName} 不存在` });
@@ -321,12 +459,14 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
321
459
  // 禁用插件
322
460
  expressApp.post('/api/plugins/:name/disable', gate(), async (req, res) => {
323
461
  const pluginName = req.params.name;
324
- const app = getApp();
325
462
  const pm = getPluginMgr();
326
- if (!app || !pm) {
327
- res.status(500).json({ error: 'App 不可用' });
463
+ if (!pm) {
464
+ res.status(500).json({ error: '插件管理服务不可用' });
328
465
  return;
329
466
  }
467
+ const doc = docOr503(res);
468
+ if (!doc)
469
+ return;
330
470
  let success;
331
471
  try {
332
472
  success = await pm.disable(pluginName);
@@ -336,23 +476,32 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
336
476
  return;
337
477
  }
338
478
  if (success) {
339
- await app.saveConfig();
479
+ // 仍在初始化、不响应 abort 的插件,宽限到期转 error 而非 disabled:照样记为禁用(重启时不再激活),但按实际状态回报
480
+ const stuck = pm.getPlugin(pluginName)?.state === 'error'
481
+ ? `插件 ${pluginName} 未在宽限内停止,已转为 error 态,详见日志`
482
+ : undefined;
483
+ doc.setPluginEnabled(pluginName, false);
484
+ if (!(await saveAfterApply(doc, res, 'restart', stuck)))
485
+ return;
486
+ if (stuck !== undefined) {
487
+ res.status(500).json({ error: `${stuck};配置文件已记为禁用` });
488
+ return;
489
+ }
340
490
  res.json({ ok: true, message: `插件 ${pluginName} 已禁用` });
341
491
  }
342
492
  else {
343
493
  res.status(404).json({ error: `插件 ${pluginName} 不在注册表或已处于终态,无法禁用` });
344
494
  }
345
495
  });
346
- // 重新扫描 packages/ 并加载新插件
496
+ // 经宿主 plugin-source 重新扫描并加载新插件
347
497
  expressApp.post('/api/plugins/scan', gate(), async (_req, res) => {
348
- const app = getApp();
349
- const pm = getPluginMgr();
350
- if (!app || !pm) {
351
- res.status(500).json({ error: 'App 不可用' });
498
+ const source = caps.source.current;
499
+ if (!source) {
500
+ res.status(503).json({ error: '宿主未提供插件来源,无法扫描' });
352
501
  return;
353
502
  }
354
503
  try {
355
- const loaded = await app.rescanPlugins();
504
+ const loaded = await source.rescan();
356
505
  res.json({ ok: true, loaded, message: loaded.length > 0 ? `新加载 ${loaded.length} 个插件` : '无新插件' });
357
506
  }
358
507
  catch (err) {
@@ -373,12 +522,14 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
373
522
  res.status(400).json({ error: 'suffix 只能包含字母、数字、下划线和连字符' });
374
523
  return;
375
524
  }
376
- const app = getApp();
377
525
  const pm = getPluginMgr();
378
- if (!app || !pm) {
379
- res.status(500).json({ error: 'App 不可用' });
526
+ if (!pm) {
527
+ res.status(500).json({ error: '插件管理服务不可用' });
380
528
  return;
381
529
  }
530
+ const doc = docOr503(res);
531
+ if (!doc)
532
+ return;
382
533
  // 实例创建编排(配置文件编排属管理面,内核只出 register 机制):
383
534
  // 查同名 module → reusable/查重校验 → 合并默认配置写入 → register 激活。
384
535
  const sourceModule = pm
@@ -399,58 +550,99 @@ export function registerPluginRoutes(expressApp, caps, identify, gate, getAction
399
550
  return;
400
551
  }
401
552
  const mergedConfig = { ...defaultsFrom(sourceModule.configSchema), ...config };
553
+ let registered;
402
554
  try {
403
- hostConfig().setPluginConfig(instanceId, mergedConfig);
404
- await pm.register(sourceModule, mergedConfig, instanceId);
555
+ doc.setPluginConfig(instanceId, mergedConfig);
556
+ // 文档里残留的禁用标记(手改配置文件留下的)照旧生效:以禁用态登记
557
+ registered = await pm.register(sourceModule, mergedConfig, instanceId, {
558
+ disabled: doc.isPluginDisabled(instanceId),
559
+ });
405
560
  }
406
561
  catch (err) {
407
562
  res.status(400).json({ error: errorMessage(err) });
408
563
  return;
409
564
  }
410
- await app.saveConfig();
411
- res.json({ ok: true, instanceId, message: `已创建实例 ${instanceId}` });
565
+ if (!registered) {
566
+ // 前面已查过重名与 reusable,走到这里的实际只有停机进行中:配置不落盘,免得下次启动按文件登记
567
+ doc.removePluginConfig(instanceId);
568
+ res.status(409).json({ error: `实例 ${instanceId} 未登记(停机中或被拒,见日志),配置未写入` });
569
+ return;
570
+ }
571
+ // 激活失败、转为 error:实例与配置照样保留并落盘(改配置保存即重试激活),但按实际状态回报
572
+ const after = await settledEntry(pm, instanceId);
573
+ const failure = after?.state === 'error'
574
+ ? `已创建实例 ${instanceId},但激活失败,已转为 error 态(${after.error ?? '详见日志'})`
575
+ : undefined;
576
+ const aside = after?.state === 'disabled'
577
+ ? '配置文件的 disabledPlugins 里有它,已按禁用态登记,启用后激活'
578
+ : notYetActive(after?.state);
579
+ if (!(await saveAfterApply(doc, res, 'reload', failure ?? aside)))
580
+ return;
581
+ if (failure !== undefined) {
582
+ res.status(500).json({ error: `${failure};配置已写入配置文件` });
583
+ return;
584
+ }
585
+ res.json({ ok: true, instanceId, message: `已创建实例 ${instanceId}${aside ? `;${aside}` : ''}` });
412
586
  });
413
587
  // 删除插件多实例
414
588
  expressApp.delete('/api/plugins/:instanceId/instance', gate(), async (req, res) => {
415
589
  const instanceId = req.params.instanceId;
416
- const app = getApp();
417
590
  const pm = getPluginMgr();
418
- if (!app || !pm) {
419
- res.status(500).json({ error: 'App 不可用' });
591
+ if (!pm) {
592
+ res.status(500).json({ error: '插件管理服务不可用' });
420
593
  return;
421
594
  }
422
- // 实例删除编排:主实例保护 → unload(内部含级联重算)→ 移除配置条目。
595
+ const doc = docOr503(res);
596
+ if (!doc)
597
+ return;
598
+ // 实例删除编排:主实例保护 → 移除配置条目与禁用标记(同名重建时不再以禁用态登记)并落盘 → unload(内部含级联重算)。
599
+ // 与其它管理路由「先生效后落盘」相反:后缀实例由配置段定义,热重载也按文件登记。先卸载后落盘时,卸载途中外部改动
600
+ // 触发的热重载会按仍带配置段的文件把实例重新登记,落盘随后删掉配置段,留下文件里没有的在跑实例
423
601
  const { suffix } = parseInstanceId(instanceId);
424
602
  if (!suffix || !pm.getPlugin(instanceId)) {
425
603
  res.status(400).json({ error: `无法删除(实例不存在或不允许删除主实例)` });
426
604
  return;
427
605
  }
606
+ const previous = Object.hasOwn(doc.getAll().plugins, instanceId) ? doc.getPluginConfig(instanceId) : undefined;
607
+ const wasDisabled = doc.isPluginDisabled(instanceId);
608
+ doc.removePluginConfig(instanceId);
609
+ doc.setPluginEnabled(instanceId, true);
610
+ try {
611
+ await doc.save();
612
+ }
613
+ catch (err) {
614
+ // 没写进文件就不卸载,并撤回文档里的改动,免得下一次任意保存把这次没删成的删除写进文件
615
+ if (previous)
616
+ doc.setPluginConfig(instanceId, previous);
617
+ doc.setPluginEnabled(instanceId, !wasDisabled);
618
+ res
619
+ .status(isConfigSaveRefused(err) ? 409 : 500)
620
+ .json({ error: `未删除实例 ${instanceId}:未写入配置文件(${errorMessage(err)})` });
621
+ return;
622
+ }
428
623
  try {
429
624
  await pm.unload(instanceId);
430
- hostConfig().removePluginConfig(instanceId);
431
625
  }
432
626
  catch (err) {
433
- res.status(400).json({ error: errorMessage(err) });
627
+ res.status(500).json({
628
+ error: `已从配置文件删除实例 ${instanceId},但卸载失败(${errorMessage(err)});重启后不再登记`,
629
+ });
434
630
  return;
435
631
  }
436
- await app.saveConfig();
437
632
  res.json({ ok: true, message: `已删除实例 ${instanceId}` });
438
633
  });
439
- // 保存配置到磁盘
634
+ // 保存配置文档:与其它落盘路由同一口径,宿主拒写回 409、其它失败回 500。宿主不持久化时 save 不写盘,
635
+ // 回执因此只说「已保存」,不说保存到磁盘
440
636
  expressApp.post('/api/config/save', gate(), async (_req, res) => {
441
- const app = getApp();
442
- const pm = getPluginMgr();
443
- if (!app || !pm) {
444
- res.status(500).json({ error: 'App 不可用' });
637
+ const doc = docOr503(res);
638
+ if (!doc)
445
639
  return;
446
- }
447
640
  try {
448
- await app.saveConfig();
449
- res.json({ ok: true, message: '配置已保存到磁盘' });
641
+ await doc.save();
642
+ res.json({ ok: true, message: '配置已保存' });
450
643
  }
451
644
  catch (err) {
452
- const msg = err instanceof Error ? err.message : String(err);
453
- res.status(500).json({ error: msg });
645
+ res.status(isConfigSaveRefused(err) ? 409 : 500).json({ error: errorMessage(err) });
454
646
  }
455
647
  });
456
648
  }