dsh-plugins-scope 0.0.0-stage → 0.5.1

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/index.js ADDED
@@ -0,0 +1,1625 @@
1
+ // Third-party plugin scope manager.
2
+ //
3
+ // One inheritance chain: global default -> workspace override -> session override.
4
+ // An entry is only ever "on", "off" or "inherit" at each level. "Off" hides that
5
+ // entry's tools inside the affected agent scopes; nothing is uninstalled and no
6
+ // configuration is changed. Official @deepseek-ai plugins are never managed.
7
+ //
8
+ // Enforcement: every agent resolves its tool set through ToolsService.resolve().
9
+ // We wrap the resolved set's view(scope) once and drop hidden names per session.
10
+ // This hides declarations from the model and rejects execution (the executor
11
+ // resolves through the same view).
12
+
13
+ import fs from 'node:fs';
14
+ import { randomUUID } from 'node:crypto';
15
+ import { createRequire } from 'node:module';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+
19
+ export const name = 'plugin-scopes';
20
+ export const inject = ['tools', 'systemPrompt', 'webServer', 'workspaceRegistry', 'sessions', 'agents', 'agentPresets'];
21
+
22
+ const API_PATH = '/plugin-scopes/api';
23
+ const PATCH_MARK = Symbol.for('dsh.plugin-scopes.resolve-patch');
24
+ const REGISTER_MARK = Symbol.for('dsh.plugin-scopes.register-patch');
25
+ const HIDDEN_HOOK = Symbol.for('dsh.plugin-scopes.hidden-hook');
26
+ const PROMPT_PATCH_MARK = Symbol.for('dsh.plugin-scopes.prompt-patch-v2');
27
+ const HIDDEN_PLUGINS_HOOK = Symbol.for('dsh.plugin-scopes.hidden-plugins');
28
+ const SECTION_OWNERS = Symbol.for('dsh.plugin-scopes.section-owners');
29
+ const CONTEXT_OWNERS = Symbol.for('dsh.plugin-scopes.context-owners');
30
+ const STREAM_PATCH_MARK = Symbol.for('dsh.plugin-scopes.stream-patch-v1');
31
+ const SKILL_PATCH_MARK = Symbol.for('dsh.plugin-scopes.skill-patch-v1');
32
+ const COMPOSE_MARK = Symbol.for('dsh.plugin-scopes.compose-mount-v1');
33
+ const STREAM_HOOK = Symbol.for('dsh.plugin-scopes.stream-hook');
34
+ const STREAM_STATS = Symbol.for('dsh.plugin-scopes.stream-stats');
35
+
36
+ // Bundles that other parts of the profile depend on (base loading, the web shell,
37
+ // the betterSidebar provider, or this manager). Turning these off breaks boot, so
38
+ // they are listed and never switchable from the UI.
39
+ const PROTECTED = new Set([
40
+ '@deepseek-ai/dsh-base',
41
+ '@deepseek-ai/dsh-web-app',
42
+ '@linxin666/dsh-web-ui-all',
43
+ 'dsh-plugins-scope',
44
+ 'dsh-plugin-scope',
45
+ ]);
46
+
47
+ // Package-name words too generic to prove tool ownership. Without this, a plugin
48
+ // named `dsh-plugin-wallpaper-engine` would claim our own `plugin_scope` tool just
49
+ // because the word "plugin" is a prefix of the tool name.
50
+ const GENERIC_PARTS = new Set([
51
+ 'plugin', 'plugins', 'tool', 'tools', 'client', 'core', 'agent', 'agents',
52
+ 'server', 'service', 'app', 'web', 'api', 'sdk', 'kit', 'lib', 'common',
53
+ 'shared', 'test', 'tests', 'auto', 'model', 'models', 'config', 'data',
54
+ 'base', 'main', 'index', 'docs', 'example', 'extension', 'extensions',
55
+ ]);
56
+
57
+ // Core tools are registered by the harness itself, never by a profile plugin.
58
+ // Runtime attribution walks the caller stack and can occasionally traverse a
59
+ // third-party fiber (dsh-ops wraps several core tools), so drop these names when
60
+ // merging attributed tools: hiding them would take away `read`, `glob`, `pwsh`
61
+ // from every agent instead of hiding the plugin's own tool.
62
+ const CORE_TOOLS = new Set([
63
+ 'read', 'write', 'edit', 'glob', 'grep', 'bash', 'pwsh',
64
+ 'web_search', 'web_fetch', 'todo_write', 'ask_user_question',
65
+ 'read_image', 'present', 'skill', 'compress', 'decompress', 'search_context',
66
+ 'create_goal', 'update_goal', 'get_goal', 'exit_plan_mode',
67
+ 'subagent', 'subagent_fork', 'workflow', 'list_agents', 'send_message', 'wait_agent',
68
+ 'job_list', 'job_output', 'job_kill',
69
+ 'terminal_open', 'terminal_read', 'terminal_send', 'terminal_signal', 'terminal_close', 'terminal_list',
70
+ 'acp_status', 'acp_cache', 'acp_read_original_image',
71
+ 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view',
72
+ 'plugin_manager', 'plugin_market', 'load_workspace_dependencies', 'working_directory',
73
+ 'cordis_inspect_list', 'cordis_inspect_query',
74
+ 'user_terminal_list', 'user_terminal_read',
75
+ ]);
76
+
77
+ // The Host usually runs a profile plugin with cwd at the profile directory, but a
78
+ // headless CLI boot keeps cwd wherever the shell was. Resolve the profile from the
79
+ // home directory, preferring a real profile directory that lists this bundle.
80
+ function dshHome() {
81
+ return process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
82
+ }
83
+
84
+ function activeProfileName() {
85
+ const args = process.argv.slice(2);
86
+ const index = args.indexOf('--profile');
87
+ if (index >= 0 && args[index + 1]) return args[index + 1];
88
+ if (args.includes('web')) return 'web';
89
+ return undefined;
90
+ }
91
+
92
+ function resolveProfileDir() {
93
+ const home = dshHome();
94
+ const profiles = path.join(home, 'profiles');
95
+ const prefer = activeProfileName();
96
+ const candidates = prefer ? [prefer] : [];
97
+ try {
98
+ for (const entry of fs.readdirSync(profiles, { withFileTypes: true })) {
99
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
100
+ if (!candidates.includes(entry.name)) candidates.push(entry.name);
101
+ }
102
+ } catch {
103
+ /* no profiles dir */
104
+ }
105
+ for (const name of candidates) {
106
+ const dir = path.join(profiles, name);
107
+ try {
108
+ if (fs.lstatSync(dir).isSymbolicLink()) continue;
109
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
110
+ const bundles = pkg.dsh?.profile?.bundles ?? [];
111
+ const deps = pkg.dependencies ?? {};
112
+ if (bundles.includes('dsh-plugins-scope') || deps['dsh-plugins-scope'] || bundles.includes('dsh-plugin-scope') || deps['dsh-plugin-scope']) return dir;
113
+ } catch {
114
+ /* not a profile */
115
+ }
116
+ }
117
+ return process.cwd();
118
+ }
119
+
120
+ const PROFILE_DIR = resolveProfileDir();
121
+
122
+ function homeDir() {
123
+ return dshHome();
124
+ }
125
+
126
+ function storageFile() {
127
+ return path.join(homeDir(), 'storages', 'plugin-scopes', `${path.basename(PROFILE_DIR)}.json`);
128
+ }
129
+
130
+ function readStore() {
131
+ const empty = { version: 1, global: {}, workspaces: {}, sessions: {}, types: {}, observed: [], managed: [] };
132
+ try {
133
+ const raw = JSON.parse(fs.readFileSync(storageFile(), 'utf8'));
134
+ return {
135
+ version: 1,
136
+ global: raw.global && typeof raw.global === 'object' ? raw.global : {},
137
+ workspaces: raw.workspaces && typeof raw.workspaces === 'object' ? raw.workspaces : {},
138
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
139
+ types: raw.types && typeof raw.types === 'object' ? raw.types : {},
140
+ observed: Array.isArray(raw.observed) ? raw.observed.filter((name) => typeof name === 'string') : [],
141
+ managed: Array.isArray(raw.managed) ? raw.managed.filter((name) => typeof name === 'string') : [],
142
+ };
143
+ } catch {
144
+ return empty;
145
+ }
146
+ }
147
+
148
+ function writeStore(store) {
149
+ const file = storageFile();
150
+ fs.mkdirSync(path.dirname(file), { recursive: true });
151
+ fs.writeFileSync(file, JSON.stringify(store, null, 2));
152
+ }
153
+
154
+ function profileDeps() {
155
+ try {
156
+ const pkg = JSON.parse(fs.readFileSync(path.join(PROFILE_DIR, 'package.json'), 'utf8'));
157
+ return { deps: Object.keys(pkg.dependencies ?? {}), bundles: pkg.dsh?.profile?.bundles ?? [] };
158
+ } catch {
159
+ return { deps: [], bundles: [] };
160
+ }
161
+ }
162
+
163
+ // Only-global (UI/service) plugins are switched by whether their bundle is in the
164
+ // profile's `dsh.profile.bundles`. Edit that one field in place and keep every
165
+ // other bundle untouched — the previous pluginManager-based path rewrote the whole
166
+ // list from stale state and silently dropped unrelated bundles.
167
+ function writeProfileBundles(mutate) {
168
+ const file = path.join(PROFILE_DIR, 'package.json');
169
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
170
+ pkg.dsh = pkg.dsh ?? {};
171
+ pkg.dsh.profile = pkg.dsh.profile ?? {};
172
+ const bundles = Array.isArray(pkg.dsh.profile.bundles) ? pkg.dsh.profile.bundles.slice() : [];
173
+ const next = mutate(bundles);
174
+ if (next == null) return false;
175
+ pkg.dsh.profile.bundles = next;
176
+ fs.writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
177
+ return true;
178
+ }
179
+
180
+ function packageDir(pkgName) {
181
+ return path.join(PROFILE_DIR, 'node_modules', ...pkgName.split('/'));
182
+ }
183
+
184
+ function isThirdParty(pkgName) {
185
+ if (pkgName.startsWith('@deepseek-ai/')) return false;
186
+ if (pkgName === 'dsh-plugins-scope' || pkgName === 'dsh-plugin-scope' || pkgName === 'dsh-scope-probe') return false;
187
+ return true;
188
+ }
189
+
190
+ // Decide whether a third-party plugin belongs in the per-session list by what
191
+ // its own description says it does. Tools / models / modes / prompt injection
192
+ // change what the agent can do, so they are session-level. Wallpapers, skins,
193
+ // panels, managers and other GUI/service work only make sense globally.
194
+ const AGENT_HINTS = [
195
+ 'tools', 'tool', '工具', 'model', '模型', 'mode', '模式', 'prompt', '提示词',
196
+ 'persona', '人格', 'context', '上下文', 'memory', '记忆', 'skill', '技能',
197
+ 'command', '命令', 'agent', '代理', 'workflow', '工作流', 'vision', '图像',
198
+ 'image', 'jailbreak', '破甲', 'search', '搜索', 'terminal', '终端', 'remote', '远程',
199
+ 'qq', 'bot', '机器人', '伙伴', '对话', '聊天', 'assistant',
200
+ ];
201
+ const GLOBAL_HINTS = [
202
+ 'wallpaper', '壁纸', 'theme', '主题', 'skin', '皮肤', 'ui', '界面', 'panel', '面板',
203
+ 'sidebar', '侧边栏', 'status bar', '状态栏', 'manager', '管理', 'cleanup', '清理',
204
+ 'cookie', 'notification', '通知', 'launcher', '启动器', 'icon', '图标',
205
+ 'font', '字体', 'layout', '布局', 'beautify', '美化',
206
+ ];
207
+
208
+ function hintHit(text, hint) {
209
+ if (/^[a-z0-9 ]+$/.test(hint)) return new RegExp(`\\b${hint.replace(/ /g, '\\s+')}\\b`).test(text);
210
+ return text.includes(hint);
211
+ }
212
+
213
+ function packageDescription(dir) {
214
+ const chunks = [];
215
+ for (const file of ['package.json', 'dsh-plugin.json']) {
216
+ try {
217
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
218
+ for (const key of ['description', 'title', 'summary']) {
219
+ if (typeof pkg[key] === 'string' && pkg[key].trim()) chunks.push(pkg[key]);
220
+ }
221
+ } catch {
222
+ /* missing file is fine */
223
+ }
224
+ }
225
+ // The manifest description is the plugin's own statement of purpose; a
226
+ // README often mixes install steps, UI screenshots and tool lists, which
227
+ // makes it a poor classifier. Only fall back to it when the manifest says
228
+ // nothing at all.
229
+ if (chunks.length) return chunks.join('\n').toLowerCase();
230
+ try {
231
+ return fs.readFileSync(path.join(dir, 'README.md'), 'utf8').slice(0, 1500).toLowerCase();
232
+ } catch {
233
+ return '';
234
+ }
235
+ }
236
+
237
+ function describeScope(dir) {
238
+ const text = packageDescription(dir);
239
+ if (!text) return { decision: null, category: 'unknown', reason: '没有描述' };
240
+ const agentHits = AGENT_HINTS.filter((word) => hintHit(text, word));
241
+ const globalHits = GLOBAL_HINTS.filter((word) => hintHit(text, word));
242
+ if (agentHits.length)
243
+ return { decision: true, category: 'agent', reason: `描述:${agentHits.slice(0, 3).join(' / ')}` };
244
+ if (globalHits.length)
245
+ return { decision: false, category: 'global', reason: `描述:${globalHits.slice(0, 3).join(' / ')}` };
246
+ return { decision: null, category: 'unknown', reason: '描述未命中,退回检测注册' };
247
+ }
248
+
249
+ // Runtime attribution: plugins such as billion-context register tools from code
250
+ // that never contains the public name as a literal. Capture the Node stack at
251
+ // registration time and map the nearest third-party package in node_modules to
252
+ // the registered tool or section name.
253
+ const ATTR_KEY = Symbol.for('dsh.plugin-scopes.attribution');
254
+ const STACK_PKG = /[\\/]node_modules[\\/](@[^\\/]+[\\/][^\\/]+|[^\\/]+)[\\/]/;
255
+
256
+ function attrStore() {
257
+ let store = globalThis[ATTR_KEY];
258
+ if (!store) {
259
+ store = { tools: new Map(), sections: new Map(), contexts: new Map(), version: 0 };
260
+ globalThis[ATTR_KEY] = store;
261
+ }
262
+ return store;
263
+ }
264
+
265
+ function packageFromStack(stack) {
266
+ for (const line of String(stack ?? '').split('\n')) {
267
+ const match = STACK_PKG.exec(line);
268
+ if (!match) continue;
269
+ const name = match[1].replace(/\\/g, '/');
270
+ if (isThirdParty(name)) return name;
271
+ }
272
+ return undefined;
273
+ }
274
+
275
+ function recordRuntime(kind, name) {
276
+ if (!name) return;
277
+ try {
278
+ const pkg = packageFromStack(new Error().stack);
279
+ if (!pkg) return;
280
+ const attr = attrStore();
281
+ let set = attr[kind].get(pkg);
282
+ if (!set) attr[kind].set(pkg, (set = new Set()));
283
+ if (!set.has(String(name))) {
284
+ set.add(String(name));
285
+ attr.version += 1;
286
+ }
287
+ } catch {
288
+ /* attribution is best effort */
289
+ }
290
+ }
291
+
292
+ // Only a package with a bundle patch can be switched on/off at the loader level.
293
+ function isBundlePackage(pkgName) {
294
+ try {
295
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageDir(pkgName), 'package.json'), 'utf8'));
296
+ return Boolean(pkg.dsh?.bundle?.patch);
297
+ } catch {
298
+ return false;
299
+ }
300
+ }
301
+
302
+ function manifestTools(dir) {
303
+ const out = new Set();
304
+ try {
305
+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'dsh-plugin.json'), 'utf8'));
306
+ const c = manifest.contributes ?? {};
307
+ for (const ns of c['x-tool-namespaces'] ?? []) {
308
+ for (const tool of ns.tools ?? []) out.add(ns.publicPrefix ? `${ns.publicPrefix}${tool}` : String(tool));
309
+ }
310
+ for (const comp of c['x-components'] ?? []) {
311
+ for (const tool of comp.tools ?? []) out.add(String(tool));
312
+ }
313
+ } catch {
314
+ /* no manifest */
315
+ }
316
+ return [...out];
317
+ }
318
+
319
+ function walkSources(dir, limit = 400) {
320
+ const files = [];
321
+ const stack = [dir];
322
+ while (stack.length > 0 && files.length < limit) {
323
+ const current = stack.pop();
324
+ let entries;
325
+ try {
326
+ entries = fs.readdirSync(current, { withFileTypes: true });
327
+ } catch {
328
+ continue;
329
+ }
330
+ for (const entry of entries) {
331
+ const full = path.join(current, entry.name);
332
+ if (entry.isDirectory()) {
333
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
334
+ stack.push(full);
335
+ } else if (/\.(m?js|cjs|ts|tsx)$/.test(entry.name)) {
336
+ files.push(full);
337
+ if (files.length >= limit) break;
338
+ }
339
+ }
340
+ }
341
+ return files;
342
+ }
343
+
344
+ function packageSlug(dir) {
345
+ try {
346
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
347
+ const full = String(pkg.name ?? '');
348
+ const bare = full.replace(/^@[^/]+\//, '').replace(/^dsh-/, '');
349
+ const first = bare.split('-')[0] ?? '';
350
+ const parts = bare
351
+ .split(/[-_/]/)
352
+ .map((part) => part.replace(/[^a-z0-9]/gi, '').toLowerCase())
353
+ .filter((part) => part.length > 2 && !GENERIC_PARTS.has(part));
354
+ return {
355
+ slug: bare.replace(/[^a-z0-9]/gi, '').toLowerCase(),
356
+ first: GENERIC_PARTS.has(first) ? '' : first.replace(/[^a-z0-9]/gi, '').toLowerCase(),
357
+ parts,
358
+ };
359
+ } catch {
360
+ return { slug: '', first: '', parts: [] };
361
+ }
362
+ }
363
+
364
+ function scanSourceTools(dir, observed, baseTools) {
365
+ const { slug, first, parts } = packageSlug(dir);
366
+ const prefixes = [...new Set([slug, first, ...(parts ?? [])])].filter((value) => value && value.length > 2);
367
+ const names = [...observed].filter((n) => {
368
+ if (typeof n !== 'string' || n.length <= 2) return false;
369
+ // Do not use the context-wide tool list as the base set: third-party plugins
370
+ // often register their tools globally (modlens_read_image, remote_*), so those
371
+ // names are in `definitions()` but still belong to the plugin. CORE_TOOLS is
372
+ // the authoritative harness-owned set.
373
+ if (CORE_TOOLS.has(n)) return false;
374
+ const lower = n.toLowerCase();
375
+ return prefixes.some((prefix) => lower === prefix || lower.startsWith(`${prefix}_`));
376
+ });
377
+ if (names.length === 0) return [];
378
+ const hits = new Set();
379
+ let registersTools = false;
380
+ for (const file of walkSources(dir)) {
381
+ let text;
382
+ try {
383
+ if (fs.statSync(file).size > 8_000_000) continue;
384
+ text = fs.readFileSync(file, 'utf8');
385
+ } catch {
386
+ continue;
387
+ }
388
+ if (!registersTools && /tools\.register\s*\(|registerTool\s*\(/.test(text)) registersTools = true;
389
+ for (const tool of names) {
390
+ if (hits.has(tool)) continue;
391
+ if (text.includes(`'${tool}'`) || text.includes(`"${tool}"`)) hits.add(tool);
392
+ }
393
+ }
394
+ // Dynamic plugins (billion-context) fetch their tool schemas and register the
395
+ // names at runtime, so no literal exists in the source. If the package clearly
396
+ // registers tools and an observed tool name starts with its slug, claim it.
397
+ // Observed names are real registrations. Prefix matching is deliberate for
398
+ // dynamic plugins: a tool like remote_create_session has no manifest and no
399
+ // source literal, but its prefix still identifies ds-harness-remote.
400
+ if (hits.size === 0 || registersTools) for (const tool of names) hits.add(tool);
401
+ return [...hits];
402
+ }
403
+
404
+ // Prompt sections are the second per-agent capability we can hide: a plugin that
405
+ // only injects a system-prompt section has no tools but still shapes every reply.
406
+ // The section name is the only stable identity, so collect the names a package
407
+ // registers (`systemPrompt.section({ name: ... })`, literals or local constants).
408
+ function promptSections(dir) {
409
+ const out = new Set();
410
+ for (const file of walkSources(dir)) {
411
+ let text;
412
+ try {
413
+ if (fs.statSync(file).size > 2_500_000) continue;
414
+ text = fs.readFileSync(file, 'utf8');
415
+ } catch {
416
+ continue;
417
+ }
418
+ if (!/systemPrompt\.section\s*\(/.test(text)) continue;
419
+ const constants = new Map();
420
+ for (const match of text.matchAll(/(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*['"]([^'"]+)['"]/g)) {
421
+ constants.set(match[1], match[2]);
422
+ }
423
+ for (const call of text.matchAll(/systemPrompt\.section\s*\(/g)) {
424
+ const windowText = text.slice(call.index, call.index + 400);
425
+ for (const match of windowText.matchAll(/name\s*:\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_$][\w$]*))/g)) {
426
+ const value = match[1] ?? match[2] ?? constants.get(match[3]);
427
+ if (typeof value === 'string' && value.length > 0 && value.length <= 160) out.add(value);
428
+ }
429
+ }
430
+ }
431
+ return [...out];
432
+ }
433
+
434
+ // Runtime prompt contexts (`systemPrompt.context({ name })`) are the sibling of
435
+ // sections: they are computed per request and injected just before the model
436
+ // sees the message. The same static name scan applies to them.
437
+ function promptContexts(dir) {
438
+ const out = new Set();
439
+ for (const file of walkSources(dir)) {
440
+ let text;
441
+ try {
442
+ if (fs.statSync(file).size > 2_500_000) continue;
443
+ text = fs.readFileSync(file, 'utf8');
444
+ } catch {
445
+ continue;
446
+ }
447
+ if (!/systemPrompt\.context\s*\(/.test(text)) continue;
448
+ const constants = new Map();
449
+ for (const match of text.matchAll(/(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*['"]([^'"]+)['"]/g)) {
450
+ constants.set(match[1], match[2]);
451
+ }
452
+ for (const call of text.matchAll(/systemPrompt\.context\s*\(/g)) {
453
+ const windowText = text.slice(call.index, call.index + 400);
454
+ for (const match of windowText.matchAll(/name\s*:\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_$][\w$]*))/g)) {
455
+ const value = match[1] ?? match[2] ?? constants.get(match[3]);
456
+ if (typeof value === 'string' && value.length > 0 && value.length <= 160) out.add(value);
457
+ }
458
+ }
459
+ }
460
+ return [...out];
461
+ }
462
+
463
+ function slugOf(value) {
464
+ return String(value ?? '')
465
+ .toLowerCase()
466
+ .replace(/^include:/, '')
467
+ .replace(/^@[^/]+\//, '')
468
+ .replace(/^dsh-/, '')
469
+ .replace(/[^a-z0-9]/g, '');
470
+ }
471
+
472
+ function packageFromSkillPath(p) {
473
+ const m = /[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)[\\/]/.exec(String(p ?? ''));
474
+ return m ? m[1].replace(/\\/g, '/') : '';
475
+ }
476
+
477
+ function skillHidden(skill, hidden) {
478
+ try {
479
+ const pkg = packageFromSkillPath(skill?.path ?? skill?.resourceBase?.path);
480
+ if (pkg && matchesHidden(pkg, hidden)) return true;
481
+ if (skill?.provider && matchesHidden(skill.provider, hidden)) return true;
482
+ } catch {
483
+ /* attribution is best effort */
484
+ }
485
+ return false;
486
+ }
487
+
488
+ function matchesHidden(owner, hidden) {
489
+ const ownerSlug = slugOf(owner);
490
+ if (ownerSlug.length < 3) return false;
491
+ for (const key of hidden) {
492
+ const keySlug = slugOf(key);
493
+ if (keySlug.length < 3) continue;
494
+ if (ownerSlug === keySlug || ownerSlug.endsWith(keySlug) || keySlug.endsWith(ownerSlug)) return true;
495
+ }
496
+ return false;
497
+ }
498
+
499
+ function sectionOwnerMap() {
500
+ if (!globalThis[SECTION_OWNERS]) globalThis[SECTION_OWNERS] = new Map();
501
+ return globalThis[SECTION_OWNERS];
502
+ }
503
+
504
+ function contextOwnerMap() {
505
+ if (!globalThis[CONTEXT_OWNERS]) globalThis[CONTEXT_OWNERS] = new Map();
506
+ return globalThis[CONTEXT_OWNERS];
507
+ }
508
+
509
+ function workspaceForCwd(registry, cwd) {
510
+ if (!cwd) return undefined;
511
+ try {
512
+ const rows = registry.list();
513
+ const norm = (p) => path.resolve(String(p)).toLowerCase();
514
+ const target = norm(cwd);
515
+ let best;
516
+ for (const w of rows) {
517
+ const base = norm(w.path);
518
+ if (target !== base && !target.startsWith(base + path.sep)) continue;
519
+ if (!best || base.length > best.length) best = { workspace: w, length: base.length };
520
+ }
521
+ return best?.workspace;
522
+ } catch {
523
+ return undefined;
524
+ }
525
+ }
526
+
527
+ function sessionIdVariants(sessionId) {
528
+ const raw = String(sessionId ?? '');
529
+ const bare = raw.replace(/^session-/, '');
530
+ return new Set([raw, `session-${bare}`, bare]);
531
+ }
532
+
533
+ // The context-menu target may carry the bare uuid while the workspace table
534
+ // stores "session-<uuid>" (or the other way around). Membership in
535
+ // workspace.sessionIds is authoritative; cwd is only a fallback.
536
+ function workspaceForSession(ctx, sessionId) {
537
+ try {
538
+ const variants = sessionIdVariants(sessionId);
539
+ const rows = ctx.workspaceRegistry.list();
540
+ for (const w of rows) {
541
+ if ((w.sessionIds ?? []).some((id) => variants.has(id))) return w;
542
+ }
543
+ let cwd;
544
+ for (const id of variants) {
545
+ try {
546
+ const session = ctx.sessions.get(id);
547
+ cwd = session?.cwd ?? session?.header?.cwd ?? session?.identity?.cwd;
548
+ if (cwd) break;
549
+ } catch {
550
+ /* try the next id shape */
551
+ }
552
+ }
553
+ return workspaceForCwd(ctx.workspaceRegistry, cwd);
554
+ } catch {
555
+ return undefined;
556
+ }
557
+ }
558
+
559
+ function workspaceById(ctx, workspaceId) {
560
+ if (!workspaceId) return undefined;
561
+ try {
562
+ return ctx.workspaceRegistry.list().find((w) => (w.workspaceId ?? w.id) === workspaceId);
563
+ } catch {
564
+ return undefined;
565
+ }
566
+ }
567
+
568
+ function levelValue(map, key) {
569
+ const value = map?.[key];
570
+ return value === 'on' || value === 'off' ? value : 'inherit';
571
+ }
572
+
573
+ // A menu target, an agent id, and a workspace row do not always agree on the
574
+ // "session-" prefix. Read through every shape instead of trusting one.
575
+ function sessionValue(store, sessionId, key) {
576
+ for (const id of sessionIdVariants(sessionId)) {
577
+ const value = levelValue(store.sessions[id], key);
578
+ if (value !== 'inherit') return value;
579
+ }
580
+ return 'inherit';
581
+ }
582
+
583
+ function canonicalSessionId(ctx, sessionId) {
584
+ const variants = sessionIdVariants(sessionId);
585
+ try {
586
+ for (const w of ctx.workspaceRegistry.list()) {
587
+ for (const id of w.sessionIds ?? []) if (variants.has(id)) return id;
588
+ }
589
+ } catch {
590
+ /* fall through */
591
+ }
592
+ const raw = String(sessionId ?? '');
593
+ return raw.startsWith('session-') ? raw : `session-${raw}`;
594
+ }
595
+
596
+ function effective(store, key, workspaceId, sessionId) {
597
+ const session = sessionId ? sessionValue(store, sessionId, key) : 'inherit';
598
+ if (session !== 'inherit') return session;
599
+ const workspace = workspaceId ? levelValue(store.workspaces[workspaceId], key) : 'inherit';
600
+ if (workspace !== 'inherit') return workspace;
601
+ const global = levelValue(store.global, key);
602
+ return global === 'inherit' ? 'on' : global;
603
+ }
604
+
605
+ function makeService(ctx) {
606
+ const initial = readStore();
607
+ const observed = new Set(initial.observed);
608
+ const cache = new Map();
609
+
610
+ function persistObserved() {
611
+ try {
612
+ const store = readStore();
613
+ const merged = new Set([...(store.observed ?? []), ...observed]);
614
+ store.observed = [...merged].sort();
615
+ writeStore(store);
616
+ } catch {
617
+ /* ignore */
618
+ }
619
+ }
620
+
621
+ function collectObserved() {
622
+ const before = observed.size;
623
+ const add = (rows) => {
624
+ for (const row of rows ?? []) if (row?.name) observed.add(row.name);
625
+ };
626
+ try {
627
+ add(ctx.tools.definitions());
628
+ } catch {
629
+ /* ignore */
630
+ }
631
+ for (const agent of ctx.agents.list()) {
632
+ // Scoped registrations live on the agent's own ToolsService instance, not the
633
+ // root one; read both so tools like modlens_* / billioncontext_* are observed.
634
+ try {
635
+ add(agent.ctx?.tools?.definitions?.(agent));
636
+ } catch {
637
+ /* ignore */
638
+ }
639
+ try {
640
+ add(ctx.tools.definitions(agent));
641
+ } catch {
642
+ /* ignore */
643
+ }
644
+ }
645
+ if (observed.size !== before) persistObserved();
646
+ cache.clear();
647
+ }
648
+
649
+ function baseToolNames() {
650
+ const names = new Set(CORE_TOOLS);
651
+ try {
652
+ for (const row of ctx.tools.definitions()) {
653
+ if (row?.name) names.add(row.name);
654
+ }
655
+ } catch {
656
+ /* ignore */
657
+ }
658
+ return names;
659
+ }
660
+
661
+ function buildRows() {
662
+ const { deps, bundles } = profileDeps();
663
+ const base = baseToolNames();
664
+ const store = readStore();
665
+ const names = [...new Set([...deps, ...bundles])].filter(isThirdParty).filter(isBundlePackage);
666
+ const rows = [];
667
+ const claimed = new Set();
668
+ for (const pkg of names) {
669
+ const dir = packageDir(pkg);
670
+ if (!fs.existsSync(dir)) continue;
671
+ const desc = describeScope(dir);
672
+ let tools = manifestTools(dir).filter((tool) => !tool.includes('${') && !base.has(tool));
673
+ if (tools.length === 0 && observed.size > 0) tools = scanSourceTools(dir, observed, base);
674
+ const runtimeTools = attrStore().tools.get(pkg);
675
+ if (runtimeTools?.size) tools = [...new Set([...tools, ...[...runtimeTools.keys()].filter((name) => !CORE_TOOLS.has(name))])];
676
+ // Never let a row claim a core tool: the same name would be hidden for the
677
+ // whole scope and `read`/`glob` would disappear together with the plugin.
678
+ tools = tools.filter((name) => typeof name === 'string' && !CORE_TOOLS.has(name) && !claimed.has(name));
679
+ for (const name of tools) claimed.add(name);
680
+ const staticPrompts = promptSections(dir);
681
+ const runtimeSections = attrStore().sections.get(pkg);
682
+ const prompts = runtimeSections?.size ? [...new Set([...staticPrompts, ...runtimeSections.keys()])] : staticPrompts;
683
+ const staticContexts = promptContexts(dir);
684
+ const runtimeContexts = attrStore().contexts.get(pkg);
685
+ const contexts = runtimeContexts?.size ? [...new Set([...staticContexts, ...runtimeContexts.keys()])] : staticContexts;
686
+ const capability = tools.length > 0 || prompts.length > 0 || contexts.length > 0;
687
+ const scoped = PROTECTED.has(pkg) ? false : (desc.decision ?? capability);
688
+ const axes = [tools.length, prompts.length, contexts.length].filter((count) => count > 0).length;
689
+ const kind = !capability ? 'global' : axes > 1 ? 'mixed' : tools.length > 0 ? 'tools' : prompts.length > 0 ? 'prompt' : 'context';
690
+ rows.push({
691
+ key: pkg,
692
+ name: pkg,
693
+ tools: [...new Set(tools)].sort(),
694
+ promptSections: prompts,
695
+ promptContexts: contexts,
696
+ kind,
697
+ capability,
698
+ scoped,
699
+ descScope: PROTECTED.has(pkg) ? false : desc.decision,
700
+ category: PROTECTED.has(pkg) ? 'global' : desc.category,
701
+ reason: PROTECTED.has(pkg) ? '基础插件,不参与作用域' : desc.reason,
702
+ protected: PROTECTED.has(pkg),
703
+ });
704
+ }
705
+ // Central attribution pass: observed tool names that no row has claimed yet
706
+ // are matched against every package's name prefixes (longest prefix wins).
707
+ // This covers plugins whose tools do not share the package's first segment
708
+ // (ds-harness-remote -> remote_*) and dynamic registrations, without relying
709
+ // on a per-package source scan.
710
+ const claimedAll = new Set(rows.flatMap((row) => row.tools));
711
+ const infos = rows.map((row) => {
712
+ const dir = packageDir(row.key);
713
+ const { slug, first, parts } = packageSlug(dir);
714
+ const prefixes = [...new Set([slug, first, ...(parts ?? [])])].filter((value) => value && value.length > 2);
715
+ return { row, prefixes };
716
+ });
717
+ for (const name of [...observed].sort((a, b) => b.length - a.length)) {
718
+ if (CORE_TOOLS.has(name) || claimedAll.has(name)) continue;
719
+ const lower = name.toLowerCase();
720
+ let best = null;
721
+ let bestLength = 0;
722
+ for (const { row, prefixes } of infos) {
723
+ for (const prefix of prefixes) {
724
+ if (lower === prefix || lower.startsWith(`${prefix}_`)) {
725
+ if (prefix.length > bestLength) {
726
+ best = row;
727
+ bestLength = prefix.length;
728
+ }
729
+ }
730
+ }
731
+ }
732
+ if (!best) continue;
733
+ if (!best.tools.includes(name)) best.tools.push(name);
734
+ best.tools.sort();
735
+ claimedAll.add(name);
736
+ }
737
+ for (const row of rows) {
738
+ row.capability = row.tools.length > 0 || row.promptSections.length > 0 || (row.promptContexts?.length ?? 0) > 0;
739
+ row.scoped = !row.protected && (row.descScope === true || row.capability);
740
+ const axes = [row.tools.length, row.promptSections.length, row.promptContexts?.length ?? 0].filter((count) => count > 0).length;
741
+ row.kind = !row.capability ? 'global' : axes > 1 ? 'mixed' : row.tools.length > 0 ? 'tools' : row.promptSections.length > 0 ? 'prompt' : 'context';
742
+ }
743
+ rows.sort((a, b) => (a.scoped === b.scoped ? a.name.localeCompare(b.name) : a.scoped ? -1 : 1));
744
+ return rows;
745
+ }
746
+
747
+ function rowsCached() {
748
+ const version = attrStore().version;
749
+ if (!cache.has('rows') || cache.get('rowVersion') !== version) {
750
+ cache.set('rows', buildRows());
751
+ cache.set('rowVersion', version);
752
+ }
753
+ return cache.get('rows');
754
+ }
755
+
756
+ function workspaceIdForSession(sessionId) {
757
+ const workspace = workspaceForSession(ctx, sessionId);
758
+ return workspace?.workspaceId ?? workspace?.id;
759
+ }
760
+
761
+ function hiddenForSession(sessionId, store) {
762
+ const rows = rowsCached();
763
+ const workspaceId = workspaceIdForSession(sessionId);
764
+ const hidden = new Set();
765
+ for (const row of rows) {
766
+ if (!row.capability) continue;
767
+ const value = row.scoped
768
+ ? effective(store, row.key, workspaceId, sessionId)
769
+ : levelValue(store.global, row.key) === 'inherit'
770
+ ? 'on'
771
+ : levelValue(store.global, row.key);
772
+ if (value === 'off') {
773
+ for (const tool of row.tools) hidden.add(tool);
774
+ }
775
+ }
776
+ return hidden;
777
+ }
778
+
779
+ const composePresets = new Map()
780
+
781
+ function managedPackagesForSession(sessionId) {
782
+ const store = readStore()
783
+ const managed = new Set(Array.isArray(store.managed) ? store.managed : [])
784
+ if (managed.size === 0) return []
785
+ const rows = rowsCached()
786
+ const workspaceId = workspaceIdForSession(sessionId)
787
+ const packages = []
788
+ for (const row of rows) {
789
+ if (!row.scoped || !managed.has(row.key)) continue
790
+ if (effective(store, row.key, workspaceId, sessionId) === 'on') packages.push(row.key)
791
+ }
792
+ return packages
793
+ }
794
+
795
+ const profileRequire = createRequire(path.join(PROFILE_DIR, 'package.json'))
796
+ function bundleConfigFor(name) {
797
+ try {
798
+ const dir = packageDir(name)
799
+ const patch = path.join(dir, 'cordis.patch.yml')
800
+ if (!fs.existsSync(patch)) return {}
801
+ const doc = profileRequire('yaml').parse(fs.readFileSync(patch, 'utf8'))
802
+ const entries = []
803
+ for (const item of Array.isArray(doc) ? doc : []) {
804
+ if (Array.isArray(item?.insert)) entries.push(...item.insert)
805
+ if (item?.name === name || item?.id === name) entries.push(item)
806
+ }
807
+ const hit = entries.find((e) => e?.name === name) ?? entries.find((e) => e?.id === name)
808
+ return hit?.config ?? {}
809
+ } catch {
810
+ return {}
811
+ }
812
+ }
813
+
814
+ async function presetForPackages(packages) {
815
+ const key = packages.join('|')
816
+ if (composePresets.has(key)) return composePresets.get(key)
817
+ let hash = 5381
818
+ for (let i = 0; i < key.length; i += 1) hash = ((hash * 33) ^ key.charCodeAt(i)) >>> 0
819
+ const id = `scope-managed-${hash.toString(36)}`
820
+ await ctx.agentPresets.register({
821
+ id,
822
+ name: `作用域 ${packages.length} 个`,
823
+ plugins: packages.map((name) => ({ id: `scope:${name}`, name, config: bundleConfigFor(name) })),
824
+ })
825
+ composePresets.set(key, id)
826
+ return id
827
+ }
828
+
829
+ function installComposeMount() {
830
+ if (globalThis[COMPOSE_MARK]) return
831
+ const loop = ctx.get('agentLoop')
832
+ if (!loop || typeof loop.initializeAgent !== 'function') return
833
+ globalThis[COMPOSE_MARK] = true
834
+ const original = loop.initializeAgent
835
+ loop.initializeAgent = async function initializeWithScopes(ownerCtx, options = {}) {
836
+ const userSetup = options.setup
837
+ const sessionId = options.session?.id ?? options.sessionId
838
+ return original.call(this, ownerCtx, {
839
+ ...options,
840
+ setup: async (agentCtx, agent) => {
841
+ if (userSetup) await userSetup(agentCtx, agent)
842
+ try {
843
+ const id = agent?.id ?? sessionId
844
+ const packages = managedPackagesForSession(id)
845
+ if (packages.length > 0) {
846
+ const presetId = await presetForPackages(packages)
847
+ await ctx.agentPresets.mount(agentCtx, presetId)
848
+ }
849
+ } catch (error) {
850
+ console.error('[plugin-scopes] compose mount failed:', error)
851
+ }
852
+ },
853
+ })
854
+ }
855
+ ctx.effect(() => () => {
856
+ loop.initializeAgent = original
857
+ delete globalThis[COMPOSE_MARK]
858
+ })
859
+ }
860
+
861
+ async function spawnTest({ basePreset, packages } = {}) {
862
+ const sessionId = `session-${randomUUID()}`
863
+ const handle = await ctx.agents.create({
864
+ sessionId,
865
+ meta: { cwd: process.cwd(), origin: 'subagent' },
866
+ setup: async (agentCtx, agent) => {
867
+ if (basePreset) await ctx.agentPresets.select(agent, basePreset)
868
+ },
869
+ })
870
+ await new Promise((resolve) => setTimeout(resolve, 800))
871
+ const agent = handle.agent
872
+ const tools = (agent?.ctx?.tools?.definitions(agent) ?? []).map((d) => d.name)
873
+ const composed = (() => {
874
+ try { return ctx.agentPresets.composedPreset(agent.ctx) } catch { return null }
875
+ })()
876
+ await handle.dispose()
877
+ return {
878
+ sessionId,
879
+ composed,
880
+ toolCount: tools.length,
881
+ opsTools: tools.filter((name) => name.startsWith('ops_')).slice(0, 30),
882
+ fishTools: tools.filter((name) => name.startsWith('fish_')),
883
+ sample: tools.slice(0, 12),
884
+ }
885
+ }
886
+
887
+ function hiddenPluginsForSession(sessionId, store) {
888
+ const rows = rowsCached();
889
+ const workspaceId = workspaceIdForSession(sessionId);
890
+ const hidden = new Set();
891
+ for (const row of rows) {
892
+ if (!row.capability) continue;
893
+ const value = row.scoped
894
+ ? effective(store, row.key, workspaceId, sessionId)
895
+ : levelValue(store.global, row.key) === 'inherit'
896
+ ? 'on'
897
+ : levelValue(store.global, row.key);
898
+ if (value === 'off') hidden.add(row.key);
899
+ }
900
+ return hidden;
901
+ }
902
+
903
+ // Stream-level plugins (for example request interceptors that never register a
904
+ // tool) still deserve a per-session off switch: their llm/stream listeners are
905
+ // skipped for sessions where the row is off. Only session-scoped rows qualify.
906
+ function hiddenPackagesForSession(sessionId, store) {
907
+ const rows = rowsCached();
908
+ const workspaceId = workspaceIdForSession(sessionId);
909
+ const hidden = new Set();
910
+ for (const row of rows) {
911
+ if (!row.scoped) continue;
912
+ if (effective(store, row.key, workspaceId, sessionId) === 'off') hidden.add(row.key);
913
+ }
914
+ return hidden;
915
+ }
916
+
917
+
918
+ function staticSectionOwners(rows) {
919
+ const map = new Map();
920
+ for (const row of rows) {
921
+ for (const section of row.promptSections ?? []) if (!map.has(section)) map.set(section, row.key);
922
+ }
923
+ return map;
924
+ }
925
+
926
+ function staticContextOwners(rows) {
927
+ const map = new Map();
928
+ for (const row of rows) {
929
+ for (const name of row.promptContexts ?? []) if (!map.has(name)) map.set(name, row.key);
930
+ }
931
+ return map;
932
+ }
933
+
934
+ function hiddenByName() {
935
+ const store = readStore();
936
+ const map = new Map();
937
+ for (const agent of ctx.agents.list()) {
938
+ const id = agent?.id;
939
+ if (!id) continue;
940
+ map.set(id, hiddenForSession(id, store));
941
+ }
942
+ return map;
943
+ }
944
+
945
+ function installResolveFilter() {
946
+ // Rewritten on every plugin load so a reloaded fiber never leaves a stale
947
+ // row cache behind the prototype patch.
948
+ globalThis[HIDDEN_HOOK] = (agentId) => hiddenForSession(agentId, readStore());
949
+ globalThis[HIDDEN_PLUGINS_HOOK] = (agentId) => hiddenPluginsForSession(agentId, readStore());
950
+ const proto = Object.getPrototypeOf(ctx.tools);
951
+ if (!proto) return;
952
+ // The register/attribution patch has its own guard: the resolve patch guard
953
+ // may already be set by a previous plugin load in the same process.
954
+ if (!proto[REGISTER_MARK] && typeof proto.register === 'function') {
955
+ Object.defineProperty(proto, REGISTER_MARK, { value: true, enumerable: false });
956
+ const originalRegister = proto.register;
957
+ proto.register = function patchedRegister(definition, options) {
958
+ try {
959
+ recordRuntime('tools', definition?.name);
960
+ } catch {
961
+ /* attribution is best effort */
962
+ }
963
+ return originalRegister.call(this, definition, options);
964
+ };
965
+ }
966
+ if (proto[PATCH_MARK]) return;
967
+ const original = proto.resolve;
968
+ if (typeof original !== 'function') return;
969
+ Object.defineProperty(proto, PATCH_MARK, { value: true, enumerable: false });
970
+ proto.resolve = async function patchedResolve(context) {
971
+ const set = await original.call(this, context);
972
+ const agentId = context?.agent?.id;
973
+ if (!agentId) return set;
974
+ const hidden = globalThis[HIDDEN_HOOK]?.(agentId) ?? new Set();
975
+ if (hidden.size === 0) return set;
976
+ return {
977
+ dispose: () => set.dispose(),
978
+ view(scope) {
979
+ // ToolSet.view() returns a Map of name → definition, not an array.
980
+ const visible = set.view(scope);
981
+ const filtered = new Map();
982
+ for (const [name, definition] of visible) {
983
+ if (!hidden.has(name) && !hidden.has(definition?.name)) filtered.set(name, definition);
984
+ }
985
+ return filtered;
986
+ },
987
+ };
988
+ };
989
+ }
990
+
991
+ function installSkillFilter() {
992
+ const skills = ctx.get('skills');
993
+ if (!skills) return;
994
+ const proto = Object.getPrototypeOf(skills);
995
+ if (!proto || proto[SKILL_PATCH_MARK]) return;
996
+ const originalList = proto.list;
997
+ const originalGet = proto.get;
998
+ if (typeof originalList !== 'function') return;
999
+ Object.defineProperty(proto, SKILL_PATCH_MARK, { value: true, enumerable: false });
1000
+
1001
+ proto.list = async function patchedSkillList(options = {}) {
1002
+ const result = await originalList.call(this, options);
1003
+ try {
1004
+ const agentId = options?.scope?.id;
1005
+ if (!agentId) return result;
1006
+ const hidden = hiddenPackagesForSession(agentId, readStore());
1007
+ if (!hidden || hidden.size === 0) return result;
1008
+ return result.filter((skill) => !skillHidden(skill, hidden));
1009
+ } catch {
1010
+ return result;
1011
+ }
1012
+ };
1013
+
1014
+ if (typeof originalGet === 'function') {
1015
+ proto.get = async function patchedSkillGet(skillName, options = {}) {
1016
+ const result = await originalGet.call(this, skillName, options);
1017
+ try {
1018
+ const agentId = options?.scope?.id;
1019
+ if (agentId && result) {
1020
+ const hidden = hiddenPackagesForSession(agentId, readStore());
1021
+ if (hidden && hidden.size > 0 && skillHidden(result, hidden)) return undefined;
1022
+ }
1023
+ } catch {
1024
+ /* never break skill lookup */
1025
+ }
1026
+ return result;
1027
+ };
1028
+ }
1029
+ }
1030
+
1031
+ function installSectionFilter() {
1032
+ const proto = Object.getPrototypeOf(ctx.systemPrompt);
1033
+ if (!proto) return;
1034
+ if (proto[PROMPT_PATCH_MARK]) return;
1035
+ const originalSection = proto.section;
1036
+ const originalAssemble = proto.assemble;
1037
+ if (typeof originalSection !== 'function' || typeof originalAssemble !== 'function') return;
1038
+ const originalContext = proto.context;
1039
+ Object.defineProperty(proto, PROMPT_PATCH_MARK, { value: true, enumerable: false });
1040
+
1041
+ // Remember which plugin registered which section. Registered sections are the
1042
+ // ones that would otherwise reach every agent even when their plugin is off.
1043
+ proto.section = function patchedSection(section) {
1044
+ try {
1045
+ const owner = this?.ctx?.fiber?.entry?.id;
1046
+ const pkg = packageFromStack(new Error().stack);
1047
+ if (section?.name) {
1048
+ if (pkg) {
1049
+ sectionOwnerMap().set(String(section.name), `include:${pkg}`);
1050
+ recordRuntime('sections', section.name);
1051
+ } else if (owner) {
1052
+ sectionOwnerMap().set(String(section.name), String(owner));
1053
+ }
1054
+ }
1055
+ } catch {
1056
+ /* attribution is best effort */
1057
+ }
1058
+ return originalSection.call(this, section);
1059
+ };
1060
+
1061
+ if (typeof originalContext === 'function') {
1062
+ proto.context = function patchedContext(definition) {
1063
+ try {
1064
+ const owner = this?.ctx?.fiber?.entry?.id;
1065
+ const pkg = packageFromStack(new Error().stack);
1066
+ if (definition?.name) {
1067
+ if (pkg) {
1068
+ contextOwnerMap().set(String(definition.name), `include:${pkg}`);
1069
+ recordRuntime('contexts', definition.name);
1070
+ } else if (owner) {
1071
+ contextOwnerMap().set(String(definition.name), String(owner));
1072
+ }
1073
+ }
1074
+ } catch {
1075
+ /* attribution is best effort */
1076
+ }
1077
+ return originalContext.call(this, definition);
1078
+ };
1079
+ }
1080
+
1081
+ proto.assemble = async function patchedAssemble(context = {}) {
1082
+ const assembly = await originalAssemble.call(this, context);
1083
+ try {
1084
+ const agentId = context?.scope?.id;
1085
+ if (!agentId) return assembly;
1086
+ const hidden = globalThis[HIDDEN_PLUGINS_HOOK]?.(agentId) ?? new Set();
1087
+ if (hidden.size === 0) return assembly;
1088
+ const owners = sectionOwnerMap();
1089
+ const staticOwners = staticSectionOwners(rowsCached());
1090
+ const sections = (assembly.sections ?? []).filter((section) => {
1091
+ const owner = owners.get(section.name);
1092
+ if (owner && matchesHidden(owner, hidden)) return false;
1093
+ const key = staticOwners.get(section.name);
1094
+ return !key || !hidden.has(key);
1095
+ });
1096
+ const contextOwners = contextOwnerMap();
1097
+ const staticContexts = staticContextOwners(rowsCached());
1098
+ const contexts = (assembly.contexts ?? []).filter((entry) => {
1099
+ const owner = contextOwners.get(entry.name);
1100
+ if (owner && matchesHidden(owner, hidden)) return false;
1101
+ const key = staticContexts.get(entry.name);
1102
+ return !key || !hidden.has(key);
1103
+ });
1104
+ const sectionsChanged = sections.length !== (assembly.sections ?? []).length;
1105
+ const contextsChanged = contexts.length !== (assembly.contexts ?? []).length;
1106
+ if (!sectionsChanged && !contextsChanged) return assembly;
1107
+ return { ...assembly, sections, contexts };
1108
+ } catch {
1109
+ /* never break prompt assembly */
1110
+ return assembly;
1111
+ }
1112
+ };
1113
+ }
1114
+
1115
+ function hookPackage(hook) {
1116
+ try {
1117
+ const entry = hook?.ctx?.fiber?.entry;
1118
+ const name = entry?.options?.name;
1119
+ if (typeof name === 'string' && name.length > 0) return name;
1120
+ const id = entry?.id;
1121
+ if (typeof id === 'string' && id.length > 0) return id.startsWith('include:') ? id.slice(8) : id;
1122
+ } catch {
1123
+ /* attribution is best effort */
1124
+ }
1125
+ return '';
1126
+ }
1127
+
1128
+ function streamHooks() {
1129
+ const events = ctx.events;
1130
+ const hooks = events?._hooks?.['llm/stream'] ?? [];
1131
+ return hooks.map((hook) => ({
1132
+ package: hookPackage(hook),
1133
+ entry: hook?.ctx?.fiber?.entry?.id ?? null,
1134
+ global: hook?.global === true,
1135
+ }));
1136
+ }
1137
+
1138
+ function installStreamFilter() {
1139
+ const events = ctx.events;
1140
+ const proto = events && Object.getPrototypeOf(events);
1141
+ if (!proto || typeof proto.waterfall !== 'function') return;
1142
+ globalThis[STREAM_HOOK] = (sessionId) => hiddenPackagesForSession(sessionId, readStore());
1143
+ if (proto[STREAM_PATCH_MARK]) return;
1144
+ Object.defineProperty(proto, STREAM_PATCH_MARK, { value: true, enumerable: false });
1145
+ const original = proto.waterfall;
1146
+ proto.waterfall = function patchedWaterfall(...args) {
1147
+ const thisArg =
1148
+ args.length > 0 && (typeof args[0] === 'object' || typeof args[0] === 'function') ? args[0] : null;
1149
+ const nameIndex = thisArg ? 1 : 0;
1150
+ if (args[nameIndex] !== 'llm/stream') return original.apply(this, args);
1151
+ const inner = args[args.length - 1];
1152
+ const listenerArgs = args.slice(nameIndex + 1, args.length - 1);
1153
+ const options = listenerArgs[0];
1154
+ const sessionId = options?.sessionId ?? options?.agent?.id;
1155
+ const hidden = sessionId ? (globalThis[STREAM_HOOK]?.(sessionId) ?? new Set()) : new Set();
1156
+ const hooks = this._hooks?.['llm/stream'] ?? [];
1157
+ if (hidden.size === 0 || hooks.length === 0) return original.apply(this, args);
1158
+ const kept = [];
1159
+ const skipped = [];
1160
+ for (const hook of hooks) {
1161
+ const pkg = hookPackage(hook);
1162
+ if (pkg && matchesHidden(pkg, hidden)) {
1163
+ skipped.push(pkg);
1164
+ continue;
1165
+ }
1166
+ kept.push(hook);
1167
+ }
1168
+ if (skipped.length === 0) return original.apply(this, args);
1169
+ globalThis[STREAM_STATS] = {
1170
+ skipped: skipped.length,
1171
+ packages: skipped,
1172
+ sessionId,
1173
+ at: Date.now(),
1174
+ };
1175
+ let index = 0;
1176
+ const dispatch = () => {
1177
+ const hook = kept[index++];
1178
+ if (!hook) return inner();
1179
+ let called = false;
1180
+ const next = () => {
1181
+ if (called) throw new Error('next() called multiple times');
1182
+ called = true;
1183
+ return dispatch();
1184
+ };
1185
+ return Reflect.apply(hook.callback, thisArg, [...listenerArgs, next]);
1186
+ };
1187
+ return dispatch();
1188
+ };
1189
+ }
1190
+
1191
+ function composable(key) {
1192
+ try {
1193
+ return fs.existsSync(path.join(packageDir(key), 'presets'))
1194
+ } catch {
1195
+ return false
1196
+ }
1197
+ }
1198
+
1199
+ function stateFor({ workspaceId, sessionId } = {}) {
1200
+ const store = readStore();
1201
+ const managedSet = new Set(store.managed);
1202
+ const sessionWorkspace = sessionId ? workspaceForSession(ctx, sessionId) : undefined;
1203
+ const resolvedWorkspaceId = workspaceId ?? (sessionWorkspace?.workspaceId ?? sessionWorkspace?.id);
1204
+ const workspaceRecord = workspaceId ? workspaceById(ctx, workspaceId) : sessionWorkspace;
1205
+ const rows = rowsCached().map((row) => {
1206
+ if (!row.capability && !row.scoped) {
1207
+ // Only-global plugins are not stored: their real switch is the profile's
1208
+ // bundle selection, so the UI must reflect that instead of a stale value.
1209
+ const on = profileDeps().bundles.includes(row.key);
1210
+ return {
1211
+ key: row.key,
1212
+ name: row.name,
1213
+ scoped: false,
1214
+ capability: false,
1215
+ kind: 'global',
1216
+ category: row.category,
1217
+ reason: row.reason,
1218
+ protected: row.protected,
1219
+ managed: managedSet.has(row.key),
1220
+ composable: row.scoped && !composable(row.key),
1221
+ tools: row.tools,
1222
+ promptSections: [],
1223
+ promptContexts: [],
1224
+ global: on ? 'on' : 'off',
1225
+ workspace: 'inherit',
1226
+ session: 'inherit',
1227
+ effective: on ? 'on' : 'off',
1228
+ };
1229
+ }
1230
+ const g = levelValue(store.global, row.key);
1231
+ const editable = row.scoped;
1232
+ const scopedWorkspaceId = resolvedWorkspaceId;
1233
+ const w = editable && scopedWorkspaceId ? levelValue(store.workspaces[scopedWorkspaceId], row.key) : 'inherit';
1234
+ const s = editable && sessionId ? sessionValue(store, sessionId, row.key) : 'inherit';
1235
+ const resolved = editable ? effective(store, row.key, scopedWorkspaceId, sessionId) : g === 'inherit' ? 'on' : g;
1236
+ const globalEffective = g === 'inherit' ? 'on' : g;
1237
+ const workspaceEffective = w === 'inherit' ? globalEffective : w;
1238
+ const parent = editable ? (sessionId ? workspaceEffective : workspaceId ? globalEffective : undefined) : undefined;
1239
+ return {
1240
+ key: row.key,
1241
+ name: row.name,
1242
+ scoped: row.scoped,
1243
+ capability: row.capability,
1244
+ kind: row.kind,
1245
+ category: row.category,
1246
+ reason: row.reason,
1247
+ protected: row.protected,
1248
+ managed: managedSet.has(row.key),
1249
+ composable: row.scoped && !composable(row.key),
1250
+ tools: row.tools,
1251
+ promptSections: row.promptSections,
1252
+ promptContexts: row.promptContexts ?? [],
1253
+ global: g === 'inherit' ? 'on' : g,
1254
+ workspace: w,
1255
+ session: s,
1256
+ parent,
1257
+ effective: resolved,
1258
+ };
1259
+ });
1260
+ let workspaces = [];
1261
+ try {
1262
+ workspaces = ctx.workspaceRegistry.list().map((w) => ({
1263
+ id: w.workspaceId ?? w.id,
1264
+ title: w.title,
1265
+ path: w.path,
1266
+ }));
1267
+ } catch {
1268
+ /* ignore */
1269
+ }
1270
+ return {
1271
+ rows,
1272
+ workspaces,
1273
+ managed: store.managed,
1274
+ storage: storageFile(),
1275
+ build: 'v7',
1276
+ sessionId: sessionId ?? null,
1277
+ workspaceId: resolvedWorkspaceId ?? null,
1278
+ workspaceTitle: workspaceRecord?.title ?? null,
1279
+ inheritFrom: sessionId ? 'workspace' : workspaceId ? 'global' : null,
1280
+ };
1281
+ }
1282
+
1283
+ async function setValue({ level, id, key, value }) {
1284
+ const store = readStore();
1285
+ const clean = value === 'on' || value === 'off' ? value : null;
1286
+ const row = rowsCached().find((r) => r.key === key);
1287
+ if (!row) throw new Error(`未知插件条目 ${key}`);
1288
+ if (row.protected && clean === 'off')
1289
+ throw new Error(`${key} 是基础插件,关掉会导致界面或启动失败,已禁止关闭`);
1290
+ if (!row.capability && !row.scoped) {
1291
+ if (level !== 'global') throw new Error('仅全局插件只能在全局层切换');
1292
+ if (clean === null) throw new Error('仅全局插件只有开/关');
1293
+ const bundles = profileDeps().bundles;
1294
+ const present = bundles.includes(key);
1295
+ if (clean === 'on') {
1296
+ if (present) return { ...stateFor({}), application: 'applied' };
1297
+ if (!fs.existsSync(packageDir(key)))
1298
+ throw new Error(`${key} 的包不在 profile 的 node_modules 里,先安装再启用`);
1299
+ const changed = writeProfileBundles((list) => {
1300
+ if (list.includes(key)) return null;
1301
+ const at = list.indexOf('@deepseek-ai/dsh-web-app');
1302
+ if (at >= 0) list.splice(at + 1, 0, key);
1303
+ else list.push(key);
1304
+ return list;
1305
+ });
1306
+ cache.delete('rows');
1307
+ return { ...stateFor({}), application: changed ? 'restart-required' : 'applied' };
1308
+ }
1309
+ if (!present) return { ...stateFor({}), application: 'applied' };
1310
+ const changed = writeProfileBundles((list) => {
1311
+ const at = list.indexOf(key);
1312
+ if (at < 0) return null;
1313
+ list.splice(at, 1);
1314
+ return list;
1315
+ });
1316
+ cache.delete('rows');
1317
+ return { ...stateFor({}), application: changed ? 'restart-required' : 'applied' };
1318
+ }
1319
+ if (!row.scoped && level !== 'global')
1320
+ throw new Error(`${key} 已标记为“仅全局”,只能在全局层切换;如需按会话控制,先把类型改回“会话级”`);
1321
+ if (level === 'global') {
1322
+ if (clean === null) delete store.global[key];
1323
+ else store.global[key] = clean;
1324
+ } else if (level === 'workspace' && id) {
1325
+ store.workspaces[id] = store.workspaces[id] ?? {};
1326
+ if (clean === null) delete store.workspaces[id][key];
1327
+ else store.workspaces[id][key] = clean;
1328
+ } else if (level === 'session' && id) {
1329
+ const sid = canonicalSessionId(ctx, id);
1330
+ store.sessions[sid] = store.sessions[sid] ?? {};
1331
+ if (clean === null) delete store.sessions[sid][key];
1332
+ else store.sessions[sid][key] = clean;
1333
+ } else {
1334
+ throw new Error(`invalid scope ${level}`);
1335
+ }
1336
+ writeStore(store);
1337
+ cache.delete('rows');
1338
+ return stateFor({ workspaceId: level === 'workspace' ? id : undefined, sessionId: level === 'session' ? id : undefined });
1339
+ }
1340
+
1341
+ // Evidence for the UI's "self-check": compare the raw tool list of a live
1342
+ // agent with the view resolve() actually hands to the model.
1343
+ async function skillListFor(sessionId) {
1344
+ const skills = ctx.get('skills');
1345
+ if (!skills) return { available: false, skills: [] };
1346
+ const agent = sessionId ? ctx.agents.get(sessionId) : undefined;
1347
+ const list = await skills.list({ scope: agent ?? ctx, cwd: process.env.DSH_HOME });
1348
+ return {
1349
+ available: true,
1350
+ skills: list.map((s) => ({ name: s.name, provider: s.provider, path: s.path ?? null })),
1351
+ };
1352
+ }
1353
+
1354
+ async function debugState(sessionId) {
1355
+ const store = readStore();
1356
+ const hidden = sessionId ? [...hiddenForSession(sessionId, store)] : [];
1357
+ const agents = [];
1358
+ for (const agent of ctx.agents.list()) {
1359
+ if (sessionId) {
1360
+ const variants = sessionIdVariants(sessionId);
1361
+ if (agent.id !== sessionId && !variants.has(agent.id)) continue;
1362
+ }
1363
+ let raw = [];
1364
+ let visible = [];
1365
+ let resolveError;
1366
+ try {
1367
+ raw = ctx.tools.definitions(agent).map((d) => d?.name).filter(Boolean);
1368
+ } catch {
1369
+ /* ignore */
1370
+ }
1371
+ try {
1372
+ const modelSelection = agent.options?.provider
1373
+ ? { provider: agent.options.provider, model: agent.options.model }
1374
+ : undefined;
1375
+ const set = await ctx.tools.resolve({ agent, modelSelection, signal: new AbortController().signal });
1376
+ visible = [...(set?.view?.(agent)?.keys?.() ?? [])];
1377
+ try { set?.dispose?.(); } catch { /* ignore */ }
1378
+ } catch (error) {
1379
+ resolveError = String(error?.message ?? error);
1380
+ }
1381
+ const agentHidden = [...hiddenForSession(agent.id, store)];
1382
+ const expected = raw.filter((name) => !agentHidden.includes(name));
1383
+ let fallback = false;
1384
+ if (visible.length === 0 && resolveError) {
1385
+ visible = expected;
1386
+ fallback = true;
1387
+ }
1388
+ agents.push({
1389
+ agentId: agent.id,
1390
+ rawCount: raw.length,
1391
+ visibleCount: visible.length,
1392
+ expectedVisibleCount: expected.length,
1393
+ fallback,
1394
+ hiddenInAgent: agentHidden.filter((name) => raw.includes(name)),
1395
+ opsRaw: raw.includes('ops_read_docx'),
1396
+ opsVisible: visible.includes('ops_read_docx'),
1397
+ resolveError,
1398
+ });
1399
+ }
1400
+ return { sessionId: sessionId ?? null, hidden, agents, storage: storageFile() };
1401
+ }
1402
+
1403
+ function debugPkg(key) {
1404
+ const dir = packageDir(key);
1405
+ const base = baseToolNames();
1406
+ return {
1407
+ key,
1408
+ dir,
1409
+ exists: fs.existsSync(dir),
1410
+ observed: observed.size,
1411
+ sample: [...observed].filter((name) => name.startsWith('remote') || name.startsWith('modlens')).slice(0, 20),
1412
+ prefixes: packageSlug(dir),
1413
+ manifest: manifestTools(dir),
1414
+ scan: scanSourceTools(dir, observed, base),
1415
+ runtime: [...(attrStore().tools.get(key)?.keys() ?? [])],
1416
+ row: rowsCached().find((row) => row.key === key) ?? null,
1417
+ };
1418
+ }
1419
+
1420
+ async function setManaged({ key, on }) {
1421
+ const row = rowsCached().find((item) => item.key === key)
1422
+ if (!row) throw new Error(`unknown plugin ${key}`)
1423
+ if (!row.scoped) throw new Error(`${key} 是仅全局插件,不走会话托管`)
1424
+ if (row.protected) throw new Error(`${key} 是基础插件,不能托管,关掉会导致界面或启动失败`)
1425
+ if (!row.capability) throw new Error(`${key} 没有检测到可挂载的 agent 能力(工具/提示词/上下文),不能托管`)
1426
+ if (composable(key)) throw new Error(`${key} 直接发布 preset,按过滤生效;不支持托管加载`)
1427
+ const store = readStore()
1428
+ const managed = new Set(store.managed)
1429
+ if (on) managed.add(key)
1430
+ else managed.delete(key)
1431
+ store.managed = [...managed]
1432
+ writeStore(store)
1433
+ let application = null
1434
+ let entryId = null
1435
+ const manager = ctx.get('pluginManager')
1436
+ if (manager) {
1437
+ try {
1438
+ const plugins = await manager.listPlugins()
1439
+ const slug = key.replace(/^@[^/]+\//, '').replace(/^dsh-/, '')
1440
+ const hit = plugins.find((plugin) => plugin?.moduleName === key)
1441
+ ?? plugins.find((plugin) => plugin?.moduleName === `dsh-${key}`)
1442
+ ?? plugins.find((plugin) => plugin?.patchId === key || plugin?.patchId === slug)
1443
+ ?? plugins.find((plugin) => {
1444
+ const id = String(plugin?.entryId ?? '')
1445
+ return id.endsWith(`:${key}`) || id.endsWith(`:${slug}`)
1446
+ })
1447
+ entryId = hit?.entryId ?? null
1448
+ } catch (error) {
1449
+ throw new Error(`托管切换失败:无法读取插件清单(${error?.message ?? error})`)
1450
+ }
1451
+ if (entryId && typeof manager.setPluginEnabled === 'function') {
1452
+ const result = await manager.setPluginEnabled(entryId, !on)
1453
+ application = result?.application ?? null
1454
+ } else if (typeof manager.setBundleEnabled === 'function' && isBundlePackage(packageDir(key))) {
1455
+ const result = await manager.setBundleEnabled(key, !on)
1456
+ application = result?.application ?? null
1457
+ }
1458
+ }
1459
+ return { managed: store.managed, application, restartRequired: application === 'restart-required' }
1460
+ }
1461
+
1462
+ async function handleRequest({ op, level, id, key, value, workspaceId, sessionId, preset, packages }) {
1463
+ if (op === 'state') return stateFor({ workspaceId, sessionId });
1464
+ if (op === 'skills') return skillListFor(sessionId);
1465
+ if (op === 'debug') return debugState(sessionId);
1466
+ if (op === 'debugpkg') return debugPkg(key);
1467
+ if (op === 'set') return setValue({ level, id, key, value });
1468
+ if (op === 'hooks') {
1469
+ return { hooks: streamHooks(), stats: globalThis[STREAM_STATS] ?? null };
1470
+ }
1471
+ if (op === 'manage') {
1472
+ return setManaged({ key, on: value === 'on' });
1473
+ }
1474
+ if (op === 'manager-debug') {
1475
+ const manager = ctx.get('pluginManager');
1476
+ if (!manager) return { manager: false };
1477
+ const plugins = await manager.listPlugins();
1478
+ const slug = String(key ?? '').replace(/^@[^/]+\//, '').replace(/^dsh-/, '');
1479
+ const matches = plugins
1480
+ .filter((plugin) => plugin?.moduleName === key
1481
+ || plugin?.moduleName === `dsh-${key}`
1482
+ || plugin?.patchId === key
1483
+ || plugin?.patchId === slug
1484
+ || String(plugin?.entryId ?? '').endsWith(`:${key}`)
1485
+ || String(plugin?.entryId ?? '').endsWith(`:${slug}`))
1486
+ .map((plugin) => ({
1487
+ entryId: String(plugin.entryId),
1488
+ moduleName: plugin.moduleName,
1489
+ patchId: plugin.patchId,
1490
+ enabled: plugin.enabled,
1491
+ readOnlyReason: plugin.readOnlyReason,
1492
+ }));
1493
+ return { manager: true, key, count: plugins.length, matches };
1494
+ }
1495
+ if (op === 'presets') {
1496
+ const listed = await ctx.agentPresets.list();
1497
+ const presets = Array.isArray(listed) ? listed : (listed?.presets ?? []);
1498
+ return { presets: presets.map((preset) => preset.id ?? preset) };
1499
+ }
1500
+ if (op === 'spawn') {
1501
+ return spawnTest({ basePreset: preset, packages });
1502
+ }
1503
+ if (op === 'refresh') {
1504
+ cache.clear();
1505
+ collectObserved();
1506
+ return stateFor({ workspaceId, sessionId });
1507
+ }
1508
+ throw new Error(`unknown op ${op}`);
1509
+ }
1510
+
1511
+ return { collectObserved, rowsCached, stateFor, setValue, handleRequest, hiddenByName, installResolveFilter, installSectionFilter, installSkillFilter, installStreamFilter, installComposeMount };
1512
+ }
1513
+
1514
+ export function apply(ctx) {
1515
+ const service = makeService(ctx);
1516
+ try {
1517
+ service.installResolveFilter();
1518
+ } catch {
1519
+ /* keep the plugin usable even if tool filtering cannot be installed */
1520
+ }
1521
+ try {
1522
+ service.installSectionFilter();
1523
+ } catch {
1524
+ /* keep the plugin usable even if prompt filtering cannot be installed */
1525
+ }
1526
+ try {
1527
+ service.installSkillFilter();
1528
+ } catch {
1529
+ /* keep the plugin usable even if skill filtering cannot be installed */
1530
+ }
1531
+ try {
1532
+ service.installStreamFilter();
1533
+ } catch {
1534
+ /* keep the plugin usable even if llm/stream filtering cannot be installed */
1535
+ }
1536
+ try {
1537
+ service.installComposeMount();
1538
+ } catch {
1539
+ /* keep the plugin usable even if composition mount cannot be installed */
1540
+ }
1541
+ try {
1542
+ service.collectObserved();
1543
+ } catch {
1544
+ /* the live agents may not be readable yet; agent/created retries */
1545
+ }
1546
+
1547
+ ctx.effect(() => {
1548
+ const off = ctx.on('agent/created', () => {
1549
+ service.collectObserved();
1550
+ });
1551
+ return off;
1552
+ }, 'plugin-scopes: observe agents');
1553
+
1554
+ ctx.effect(() => {
1555
+ const dispose = ctx.webServer.register({
1556
+ kind: 'exact',
1557
+ path: API_PATH,
1558
+ handler: (req, res) => {
1559
+ const chunks = [];
1560
+ req.on('data', (chunk) => chunks.push(chunk));
1561
+ req.on('end', () => {
1562
+ let payload = {};
1563
+ try {
1564
+ payload = chunks.length > 0 ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {};
1565
+ } catch {
1566
+ res.statusCode = 400;
1567
+ res.end(JSON.stringify({ error: 'invalid json' }));
1568
+ return;
1569
+ }
1570
+ Promise.resolve()
1571
+ .then(() => service.handleRequest(payload))
1572
+ .then((data) => {
1573
+ res.statusCode = 200;
1574
+ res.setHeader('content-type', 'application/json; charset=utf-8');
1575
+ res.end(JSON.stringify({ ok: true, data }));
1576
+ })
1577
+ .catch((error) => {
1578
+ res.statusCode = 500;
1579
+ res.setHeader('content-type', 'application/json; charset=utf-8');
1580
+ res.end(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }));
1581
+ });
1582
+ });
1583
+ },
1584
+ });
1585
+ return dispose;
1586
+ }, 'plugin-scopes: web api');
1587
+
1588
+ ctx.tools.register({
1589
+ name: 'plugin_scope',
1590
+ description: 'Inspect or change third-party plugin scope (global / workspace / session inheritance).',
1591
+ parameters: {
1592
+ type: 'object',
1593
+ properties: {
1594
+ action: { type: 'string', enum: ['state', 'set', 'refresh', 'hooks', 'presets', 'spawn', 'skills'] },
1595
+ level: { type: 'string', enum: ['global', 'workspace', 'session'] },
1596
+ id: { type: 'string' },
1597
+ key: { type: 'string' },
1598
+ value: { type: 'string', enum: ['on', 'off', 'inherit'] },
1599
+ sessionId: { type: 'string' },
1600
+ workspaceId: { type: 'string' },
1601
+ preset: { type: 'string' },
1602
+ packages: { type: 'array', items: { type: 'string' } },
1603
+ },
1604
+ required: ['action'],
1605
+ additionalProperties: false,
1606
+ },
1607
+ output: {
1608
+ schema: {
1609
+ type: 'object',
1610
+ properties: {
1611
+ ok: { type: 'boolean' },
1612
+ data: { type: 'object' },
1613
+ },
1614
+ required: ['ok'],
1615
+ additionalProperties: true,
1616
+ },
1617
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
1618
+ },
1619
+ async execute(args) {
1620
+ const { action, ...rest } = args ?? {};
1621
+ const data = await service.handleRequest({ ...rest, op: action });
1622
+ return { ok: true, data: JSON.parse(JSON.stringify(data ?? null)) };
1623
+ },
1624
+ });
1625
+ }