dsh-skill-pool 0.0.0-stage → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,854 @@
1
+ /**
2
+ * Per-Agent application of the single global resource pool.
3
+ *
4
+ * The pool is the user's library, so "what the pool activates" is exactly
5
+ * "what this Agent may see". Two effects express that, one per namespace:
6
+ *
7
+ * 1. Skills — a library provider is registered on the **Agent's own context**.
8
+ * `SkillRegistry.registerProvider` files a provider into the layer of the
9
+ * calling context's scope, and an Agent's scope key is the Agent object, so
10
+ * that layer is visible to this Agent alone. A skill the pool did not admit
11
+ * is therefore absent from this Agent's catalog AND unloadable: strict hiding
12
+ * falls out of the registry instead of tool replacement.
13
+ * 2. MCP — `agent.ctx.tools.restrict({ deny })` removes exactly the public tool
14
+ * names of servers the pool did not activate. There is no layered equivalent
15
+ * for tools, so this remains a restriction.
16
+ *
17
+ * A system-prompt section then states the mode, workspace and what is active, so
18
+ * the model neither guesses nor tries to recall a resource it cannot reach.
19
+ *
20
+ * Everything is computed before the live activation is released, so a
21
+ * configuration change never leaves a window where the old restrictions are
22
+ * lifted but the new ones are not installed yet. Registrations are owned by
23
+ * `agent.ctx` and released on disposal.
24
+ *
25
+ * @module dsh-skill-pool/activation
26
+ */
27
+
28
+ import { librarySkillsRoot } from './library.js'
29
+ import { createLibraryProvider } from './provider.js'
30
+ import { isAmbiguousMcpToolName, mcpServerOf, MCP_TOOL_PREFIX, resolvePool } from './rules.js'
31
+
32
+ const SECTION_NAME = 'resource-pool:active'
33
+
34
+ /** Labels of effects that restrict the MCP tool surface (normal or fallback). */
35
+ const RESTRICT_LABELS = new Set(['mcp-restrict', 'mcp-restrict-fallback'])
36
+
37
+ /**
38
+ * Read the Agent mode of one live Agent.
39
+ * @param {object} ctx - plugin context.
40
+ * @param {any} agent - live Agent.
41
+ * @returns {string} preset id, never empty.
42
+ */
43
+ export function modeOf(ctx, agent) {
44
+ // Order matters. `session.header.agentPreset` is a snapshot taken when the
45
+ // session was created and is never rewritten, so a session that switched preset
46
+ // before its first turn keeps reporting the original one forever. The live
47
+ // sources must win, or the pool resolves against a mode the Agent is not in.
48
+ const registry = ctx.get('agentPresets')
49
+ if (registry !== undefined && typeof registry.composedPreset === 'function' && agent?.ctx !== undefined) {
50
+ try {
51
+ const composed = registry.composedPreset(agent.ctx)
52
+ if (typeof composed === 'string' && composed.length > 0) return composed
53
+ } catch {
54
+ /* fall through to the logged selection */
55
+ }
56
+ }
57
+ // The preset projection is the latest `agent-preset/selected` in the session log.
58
+ const projections = ctx.get('sessionProjections')
59
+ if (projections !== undefined && typeof projections.stateOf === 'function' && agent?.session !== undefined) {
60
+ try {
61
+ const selected = projections.stateOf(agent.session, 'agentPreset')
62
+ if (typeof selected === 'string' && selected.length > 0) return selected
63
+ } catch {
64
+ /* fall through to the creation-time header */
65
+ }
66
+ }
67
+ const header = agent?.session?.header?.agentPreset
68
+ if (typeof header === 'string' && header.trim().length > 0) return header.trim()
69
+ return 'default'
70
+ }
71
+
72
+ /**
73
+ * Whether the preset a live Agent actually runs differs from its session header.
74
+ *
75
+ * A switch before the first turn only appends `agent-preset/selected`; the header
76
+ * stays as the creation snapshot. Callers use this to notice that re-applying the
77
+ * pool is warranted even though no document changed.
78
+ *
79
+ * @param {object} ctx - plugin context.
80
+ * @param {any} agent - live Agent.
81
+ * @returns {boolean} whether the header is stale for this Agent.
82
+ */
83
+ export function presetHeaderStale(ctx, agent) {
84
+ const header = agent?.session?.header?.agentPreset
85
+ if (typeof header !== 'string' || header.trim().length === 0) return false
86
+ return modeOf(ctx, agent) !== header.trim()
87
+ }
88
+
89
+ /**
90
+ * Read the working directory of one live Agent.
91
+ * @param {any} agent - live Agent.
92
+ * @returns {string} absolute directory or the process cwd.
93
+ */
94
+ export function workspaceOf(agent) {
95
+ const cwd = agent?.session?.header?.cwd
96
+ if (typeof cwd === 'string' && cwd.length > 0) return cwd
97
+ return process.cwd()
98
+ }
99
+
100
+ /** Chinese prompt summary. */
101
+ function summaryTextZh({ mode, cwd, skillNames, servers, skillGated, mcpGated }) {
102
+ const lines = ['## 技能池已激活', '', `Agent 模式:\`${mode}\`,工作区:\`${cwd}\`。`]
103
+ if (skillGated) {
104
+ lines.push(
105
+ skillNames.length > 0
106
+ ? `技能池在本会话提供了这些技能:${skillNames.join('、')}。`
107
+ : '技能池在本会话没有提供任何技能。',
108
+ )
109
+ }
110
+ if (mcpGated) {
111
+ if (servers.length > 0) {
112
+ // The authoritative list of admitted connections: every other MCP tool
113
+ // is hidden in this session.
114
+ lines.push(`本会话可用的 MCP 连接只有:${servers.join('、')};其它 MCP 工具已被隐藏。`)
115
+ } else {
116
+ lines.push('本会话没有任何可用 MCP 连接;所有 MCP 工具已被隐藏。')
117
+ }
118
+ }
119
+ lines.push(
120
+ '未列出的技能池资源在本模式/工作区下确实不可用:不要尝试调用,也不要凭记忆复述它们的内容。',
121
+ '如果任务确实需要某个不可用的资源,请让用户在「设置 → 技能池」里为它加上当前的 Agent 模式或工作区条件。',
122
+ )
123
+ return lines.join('\n')
124
+ }
125
+
126
+ /** English prompt summary. */
127
+ function summaryTextEn({ mode, cwd, skillNames, servers, skillGated, mcpGated }) {
128
+ const lines = ['## Resource pool active', '', `Agent mode \`${mode}\`, workspace \`${cwd}\`.`]
129
+ if (skillGated) {
130
+ lines.push(
131
+ skillNames.length > 0
132
+ ? `The resource pool supplies these skills in this session: ${skillNames.join(', ')}.`
133
+ : 'The resource pool supplies no skills in this session.',
134
+ )
135
+ }
136
+ if (mcpGated) {
137
+ if (servers.length > 0) {
138
+ lines.push(
139
+ `The only MCP connections available in this session are: ${servers.join('; ')}; every other MCP tool is hidden.`,
140
+ )
141
+ } else {
142
+ lines.push('No MCP connections are available in this session; all MCP tools are hidden.')
143
+ }
144
+ }
145
+ lines.push(
146
+ 'Resource-pool resources that are not listed are genuinely unavailable in this mode/workspace: do not try to call them and do not recall their content from memory.',
147
+ 'If a task really needs an unavailable resource, ask the user to add the current Agent mode or workspace to its condition in Settings → Resource pool.',
148
+ )
149
+ return lines.join('\n')
150
+ }
151
+
152
+ /**
153
+ * Create the activation manager.
154
+ * @param {object} options - manager options.
155
+ * @param {object} options.ctx - plugin context.
156
+ * @param {(fresh?: boolean) => Promise<object>} options.getState - read the current document.
157
+ * @param {{ debug?: Function, warn?: Function }} [options.logger] - logger.
158
+ * @param {() => string} [options.promptLanguage] - 'zh' | 'en'.
159
+ * @param {() => string} [options.libraryRoot] - library skills root override.
160
+ * @returns {object} manager with applyToAgent/reapplyAll/disposeAgent/disposeAll.
161
+ */
162
+ export function createActivation({ ctx, getState, logger, promptLanguage = () => 'zh', libraryRoot = () => librarySkillsRoot() }) {
163
+ /** @type {WeakMap<object, {disposers: {dispose: Function, label: string}[], signature: string, activated: boolean, chain: Promise<void>}>} */
164
+ const agents = new WeakMap()
165
+
166
+ /** Dispose one recorded registration, tolerating an already-disposed effect. */
167
+ const disposeEntry = (entry) => {
168
+ try {
169
+ entry.dispose()
170
+ } catch {
171
+ /* already disposed */
172
+ }
173
+ }
174
+
175
+ /** Release every registration owned for one Agent. */
176
+ const release = (agent) => {
177
+ const record = agents.get(agent)
178
+ if (record === undefined) return
179
+ for (const entry of record.disposers.reverse()) disposeEntry(entry)
180
+ record.disposers = []
181
+ record.signature = ''
182
+ record.activated = false
183
+ record.conservative = false
184
+ record.degraded = false
185
+ record.underRestricted = false
186
+ record.mcpGateActive = false
187
+ }
188
+
189
+ /** Signature of a decision, used to skip no-op re-applications. */
190
+ const signatureOf = (pool, allowed, libraryNames) =>
191
+ JSON.stringify({
192
+ gated: pool.gated,
193
+ skills: allowed,
194
+ mcp: pool.mcpServers,
195
+ gs: pool.gateSkills,
196
+ gm: pool.gateMcp,
197
+ lib: libraryNames,
198
+ })
199
+
200
+ /**
201
+ * Serialize applications per Agent.
202
+ *
203
+ * A failure for an Agent that already has a live activation is contained: the
204
+ * previous registrations stay installed and are never released before the new
205
+ * ones are known to be safe. A failure for an Agent with no activation is
206
+ * propagated to the caller, so `agent/created` rejects and no ungated Agent is
207
+ * published.
208
+ */
209
+ const applyToAgent = async (agent, { force = false, conservative = false } = {}) => {
210
+ if (agent?.ctx === undefined) return
211
+ let record = agents.get(agent)
212
+ if (record === undefined) {
213
+ record = {
214
+ disposers: [],
215
+ signature: '',
216
+ activated: false,
217
+ conservative: false,
218
+ degraded: false,
219
+ underRestricted: false,
220
+ mcpGateActive: false,
221
+ chain: Promise.resolve(),
222
+ }
223
+ agents.set(agent, record)
224
+ }
225
+ const run = record.chain.then(() => applyNow(agent, record, { force }))
226
+ // Keep the per-Agent chain fulfilled even when this application failed, so a
227
+ // later retry (after the file is repaired) is not wedged behind it.
228
+ record.chain = run.then(
229
+ () => undefined,
230
+ () => undefined,
231
+ )
232
+ try {
233
+ await run
234
+ if (record.underRestricted) {
235
+ return {
236
+ ok: false,
237
+ code: 'resource-pool/activation-incomplete',
238
+ message: 'MCP deny is incomplete; a tool whose restrict layer failed may be callable until the next replay',
239
+ underRestricted: true,
240
+ overRestricted: record.degraded === true,
241
+ conservative: false,
242
+ noVisibleTools: false,
243
+ }
244
+ }
245
+ return record.degraded
246
+ ? {
247
+ ok: true,
248
+ degraded: true,
249
+ code: 'resource-pool/activation-over-restricted',
250
+ message: 'some previously denied tools are not currently visible; old deny layers were retained and may over-restrict',
251
+ underRestricted: false,
252
+ overRestricted: true,
253
+ conservative: false,
254
+ noVisibleTools: false,
255
+ }
256
+ : { ok: true, underRestricted: false, overRestricted: false, conservative: false, noVisibleTools: false }
257
+ } catch (error) {
258
+ const hadActivation = record.activated
259
+ logger?.warn?.(`[resource-pool] activation failed: ${error instanceof Error ? error.message : String(error)}`)
260
+ if (hadActivation) {
261
+ // A conservative fallback is refreshable: every explicit re-apply must
262
+ // see newly registered MCP tools even while the document is unreadable.
263
+ if (record.conservative && conservative) {
264
+ try {
265
+ return conservativeResult(agent)
266
+ } catch (gateError) {
267
+ logger?.warn?.(`[resource-pool] conservative MCP gate refresh failed: ${gateError instanceof Error ? gateError.message : String(gateError)}`)
268
+ const retained = record.disposers.some((entry) => RESTRICT_LABELS.has(entry.label))
269
+ return {
270
+ ok: false,
271
+ code: 'resource-pool/activation-degraded',
272
+ message: 'state unavailable; conservative MCP deny refresh failed and previous layers were retained',
273
+ fallbackFailed: true,
274
+ retainedOldGate: retained,
275
+ underRestricted: false,
276
+ overRestricted: false,
277
+ conservative: false,
278
+ noVisibleTools: false,
279
+ }
280
+ }
281
+ }
282
+ // A healthy old layer is deliberately still installed. Reporting success
283
+ // would hide a degraded state; rejecting would make the Agent unusable
284
+ // even though its previous, authorized gate still protects it.
285
+ const hasRestrictLayer = record.disposers.some((entry) => RESTRICT_LABELS.has(entry.label))
286
+ if (conservative && record.mcpGateActive !== false && !hasRestrictLayer) {
287
+ // The previous successful activation intentionally allowed every
288
+ // visible tool (so it had zero restrict layers). Treating that as a
289
+ // "retained gate" would leave a later failure ungated. Install a
290
+ // conservative deny for all currently known MCP tools instead.
291
+ try {
292
+ return conservativeResult(agent)
293
+ } catch (gateError) {
294
+ logger?.warn?.(
295
+ `[resource-pool] conservative MCP gate failed without a prior layer: ${gateError instanceof Error ? gateError.message : String(gateError)}`,
296
+ )
297
+ return {
298
+ ok: false,
299
+ code: 'resource-pool/activation-degraded',
300
+ message: 'state unavailable and no prior MCP restriction could be installed',
301
+ fallbackFailed: true,
302
+ retainedOldGate: false,
303
+ }
304
+ }
305
+ }
306
+ if (hasRestrictLayer) {
307
+ return {
308
+ ok: false,
309
+ code: 'resource-pool/activation-degraded',
310
+ message: 'activation failed; previous MCP restriction layer retained',
311
+ retainedOldGate: true,
312
+ underRestricted: false,
313
+ overRestricted: false,
314
+ conservative: false,
315
+ noVisibleTools: false,
316
+ }
317
+ }
318
+ return {
319
+ ok: false,
320
+ code: 'resource-pool/activation-degraded',
321
+ message: 'activation failed; no prior MCP restriction layer to retain',
322
+ retainedOldGate: false,
323
+ underRestricted: false,
324
+ overRestricted: false,
325
+ conservative: false,
326
+ noVisibleTools: false,
327
+ }
328
+ }
329
+ if (conservative) {
330
+ // A live Agent with no layer of ours (for example one that existed before
331
+ // a plugin reload) cannot be left ungated while the document is
332
+ // unreadable. Deny every currently visible MCP tool and keep the Agent
333
+ // alive; dynamic additions remain a documented gap.
334
+ try {
335
+ return conservativeResult(agent)
336
+ } catch (gateError) {
337
+ logger?.warn?.(
338
+ `[resource-pool] conservative MCP gate failed: ${gateError instanceof Error ? gateError.message : String(gateError)}`,
339
+ )
340
+ return {
341
+ ok: false,
342
+ code: 'resource-pool/activation-degraded',
343
+ message: 'state unavailable; conservative MCP deny could not be installed',
344
+ fallbackFailed: true,
345
+ retainedOldGate: false,
346
+ underRestricted: false,
347
+ overRestricted: false,
348
+ conservative: false,
349
+ noVisibleTools: false,
350
+ }
351
+ }
352
+ }
353
+ // This is also the only safe response for an Agent with no previous gate:
354
+ // no caller may be told "activated" while nothing protects the Agent.
355
+ throw error
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Apply a deny-all-visible-MCP layer to one live Agent when the state cannot
361
+ * be read and there is no previous layer to keep. This is deliberately a
362
+ * static list: newly registered MCP tools can still appear, as documented.
363
+ */
364
+ const applyConservativeGate = (agent) => {
365
+ const tools = ctx.get('tools')
366
+ if (tools === undefined || typeof tools.schemas !== 'function') {
367
+ throw new Error('global tools service is unavailable')
368
+ }
369
+ const schemas = tools.schemas()
370
+ if (!Array.isArray(schemas)) throw new Error('global tool list is not an array')
371
+ const visible = schemas
372
+ .map((schema) => schema?.name)
373
+ .filter((name) => typeof name === 'string' && name.startsWith(MCP_TOOL_PREFIX))
374
+ const visibleSet = new Set(visible)
375
+ const record = agents.get(agent)
376
+ if (record === undefined) throw new Error('agent activation record is missing')
377
+
378
+ if (visible.length === 0) {
379
+ // Keep every previous per-tool layer: an absent tool may simply be
380
+ // between generations, and we cannot register its name again now. There
381
+ // is nothing we can truthfully claim as a newly installed deny. Any old
382
+ // denied name is currently invisible, so retaining it is over-restriction
383
+ // risk (we cannot know whether it is still meant to be denied).
384
+ const retainedNames = record.disposers
385
+ .filter((entry) => RESTRICT_LABELS.has(entry.label))
386
+ .flatMap((entry) => (Array.isArray(entry.deny) ? entry.deny : []))
387
+ const over = retainedNames.length > 0
388
+ record.signature = ''
389
+ record.activated = true
390
+ record.conservative = true
391
+ record.degraded = over
392
+ record.underRestricted = false
393
+ logger?.warn?.('[resource-pool] state unavailable; no visible MCP tools, kept previous conservative deny')
394
+ return { visible: 0, failed: 0, under: false, over, kept: record.disposers.length > 0 }
395
+ }
396
+
397
+ const previous = record.disposers
398
+ const oldRestrictions = []
399
+ for (const entry of previous) {
400
+ if (RESTRICT_LABELS.has(entry.label)) oldRestrictions.push(entry)
401
+ else disposeEntry(entry)
402
+ }
403
+ const pending = []
404
+ const failedNames = []
405
+ const newEntries = []
406
+ try {
407
+ for (const name of visible) {
408
+ try {
409
+ const dispose = agent.ctx.effect(
410
+ () => agent.ctx.tools.restrict({ deny: [name] }),
411
+ 'resource-pool.mcp-restrict-fallback',
412
+ )
413
+ const entry = {
414
+ dispose: typeof dispose === 'function' ? dispose : () => {},
415
+ label: 'mcp-restrict-fallback',
416
+ deny: [name],
417
+ }
418
+ pending.push(entry)
419
+ newEntries.push(entry)
420
+ } catch (error) {
421
+ failedNames.push(name)
422
+ logger?.warn?.(
423
+ `[resource-pool] one conservative MCP deny could not be registered (retaining old layers): ${error instanceof Error ? error.message : String(error)}`,
424
+ )
425
+ }
426
+ }
427
+
428
+ const oldCoverage = new Set(oldRestrictions.flatMap((entry) => (Array.isArray(entry.deny) ? entry.deny : [])))
429
+ let retained = []
430
+ let retainedInvisible = false
431
+ if (failedNames.length > 0) {
432
+ retained = oldRestrictions
433
+ retainedInvisible = oldRestrictions.length > 0
434
+ } else {
435
+ for (const entry of oldRestrictions) {
436
+ const names = Array.isArray(entry.deny) ? entry.deny : []
437
+ if (names.some((name) => !visibleSet.has(name))) {
438
+ retained.push(entry)
439
+ retainedInvisible = true
440
+ } else {
441
+ disposeEntry(entry)
442
+ }
443
+ }
444
+ }
445
+ record.disposers = [...pending, ...retained]
446
+
447
+ const retainedCoverage = new Set(
448
+ retained.flatMap((entry) => (Array.isArray(entry.deny) ? entry.deny : [])),
449
+ )
450
+ for (const entry of newEntries) {
451
+ const name = entry.deny?.[0]
452
+ if (!retainedCoverage.has(name)) continue
453
+ disposeEntry(entry)
454
+ const index = pending.indexOf(entry)
455
+ if (index >= 0) pending.splice(index, 1)
456
+ record.disposers = record.disposers.filter((candidate) => candidate !== entry)
457
+ }
458
+
459
+ const over = retained.some((entry) =>
460
+ (Array.isArray(entry.deny) ? entry.deny : []).some((name) => !visibleSet.has(name)),
461
+ )
462
+ record.signature = ''
463
+ record.activated = true
464
+ record.conservative = true
465
+ record.degraded = over
466
+ const under = failedNames.some((name) => !oldCoverage.has(name))
467
+ record.underRestricted = under
468
+ logger?.warn?.(
469
+ failedNames.length > 0
470
+ ? `[resource-pool] state unavailable; conservative MCP deny is incomplete (${failedNames.length} failed)`
471
+ : `[resource-pool] state unavailable; conservative MCP deny covers ${visible.length} visible tool${visible.length === 1 ? '' : 's'}`,
472
+ )
473
+ return { visible: visible.length, failed: failedNames.length, under, over, kept: retainedInvisible }
474
+ } catch (error) {
475
+ for (const entry of pending.reverse()) disposeEntry(entry)
476
+ throw error
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Convert one conservative-gate outcome into the exact external result.
482
+ * A partial failure is under-restriction; empty visibility never claims a
483
+ * deny was installed; success is the conservative mode result.
484
+ */
485
+ const conservativeResult = (agent) => {
486
+ const info = applyConservativeGate(agent)
487
+ const common = {
488
+ underRestricted: info.under === true,
489
+ overRestricted: info.over === true,
490
+ conservative: info.visible > 0,
491
+ noVisibleTools: info.visible === 0,
492
+ }
493
+ if (info.under) {
494
+ return {
495
+ ok: false,
496
+ code: 'resource-pool/activation-incomplete',
497
+ message: 'state unavailable; conservative MCP deny is incomplete and a failed tool may be callable',
498
+ ...common,
499
+ }
500
+ }
501
+ if (info.visible === 0) {
502
+ return {
503
+ ok: false,
504
+ code: 'resource-pool/activation-degraded',
505
+ message: info.kept
506
+ ? 'state unavailable; no MCP tools visible, previous layers kept, no new deny installed'
507
+ : 'state unavailable; no MCP tools visible, no deny could be installed',
508
+ ...common,
509
+ }
510
+ }
511
+ return {
512
+ ok: false,
513
+ code: 'resource-pool/activation-conservative',
514
+ message: 'state unavailable; conservative MCP deny applied to visible tools',
515
+ ...common,
516
+ }
517
+ }
518
+
519
+ /** Build one Agent's registrations. Runs serialized per Agent. */
520
+ const applyNow = async (agent, record, { force }) => {
521
+ // This read is fail-closed: a corrupt/unreadable/unsupported document throws
522
+ // instead of resolving to an empty pool. It happens before any live
523
+ // registration is touched, so an already-gated Agent keeps its old layers.
524
+ const state = await getState()
525
+ const settings = state.settings ?? {}
526
+ const mode = modeOf(ctx, agent)
527
+ const cwd = workspaceOf(agent)
528
+ const pool = resolvePool(state, { mode, cwd })
529
+ // Only servers this Agent may use enter the summary.
530
+ const servers = pool.gateMcp ? [...pool.mcpServers] : []
531
+
532
+ // The pool owns every library skill, so an Agent sees a skill only when the
533
+ // pool admits it here. A disabled master switch means "do not gate at all",
534
+ // which for a per-Agent provider means "admit the whole library".
535
+ const libraryNames = Object.keys(state.skills ?? {}).sort()
536
+ const allowed = settings.enabled === false ? libraryNames : pool.skills
537
+ const signature = `${signatureOf(pool, allowed, libraryNames)}|${mode}|${cwd}`
538
+ if (!force && record.signature === signature) return
539
+
540
+ const tools = ctx.get('tools')
541
+ const skills = agent.ctx.get('skills')
542
+
543
+ // ---- Compute the whole next activation before touching the live one.
544
+ const allowedSkills = new Set(allowed)
545
+ let denyMcp = []
546
+ let observedMcp = 0
547
+ const visibleMcpNames = []
548
+ if (pool.gateMcp) {
549
+ // A missing/unreadable global tool surface is not "nothing to hide": it
550
+ // means the MCP gate cannot be established. Treat it as an activation
551
+ // failure instead of publishing an Agent without its deny layer.
552
+ if (tools === undefined || typeof tools.schemas !== 'function') {
553
+ throw new Error('MCP gate is required but the global tools service is unavailable')
554
+ }
555
+ let schemas
556
+ try {
557
+ schemas = tools.schemas()
558
+ } catch (error) {
559
+ throw new Error('MCP gate is required but the global tool list could not be read', { cause: error })
560
+ }
561
+ if (!Array.isArray(schemas)) throw new Error('MCP gate is required but the global tool list is not an array')
562
+ const allowedServers = new Set(pool.mcpServers)
563
+ let ambiguous = 0
564
+ for (const schema of schemas) {
565
+ const name = schema?.name
566
+ if (typeof name !== 'string' || !name.startsWith(MCP_TOOL_PREFIX)) continue
567
+ observedMcp += 1
568
+ visibleMcpNames.push(name)
569
+ if (isAmbiguousMcpToolName(name)) {
570
+ // The public name cannot be attributed to one server; deny rather than
571
+ // allow by a prefix that an external server could share.
572
+ ambiguous += 1
573
+ denyMcp.push(name)
574
+ continue
575
+ }
576
+ if (!allowedServers.has(mcpServerOf(name))) denyMcp.push(name)
577
+ }
578
+ if (ambiguous > 0) {
579
+ logger?.warn?.(`[resource-pool] denied ${ambiguous} ambiguous MCP tool name${ambiguous === 1 ? '' : 's'} to avoid cross-server prefix allow`)
580
+ }
581
+ }
582
+
583
+ // ---- Apply transactionally: install the new MCP deny while the old one is
584
+ // still active (restrictions intersect, so this can only tighten), release
585
+ // only the non-critical old effects, and release the old deny last. A
586
+ // failed critical registration leaves the previous gate untouched.
587
+ const previous = record.disposers
588
+ const pending = []
589
+ let incomplete = false
590
+ const addEffect = (register, label, { critical = false, deny } = {}) => {
591
+ try {
592
+ const dispose = agent.ctx.effect(register, `resource-pool.${label}`)
593
+ pending.push({
594
+ dispose: typeof dispose === 'function' ? dispose : () => {},
595
+ label,
596
+ ...(Array.isArray(deny) ? { deny: [...deny] } : {}),
597
+ })
598
+ return true
599
+ } catch (error) {
600
+ if (critical) throw error
601
+ incomplete = true
602
+ logger?.debug?.(`[resource-pool] ${label} registration failed: ${error instanceof Error ? error.message : String(error)}`)
603
+ return false
604
+ }
605
+ }
606
+
607
+ let retainedInvisible = false
608
+ let underRestricted = false
609
+ let overRestricted = false
610
+ try {
611
+ // Separate old restriction layers before registering anything.
612
+ const oldRestrictions = []
613
+ for (const entry of previous) {
614
+ if (RESTRICT_LABELS.has(entry.label)) oldRestrictions.push(entry)
615
+ else disposeEntry(entry)
616
+ }
617
+ record.disposers = oldRestrictions
618
+
619
+ const visibleSet = new Set(visibleMcpNames)
620
+ // Old layers that cover an invisible name will be retained; their visible
621
+ // denied names are already covered, so do not stack duplicates.
622
+ const retainedCoverage = new Set(
623
+ oldRestrictions
624
+ .filter((entry) => {
625
+ const names = Array.isArray(entry.deny) ? entry.deny : []
626
+ return names.some((name) => !visibleSet.has(name))
627
+ })
628
+ .flatMap((entry) => (Array.isArray(entry.deny) ? entry.deny : [])),
629
+ )
630
+ const failedNames = []
631
+ const newEntries = []
632
+ let restrictFailures = 0
633
+ if (pool.gateMcp && observedMcp > 0) {
634
+ for (const name of denyMcp) {
635
+ if (retainedCoverage.has(name)) continue
636
+ try {
637
+ const dispose = agent.ctx.effect(
638
+ () => agent.ctx.tools.restrict({ deny: [name] }),
639
+ 'resource-pool.mcp-restrict',
640
+ )
641
+ const entry = {
642
+ dispose: typeof dispose === 'function' ? dispose : () => {},
643
+ label: 'mcp-restrict',
644
+ deny: [name],
645
+ }
646
+ pending.push(entry)
647
+ newEntries.push(entry)
648
+ } catch (error) {
649
+ restrictFailures += 1
650
+ failedNames.push(name)
651
+ incomplete = true
652
+ logger?.warn?.(
653
+ `[resource-pool] one MCP restrict layer could not be registered (retaining old layers): ${error instanceof Error ? error.message : String(error)}`,
654
+ )
655
+ }
656
+ }
657
+ }
658
+
659
+ // Skill providers and prompt sections are keyed by name, so the old
660
+ // registration of that kind must be gone before the new one is inserted.
661
+ // They are not a rights-widening boundary: if the new one fails, the Agent
662
+ // has no pool skills / summary, which fails closed for this Agent.
663
+ if (allowedSkills.size > 0) {
664
+ if (skills === undefined || typeof skills.registerProvider !== 'function') {
665
+ logger?.warn?.('[resource-pool] skills registry unavailable; library skills cannot be served')
666
+ } else {
667
+ const root = libraryRoot()
668
+ addEffect(
669
+ () => skills.registerProvider((control) => createLibraryProvider({ root, allowed: allowedSkills, logger, control })),
670
+ 'skill-provider',
671
+ )
672
+ }
673
+ }
674
+
675
+ const systemPrompt = ctx.get('systemPrompt')
676
+ if (
677
+ settings.injectSummary !== false &&
678
+ pool.gated &&
679
+ systemPrompt !== undefined &&
680
+ typeof systemPrompt.getSectionOrder === 'function'
681
+ ) {
682
+ const skillNames = allowedSkills.size > 0 ? [...allowedSkills].sort() : []
683
+ const summary = (promptLanguage() === 'en' ? summaryTextEn : summaryTextZh)({
684
+ mode,
685
+ cwd,
686
+ skillNames,
687
+ servers,
688
+ skillGated: pool.gateSkills,
689
+ mcpGated: pool.gateMcp,
690
+ })
691
+ addEffect(
692
+ () =>
693
+ agent.ctx.systemPrompt.section({
694
+ name: SECTION_NAME,
695
+ order: systemPrompt.getSectionOrder('TOOL_READ') - 30,
696
+ text: summary,
697
+ }),
698
+ 'summary',
699
+ )
700
+ }
701
+
702
+ if (!pool.gateMcp) {
703
+ // Explicit no-gate intent: release every layer, including names that
704
+ // are not currently visible.
705
+ for (const entry of oldRestrictions) disposeEntry(entry)
706
+ record.disposers = pending
707
+ } else if (observedMcp === 0) {
708
+ // No MCP tool is visible: we cannot name anything new, so keep every old
709
+ // per-tool layer (transient host generation change).
710
+ record.disposers = [...pending, ...oldRestrictions]
711
+ retainedInvisible = oldRestrictions.length > 0
712
+ overRestricted = oldRestrictions.some((entry) =>
713
+ (Array.isArray(entry.deny) ? entry.deny : []).some((name) => !visibleSet.has(name)),
714
+ )
715
+ } else if (restrictFailures > 0) {
716
+ // A brand-new Agent has no prior authorization to fall back on: partial
717
+ // MCP coverage must fail creation.
718
+ if (!record.activated) throw new Error('MCP restrict registration failed for a new Agent')
719
+ const oldCoverage = new Set(
720
+ oldRestrictions.flatMap((entry) => (Array.isArray(entry.deny) ? entry.deny : [])),
721
+ )
722
+ // Drop a successful new layer if an old retained layer already covers
723
+ // the same name, so repeated failures cannot grow the active set.
724
+ for (const entry of newEntries) {
725
+ const name = entry.deny?.[0]
726
+ if (!oldCoverage.has(name)) continue
727
+ disposeEntry(entry)
728
+ const index = pending.indexOf(entry)
729
+ if (index >= 0) pending.splice(index, 1)
730
+ }
731
+ retainedInvisible = oldRestrictions.length > 0
732
+ underRestricted = failedNames.some((name) => !oldCoverage.has(name))
733
+ const deniedSet = new Set(denyMcp)
734
+ overRestricted = oldRestrictions.some((entry) =>
735
+ (Array.isArray(entry.deny) ? entry.deny : []).some(
736
+ (name) => !visibleSet.has(name) || !deniedSet.has(name),
737
+ ),
738
+ )
739
+ record.disposers = [...pending, ...oldRestrictions]
740
+ } else {
741
+ const retained = []
742
+ for (const entry of oldRestrictions) {
743
+ const names = Array.isArray(entry.deny) ? entry.deny : []
744
+ // A name not visible now cannot be re-registered; keep the old layer
745
+ // that covers it. If it also covered a currently visible allowed name,
746
+ // the old layer must stay too (it cannot be split), so the result is
747
+ // reported as degraded rather than claimed fully applied.
748
+ if (names.some((name) => !visibleSet.has(name))) {
749
+ retained.push(entry)
750
+ retainedInvisible = true
751
+ } else {
752
+ disposeEntry(entry)
753
+ }
754
+ }
755
+ record.disposers = [...pending, ...retained]
756
+ const deniedSet = new Set(denyMcp)
757
+ overRestricted = retained.some((entry) =>
758
+ (Array.isArray(entry.deny) ? entry.deny : []).some(
759
+ (name) => !visibleSet.has(name) || !deniedSet.has(name),
760
+ ),
761
+ )
762
+ }
763
+
764
+ record.activated = true
765
+ record.mcpGateActive = pool.gateMcp
766
+ // Any retained layer covering a currently invisible name means the last
767
+ // safe activation could not be reconstructed exactly. Keep conservative
768
+ // semantics so a later state failure refreshes coverage for new tools.
769
+ // An under-restriction activation has no complete prior gate, so a later
770
+ // state failure must attempt a conservative refresh even if some new
771
+ // per-tool layers succeeded and there were no old layers.
772
+ record.conservative = retainedInvisible || underRestricted
773
+ record.degraded = overRestricted
774
+ record.underRestricted = underRestricted
775
+ record.signature = incomplete || retainedInvisible ? '' : signature
776
+ } catch (error) {
777
+ // No successful commit: remove anything this attempt registered and leave
778
+ // the previous gate (still in `record.disposers`) in force. Clear the
779
+ // signature so a later ordinary re-apply retries the failed layer set.
780
+ for (const entry of pending.reverse()) disposeEntry(entry)
781
+ record.signature = ''
782
+ throw error
783
+ }
784
+
785
+ logger?.debug?.(
786
+ `[resource-pool] activated mode=${mode} cwd=${cwd} skills=${allowedSkills.size}/${libraryNames.length} mcpHidden=${denyMcp.length}`,
787
+ )
788
+ }
789
+
790
+ /** Re-apply the current document to every live Agent. */
791
+ const reapplyAll = async () => {
792
+ const registry = ctx.get('agents')
793
+ const live = typeof registry?.list === 'function' ? registry.list() : []
794
+ // A failure for one Agent must not stop the others, and it must not be
795
+ // reported as a successful application for that Agent. Messages are fixed
796
+ // so callers can show a warning without echoing tool names or state bytes.
797
+ const results = await Promise.all(
798
+ live.map(async (agent) => {
799
+ try {
800
+ return await applyToAgent(agent, { force: true, conservative: true })
801
+ } catch (error) {
802
+ logger?.warn?.(`[resource-pool] re-apply failed: ${error instanceof Error ? error.message : String(error)}`)
803
+ return { ok: false, code: 'resource-pool/activation-failed', message: 'activation failed' }
804
+ }
805
+ }),
806
+ )
807
+ const failed = results.filter((result) => result !== undefined && result.ok === false)
808
+ const count = (key) => results.filter((result) => result?.[key] === true).length
809
+ const under = count('underRestricted')
810
+ const over = count('overRestricted')
811
+ const conservative = count('conservative')
812
+ const noVisible = count('noVisibleTools')
813
+ const retainedOldGate = count('retainedOldGate')
814
+ const fallbackFailed = count('fallbackFailed')
815
+ const degraded = over
816
+ const seen = new Set()
817
+ const warnings = []
818
+ for (const result of results) {
819
+ if (result === undefined || typeof result.code !== 'string' || typeof result.message !== 'string') continue
820
+ if (result.ok === true && result.degraded !== true) continue
821
+ const key = `${result.code}|${result.message}`
822
+ if (seen.has(key)) continue
823
+ seen.add(key)
824
+ warnings.push({ code: result.code, message: result.message })
825
+ }
826
+ return {
827
+ total: live.length,
828
+ failed: failed.length,
829
+ degraded,
830
+ under,
831
+ over,
832
+ conservative,
833
+ noVisible,
834
+ retainedOldGate,
835
+ fallbackFailed,
836
+ warnings,
837
+ }
838
+ }
839
+
840
+ /** Release one Agent's registrations. */
841
+ const disposeAgent = (agent) => {
842
+ release(agent)
843
+ agents.delete(agent)
844
+ }
845
+
846
+ /** Release every Agent's registrations (plugin unload). */
847
+ const disposeAll = () => {
848
+ const registry = ctx.get('agents')
849
+ const live = typeof registry?.list === 'function' ? registry.list() : []
850
+ for (const agent of live) disposeAgent(agent)
851
+ }
852
+
853
+ return { applyToAgent, reapplyAll, disposeAgent, disposeAll }
854
+ }