dsh-submodel 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/lib/delegation.js CHANGED
@@ -32,9 +32,11 @@
32
32
  */
33
33
  import {
34
34
  DELEGATE_TOOL_NAME,
35
+ classifyExplicitRoute,
35
36
  modeForRoute,
36
37
  resolveCallerRole,
37
38
  resolveDelegationArgs,
39
+ routeKey,
38
40
  } from './policy.js';
39
41
 
40
42
  /** 子调用 callId 的后缀:既能被日志一眼认出,又不会和原生 callId 撞(原生用随机 id)。 */
@@ -193,9 +195,8 @@ export function describeBatchFailure(error) {
193
195
  * - `logger`:日志器
194
196
  * @returns 可直接 `ctx.tools.register(...)` 的工具定义。
195
197
  */
196
- export function createDelegateTool({ ctx, nativeDefinition, executor, economyRoutes = [], logger }) {
197
- /** 执行期模式判定用的运行期策略(与 policy.js 纯函数同口径)。 */
198
- const routingPolicy = { executor, economyRoutes: Array.isArray(economyRoutes) ? economyRoutes : [] };
198
+ export function createDelegateTool({ ctx, nativeDefinition, executor, experts = [], modelGroups, economyRoutes = [], watchdog, logger }) {
199
+ const routingPolicy = { executor, modelGroups, economyRoutes: Array.isArray(economyRoutes) ? economyRoutes : [] };
199
200
  const parameters = cloneNativeParameters(nativeDefinition);
200
201
  // output 同样复用原生 schema/render,保持 runId/agentId 与 foreground/continuable 格式一致。
201
202
  const output = nativeDefinition.output;
@@ -206,66 +207,63 @@ export function createDelegateTool({ ctx, nativeDefinition, executor, economyRou
206
207
  return {
207
208
  name: DELEGATE_TOOL_NAME,
208
209
  description:
209
- 'Delegate one independent task to a subagent. It starts an independently managed subagent and ' +
210
- 'immediately returns its id; the runtime notifies you when it finishes. ' +
211
- 'Parameters are identical to the native `subagent` tool. Omit provider/model to inherit the ' +
212
- 'current route or use the configured execution route. ' +
213
- 'An explicit route must name provider AND model together. ' +
214
- 'Prefer this over the raw `subagent` tool for ordinary delegation.',
210
+ 'Start an independent subagent and get its name. The runtime delivers a completion notice. ' +
211
+ 'Omit provider and model for ordinary delegation, or supply both to select a model.',
215
212
  parameters,
216
213
  output,
217
214
  async execute(args, exec) {
218
- // ① 调用方身份必须是 live Agent,且必须是合格 standard 顶层。
219
215
  const caller = resolveCallerRole(exec);
220
- if (!caller.ok) throw new Error(caller.reason);
221
- if (caller.role !== 'root') throw new Error(`delegate_task is only available to a top-level agent (got role "${caller.role}")`);
216
+ if (!caller.ok) throw new Error('This delegation needs an active main conversation.');
217
+ if (caller.role !== 'root') throw new Error('Only the main conversation can delegate work.');
222
218
 
223
- // ② 同步快照执行期模式,再 await:描述"当前发起这笔调用的主脑",
224
- // 不读 GUI 里可能中途变化的 pending selection。
225
219
  const accepted = caller.header?.config ?? caller.agent.options ?? {};
226
220
  const route = {
227
- provider: typeof accepted?.provider === 'string' ? accepted.provider : '',
228
- model: typeof accepted?.model === 'string' ? accepted.model : '',
221
+ provider: typeof accepted.provider === 'string' ? accepted.provider : '',
222
+ model: typeof accepted.model === 'string' ? accepted.model : '',
229
223
  };
230
224
  const mode = modeForRoute(route, routingPolicy);
231
-
232
- // ③ 解析最终子代参数(原 exec/arguments 不可变,派生新对象)。
233
- const resolved = resolveDelegationArgs(args, mode, executor);
234
- if (!resolved.ok) throw new Error(resolved.reason);
235
-
236
- logger.info(
237
- `dsh-submodel: delegate_task session=${caller.header?.id ?? '?'} call=${exec.callId} mode=${mode} ` +
238
- `route=${resolved.applied} -> ${resolved.args.provider ?? '(inherit)'}/${resolved.args.model ?? '(inherit)'}`,
239
- );
240
-
241
- // ④ 发起一次真正的原生调用:保留它的全部校验与事件链(0.2.2 批量签名)。
242
- const nested = buildNestedCall(exec, resolved.args);
243
- const callId = nested.calls[0].id;
244
- let batch;
245
- try {
246
- batch = await ctx.tools.execute(nested);
247
- } catch (error) {
248
- throw new Error(`delegate_task: nested tool batch failed: ${describeBatchFailure(error)}`);
225
+ const resolved = resolveDelegationArgs(args, mode, executor, modelGroups);
226
+ if (!resolved.ok) {
227
+ throw new Error(classifyExplicitRoute(args).kind === 'invalid'
228
+ ? 'To select a model, provide both its provider and model.'
229
+ : 'Choose an execution model in the plugin settings or run the setup tool.');
249
230
  }
250
231
 
251
- const inner = resultOfNestedCall(batch, callId);
252
- if (inner === undefined) {
253
- throw new Error(
254
- 'delegate_task: the nested `subagent` call produced no result (the batch was aborted, ' +
255
- 'or the tool was not admitted for this step)',
256
- );
257
- }
258
-
259
- // ⑤ inner.isError 必须**抛出**:body 返回 error 对象会被当成功 value(见文件头契约 3)。
260
- if (inner.isError === true) {
261
- throw new Error(describeInnerFailure(inner));
232
+ const childRoute = resolved.applied === 'inherit' ? route : resolved.args;
233
+ const childKey = routeKey(childRoute);
234
+ const explicitExpert = resolved.applied === 'explicit' && experts.some(expert => routeKey(expert) === childKey);
235
+ const isExecutor = modelGroups ? modelGroups.executors.some(model => routeKey(model) === childKey)
236
+ : childKey === routeKey(executor);
237
+ const tier = explicitExpert ? 'expert' : isExecutor ? 'executor' : undefined;
238
+ let ticket;
239
+ try { ticket = watchdog?.begin(resolved.args, childRoute, tier, exec); }
240
+ catch { logger?.warn?.('dsh-submodel: monitoring could not start'); }
241
+ let receipt;
242
+ try {
243
+ const nested = buildNestedCall(exec, ticket?.args ?? resolved.args);
244
+ let batch;
245
+ try { batch = await ctx.tools.execute(nested); }
246
+ catch {
247
+ throw new Error('Delegation could not start. Check the subagent panel before trying again.');
248
+ }
249
+ const inner = resultOfNestedCall(batch, nested.calls[0].id);
250
+ if (inner === undefined) {
251
+ throw new Error('Delegation returned no confirmation. Check the subagent panel before trying again.');
252
+ }
253
+ if (inner.isError === true) {
254
+ if (describeInnerFailure(inner).includes('is not allowed for this Session')) {
255
+ throw new Error('This model is not allowed for the current conversation. Check the subagent settings and start a new conversation.');
256
+ }
257
+ throw new Error('Delegation was refused. Check model availability and permission in the subagent settings.');
258
+ }
259
+ receipt = inner.value;
260
+ for (const context of inner.additionalContexts ?? []) exec.deferContext(context);
261
+ if (inner.concludesTurn === true) exec.concludeTurn();
262
+ return receipt;
263
+ } finally {
264
+ try { watchdog?.finish(ticket, receipt); }
265
+ catch { logger?.warn?.('dsh-submodel: monitoring could not confirm the start'); }
262
266
  }
263
-
264
- // ⑥ 转移延迟上下文 / 结论标记,再只返回 inner.value。
265
- for (const context of inner.additionalContexts ?? []) exec.deferContext(context);
266
- if (inner.concludesTurn === true) exec.concludeTurn();
267
-
268
- return inner.value;
269
267
  },
270
268
  };
271
269
  }
package/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * dsh-submodel / index.js —— 插件入口(v0.1.0)。
3
3
  *
4
- * 职责:全局注册**唯一的策略提示词段**;`enabled` 时再对每个合格的 standard agent 安装
4
+ * 职责:全局注册策略提示词段及可选的团队队形自检段;`enabled` 时再对每个合格的 standard agent 安装
5
5
  * scoped 能力(提示词段正文替换、角色 guard、统一委派入口 `delegate_task`),并在
6
6
  * Agent 释放 / 组合变化 / 配置重载时**准确卸载自己装的东西**。
7
7
  *
@@ -38,7 +38,9 @@
38
38
  *
39
39
  * @module dsh-submodel
40
40
  */
41
- import z from '@deepseek-ai/schemastery';
41
+ import { executorConfigured, routingSnapshot } from './config.js';
42
+ export { Config } from './config.js';
43
+ import { installWatchdog } from './watchdog.js';
42
44
  import {
43
45
  CHILD_FORBIDDEN_TOOLS,
44
46
  ROUTING_ORDER,
@@ -49,6 +51,7 @@ import {
49
51
  routeFromAssembly,
50
52
  routingTextFor,
51
53
  } from './policy.js';
54
+ import { TEAM_FIT_SECTION, teamFitTextFor } from './team-fit.js';
52
55
  import { createDelegateTool, findNativeSubagent } from './delegation.js';
53
56
  import { createSetupTool } from './setup.js';
54
57
 
@@ -57,62 +60,6 @@ export const name = 'dsh-submodel';
57
60
  /** 用到的服务必须列全:apply 会等到它们可用才执行。 */
58
61
  export const inject = ['tools', 'systemPrompt'];
59
62
 
60
- export const Config = z.object({
61
- /** 自动策略总开关。默认开启:公开版的目标就是"装上一次配好"。 */
62
- enabled: z.boolean().default(true),
63
- /** 只对这一个 composition 生效;其他 preset 不安装任何东西。 */
64
- preset: z.string().default('standard'),
65
- /** 能力门控工具名:该 scope 不可见时策略段不渲染(工具仍按注册门控安装)。 */
66
- toolName: z.string().default('list_subagent_models'),
67
- /** 段顺序;默认紧接 TOOL_SUBAGENT(2800)。 */
68
- order: z.number().default(ROUTING_ORDER),
69
- /**
70
- * 执行路由(非 Flash 主脑的默认派工目标)。**唯一配置源**:执行期注入的 pair 由它派生,
71
- * 正文里的执行路由也只经占位符从它渲染,不允许 YAML/JS 双写两个不同的路由名。
72
- */
73
- executor: z.object({
74
- provider: z.string().default(''),
75
- model: z.string().default(''),
76
- reasoningEffort: z.string().default('max'),
77
- }).default({ provider: '', model: '', reasoningEffort: 'max' }),
78
- /**
79
- * 专家路由:升级时允许显式点名的 `{label, provider, model, reasoningEffort?}` 列表。
80
- * 空数组时正文给出"未配置专家路由"提示,不渲染任何具体路由名。
81
- */
82
- experts: z.array(z.object({
83
- label: z.string(),
84
- provider: z.string(),
85
- model: z.string(),
86
- reasoningEffort: z.string().default('max'),
87
- })).default([]),
88
- /**
89
- * 正文覆盖:任一项非空时**整段替换**内置模板(替换后不再插值),方便用户写自己的话术。
90
- */
91
- texts: z.object({
92
- economize: z.string().default(''),
93
- boss: z.string().default(''),
94
- child: z.string().default(''),
95
- }).default({ economize: '', boss: '', child: '' }),
96
- /**
97
- * 是否安装"非经济路由顶层用原生 subagent 时必须给完整显式 pair"的 guard。
98
- * 默认开启;关掉后原生 subagent 的行为完全交给宿主。
99
- */
100
- guardNativeSubagent: z.boolean().default(true),
101
- /**
102
- * 自动配置开关:root 且 `executor` 未配置时注册 `configure_submodel` 向导
103
- * (探测宿主渠道/模型 → 一张卡确认 → 写插件配置 + 宿主授权表)。默认开启。
104
- */
105
- autoConfigure: z.boolean().default(true),
106
- /**
107
- * 经济路由列表:主模型命中其中一项即走 economize 模式(不再要求模型名以 flash 结尾)。
108
- * 每项 `{provider?, model}`;`provider` 为空时只比 model。为空数组时保留 flash 后缀兼容。
109
- */
110
- economyRoutes: z.array(z.object({
111
- provider: z.string().default(''),
112
- model: z.string().min(1),
113
- })).default([]),
114
- });
115
-
116
63
  /** 判断一个 agent 是否属于本插件负责的 composition。 */
117
64
  function belongsToComposition(agent, presetId, presetService) {
118
65
  if (presetService === undefined) return false;
@@ -125,43 +72,27 @@ function belongsToComposition(agent, presetId, presetService) {
125
72
  }
126
73
  }
127
74
 
75
+ /** 团队服务是首选。回退时只看本步获准的工具,注册表在团队关闭时也有同名工具。 */
76
+ function teamEnabledFor(ctx, agent, toolSet) {
77
+ try {
78
+ const teams = ctx.get('agentTeams');
79
+ if (teams != null) return teams.isEnabled(agent) === true;
80
+ } catch {
81
+ // 服务不可用时仍可从这次 assembly 的工具集合取得正向证据。
82
+ }
83
+ return toolSet != null && ctx.tools.get('team_task_create', agent, toolSet) !== undefined;
84
+ }
85
+
128
86
  export function apply(ctx, config) {
129
87
  const enabled = config.enabled === true;
130
88
  const presetId = config.preset ?? 'standard';
131
89
  const toolName = config.toolName ?? 'list_subagent_models';
132
90
  const order = config.order ?? ROUTING_ORDER;
133
- const executor = {
134
- provider: config.executor?.provider ?? '',
135
- model: config.executor?.model ?? '',
136
- reasoningEffort: config.executor?.reasoningEffort ?? 'max',
137
- };
138
- const experts = Array.isArray(config.experts) ? config.experts : [];
139
- const texts = {
140
- economize: config.texts?.economize ?? '',
141
- boss: config.texts?.boss ?? '',
142
- child: config.texts?.child ?? '',
143
- };
144
- const economyRoutes = Array.isArray(config.economyRoutes)
145
- ? config.economyRoutes
146
- .filter(
147
- (row) =>
148
- row !== null &&
149
- typeof row === 'object' &&
150
- typeof row.model === 'string' &&
151
- row.model !== '',
152
- )
153
- .map((row) => ({ provider: typeof row.provider === 'string' ? row.provider : '', model: row.model }))
154
- : [];
155
- const guardNativeSubagent = config.guardNativeSubagent !== false;
156
91
  const autoConfigure = config.autoConfigure !== false;
157
- /** 模式判定用的运行期策略(与 policy.js 纯函数同口径)。 */
158
- const routingPolicy = { executor, economyRoutes };
159
- /** 每次 assembly 现渲染正文用的运行期上下文(纯函数层只认它)。 */
160
- const renderContext = { executor, experts, texts, economyRoutes };
161
- /** 执行路由是否未配置(未配置时才注册自动配置向导)。 */
162
- const executorIncomplete = executor.provider === '' || executor.model === '';
92
+ ctx.inject?.(['settings'], (bound) => {
93
+ bound.effect(() => bound.settings.configure({ auto: false }, ctx.fiber));
94
+ });
163
95
 
164
- /** 每个 agent 的 assembly listener 装的文本解析器:`(resolved) => string|null`。 */
165
96
  const textResolvers = new WeakMap();
166
97
 
167
98
  // ── 全局唯一的段(只注册一次,绝不重复注册同名段) ─────────────────────────
@@ -178,18 +109,48 @@ export function apply(ctx, config) {
178
109
  return;
179
110
  }
180
111
 
112
+ // ── 可选的团队队形自检段(总开关与 teamFit.enabled 同时为 true 才注册一次) ──────
113
+ // 每次组装现判「主脑 / 目标预设 / 团队是否开启」,条件不满足或查询异常返回空串,
114
+ // 宿主会省略整段;提示词组装与重试都没有写入副作用。
115
+ if (config.teamFit?.enabled === true) {
116
+ ctx.systemPrompt.section({
117
+ name: TEAM_FIT_SECTION,
118
+ // 紧跟官方团队段:SECTION_ORDERS.TEAM_POLICY = 600,+1 让自检段排在它后面。
119
+ order: ctx.systemPrompt.getSectionOrder('TEAM_POLICY') + 1,
120
+ text: (context) => {
121
+ try {
122
+ const { agent, scope, toolSet } = context;
123
+ if (!agent?.ctx || scope !== agent) return '';
124
+ // session.header 在首轮前已验证;requestHeader() 要等第一次模型请求才有值。
125
+ const header = agent.session?.header;
126
+ if (typeof header?.id !== 'string' || header.id !== agent.session.id) return '';
127
+ // 本仓库的 roleOf(agent) 读的就是这份 durable header 与 options,
128
+ // 等价于参考实现的 roleOf(header, agent.options)。
129
+ const role = roleOf(agent);
130
+ if (role !== 'root') return '';
131
+ const preset = ctx.get('agentPresets')?.composedPreset(agent.ctx);
132
+ if (preset !== presetId) return '';
133
+ return teamFitTextFor({ role, preset, presetId, teamEnabled: teamEnabledFor(ctx, agent, toolSet) });
134
+ } catch {
135
+ return '';
136
+ }
137
+ },
138
+ });
139
+ }
140
+
181
141
  // ── fail-fast(只记日志、绝不抛) ──────────────────────────────────────────
182
- if (executorIncomplete) {
142
+ if (!executorConfigured(config)) {
183
143
  ctx.logger.error(
184
144
  'dsh-submodel: config.executor.provider/model 未配置,自动委派不可用;可调用 `configure_submodel` 自动配置或按 README 两步配置',
185
145
  );
186
146
  }
187
147
  ctx.logger.info(
188
- `dsh-submodel: 自动策略已启用(preset=${presetId}, executor=${executor.provider || '(未配置)'}/${executor.model || '(未配置)'}, experts=${experts.length})`,
148
+ 'dsh-submodel: automatic delegation policy enabled',
189
149
  );
190
150
 
191
151
  // ── 逐 agent 安装 ──────────────────────────────────────────────────────────
192
- const installed = new WeakMap();
152
+ const installed = new Map();
153
+ let closed = false;
193
154
  const installing = new WeakSet();
194
155
  const pendingInstalls = new WeakMap();
195
156
 
@@ -239,7 +200,7 @@ export function apply(ctx, config) {
239
200
  * 为 agent 安装自动能力。幂等:已装直接返回;正在装共用同一 Promise。
240
201
  */
241
202
  const installAgent = async (agent) => {
242
- if (installed.has(agent)) return;
203
+ if (closed || installed.has(agent)) return;
243
204
  const existing = pendingInstalls.get(agent);
244
205
  if (existing !== undefined) return existing;
245
206
  if (installing.has(agent)) return undefined;
@@ -271,6 +232,7 @@ export function apply(ctx, config) {
271
232
  // 角色只在安装时判定一次:它来自 durable session header,agent 生命周期内不变。
272
233
  // 改读 agent(而不是已作废的 EpochHeader)是为了修复"冷恢复子代永远判成 root"的缺陷。
273
234
  const callerRole = roleOf(agent);
235
+ const snapshot = routingSnapshot(config);
274
236
 
275
237
  // ① 角色 guard:子代硬边界。**返回字符串即拒绝**(不是抛异常)。
276
238
  const guard = (exec) => {
@@ -291,21 +253,21 @@ export function apply(ctx, config) {
291
253
  if (exec?.name !== 'subagent') return undefined;
292
254
  if (callerRole !== 'root') return undefined;
293
255
  // 执行期模式判定:取最新已接受 header 的 config,回退 agent.options。
294
- if (isEconomyRoute(routeFromAgent(agent), routingPolicy)) return undefined; // 经济路由顶层原生调用不改变行为
256
+ if (isEconomyRoute(routeFromAgent(agent), snapshot)) return undefined; // 经济路由顶层原生调用不改变行为
295
257
  const args = exec.arguments ?? {};
296
258
  const hasProvider = args.provider !== undefined && args.provider !== null && args.provider !== '';
297
259
  const hasModel = args.model !== undefined && args.model !== null && args.model !== '';
298
260
  if (hasProvider && hasModel) return undefined; // 完整显式 pair:放行
299
261
  return 'dsh-submodel: the native `subagent` tool needs an explicit and COMPLETE provider/model pair here. Omit the raw tool and use `delegate_task` for ordinary delegation (it applies the configured executor route), or name both provider and model.';
300
262
  };
301
- if (guardNativeSubagent) disposers.push(tools.guard(nativeGuard));
263
+ if (snapshot.guardNativeSubagent) disposers.push(tools.guard(nativeGuard));
302
264
 
303
265
  // ③ assembly listener:先 await next(),再只替换自有段。
304
266
  const listener = async (assembly, context, next) => {
305
267
  const resolved = await next();
306
268
  try {
307
269
  const resolver = textResolvers.get(agent);
308
- const text = resolver === undefined ? null : resolver(resolved);
270
+ const text = resolver === undefined ? null : resolver(resolved, context.toolSet);
309
271
  if (text === null) return resolved;
310
272
  return {
311
273
  ...resolved,
@@ -324,30 +286,32 @@ export function apply(ctx, config) {
324
286
 
325
287
  // ④ 只有顶层注册统一委派入口(子代不再有委派能力)。
326
288
  if (callerRole === 'root') {
327
- disposers.push(
328
- tools.register(
329
- createDelegateTool({
330
- ctx: agent.ctx,
331
- nativeDefinition,
332
- executor,
333
- economyRoutes,
334
- logger: ctx.logger,
335
- }),
336
- ),
337
- );
338
- // ⑤ executor 未配置时注册自动配置向导(已配置/子代/autoConfigure=false 都不注册)。
339
- // 向导走 agent.ctx.tools,随 agent 释放;它内部用插件顶层 ctx 取服务。
340
- if (autoConfigure && executorIncomplete) {
341
- disposers.push(tools.register(createSetupTool({ ctx, config, logger: ctx.logger })));
289
+ const watchdog = installWatchdog({ ctx, parent: agent, config, nativeDefinition, modelGroups: snapshot.modelGroups });
290
+ if (watchdog) disposers.push(watchdog.dispose);
291
+ disposers.push(tools.register(createDelegateTool({
292
+ ctx: agent.ctx,
293
+ nativeDefinition,
294
+ executor: snapshot.executor,
295
+ experts: snapshot.experts,
296
+ modelGroups: snapshot.modelGroups,
297
+ economyRoutes: snapshot.economyRoutes,
298
+ watchdog,
299
+ logger: ctx.logger,
300
+ })));
301
+ if (autoConfigure) {
302
+ disposers.push(tools.register(createSetupTool({ ctx, config, logger: ctx.logger }), {
303
+ when: () => !executorConfigured(config),
304
+ }));
342
305
  }
343
306
  }
344
307
 
345
- // 正文解析器:角色安装时固定,模式每次 assembly 现判。
346
- // `list_subagent_models` 不可见时**只门控正文段**(info 一次/agent),
347
- // 工具仍按上面的注册门控安装。
348
- textResolvers.set(agent, (resolved) => {
308
+ textResolvers.set(agent, (resolved, toolSet) => {
309
+ const visibleTools = toolSet === undefined ? [] : [
310
+ 'list_agents', 'send_message', 'wait_agent', 'interrupt_agent', 'list_subagent_models',
311
+ ].filter(name => ctx.tools.get(name, agent, toolSet) !== undefined);
312
+ const renderContext = { ...snapshot, visibleTools };
349
313
  if (callerRole === 'child') return routingTextFor('child', undefined, renderContext);
350
- if (ctx.tools.get(toolName, agent) === undefined) {
314
+ if (ctx.tools.get(toolName, agent, toolSet) === undefined) {
351
315
  if (!informedNoModelSelection.has(agent)) {
352
316
  informedNoModelSelection.add(agent);
353
317
  ctx.logger.info(
@@ -431,24 +395,14 @@ export function apply(ctx, config) {
431
395
  });
432
396
  reconcile();
433
397
 
434
- // 根插件 cleanup:等自有安装全部卸载,再删状态。
435
- //
436
- // cordis 的插件拆卸通知是 `internal/plugin` 事件,listener 的 Promise 是 fire-and-forget;
437
- // 并没有名为 `dispose` 的事件被发射——因此原来的 `ctx.on('dispose', …)` 清理回调**永不执行**。
438
- // 两个通道都保留——谁先来谁触发,幂等。
398
+ let uninstallAllTask;
439
399
  const cleanupAll = () => {
440
- if (uninstallAllTask !== undefined) return uninstallAllTask;
441
- const agents = agentsService();
442
- if (agents === undefined) return undefined;
443
- const tasks = [];
444
- for (const candidate of agents.list()) {
445
- tasks.push(uninstallAgent(candidate, 'plugin cleanup'));
446
- textResolvers.delete(candidate);
447
- }
448
- uninstallAllTask = Promise.all(tasks).finally(() => { uninstallAllTask = undefined; });
400
+ if (closed) return uninstallAllTask;
401
+ closed = true;
402
+ uninstallAllTask = Promise.all([...installed.keys()].map(agent => uninstallAgent(agent, 'plugin cleanup')));
449
403
  return uninstallAllTask;
450
404
  };
451
- let uninstallAllTask;
405
+ ctx.effect?.(() => cleanupAll);
452
406
  ctx.on('dispose', cleanupAll);
453
407
  ctx.on('internal/plugin', (fiber) => {
454
408
  // 只在"自己这条 fiber 被拆掉"的那一刻触发(该事件正是 emitPluginDisposed 的载荷)。