@hcstar/dsh-tool-manage 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,3113 @@
1
+ // src/host/mcp-server.ts
2
+ import { randomBytes } from "crypto";
3
+ import { createServer } from "http";
4
+
5
+ // src/shared/identity.ts
6
+ var SERVER_NAME = "dsh-tool-manage";
7
+ var LEGACY_SERVER_NAME = "tool-manager";
8
+ var ROUTE_BASE = "dsh-tool-manage";
9
+
10
+ // src/shared/variables.ts
11
+ var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
12
+ var SUGAR_TOKEN = /\{\{\s*([^{}]+?)\s*\}\}/g;
13
+ var NATIVE_TOKEN = /\$\{credential:([A-Za-z_][A-Za-z0-9_]*)\}/g;
14
+ function isVariableName(value) {
15
+ return VARIABLE_NAME.test(value);
16
+ }
17
+ function mapEntryStrings(entry, map) {
18
+ const next = { ...entry };
19
+ if (typeof entry.command === "string") next.command = map(entry.command);
20
+ if (Array.isArray(entry.args)) next.args = entry.args.map(map);
21
+ if (typeof entry.cwd === "string") next.cwd = map(entry.cwd);
22
+ if (typeof entry.url === "string") next.url = map(entry.url);
23
+ if (entry.env !== void 0) {
24
+ next.env = Object.fromEntries(Object.entries(entry.env).map(([key, value]) => [key, map(value)]));
25
+ }
26
+ if (entry.headers !== void 0) {
27
+ next.headers = Object.fromEntries(Object.entries(entry.headers).map(([key, value]) => [key, map(value)]));
28
+ }
29
+ return next;
30
+ }
31
+ function toNativeToken(value, known) {
32
+ return value.replace(
33
+ SUGAR_TOKEN,
34
+ (match, name) => isVariableName(name) && known(name) ? `\${credential:${name}}` : match
35
+ );
36
+ }
37
+ function toSugarToken(value, known) {
38
+ return value.replace(NATIVE_TOKEN, (match, name) => known(name) ? `{{${name}}}` : match);
39
+ }
40
+
41
+ // src/shared/mcp.ts
42
+ var MCP_SERVER_NAME = /^[A-Za-z0-9_-]{1,32}$/;
43
+ var DEFAULT_RECONNECT = {
44
+ enabled: true,
45
+ initialDelayMs: 500,
46
+ maxDelayMs: 3e4,
47
+ maxAttempts: 10
48
+ };
49
+ function defaultMcpEntry() {
50
+ return {
51
+ transport: "stdio",
52
+ command: "",
53
+ args: [],
54
+ env: {},
55
+ cwd: "",
56
+ url: "",
57
+ headers: {},
58
+ enabled: true,
59
+ startupTimeoutMs: 3e4,
60
+ reconnect: { ...DEFAULT_RECONNECT }
61
+ };
62
+ }
63
+ function isMcpTransport(value) {
64
+ return value === "stdio" || value === "streamable-http";
65
+ }
66
+ function cloneMcpEntry(entry) {
67
+ return structuredClone(entry);
68
+ }
69
+ function normalizeMcpEntry(entry) {
70
+ const next = cloneMcpEntry(entry);
71
+ if (next.transport === "stdio") {
72
+ next.url = "";
73
+ next.headers = {};
74
+ } else {
75
+ next.command = "";
76
+ next.args = [];
77
+ next.env = {};
78
+ next.cwd = "";
79
+ }
80
+ next.args = next.args.filter((arg) => arg !== "");
81
+ if (next.toolCallTimeoutMs === void 0 || !Number.isFinite(next.toolCallTimeoutMs) || next.toolCallTimeoutMs <= 0) {
82
+ delete next.toolCallTimeoutMs;
83
+ }
84
+ if (next.closeTimeoutMs !== void 0 && (!Number.isFinite(next.closeTimeoutMs) || next.closeTimeoutMs <= 0)) {
85
+ delete next.closeTimeoutMs;
86
+ }
87
+ if (!Number.isFinite(next.startupTimeoutMs) || next.startupTimeoutMs <= 0) next.startupTimeoutMs = 3e4;
88
+ return next;
89
+ }
90
+
91
+ // src/host/mcp-tools.ts
92
+ var MCP_TOOL_PREFIX = "mcp__";
93
+ function splitMcpToolName(name) {
94
+ if (!name.startsWith(MCP_TOOL_PREFIX)) return void 0;
95
+ const rest = name.slice(MCP_TOOL_PREFIX.length);
96
+ const separator = rest.indexOf("__");
97
+ if (separator <= 0) return void 0;
98
+ const server = rest.slice(0, separator);
99
+ const tool = rest.slice(separator + 2);
100
+ if (tool === "") return void 0;
101
+ return { server, tool };
102
+ }
103
+ function mcpToolName(server, tool) {
104
+ return `${MCP_TOOL_PREFIX}${server}__${tool}`;
105
+ }
106
+ function groupMcpTools(definitions) {
107
+ const servers = {};
108
+ for (const definition of definitions) {
109
+ const parsed = splitMcpToolName(definition.name);
110
+ if (parsed === void 0) continue;
111
+ const list = servers[parsed.server] ?? [];
112
+ list.push({ name: parsed.tool, description: definition.description, parameters: definition.parameters });
113
+ servers[parsed.server] = list;
114
+ }
115
+ for (const list of Object.values(servers)) list.sort((left, right) => left.name.localeCompare(right.name));
116
+ return { servers };
117
+ }
118
+
119
+ // src/host/tool-kit.ts
120
+ function asRecord(value) {
121
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
122
+ const prototype = Object.getPrototypeOf(value);
123
+ return prototype === Object.prototype || prototype === null ? value : void 0;
124
+ }
125
+ function argsRecord(args) {
126
+ const record = asRecord(args);
127
+ if (record === void 0) throw new Error("arguments must be a JSON object");
128
+ return record;
129
+ }
130
+ function readString(record, key) {
131
+ const value = record[key];
132
+ if (value === void 0) return void 0;
133
+ if (typeof value !== "string") throw new Error(`argument "${key}" must be a string`);
134
+ return value;
135
+ }
136
+ function requireString(record, key) {
137
+ const value = readString(record, key);
138
+ if (value === void 0 || value.trim() === "") throw new Error(`argument "${key}" is required`);
139
+ return value;
140
+ }
141
+ function readEnum(record, key, values) {
142
+ const value = record[key];
143
+ if (value === void 0) return void 0;
144
+ if (typeof value !== "string" || !values.includes(value)) {
145
+ throw new Error(`argument "${key}" must be one of ${values.join(", ")}`);
146
+ }
147
+ return value;
148
+ }
149
+ function requireEnum(record, key, values) {
150
+ const value = readEnum(record, key, values);
151
+ if (value === void 0) throw new Error(`argument "${key}" is required`);
152
+ return value;
153
+ }
154
+ function readBoolean(record, key) {
155
+ const value = record[key];
156
+ if (value === void 0) return void 0;
157
+ if (typeof value !== "boolean") throw new Error(`argument "${key}" must be a boolean`);
158
+ return value;
159
+ }
160
+ function readNumber(record, key) {
161
+ const value = record[key];
162
+ if (value === void 0) return void 0;
163
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`argument "${key}" must be a finite number`);
164
+ return value;
165
+ }
166
+ function readStringArray(record, key) {
167
+ const value = record[key];
168
+ if (value === void 0) return void 0;
169
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
170
+ throw new Error(`argument "${key}" must be an array of strings`);
171
+ }
172
+ return value;
173
+ }
174
+ function readObject(record, key) {
175
+ const value = record[key];
176
+ if (value === void 0) return void 0;
177
+ const object = asRecord(value);
178
+ if (object === void 0) throw new Error(`argument "${key}" must be an object`);
179
+ return object;
180
+ }
181
+ function renderJson(value) {
182
+ const text = JSON.stringify(value, null, 2);
183
+ return [{ type: "text", text: text === void 0 ? "null" : text }];
184
+ }
185
+ var ToolError = class extends Error {
186
+ /** Stable code the caller can branch on. */
187
+ code;
188
+ constructor(code, message) {
189
+ super(message);
190
+ this.name = "ToolError";
191
+ this.code = code;
192
+ }
193
+ };
194
+ function requireConfirm(record, action) {
195
+ if (record["confirm"] !== true) {
196
+ throw new ToolError("confirmation_required", `${action} requires "confirm": true`);
197
+ }
198
+ }
199
+
200
+ // src/host/mcp-config.ts
201
+ function settingsOf(ctx) {
202
+ const value = ctx.get("settings");
203
+ if (typeof value !== "object" || value === null) return void 0;
204
+ return typeof Reflect.get(value, "describe") === "function" ? value : void 0;
205
+ }
206
+ function managerOf(ctx) {
207
+ const value = ctx.get("mcpManager");
208
+ if (typeof value !== "object" || value === null) return void 0;
209
+ return value;
210
+ }
211
+ function readMcpConfig(ctx) {
212
+ const settings = settingsOf(ctx);
213
+ if (settings === void 0) return void 0;
214
+ try {
215
+ const descriptors = settings.describe();
216
+ const exact = descriptors.find((descriptor2) => descriptor2.ns === "mcp-manager");
217
+ const shaped = descriptors.find((descriptor2) => {
218
+ const value2 = asRecord(descriptor2.value);
219
+ return value2 !== void 0 && asRecord(value2["servers"]) !== void 0;
220
+ });
221
+ const descriptor = exact ?? shaped;
222
+ if (descriptor === void 0) return void 0;
223
+ const value = asRecord(descriptor.value);
224
+ const servers = value === void 0 ? {} : asRecord(value["servers"]) ?? {};
225
+ return { ns: descriptor.ns, revision: descriptor.revision, servers };
226
+ } catch {
227
+ return void 0;
228
+ }
229
+ }
230
+ function liveMcpServers(ctx) {
231
+ try {
232
+ return managerOf(ctx)?.config?.servers?.get() ?? {};
233
+ } catch {
234
+ return {};
235
+ }
236
+ }
237
+ function listMcpServers(ctx) {
238
+ const warnings = [];
239
+ const snapshot = readMcpConfig(ctx);
240
+ const servers = snapshot?.servers ?? liveMcpServers(ctx);
241
+ const manager = managerOf(ctx);
242
+ let views = [];
243
+ if (manager?.list !== void 0) {
244
+ try {
245
+ views = manager.list();
246
+ } catch (error) {
247
+ warnings.push(`\u8BFB\u53D6 MCP \u8FD0\u884C\u72B6\u6001\u5931\u8D25\uFF1A${messageOf(error)}`);
248
+ }
249
+ }
250
+ let tools = {};
251
+ try {
252
+ const registry = ctx.get("tools");
253
+ tools = groupMcpTools(registry?.definitions() ?? []).servers;
254
+ } catch (error) {
255
+ warnings.push(`\u8BFB\u53D6 MCP \u5DE5\u5177\u5931\u8D25\uFF1A${messageOf(error)}`);
256
+ }
257
+ const viewByName = new Map(views.map((view) => [view.name, view]));
258
+ const names = /* @__PURE__ */ new Set([...Object.keys(servers), ...viewByName.keys()]);
259
+ const out = [];
260
+ for (const name of [...names].sort((left, right) => left.localeCompare(right))) {
261
+ const entry = servers[name];
262
+ const view = viewByName.get(name);
263
+ out.push({
264
+ name,
265
+ configured: entry !== void 0,
266
+ registered: entry === void 0 && view !== void 0,
267
+ enabled: entry?.enabled ?? true,
268
+ transport: entry?.transport ?? "unknown",
269
+ endpoint: entry === void 0 ? "" : entry.transport === "stdio" ? entry.command : entry.url,
270
+ ...view === void 0 ? {} : { status: view.status },
271
+ tools: (tools[name] ?? []).map((tool) => tool.name)
272
+ });
273
+ }
274
+ return { servers: out, warnings };
275
+ }
276
+ function findMcpEntry(ctx, name) {
277
+ return (readMcpConfig(ctx)?.servers ?? liveMcpServers(ctx))[name];
278
+ }
279
+ function mergeMcpEntry(base, patch) {
280
+ const source = base ?? defaultMcpEntry();
281
+ const transport = patch["transport"] === void 0 ? source.transport : patch["transport"];
282
+ if (!isMcpTransport(transport)) throw new Error('entry.transport must be "stdio" or "streamable-http"');
283
+ const reconnectSource = source.reconnect ?? DEFAULT_RECONNECT;
284
+ const reconnectPatch = asRecord(patch["reconnect"]);
285
+ const reconnect = {
286
+ enabled: readBoolean2(reconnectPatch, "enabled") ?? reconnectSource.enabled,
287
+ initialDelayMs: readPositive(reconnectPatch, "initialDelayMs") ?? reconnectSource.initialDelayMs,
288
+ maxDelayMs: readPositive(reconnectPatch, "maxDelayMs") ?? reconnectSource.maxDelayMs,
289
+ maxAttempts: readPositive(reconnectPatch, "maxAttempts") ?? reconnectSource.maxAttempts
290
+ };
291
+ const toolCallTimeoutMs = optionalPositive(patch, "toolCallTimeoutMs", source.toolCallTimeoutMs);
292
+ const closeTimeoutMs = optionalPositive(patch, "closeTimeoutMs", source.closeTimeoutMs);
293
+ const toolLoading = patch["toolLoading"] ?? source.toolLoading;
294
+ if (toolLoading !== void 0 && toolLoading !== "eager" && toolLoading !== "on-demand") {
295
+ throw new Error('entry.toolLoading must be "eager" or "on-demand"');
296
+ }
297
+ const oauth = patch["oauth"] === void 0 ? source.oauth : asRecord(patch["oauth"]);
298
+ const next = normalizeMcpEntry({
299
+ transport,
300
+ command: readString2(patch, "command") ?? source.command,
301
+ args: readStringArray2(patch, "args") ?? source.args,
302
+ env: readStringMap(patch, "env") ?? source.env,
303
+ cwd: readString2(patch, "cwd") ?? source.cwd,
304
+ url: readString2(patch, "url") ?? source.url,
305
+ headers: readStringMap(patch, "headers") ?? source.headers,
306
+ enabled: readBoolean2(patch, "enabled") ?? source.enabled,
307
+ startupTimeoutMs: readPositive(patch, "startupTimeoutMs") ?? source.startupTimeoutMs,
308
+ ...toolCallTimeoutMs === void 0 ? {} : { toolCallTimeoutMs },
309
+ ...closeTimeoutMs === void 0 ? {} : { closeTimeoutMs },
310
+ reconnect,
311
+ ...toolLoading === void 0 ? {} : { toolLoading },
312
+ ...oauth === void 0 ? {} : { oauth }
313
+ });
314
+ if (next.transport === "stdio" && next.command.trim() === "") {
315
+ throw new Error("a stdio server requires a non-empty command");
316
+ }
317
+ if (next.transport === "streamable-http" && next.url.trim() === "") {
318
+ throw new Error("a streamable-http server requires a non-empty url");
319
+ }
320
+ return next;
321
+ }
322
+ function isConflict(error) {
323
+ return typeof error === "object" && error !== null && Reflect.get(error, "code") === "SETTINGS_CONFLICT";
324
+ }
325
+ async function writeMcpServers(ctx, mutate) {
326
+ const settings = settingsOf(ctx);
327
+ if (settings === void 0) throw new Error("settings service is unavailable; MCP servers cannot be saved");
328
+ let lastError;
329
+ for (let attempt = 0; attempt < 2; attempt += 1) {
330
+ const snapshot = readMcpConfig(ctx);
331
+ if (snapshot === void 0) throw new Error("mcp-manager settings row is unavailable");
332
+ const next = mutate(snapshot.servers);
333
+ try {
334
+ await settings.replace(snapshot.ns, { servers: next }, snapshot.revision);
335
+ return next;
336
+ } catch (error) {
337
+ lastError = error;
338
+ if (attempt > 0 || !isConflict(error)) throw error;
339
+ }
340
+ }
341
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
342
+ }
343
+ async function upsertMcpServer(ctx, name, patch) {
344
+ if (!MCP_SERVER_NAME.test(name)) {
345
+ throw new Error("server name must match /^[A-Za-z0-9_-]{1,32}$/");
346
+ }
347
+ const manager = managerOf(ctx);
348
+ if (manager?.list !== void 0) {
349
+ const view = manager.list().find((candidate) => candidate.name === name);
350
+ if (view !== void 0 && !view.configured) {
351
+ throw new Error(`server "${name}" is contributed by a plugin and cannot be edited here`);
352
+ }
353
+ }
354
+ let entry;
355
+ await writeMcpServers(ctx, (servers) => {
356
+ entry = mergeMcpEntry(servers[name], patch);
357
+ return { ...servers, [name]: entry };
358
+ });
359
+ return entry;
360
+ }
361
+ async function removeMcpServer(ctx, name) {
362
+ const snapshot = readMcpConfig(ctx);
363
+ if (snapshot === void 0) {
364
+ throw new Error("settings service is unavailable; MCP servers cannot be removed");
365
+ }
366
+ if (!Object.hasOwn(snapshot.servers, name)) {
367
+ const view = managerOf(ctx)?.list?.().find((candidate) => candidate.name === name);
368
+ if (view !== void 0) throw new Error(`server "${name}" is contributed by a plugin and cannot be removed here`);
369
+ throw new Error(`unknown MCP server "${name}"`);
370
+ }
371
+ await writeMcpServers(ctx, (servers) => {
372
+ const next = { ...servers };
373
+ delete next[name];
374
+ return next;
375
+ });
376
+ }
377
+ async function probeMcpServer(ctx, name, options) {
378
+ const manager = managerOf(ctx);
379
+ if (manager?.probe === void 0) throw new Error("mcpManager service is unavailable; the server cannot be probed");
380
+ return await manager.probe(name, {
381
+ ...options.signal === void 0 ? {} : { signal: options.signal },
382
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
383
+ });
384
+ }
385
+ async function restartMcpServer(ctx, name) {
386
+ const manager = managerOf(ctx);
387
+ if (manager?.restart === void 0)
388
+ throw new Error("mcpManager service is unavailable; the server cannot be restarted");
389
+ await manager.restart(name);
390
+ }
391
+ function mcpServerTools(ctx, name) {
392
+ try {
393
+ const registry = ctx.get("tools");
394
+ return groupMcpTools(registry?.definitions() ?? []).servers[name] ?? [];
395
+ } catch {
396
+ return [];
397
+ }
398
+ }
399
+ function readString2(patch, key) {
400
+ const value = patch[key];
401
+ if (value === void 0) return void 0;
402
+ if (typeof value !== "string") throw new Error(`entry.${key} must be a string`);
403
+ return value;
404
+ }
405
+ function readBoolean2(patch, key) {
406
+ if (patch === void 0) return void 0;
407
+ const value = patch[key];
408
+ if (value === void 0) return void 0;
409
+ if (typeof value !== "boolean") throw new Error(`entry.${key} must be a boolean`);
410
+ return value;
411
+ }
412
+ function readPositive(patch, key) {
413
+ if (patch === void 0) return void 0;
414
+ const value = patch[key];
415
+ if (value === void 0) return void 0;
416
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
417
+ throw new Error(`entry.${key} must be a positive finite number`);
418
+ }
419
+ return value;
420
+ }
421
+ function optionalPositive(patch, key, fallback) {
422
+ if (!Object.hasOwn(patch, key)) return fallback;
423
+ const value = patch[key];
424
+ if (value === null) return void 0;
425
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
426
+ throw new Error(`entry.${key} must be a positive finite number or null`);
427
+ }
428
+ return value;
429
+ }
430
+ function readStringArray2(patch, key) {
431
+ const value = patch[key];
432
+ if (value === void 0) return void 0;
433
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
434
+ throw new Error(`entry.${key} must be an array of strings`);
435
+ }
436
+ return value;
437
+ }
438
+ function readStringMap(patch, key) {
439
+ const value = patch[key];
440
+ if (value === void 0) return void 0;
441
+ const map = asRecord(value);
442
+ if (map === void 0) throw new Error(`entry.${key} must be an object of strings`);
443
+ const out = {};
444
+ for (const [entryKey, entryValue] of Object.entries(map)) {
445
+ if (typeof entryValue !== "string") throw new Error(`entry.${key}.${entryKey} must be a string`);
446
+ out[entryKey] = entryValue;
447
+ }
448
+ return out;
449
+ }
450
+ function messageOf(error) {
451
+ return error instanceof Error ? error.message : String(error);
452
+ }
453
+
454
+ // src/host/other-tools.ts
455
+ var MAX_TOOLS = 500;
456
+ function presetOf(host, agent) {
457
+ try {
458
+ const registry = host.get("agentPresets");
459
+ const selected = registry?.presetForSession?.(agent.session);
460
+ if (typeof selected === "string" && selected !== "") return selected;
461
+ } catch {
462
+ }
463
+ const header = agent.session?.header?.agentPreset;
464
+ return typeof header === "string" && header !== "" ? header : void 0;
465
+ }
466
+ function remember(map, definition, preset, global) {
467
+ if (definition.name.startsWith(MCP_TOOL_PREFIX)) return;
468
+ if (definition.name === "run_code") return;
469
+ const existing = map.get(definition.name);
470
+ if (existing === void 0) {
471
+ map.set(definition.name, {
472
+ name: definition.name,
473
+ description: definition.description,
474
+ parameters: definition.parameters,
475
+ global,
476
+ presets: preset === void 0 ? [] : [preset]
477
+ });
478
+ return;
479
+ }
480
+ if (global) existing.global = true;
481
+ if (preset !== void 0 && !existing.presets.includes(preset)) existing.presets.push(preset);
482
+ }
483
+ function collectOtherTools(host) {
484
+ const map = /* @__PURE__ */ new Map();
485
+ const warnings = [];
486
+ try {
487
+ const tools2 = host.get("tools");
488
+ for (const definition of tools2?.definitions() ?? []) remember(map, definition, void 0, true);
489
+ } catch (error) {
490
+ warnings.push(`\u5168\u5C40\u5DE5\u5177\u6CE8\u518C\u8868\u8BFB\u53D6\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
491
+ }
492
+ let agents = [];
493
+ try {
494
+ agents = host.get("agents")?.list() ?? [];
495
+ } catch {
496
+ agents = [];
497
+ }
498
+ for (const agent of agents) {
499
+ const preset = presetOf(host, agent);
500
+ try {
501
+ const tools2 = agent.ctx.tools;
502
+ for (const definition of tools2?.definitions() ?? []) remember(map, definition, preset, false);
503
+ } catch {
504
+ }
505
+ }
506
+ const tools = [...map.values()].sort((left, right) => left.name.localeCompare(right.name)).slice(0, MAX_TOOLS);
507
+ if (map.size > MAX_TOOLS) warnings.push(`\u5DE5\u5177\u6570\u91CF\u8D85\u8FC7 ${String(MAX_TOOLS)}\uFF0C\u53EA\u5C55\u793A\u524D ${String(MAX_TOOLS)} \u4E2A\u3002`);
508
+ return { tools, warnings };
509
+ }
510
+
511
+ // src/host/skills.ts
512
+ import { homedir } from "os";
513
+ import { basename, dirname, isAbsolute, join, relative, sep } from "path";
514
+ import { mkdir, readFile, readdir, realpath, rm, stat, unlink, writeFile } from "fs/promises";
515
+
516
+ // src/host/frontmatter.ts
517
+ var SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
518
+ var TOP_KEY = /^([A-Za-z0-9_-]+):(.*)$/;
519
+ function normalize(raw) {
520
+ return raw.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
521
+ }
522
+ function splitDocument(raw) {
523
+ const text = normalize(raw);
524
+ const lines = text.split("\n");
525
+ if (lines[0] !== "---") return void 0;
526
+ let close = -1;
527
+ for (let index = 1; index < lines.length; index += 1) {
528
+ if (lines[index] === "---") {
529
+ close = index;
530
+ break;
531
+ }
532
+ }
533
+ if (close < 0) return void 0;
534
+ return { yamlLines: lines.slice(1, close), body: lines.slice(close + 1).join("\n") };
535
+ }
536
+ function parseScalar(raw) {
537
+ const value = raw.trim();
538
+ if (value === "") return "";
539
+ if (value === "true") return true;
540
+ if (value === "false") return false;
541
+ if (value === "null" || value === "~") return null;
542
+ if (value.startsWith('"')) {
543
+ try {
544
+ return JSON.parse(value);
545
+ } catch {
546
+ return value.replace(/^"|"$/g, "").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
547
+ }
548
+ }
549
+ if (value.startsWith("'")) {
550
+ return value.replace(/^'|'$/g, "").replace(/''/g, "'");
551
+ }
552
+ const comment = value.indexOf(" #");
553
+ return comment < 0 ? value : value.slice(0, comment).trim();
554
+ }
555
+ function parseYamlScalars(lines) {
556
+ const out = {};
557
+ for (let index = 0; index < lines.length; index += 1) {
558
+ const line = lines[index] ?? "";
559
+ const match = TOP_KEY.exec(line);
560
+ if (match === null) continue;
561
+ const key = match[1];
562
+ if (key === void 0) continue;
563
+ let value = (match[2] ?? "").trim();
564
+ const blockScalar = value === "" || value.startsWith("|") || value.startsWith(">");
565
+ if (!blockScalar) {
566
+ out[key] = parseScalar(value);
567
+ continue;
568
+ }
569
+ const block = [];
570
+ let cursor = index + 1;
571
+ for (; cursor < lines.length; cursor += 1) {
572
+ const candidate = lines[cursor] ?? "";
573
+ if (candidate === "") {
574
+ block.push("");
575
+ continue;
576
+ }
577
+ if (!/^\s/.test(candidate)) break;
578
+ block.push(candidate);
579
+ }
580
+ index = cursor - 1;
581
+ if (block.length === 0) {
582
+ out[key] = "";
583
+ continue;
584
+ }
585
+ const indents = block.filter((entry) => entry.trim() !== "").map((entry) => /^\s*/.exec(entry)?.[0].length ?? 0);
586
+ const indent = indents.length === 0 ? 0 : Math.min(...indents);
587
+ const dedented = block.map((entry) => entry.slice(Math.min(indent, entry.length)));
588
+ value = value.startsWith(">") ? dedented.join(" ").replace(/[ \t]+/g, " ").trim() : dedented.join("\n").replace(/\n+$/, "");
589
+ out[key] = value;
590
+ }
591
+ return out;
592
+ }
593
+ function stringField(data, key) {
594
+ const value = data[key];
595
+ return typeof value === "string" && value.length > 0 ? value : void 0;
596
+ }
597
+ function booleanField(data, key) {
598
+ const value = data[key];
599
+ if (value === void 0 || value === null) return void 0;
600
+ if (typeof value === "boolean") return value;
601
+ return "invalid";
602
+ }
603
+ function parseSkillDocument(raw, fallbackName) {
604
+ const split = splitDocument(raw);
605
+ if (split === void 0) {
606
+ return {
607
+ name: fallbackName,
608
+ description: "",
609
+ disableModelInvocation: false,
610
+ userInvocable: true,
611
+ body: normalize(raw).replace(/^\n+/, ""),
612
+ valid: false,
613
+ issue: "\u7F3A\u5C11 YAML frontmatter\uFF08\u6587\u4EF6\u5FC5\u987B\u4EE5 --- \u5F00\u5934\u5E76\u95ED\u5408\uFF09"
614
+ };
615
+ }
616
+ const data = parseYamlScalars(split.yamlLines);
617
+ const declaredName = stringField(data, "name");
618
+ const description = stringField(data, "description");
619
+ const whenToUse = stringField(data, "whenToUse");
620
+ const modelFlag = booleanField(data, "disable-model-invocation");
621
+ const userFlag = booleanField(data, "user-invocable");
622
+ const issues = [];
623
+ if (declaredName === void 0) issues.push("\u7F3A\u5C11 name");
624
+ else if (!SKILL_NAME_PATTERN.test(declaredName)) issues.push(`name "${declaredName}" \u4E0D\u662F kebab-case`);
625
+ if (description === void 0) issues.push("\u7F3A\u5C11 description");
626
+ if (modelFlag === "invalid") issues.push("disable-model-invocation \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
627
+ if (userFlag === "invalid") issues.push("user-invocable \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
628
+ return {
629
+ name: declaredName ?? fallbackName,
630
+ description: description ?? "",
631
+ ...whenToUse === void 0 ? {} : { whenToUse },
632
+ disableModelInvocation: modelFlag === true,
633
+ userInvocable: userFlag !== false,
634
+ body: split.body.replace(/^\n+/, "").replace(/\s+$/, "\n"),
635
+ valid: issues.length === 0,
636
+ ...issues.length === 0 ? {} : { issue: issues.join("\uFF1B") }
637
+ };
638
+ }
639
+ function quote(value) {
640
+ return JSON.stringify(value);
641
+ }
642
+ function entriesOf(lines) {
643
+ const entries = [];
644
+ for (const line of lines) {
645
+ const match = TOP_KEY.exec(line);
646
+ if (match !== null) {
647
+ const key = match[1];
648
+ entries.push({ key: key === void 0 ? null : key, lines: [line] });
649
+ continue;
650
+ }
651
+ const last = entries[entries.length - 1];
652
+ if (last === void 0) entries.push({ key: null, lines: [line] });
653
+ else last.lines.push(line);
654
+ }
655
+ return entries;
656
+ }
657
+ var MANAGED_KEYS = /* @__PURE__ */ new Set(["name", "description", "whenToUse", "disable-model-invocation", "user-invocable"]);
658
+ function fieldLines(fields) {
659
+ const lines = [];
660
+ lines.push(["name", quote(fields.name)]);
661
+ lines.push(["description", quote(fields.description)]);
662
+ if (fields.whenToUse.trim() !== "") lines.push(["whenToUse", quote(fields.whenToUse.trim())]);
663
+ if (fields.disableModelInvocation) lines.push(["disable-model-invocation", "true"]);
664
+ if (!fields.userInvocable) lines.push(["user-invocable", "false"]);
665
+ return lines;
666
+ }
667
+ function applySkillFields(raw, fields, body) {
668
+ const split = splitDocument(raw);
669
+ if (split === void 0) return createSkillContent({ ...fields, body });
670
+ const owned = new Map(fieldLines(fields));
671
+ const entries = entriesOf(split.yamlLines);
672
+ const emitted = /* @__PURE__ */ new Set();
673
+ const next = [];
674
+ for (const entry of entries) {
675
+ if (entry.key === null || !MANAGED_KEYS.has(entry.key)) {
676
+ next.push(...entry.lines);
677
+ continue;
678
+ }
679
+ if (emitted.has(entry.key)) continue;
680
+ emitted.add(entry.key);
681
+ const line = owned.get(entry.key);
682
+ if (line !== void 0) next.push(`${entry.key}: ${line}`);
683
+ }
684
+ for (const [key, line] of owned) {
685
+ if (!emitted.has(key)) next.push(`${key}: ${line}`);
686
+ }
687
+ return envelope(next, body);
688
+ }
689
+ function createSkillContent(input) {
690
+ return envelope(
691
+ fieldLines(input).map(([key, line]) => `${key}: ${line}`),
692
+ input.body
693
+ );
694
+ }
695
+ function envelope(lines, body) {
696
+ const cleanBody = body.replace(/^\n+/, "").replace(/\s+$/, "");
697
+ return `---
698
+ ${lines.join("\n")}
699
+ ---
700
+
701
+ ${cleanBody === "" ? "" : `${cleanBody}
702
+ `}`;
703
+ }
704
+
705
+ // src/host/skills.ts
706
+ function skillRegistryOf(host) {
707
+ const value = host.get("skills");
708
+ if (typeof value !== "object" || value === null) return void 0;
709
+ const list = Reflect.get(value, "list");
710
+ return typeof list === "function" ? value : void 0;
711
+ }
712
+ var MAX_SKILL_BYTES = 1e6;
713
+ function defaultSkillRoots(environment = process.env, home = homedir()) {
714
+ const dshHome2 = environment.DSH_HOME?.trim() || join(home, ".dsh");
715
+ const agentsHome = environment.DSH_AGENTS_HOME?.trim() || join(home, ".agents");
716
+ return [
717
+ { key: "user-dsh", label: "DSH \u5168\u5C40", path: join(dshHome2, "skills"), writable: true, exists: false },
718
+ { key: "user-agents", label: "\u5171\u4EAB Agent", path: join(agentsHome, "skills"), writable: true, exists: false }
719
+ ];
720
+ }
721
+ var MAX_RESOURCE_ENTRIES = 300;
722
+ async function walkResources(directory, base, prefix, depth, out) {
723
+ if (out.length >= MAX_RESOURCE_ENTRIES || depth > 8) return;
724
+ let entries;
725
+ try {
726
+ entries = await readdir(join(directory, ...prefix.split("/").filter(Boolean)), { withFileTypes: true });
727
+ } catch {
728
+ return;
729
+ }
730
+ entries.sort((left, right) => {
731
+ const leftDir = left.isDirectory() ? 0 : 1;
732
+ const rightDir = right.isDirectory() ? 0 : 1;
733
+ return leftDir - rightDir || left.name.localeCompare(right.name);
734
+ });
735
+ for (const entry of entries) {
736
+ if (out.length >= MAX_RESOURCE_ENTRIES) return;
737
+ if (entry.name === "SKILL.md" || entry.name.startsWith(".")) continue;
738
+ if (entry.isSymbolicLink()) continue;
739
+ const relative2 = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
740
+ if (entry.isDirectory()) {
741
+ out.push({ name: entry.name, path: relative2, bytes: 0, directory: true });
742
+ await walkResources(directory, base, relative2, depth + 1, out);
743
+ continue;
744
+ }
745
+ try {
746
+ const info = await stat(join(base, ...relative2.split("/")));
747
+ out.push({ name: entry.name, path: relative2, bytes: info.size, directory: false });
748
+ } catch {
749
+ out.push({ name: entry.name, path: relative2, bytes: 0, directory: false });
750
+ }
751
+ }
752
+ }
753
+ async function listResources(directory) {
754
+ const out = [];
755
+ await walkResources(directory, directory, "", 0, out);
756
+ return out;
757
+ }
758
+ async function summarizeSkillFile(filePath, root, fallbackName, directory) {
759
+ const [raw, info] = await Promise.all([readFile(filePath, "utf8"), stat(filePath)]);
760
+ const parsed = parseSkillDocument(raw, fallbackName);
761
+ const resources = directory === void 0 ? [] : await listResources(directory);
762
+ return {
763
+ name: parsed.name,
764
+ description: parsed.description,
765
+ ...parsed.whenToUse === void 0 ? {} : { whenToUse: parsed.whenToUse },
766
+ path: filePath,
767
+ ...directory === void 0 ? {} : { dir: directory },
768
+ source: root.key,
769
+ sourceLabel: root.label,
770
+ rootKey: root.key,
771
+ writable: root.writable,
772
+ valid: parsed.valid,
773
+ ...parsed.issue === void 0 ? {} : { issue: parsed.issue },
774
+ modelInvocable: !parsed.disableModelInvocation,
775
+ userInvocable: parsed.userInvocable,
776
+ bytes: info.size,
777
+ resources
778
+ };
779
+ }
780
+ async function scanRoot(root) {
781
+ const warnings = [];
782
+ let entries;
783
+ try {
784
+ entries = await readdir(root.path, { withFileTypes: true });
785
+ } catch (error) {
786
+ const code = error.code;
787
+ if (code !== "ENOENT" && code !== "ENOTDIR") warnings.push(`${root.label}\uFF08${root.path}\uFF09\u65E0\u6CD5\u8BFB\u53D6`);
788
+ return { skills: [], warnings };
789
+ }
790
+ const skills = [];
791
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
792
+ if (entry.name.startsWith(".")) continue;
793
+ if (entry.isDirectory()) {
794
+ const file2 = join(root.path, entry.name, "SKILL.md");
795
+ try {
796
+ const info = await stat(file2);
797
+ if (!info.isFile()) continue;
798
+ skills.push(await summarizeSkillFile(file2, root, entry.name, join(root.path, entry.name)));
799
+ } catch (error) {
800
+ if (error.code !== "ENOENT") warnings.push(`${entry.name}/SKILL.md \u65E0\u6CD5\u8BFB\u53D6`);
801
+ }
802
+ continue;
803
+ }
804
+ if (!entry.name.endsWith(".md")) continue;
805
+ const file = join(root.path, entry.name);
806
+ try {
807
+ skills.push(await summarizeSkillFile(file, root, basename(entry.name, ".md")));
808
+ } catch {
809
+ warnings.push(`${entry.name} \u65E0\u6CD5\u8BFB\u53D6`);
810
+ }
811
+ }
812
+ return { skills, warnings };
813
+ }
814
+ function runtimeLabel(summary) {
815
+ if (summary.provider.startsWith("dsh-") && summary.provider.includes("office")) return "\u5185\u7F6E Office";
816
+ if (summary.source === "bundled") return "\u5185\u7F6E Skills";
817
+ return "\u8FD0\u884C\u65F6\u6280\u80FD";
818
+ }
819
+ async function runtimeSkills(registry) {
820
+ if (registry === void 0) return { skills: [] };
821
+ try {
822
+ const list = await registry.list();
823
+ const skills = [];
824
+ for (const summary of list) {
825
+ if (summary.path === void 0) continue;
826
+ let bytes = 0;
827
+ try {
828
+ bytes = (await stat(summary.path)).size;
829
+ } catch {
830
+ continue;
831
+ }
832
+ skills.push({
833
+ name: summary.name,
834
+ description: summary.description,
835
+ ...summary.whenToUse === void 0 ? {} : { whenToUse: summary.whenToUse },
836
+ path: summary.path,
837
+ source: summary.source,
838
+ sourceLabel: runtimeLabel(summary),
839
+ writable: false,
840
+ valid: true,
841
+ modelInvocable: summary.invocation.modelInvocable,
842
+ userInvocable: summary.invocation.userInvocable,
843
+ bytes,
844
+ resources: []
845
+ });
846
+ }
847
+ return { skills };
848
+ } catch {
849
+ return { skills: [], warning: "\u8BFB\u53D6\u8FD0\u884C\u65F6\u6280\u80FD\u76EE\u5F55\u5931\u8D25" };
850
+ }
851
+ }
852
+ function isInside(root, candidate) {
853
+ const rel = relative(root, candidate);
854
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
855
+ }
856
+ async function listLocalSkills(roots = defaultSkillRoots()) {
857
+ const warnings = [];
858
+ const byName = /* @__PURE__ */ new Map();
859
+ const order = [];
860
+ for (const root of roots) {
861
+ try {
862
+ root.exists = (await stat(root.path)).isDirectory();
863
+ } catch {
864
+ root.exists = false;
865
+ }
866
+ const scan = await scanRoot(root);
867
+ warnings.push(...scan.warnings);
868
+ for (const skill of scan.skills) {
869
+ if (!byName.has(skill.name)) order.push(skill.name);
870
+ byName.set(skill.name, skill);
871
+ }
872
+ }
873
+ const rank = new Map(roots.map((root, index) => [root.key, index]));
874
+ const skills = order.map((name) => byName.get(name)).filter((skill) => skill !== void 0).sort((left, right) => {
875
+ const leftRank = rank.get(left.rootKey ?? "") ?? roots.length;
876
+ const rightRank = rank.get(right.rootKey ?? "") ?? roots.length;
877
+ if (leftRank !== rightRank) return leftRank - rightRank;
878
+ return left.name.localeCompare(right.name);
879
+ });
880
+ return { roots, skills, warnings };
881
+ }
882
+ async function listSkills(registry, roots = defaultSkillRoots()) {
883
+ const local = await listLocalSkills(roots);
884
+ const warnings = [...local.warnings];
885
+ const byName = new Map(local.skills.map((skill) => [skill.name, skill]));
886
+ const order = local.skills.map((skill) => skill.name);
887
+ const runtime = await runtimeSkills(registry);
888
+ warnings.push(...runtime.warning === void 0 ? [] : [runtime.warning]);
889
+ for (const skill of runtime.skills) {
890
+ if (byName.has(skill.name)) {
891
+ warnings.push(`\u6280\u80FD ${skill.name} \u88AB\u8FD0\u884C\u65F6\u63D0\u4F9B\u8005\u8986\u76D6\uFF0C\u5217\u8868\u4E2D\u663E\u793A\u53EA\u8BFB\u7248\u672C`);
892
+ } else {
893
+ order.push(skill.name);
894
+ }
895
+ byName.set(skill.name, skill);
896
+ }
897
+ const rank = new Map(local.roots.map((root, index) => [root.key, index]));
898
+ const skills = order.map((name) => byName.get(name)).filter((skill) => skill !== void 0).sort((left, right) => {
899
+ const leftRank = rank.get(left.rootKey ?? "") ?? local.roots.length;
900
+ const rightRank = rank.get(right.rootKey ?? "") ?? local.roots.length;
901
+ if (leftRank !== rightRank) return leftRank - rightRank;
902
+ return left.name.localeCompare(right.name);
903
+ });
904
+ return { roots: local.roots, skills, warnings };
905
+ }
906
+ async function resolveSkillFile(requested, roots = defaultSkillRoots()) {
907
+ for (const root of roots) {
908
+ let realRoot;
909
+ try {
910
+ realRoot = await realpath(root.path);
911
+ } catch {
912
+ continue;
913
+ }
914
+ let file;
915
+ try {
916
+ file = await realpath(requested);
917
+ } catch {
918
+ continue;
919
+ }
920
+ if (!isInside(realRoot, file)) continue;
921
+ const parts = relative(realRoot, file).split(sep);
922
+ if (parts.length === 2 && parts[1] === "SKILL.md") {
923
+ const directory = dirname(file);
924
+ try {
925
+ if (!(await stat(directory)).isDirectory()) continue;
926
+ } catch {
927
+ continue;
928
+ }
929
+ return { root, file, directory };
930
+ }
931
+ if (parts.length === 1 && parts[0] !== void 0 && parts[0].endsWith(".md")) {
932
+ return { root, file };
933
+ }
934
+ }
935
+ return void 0;
936
+ }
937
+ async function isRuntimeSkillFile(path, registry) {
938
+ if (registry === void 0) return false;
939
+ try {
940
+ const list = await registry.list();
941
+ let real;
942
+ try {
943
+ real = await realpath(path);
944
+ } catch {
945
+ return false;
946
+ }
947
+ for (const summary of list) {
948
+ if (summary.path === void 0) continue;
949
+ try {
950
+ if (await realpath(summary.path) === real) return true;
951
+ } catch {
952
+ continue;
953
+ }
954
+ }
955
+ } catch {
956
+ return false;
957
+ }
958
+ return false;
959
+ }
960
+ async function readSkillDocument(registry, path, roots = defaultSkillRoots()) {
961
+ const local = await resolveSkillFile(path, roots);
962
+ if (local !== void 0) {
963
+ const fallback = local.directory === void 0 ? basename(local.file, ".md") : basename(local.directory);
964
+ const summary = await summarizeSkillFile(local.file, local.root, fallback, local.directory);
965
+ const content = await readFile(local.file, "utf8");
966
+ if (Buffer.byteLength(content, "utf8") > MAX_SKILL_BYTES) throw new Error("\u6280\u80FD\u6587\u4EF6\u8D85\u8FC7 1 MB");
967
+ const parsed = parseSkillDocument(content, fallback);
968
+ return { ...summary, content, body: parsed.body };
969
+ }
970
+ if (await isRuntimeSkillFile(path, registry)) {
971
+ const content = await readFile(path, "utf8");
972
+ const fallback = basename(dirname(path));
973
+ const parsed = parseSkillDocument(content, fallback);
974
+ return {
975
+ name: parsed.name,
976
+ description: parsed.description,
977
+ ...parsed.whenToUse === void 0 ? {} : { whenToUse: parsed.whenToUse },
978
+ path,
979
+ source: "runtime",
980
+ sourceLabel: "\u8FD0\u884C\u65F6\u6280\u80FD",
981
+ writable: false,
982
+ valid: parsed.valid,
983
+ ...parsed.issue === void 0 ? {} : { issue: parsed.issue },
984
+ modelInvocable: !parsed.disableModelInvocation,
985
+ userInvocable: parsed.userInvocable,
986
+ bytes: Buffer.byteLength(content, "utf8"),
987
+ resources: [],
988
+ content,
989
+ body: parsed.body
990
+ };
991
+ }
992
+ throw new Error("\u8BE5\u6280\u80FD\u6587\u4EF6\u4E0D\u5728\u53EF\u7BA1\u7406\u7684\u76EE\u5F55\u4E2D");
993
+ }
994
+ async function saveSkillDocument(registry, request, roots = defaultSkillRoots()) {
995
+ const resolved = await resolveSkillFile(request.path, roots);
996
+ if (resolved === void 0) throw new Error("\u8BE5\u6280\u80FD\u6587\u4EF6\u4E0D\u5728\u53EF\u7BA1\u7406\u7684\u76EE\u5F55\u4E2D");
997
+ if (!resolved.root.writable) throw new Error("\u8BE5\u76EE\u5F55\u662F\u53EA\u8BFB\u7684");
998
+ const current = await readFile(resolved.file, "utf8");
999
+ let next;
1000
+ if (request.content !== void 0) {
1001
+ if (Buffer.byteLength(request.content, "utf8") > MAX_SKILL_BYTES) throw new Error("\u6280\u80FD\u6587\u4EF6\u8D85\u8FC7 1 MB");
1002
+ next = request.content;
1003
+ } else {
1004
+ if (request.fields === void 0) throw new Error("\u7F3A\u5C11\u8981\u4FDD\u5B58\u7684\u5B57\u6BB5");
1005
+ const fields = validateFields(request.fields);
1006
+ next = applySkillFields(current, fields, request.body ?? "");
1007
+ if (Buffer.byteLength(next, "utf8") > MAX_SKILL_BYTES) throw new Error("\u6280\u80FD\u6587\u4EF6\u8D85\u8FC7 1 MB");
1008
+ }
1009
+ await writeFile(resolved.file, next, "utf8");
1010
+ return await readSkillDocument(registry, resolved.file, roots);
1011
+ }
1012
+ function validateFields(fields) {
1013
+ const name = fields.name.trim();
1014
+ if (!SKILL_NAME_PATTERN.test(name)) throw new Error("\u6280\u80FD\u540D\u5FC5\u987B\u662F\u5C0F\u5199 kebab-case\uFF08\u4F8B\u5982 my-skill\uFF09");
1015
+ const description = fields.description.trim();
1016
+ if (description === "") throw new Error("\u63CF\u8FF0\u4E0D\u80FD\u4E3A\u7A7A");
1017
+ return { ...fields, name, description, whenToUse: fields.whenToUse.trim() };
1018
+ }
1019
+ async function createSkillDocument(registry, request, roots = defaultSkillRoots()) {
1020
+ const fields = validateFields({
1021
+ name: request.name,
1022
+ description: request.description,
1023
+ whenToUse: request.whenToUse ?? "",
1024
+ disableModelInvocation: request.disableModelInvocation === true,
1025
+ userInvocable: request.userInvocable !== false
1026
+ });
1027
+ const root = roots.find((candidate) => candidate.key === request.rootKey);
1028
+ if (root === void 0 || !root.writable) throw new Error("\u76EE\u6807\u76EE\u5F55\u4E0D\u53EF\u5199");
1029
+ await mkdir(root.path, { recursive: true });
1030
+ const realRoot = await realpath(root.path);
1031
+ const flat = join(realRoot, `${fields.name}.md`);
1032
+ try {
1033
+ await stat(flat);
1034
+ throw new Error(`\u5DF2\u5B58\u5728\u540C\u540D\u6280\u80FD\u6587\u4EF6 ${fields.name}.md`);
1035
+ } catch (error) {
1036
+ if (error.code !== "ENOENT") throw error;
1037
+ }
1038
+ const directory = join(realRoot, fields.name);
1039
+ try {
1040
+ await stat(directory);
1041
+ throw new Error(`\u5DF2\u5B58\u5728\u540C\u540D\u6280\u80FD\u76EE\u5F55 ${fields.name}/`);
1042
+ } catch (error) {
1043
+ if (error.code !== "ENOENT") throw error;
1044
+ }
1045
+ const requestedBody = request.body?.trim() ?? "";
1046
+ const body = requestedBody === "" ? `# ${fields.name}
1047
+ ` : requestedBody;
1048
+ const content = createSkillContent({ ...fields, body });
1049
+ await mkdir(directory);
1050
+ try {
1051
+ await writeFile(join(directory, "SKILL.md"), content, "utf8");
1052
+ } catch (error) {
1053
+ await rm(directory, { recursive: true, force: true });
1054
+ throw error;
1055
+ }
1056
+ return await readSkillDocument(registry, join(directory, "SKILL.md"), roots);
1057
+ }
1058
+ async function deleteSkillDocument(path, roots = defaultSkillRoots()) {
1059
+ const resolved = await resolveSkillFile(path, roots);
1060
+ if (resolved === void 0) throw new Error("\u8BE5\u6280\u80FD\u6587\u4EF6\u4E0D\u5728\u53EF\u7BA1\u7406\u7684\u76EE\u5F55\u4E2D");
1061
+ if (!resolved.root.writable) throw new Error("\u8BE5\u76EE\u5F55\u662F\u53EA\u8BFB\u7684");
1062
+ if (resolved.directory === void 0) {
1063
+ await unlink(resolved.file);
1064
+ return;
1065
+ }
1066
+ const realRoot = await realpath(resolved.root.path);
1067
+ if (dirname(resolved.directory) !== realRoot) throw new Error("\u62D2\u7EDD\u5220\u9664\u975E\u6280\u80FD\u76EE\u5F55");
1068
+ await rm(resolved.directory, { recursive: true, force: false });
1069
+ }
1070
+ async function readSkillResource(registry, skillPath, resource, roots = defaultSkillRoots()) {
1071
+ const resolved = await resolveSkillFile(skillPath, roots);
1072
+ if (resolved === void 0 || resolved.directory === void 0) {
1073
+ throw new Error("\u8BE5\u6280\u80FD\u6CA1\u6709\u53EF\u6D4F\u89C8\u7684\u76EE\u5F55");
1074
+ }
1075
+ const parts = resource.split("/");
1076
+ if (resource.trim() === "" || isAbsolute(resource) || parts.some((part) => part === ".." || part === "")) {
1077
+ throw new Error("\u8D44\u6E90\u8DEF\u5F84\u65E0\u6548");
1078
+ }
1079
+ let realDir;
1080
+ let file;
1081
+ try {
1082
+ realDir = await realpath(resolved.directory);
1083
+ file = await realpath(join(resolved.directory, ...parts));
1084
+ } catch {
1085
+ throw new Error("\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
1086
+ }
1087
+ if (!isInside(realDir, file)) throw new Error("\u8D44\u6E90\u6587\u4EF6\u4E0D\u5728\u6280\u80FD\u76EE\u5F55\u4E2D");
1088
+ const info = await stat(file);
1089
+ if (!info.isFile()) throw new Error("\u8BE5\u8DEF\u5F84\u4E0D\u662F\u6587\u4EF6");
1090
+ if (info.size > MAX_SKILL_BYTES) throw new Error("\u8D44\u6E90\u6587\u4EF6\u8D85\u8FC7 1 MB");
1091
+ const buffer = await readFile(file);
1092
+ const binary = buffer.includes(0);
1093
+ return {
1094
+ path: resource,
1095
+ bytes: info.size,
1096
+ ...binary ? {} : { content: buffer.toString("utf8") },
1097
+ binary
1098
+ };
1099
+ }
1100
+
1101
+ // src/host/skill-roots.ts
1102
+ import { createHash } from "crypto";
1103
+ import { mkdir as mkdir2, readFile as readFile2, stat as stat2, writeFile as writeFile2 } from "fs/promises";
1104
+ import { homedir as homedir3 } from "os";
1105
+ import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute2, normalize as normalize2 } from "path";
1106
+
1107
+ // src/host/state.ts
1108
+ import { existsSync, mkdirSync, renameSync } from "fs";
1109
+ import { homedir as homedir2 } from "os";
1110
+ import { join as join2 } from "path";
1111
+ function dshHome(environment = process.env, home = homedir2()) {
1112
+ return environment.DSH_HOME?.trim() || join2(home, ".dsh");
1113
+ }
1114
+ function stateDir(environment = process.env, home = homedir2()) {
1115
+ const root = dshHome(environment, home);
1116
+ const next = join2(root, "dsh-tool-manage");
1117
+ const previous = join2(root, "tool-manager");
1118
+ if (existsSync(next) || !existsSync(previous)) return next;
1119
+ try {
1120
+ mkdirSync(root, { recursive: true });
1121
+ renameSync(previous, next);
1122
+ return next;
1123
+ } catch {
1124
+ return existsSync(next) ? next : previous;
1125
+ }
1126
+ }
1127
+ function statePath(name, environment = process.env, home = homedir2()) {
1128
+ return join2(stateDir(environment, home), name);
1129
+ }
1130
+
1131
+ // src/host/skill-roots.ts
1132
+ var MAX_CUSTOM_ROOTS = 20;
1133
+ function customKey(path) {
1134
+ return `custom:${createHash("sha1").update(path).digest("hex").slice(0, 10)}`;
1135
+ }
1136
+ function skillRootsPath(environment = process.env, home = homedir3()) {
1137
+ return statePath("skill-roots.json", environment, home);
1138
+ }
1139
+ function normalizeDirectory(input) {
1140
+ if (typeof input !== "string") throw new Error("\u626B\u63CF\u76EE\u5F55\u5FC5\u987B\u662F\u5B57\u7B26\u4E32");
1141
+ const value = input.trim();
1142
+ if (value === "") throw new Error("\u626B\u63CF\u76EE\u5F55\u4E0D\u80FD\u4E3A\u7A7A");
1143
+ if (!isAbsolute2(value)) throw new Error(`\u626B\u63CF\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\uFF1A${value}`);
1144
+ const normalized = normalize2(value);
1145
+ if (normalized === "/" || normalized === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u626B\u63CF\u76EE\u5F55");
1146
+ return normalized;
1147
+ }
1148
+ async function readCustomSkillDirectories() {
1149
+ let raw;
1150
+ try {
1151
+ raw = await readFile2(skillRootsPath(), "utf8");
1152
+ } catch {
1153
+ return [];
1154
+ }
1155
+ try {
1156
+ const parsed = JSON.parse(raw);
1157
+ if (typeof parsed !== "object" || parsed === null) return [];
1158
+ const list = Reflect.get(parsed, "directories");
1159
+ if (!Array.isArray(list)) return [];
1160
+ const out = [];
1161
+ for (const entry of list) {
1162
+ try {
1163
+ const path = normalizeDirectory(entry);
1164
+ if (!out.includes(path)) out.push(path);
1165
+ } catch {
1166
+ }
1167
+ }
1168
+ return out.slice(0, MAX_CUSTOM_ROOTS);
1169
+ } catch {
1170
+ return [];
1171
+ }
1172
+ }
1173
+ async function withExists(root) {
1174
+ return {
1175
+ ...root,
1176
+ exists: await stat2(root.path).then((info) => info.isDirectory()).catch(() => false)
1177
+ };
1178
+ }
1179
+ async function allSkillRoots() {
1180
+ const custom = await readCustomSkillDirectories();
1181
+ const builtIns = await Promise.all(defaultSkillRoots().map(withExists));
1182
+ const customRoots = await Promise.all(
1183
+ custom.map(
1184
+ async (path) => withExists({
1185
+ key: customKey(path),
1186
+ label: basename2(path) || path,
1187
+ path,
1188
+ writable: true,
1189
+ exists: false,
1190
+ custom: true
1191
+ })
1192
+ )
1193
+ );
1194
+ return [...builtIns, ...customRoots];
1195
+ }
1196
+ async function saveCustomSkillDirectories(input) {
1197
+ if (!Array.isArray(input)) throw new Error("directories \u5FC5\u987B\u662F\u6570\u7EC4");
1198
+ const out = [];
1199
+ for (const entry of input) {
1200
+ const path = normalizeDirectory(entry);
1201
+ if (!out.includes(path)) out.push(path);
1202
+ if (out.length > MAX_CUSTOM_ROOTS) throw new Error(`\u6700\u591A\u914D\u7F6E ${String(MAX_CUSTOM_ROOTS)} \u4E2A\u626B\u63CF\u76EE\u5F55`);
1203
+ }
1204
+ const file = skillRootsPath();
1205
+ await mkdir2(dirname2(file), { recursive: true });
1206
+ await writeFile2(file, `${JSON.stringify({ version: 1, directories: out }, null, 2)}
1207
+ `, "utf8");
1208
+ return out;
1209
+ }
1210
+
1211
+ // src/host/variables.ts
1212
+ import { mkdir as mkdir3, readFile as readFile3, rename, writeFile as writeFile3 } from "fs/promises";
1213
+ import { homedir as homedir4 } from "os";
1214
+ import { dirname as dirname3 } from "path";
1215
+ var DOCUMENT_VERSION = 1;
1216
+ var MAX_NAME = 100;
1217
+ var MAX_LABEL = 200;
1218
+ var MAX_DESCRIPTION = 2e3;
1219
+ var FALLBACK_MASK = "\u2022\u2022\u2022\u2022\u2022\u2022";
1220
+ function variablesPath(environment = process.env, home = homedir4()) {
1221
+ return statePath("variables.json", environment, home);
1222
+ }
1223
+ function defaultPermissions() {
1224
+ return {
1225
+ human: { read: true, write: true, delete: true },
1226
+ ai: { read: false, write: true, delete: false }
1227
+ };
1228
+ }
1229
+ function emptyDocument() {
1230
+ return { version: DOCUMENT_VERSION, variables: {} };
1231
+ }
1232
+ function credentialsOf(host) {
1233
+ const value = host.get("credentials");
1234
+ if (typeof value !== "object" || value === null) return void 0;
1235
+ if (typeof Reflect.get(value, "set") !== "function") return void 0;
1236
+ return value;
1237
+ }
1238
+ function normalizePermissions(raw) {
1239
+ const base = defaultPermissions();
1240
+ if (typeof raw !== "object" || raw === null) return base;
1241
+ const pick = (actor) => {
1242
+ const source = Reflect.get(raw, actor);
1243
+ if (typeof source !== "object" || source === null) return base[actor];
1244
+ const flag = (key) => {
1245
+ const value = Reflect.get(source, key);
1246
+ return typeof value === "boolean" ? value : base[actor][key];
1247
+ };
1248
+ return { read: flag("read"), write: flag("write"), delete: flag("delete") };
1249
+ };
1250
+ return { human: pick("human"), ai: pick("ai") };
1251
+ }
1252
+ function normalizeRecord(raw, name) {
1253
+ if (typeof raw !== "object" || raw === null) throw new Error(`variables: "${name}" is not an object`);
1254
+ const record = raw;
1255
+ const source = record["source"];
1256
+ if (source !== "plugin" && source !== "manual" && source !== "ai") {
1257
+ throw new Error(`variables: "${name}" has an invalid source`);
1258
+ }
1259
+ const createdAt = typeof record["createdAt"] === "string" ? record["createdAt"] : (/* @__PURE__ */ new Date(0)).toISOString();
1260
+ const updatedAt = typeof record["updatedAt"] === "string" ? record["updatedAt"] : createdAt;
1261
+ return {
1262
+ label: typeof record["label"] === "string" ? record["label"].slice(0, MAX_LABEL) : "",
1263
+ description: typeof record["description"] === "string" ? record["description"].slice(0, MAX_DESCRIPTION) : "",
1264
+ source,
1265
+ permissions: normalizePermissions(record["permissions"]),
1266
+ createdAt,
1267
+ updatedAt
1268
+ };
1269
+ }
1270
+ async function readVariableDocument(path = variablesPath()) {
1271
+ let text;
1272
+ try {
1273
+ text = await readFile3(path, "utf8");
1274
+ } catch (error) {
1275
+ if (typeof error === "object" && error !== null && Reflect.get(error, "code") === "ENOENT") return emptyDocument();
1276
+ throw error;
1277
+ }
1278
+ const parsed = JSON.parse(text);
1279
+ if (typeof parsed !== "object" || parsed === null) throw new Error("variables: the document is not an object");
1280
+ const variables = Reflect.get(parsed, "variables");
1281
+ if (typeof variables !== "object" || variables === null) return emptyDocument();
1282
+ const out = {};
1283
+ for (const [name, record] of Object.entries(variables)) {
1284
+ if (!isVariableName(name)) continue;
1285
+ out[name] = normalizeRecord(record, name);
1286
+ }
1287
+ return { version: DOCUMENT_VERSION, variables: out };
1288
+ }
1289
+ async function writeVariableDocument(document, path = variablesPath()) {
1290
+ await mkdir3(dirname3(path), { recursive: true });
1291
+ const temporary = `${path}.${String(process.pid)}.tmp`;
1292
+ await writeFile3(temporary, `${JSON.stringify(document, null, 2)}
1293
+ `, { encoding: "utf8", mode: 384 });
1294
+ await rename(temporary, path);
1295
+ }
1296
+ var writeTail = Promise.resolve();
1297
+ function serialized(work) {
1298
+ const next = writeTail.then(work, work);
1299
+ writeTail = next.catch(() => void 0);
1300
+ return next;
1301
+ }
1302
+ async function variableNames() {
1303
+ const document = await readVariableDocument();
1304
+ const known = new Set(Object.keys(document.variables));
1305
+ return (name) => known.has(name);
1306
+ }
1307
+ async function entryToNative(entry) {
1308
+ const known = await variableNames();
1309
+ return mapEntryStrings(entry, (value) => toNativeToken(value, known));
1310
+ }
1311
+ async function entryToSugar(entry) {
1312
+ const known = await variableNames();
1313
+ return mapEntryStrings(entry, (value) => toSugarToken(value, known));
1314
+ }
1315
+ function permissionsFor(record, actor) {
1316
+ const permissions = record?.permissions ?? defaultPermissions();
1317
+ return { ...permissions[actor] };
1318
+ }
1319
+ async function summarize(credentials, name, record, actor) {
1320
+ const can = permissionsFor(record, actor);
1321
+ let configured = false;
1322
+ let masked = FALLBACK_MASK;
1323
+ let value;
1324
+ if (credentials !== void 0) {
1325
+ try {
1326
+ const info = await credentials.describe(name);
1327
+ configured = info.configured;
1328
+ if (typeof info.masked === "string" && info.masked !== "") masked = info.masked;
1329
+ if (can.read && info.configured) value = (await credentials.resolve(name))?.value;
1330
+ } catch {
1331
+ }
1332
+ }
1333
+ return {
1334
+ name,
1335
+ label: record.label,
1336
+ description: record.description,
1337
+ source: record.source,
1338
+ configured,
1339
+ masked,
1340
+ ...value === void 0 ? {} : { value },
1341
+ permissions: { human: { ...record.permissions.human }, ai: { ...record.permissions.ai } },
1342
+ can,
1343
+ createdAt: record.createdAt,
1344
+ updatedAt: record.updatedAt
1345
+ };
1346
+ }
1347
+ async function listVariables(host, actor) {
1348
+ const document = await readVariableDocument();
1349
+ const credentials = credentialsOf(host);
1350
+ const warnings = [];
1351
+ if (credentials === void 0) warnings.push("\u51ED\u636E\u670D\u52A1\u4E0D\u53EF\u7528\uFF1A\u53D8\u91CF\u503C\u65E0\u6CD5\u8BFB\u53D6\u6216\u4FDD\u5B58");
1352
+ const rows = [];
1353
+ for (const name of Object.keys(document.variables).sort((left, right) => left.localeCompare(right))) {
1354
+ const record = document.variables[name];
1355
+ if (record === void 0) continue;
1356
+ rows.push(await summarize(credentials, name, record, actor));
1357
+ }
1358
+ return { variables: rows, warnings };
1359
+ }
1360
+ async function getVariable(host, name, actor) {
1361
+ const document = await readVariableDocument();
1362
+ const record = document.variables[name];
1363
+ if (record === void 0) throw new Error(`\u53D8\u91CF "${name}" \u4E0D\u5B58\u5728`);
1364
+ return await summarize(credentialsOf(host), name, record, actor);
1365
+ }
1366
+ function bounded(value, limit, field) {
1367
+ if (value.length > limit) throw new Error(`${field} \u8D85\u8FC7 ${String(limit)} \u4E2A\u5B57\u7B26`);
1368
+ return value;
1369
+ }
1370
+ async function saveVariable(host, input, actor) {
1371
+ const name = typeof input.name === "string" ? input.name.trim() : "";
1372
+ if (!isVariableName(name)) throw new Error("\u53D8\u91CF\u540D\u5FC5\u987B\u662F POSIX \u6807\u8BC6\u7B26\uFF1A\u5B57\u6BCD\u6216\u4E0B\u5212\u7EBF\u5F00\u5934\uFF0C\u53EA\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF");
1373
+ bounded(name, MAX_NAME, "\u53D8\u91CF\u540D");
1374
+ const credentials = credentialsOf(host);
1375
+ if (credentials === void 0) throw new Error("\u51ED\u636E\u670D\u52A1\u4E0D\u53EF\u7528\uFF1A\u53D8\u91CF\u65E0\u6CD5\u4FDD\u5B58");
1376
+ return await serialized(async () => {
1377
+ const document = await readVariableDocument();
1378
+ const existing = document.variables[name];
1379
+ const can = permissionsFor(existing, actor);
1380
+ if (existing !== void 0 && !can.write) throw new Error(`\u5F53\u524D\u8EAB\u4EFD\u6CA1\u6709\u4FEE\u6539\u53D8\u91CF "${name}" \u7684\u6743\u9650`);
1381
+ if (existing === void 0 && (await credentials.describe(name)).configured) {
1382
+ throw new Error(`\u51ED\u636E "${name}" \u5DF2\u88AB\u5176\u4ED6\u6765\u6E90\u4F7F\u7528\uFF1B\u8BF7\u6362\u4E00\u4E2A\u53D8\u91CF\u540D`);
1383
+ }
1384
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1385
+ const record = existing ?? {
1386
+ label: "",
1387
+ description: "",
1388
+ source: actor === "ai" ? "ai" : "manual",
1389
+ permissions: defaultPermissions(),
1390
+ createdAt: now,
1391
+ updatedAt: now
1392
+ };
1393
+ if (typeof input.label === "string") record.label = bounded(input.label.trim(), MAX_LABEL, "\u663E\u793A\u540D");
1394
+ if (typeof input.description === "string") {
1395
+ record.description = bounded(input.description.trim(), MAX_DESCRIPTION, "\u63CF\u8FF0");
1396
+ }
1397
+ if (input.permissions !== void 0) {
1398
+ record.permissions = normalizePermissions({
1399
+ human: { ...record.permissions.human, ...input.permissions.human ?? {} },
1400
+ ai: { ...record.permissions.ai, ...input.permissions.ai ?? {} }
1401
+ });
1402
+ }
1403
+ record.updatedAt = now;
1404
+ if (typeof input.value === "string") {
1405
+ if (input.value.length > 0) await credentials.set(name, input.value);
1406
+ else await credentials.unset(name);
1407
+ }
1408
+ document.variables[name] = record;
1409
+ await writeVariableDocument(document);
1410
+ return await summarize(credentials, name, record, actor);
1411
+ });
1412
+ }
1413
+ async function deleteVariable(host, name, actor) {
1414
+ await serialized(async () => {
1415
+ const document = await readVariableDocument();
1416
+ const record = document.variables[name];
1417
+ if (record === void 0) throw new Error(`\u53D8\u91CF "${name}" \u4E0D\u5B58\u5728`);
1418
+ if (!permissionsFor(record, actor).delete) throw new Error(`\u5F53\u524D\u8EAB\u4EFD\u6CA1\u6709\u5220\u9664\u53D8\u91CF "${name}" \u7684\u6743\u9650`);
1419
+ const credentials = credentialsOf(host);
1420
+ if (credentials !== void 0) await credentials.unset(name);
1421
+ delete document.variables[name];
1422
+ await writeVariableDocument(document);
1423
+ });
1424
+ }
1425
+
1426
+ // src/host/agent-tools.ts
1427
+ function renderResult(_args, value) {
1428
+ return renderJson(value);
1429
+ }
1430
+ var SKILL_ACTIONS = ["list", "get", "create", "update", "delete", "read_resource"];
1431
+ var SKILL_ROOT_ACTIONS = ["list", "set"];
1432
+ var MCP_ACTIONS = [
1433
+ "list",
1434
+ "get",
1435
+ "create",
1436
+ "update",
1437
+ "delete",
1438
+ "test",
1439
+ "restart",
1440
+ "enable",
1441
+ "disable",
1442
+ "set_icon"
1443
+ ];
1444
+ var VISIBILITY_ACTIONS = ["get", "set_mcp_injection", "set_skill_injection", "remove_injection"];
1445
+ var CATALOG_ACTIONS = ["tools", "tool", "presets"];
1446
+ var VARIABLE_ACTIONS = ["list", "get", "create", "update", "delete"];
1447
+ function readBooleanMap(record, key) {
1448
+ const value = record[key];
1449
+ if (value === void 0) return {};
1450
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1451
+ throw new ToolError("invalid_argument", `"${key}" must be an object of booleans`);
1452
+ }
1453
+ const out = {};
1454
+ for (const [name, enabled] of Object.entries(value)) {
1455
+ if (typeof enabled !== "boolean") {
1456
+ throw new ToolError("invalid_argument", `"${key}.${name}" must be a boolean`);
1457
+ }
1458
+ out[name] = enabled;
1459
+ }
1460
+ return out;
1461
+ }
1462
+ function presetOfAgent(ctx, agent) {
1463
+ const session = agent?.session;
1464
+ try {
1465
+ const presets = ctx.get("agentPresets");
1466
+ const selected = presets?.presetForSession?.(session);
1467
+ if (typeof selected === "string" && selected !== "") return selected;
1468
+ } catch {
1469
+ }
1470
+ const header = session?.header?.agentPreset;
1471
+ return typeof header === "string" && header !== "" ? header : void 0;
1472
+ }
1473
+ async function resolveSkill(ctx, options, roots) {
1474
+ const registry = skillRegistryOf(ctx);
1475
+ if (options.path !== void 0) {
1476
+ const document = await readSkillDocument(registry, options.path, roots);
1477
+ if (options.writable && !document.writable) throw new Error("this skill file is not writable");
1478
+ return { path: document.path ?? options.path, writable: document.writable };
1479
+ }
1480
+ const name = options.name;
1481
+ if (name === void 0 || name.trim() === "") throw new Error('provide "name" or "path"');
1482
+ const local = await listLocalSkills(roots);
1483
+ const candidates = local.skills.filter((skill) => skill.name === name && skill.path !== void 0);
1484
+ const localMatch = candidates.find((skill) => skill.writable) ?? candidates[0];
1485
+ if (localMatch?.path !== void 0) {
1486
+ if (options.writable && !localMatch.writable) throw new Error(`skill "${name}" is read-only`);
1487
+ return { path: localMatch.path, writable: localMatch.writable };
1488
+ }
1489
+ const all = await listSkills(registry, roots);
1490
+ const runtimeMatch = all.skills.find((skill) => skill.name === name && skill.path !== void 0);
1491
+ if (runtimeMatch?.path === void 0) throw new Error(`unknown skill "${name}"`);
1492
+ if (options.writable) throw new Error(`skill "${name}" is provided at runtime and is read-only`);
1493
+ return { path: runtimeMatch.path, writable: false };
1494
+ }
1495
+ function summarizeSkill(skill) {
1496
+ const truncated = skill.description.length > 240;
1497
+ return {
1498
+ name: skill.name,
1499
+ description: truncated ? `${skill.description.slice(0, 237)}\u2026` : skill.description,
1500
+ ...truncated ? { descriptionTruncated: true } : {},
1501
+ ...skill.path === void 0 ? {} : { path: skill.path },
1502
+ ...skill.dir === void 0 ? {} : { dir: skill.dir },
1503
+ source: skill.source,
1504
+ sourceLabel: skill.sourceLabel,
1505
+ ...skill.rootKey === void 0 ? {} : { rootKey: skill.rootKey },
1506
+ writable: skill.writable,
1507
+ valid: skill.valid,
1508
+ ...skill.issue === void 0 ? {} : { issue: skill.issue },
1509
+ modelInvocable: skill.modelInvocable,
1510
+ userInvocable: skill.userInvocable,
1511
+ bytes: skill.bytes,
1512
+ resources: skill.resources.map((resource) => resource.name)
1513
+ };
1514
+ }
1515
+ async function runSkillAction(ctx, args) {
1516
+ const action = requireEnum(args, "action", SKILL_ACTIONS);
1517
+ const registry = skillRegistryOf(ctx);
1518
+ const roots = await allSkillRoots();
1519
+ if (action === "list") {
1520
+ const result = await listSkills(registry, roots);
1521
+ return {
1522
+ roots: result.roots,
1523
+ skills: result.skills.map(summarizeSkill),
1524
+ warnings: result.warnings
1525
+ };
1526
+ }
1527
+ if (action === "get") {
1528
+ const resolved2 = await resolveSkill(
1529
+ ctx,
1530
+ {
1531
+ ...readString(args, "name") === void 0 ? {} : { name: readString(args, "name") },
1532
+ ...readString(args, "path") === void 0 ? {} : { path: readString(args, "path") },
1533
+ writable: false
1534
+ },
1535
+ roots
1536
+ );
1537
+ const document = await readSkillDocument(registry, resolved2.path, roots);
1538
+ return { skill: document };
1539
+ }
1540
+ if (action === "read_resource") {
1541
+ const resolved2 = await resolveSkill(
1542
+ ctx,
1543
+ {
1544
+ ...readString(args, "name") === void 0 ? {} : { name: readString(args, "name") },
1545
+ ...readString(args, "path") === void 0 ? {} : { path: readString(args, "path") },
1546
+ writable: false
1547
+ },
1548
+ roots
1549
+ );
1550
+ return { resource: await readSkillResource(registry, resolved2.path, requireString(args, "resource"), roots) };
1551
+ }
1552
+ if (action === "create") {
1553
+ const rootKey = requireString(args, "rootKey");
1554
+ const name = requireString(args, "name");
1555
+ const description = requireString(args, "description");
1556
+ const document = await createSkillDocument(
1557
+ registry,
1558
+ {
1559
+ rootKey,
1560
+ name,
1561
+ description,
1562
+ ...readString(args, "whenToUse") === void 0 ? {} : { whenToUse: readString(args, "whenToUse") },
1563
+ ...readString(args, "body") === void 0 ? {} : { body: readString(args, "body") },
1564
+ disableModelInvocation: readBoolean(args, "disableModelInvocation") === true,
1565
+ userInvocable: readBoolean(args, "userInvocable") !== false
1566
+ },
1567
+ roots
1568
+ );
1569
+ return { skill: document };
1570
+ }
1571
+ if (action === "update") {
1572
+ const resolved2 = await resolveSkill(
1573
+ ctx,
1574
+ {
1575
+ ...readString(args, "name") === void 0 ? {} : { name: readString(args, "name") },
1576
+ ...readString(args, "path") === void 0 ? {} : { path: readString(args, "path") },
1577
+ writable: true
1578
+ },
1579
+ roots
1580
+ );
1581
+ const content = readString(args, "content");
1582
+ const fields = {
1583
+ description: readString(args, "description"),
1584
+ whenToUse: readString(args, "whenToUse"),
1585
+ body: readString(args, "body"),
1586
+ disableModelInvocation: readBoolean(args, "disableModelInvocation"),
1587
+ userInvocable: readBoolean(args, "userInvocable")
1588
+ };
1589
+ const provided = Object.values(fields).some((value) => value !== void 0);
1590
+ if (content !== void 0 && provided) throw new Error('provide "content" or form fields, not both');
1591
+ if (content === void 0 && !provided) throw new Error('update requires "content" or at least one form field');
1592
+ if (content !== void 0) {
1593
+ return { skill: await saveSkillDocument(registry, { path: resolved2.path, content }, roots) };
1594
+ }
1595
+ const current = await readSkillDocument(registry, resolved2.path, roots);
1596
+ return {
1597
+ skill: await saveSkillDocument(
1598
+ registry,
1599
+ {
1600
+ path: resolved2.path,
1601
+ fields: {
1602
+ name: current.valid ? current.name : readString(args, "name") ?? current.name,
1603
+ description: fields.description ?? current.description,
1604
+ whenToUse: fields.whenToUse ?? current.whenToUse ?? "",
1605
+ disableModelInvocation: fields.disableModelInvocation ?? !current.modelInvocable,
1606
+ userInvocable: fields.userInvocable ?? current.userInvocable
1607
+ },
1608
+ body: fields.body ?? current.body
1609
+ },
1610
+ roots
1611
+ )
1612
+ };
1613
+ }
1614
+ requireConfirm(args, "delete");
1615
+ const resolved = await resolveSkill(
1616
+ ctx,
1617
+ {
1618
+ ...readString(args, "name") === void 0 ? {} : { name: readString(args, "name") },
1619
+ ...readString(args, "path") === void 0 ? {} : { path: readString(args, "path") },
1620
+ writable: true
1621
+ },
1622
+ roots
1623
+ );
1624
+ await deleteSkillDocument(resolved.path, roots);
1625
+ return { deleted: resolved.path };
1626
+ }
1627
+ function requireServer(ctx, name, options = {}) {
1628
+ const server = listMcpServers(ctx).servers.find((candidate) => candidate.name === name);
1629
+ if (server === void 0) throw new ToolError("not_found", `unknown MCP server "${name}"`);
1630
+ if (options.configured === true && !server.configured) {
1631
+ throw new ToolError("read_only", `server "${name}" is plugin-provided and cannot be edited here`);
1632
+ }
1633
+ return server;
1634
+ }
1635
+ async function displayEntry(entry) {
1636
+ return entry === void 0 ? void 0 : await entryToSugar(entry);
1637
+ }
1638
+ async function runMcpAction(ctx, policy, args, exec) {
1639
+ const action = requireEnum(args, "action", MCP_ACTIONS);
1640
+ if (action === "list") {
1641
+ const known = await variableNames();
1642
+ const listed = listMcpServers(ctx);
1643
+ return {
1644
+ ...listed,
1645
+ servers: listed.servers.map((server) => ({ ...server, endpoint: toSugarToken(server.endpoint, known) }))
1646
+ };
1647
+ }
1648
+ const name = requireString(args, "name");
1649
+ if (action === "get") {
1650
+ const server = requireServer(ctx, name);
1651
+ return {
1652
+ server: {
1653
+ ...server,
1654
+ ...server.configured ? { entry: await displayEntry(findMcpEntry(ctx, name)) } : {}
1655
+ },
1656
+ tools: mcpServerTools(ctx, name)
1657
+ };
1658
+ }
1659
+ if (action === "create") {
1660
+ const entry = readObject(args, "entry");
1661
+ if (entry === void 0) throw new ToolError("invalid_argument", 'create requires "entry"');
1662
+ const existing = listMcpServers(ctx).servers.find((candidate) => candidate.name === name);
1663
+ if (existing?.configured === true) throw new ToolError("conflict", `MCP server "${name}" already exists`);
1664
+ if (existing?.registered === true) throw new ToolError("read_only", `server "${name}" is plugin-provided`);
1665
+ return { name, entry: await displayEntry(await upsertMcpServer(ctx, name, await entryToNative(entry))) };
1666
+ }
1667
+ if (action === "update") {
1668
+ requireServer(ctx, name, { configured: true });
1669
+ const patch = readObject(args, "entry");
1670
+ if (patch === void 0 || Object.keys(patch).length === 0) {
1671
+ throw new ToolError("invalid_argument", 'update requires a non-empty "entry" patch');
1672
+ }
1673
+ return { name, entry: await displayEntry(await upsertMcpServer(ctx, name, await entryToNative(patch))) };
1674
+ }
1675
+ if (action === "delete") {
1676
+ requireConfirm(args, "delete");
1677
+ await removeMcpServer(ctx, name);
1678
+ return { deleted: name };
1679
+ }
1680
+ if (action === "test") {
1681
+ requireServer(ctx, name);
1682
+ const timeoutMs = readNumber(args, "timeoutMs");
1683
+ return {
1684
+ name,
1685
+ result: await probeMcpServer(ctx, name, {
1686
+ signal: exec.signal,
1687
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
1688
+ })
1689
+ };
1690
+ }
1691
+ if (action === "restart") {
1692
+ requireServer(ctx, name);
1693
+ await restartMcpServer(ctx, name);
1694
+ return { restarted: name };
1695
+ }
1696
+ if (action === "enable" || action === "disable") {
1697
+ requireServer(ctx, name, { configured: true });
1698
+ const enabled = action === "enable";
1699
+ return { name, enabled, entry: await upsertMcpServer(ctx, name, { enabled }) };
1700
+ }
1701
+ requireServer(ctx, name);
1702
+ const icon = readString(args, "icon");
1703
+ if (icon === void 0) throw new ToolError("invalid_argument", 'set_icon requires "icon" (empty clears it)');
1704
+ const current = policy.current();
1705
+ const icons = { ...current.icons };
1706
+ const next = icon.trim();
1707
+ if (next === "") delete icons[name];
1708
+ else icons[name] = next;
1709
+ const saved = await policy.save({ ...current, icons });
1710
+ return { name, icon: next === "" ? null : next, policy: saved };
1711
+ }
1712
+ async function runSkillRootsAction(args) {
1713
+ const action = requireEnum(args, "action", SKILL_ROOT_ACTIONS);
1714
+ if (action === "set") {
1715
+ const directories = readStringArray(args, "directories");
1716
+ if (directories === void 0) throw new ToolError("invalid_argument", 'set requires "directories"');
1717
+ await saveCustomSkillDirectories(directories);
1718
+ }
1719
+ return { roots: await allSkillRoots() };
1720
+ }
1721
+ async function runVisibilityAction(policy, args) {
1722
+ const action = requireEnum(args, "action", VISIBILITY_ACTIONS);
1723
+ if (action === "get") return { policy: policy.current() };
1724
+ const next = JSON.parse(JSON.stringify(policy.current()));
1725
+ if (action === "remove_injection") {
1726
+ const kind = requireEnum(args, "kind", ["mcp", "skill"]);
1727
+ const name2 = requireString(args, "name");
1728
+ if (kind === "mcp") delete next.mcp[name2];
1729
+ else delete next.skillInjection[name2];
1730
+ return { policy: await policy.save(next) };
1731
+ }
1732
+ const key = action === "set_mcp_injection" ? "mcp" : "skillInjection";
1733
+ const name = requireString(args, action === "set_mcp_injection" ? "server" : "skill");
1734
+ const fallback = readBoolean(args, "default");
1735
+ if (fallback === void 0) throw new ToolError("invalid_argument", 'argument "default" is required');
1736
+ const existing = next[key][name];
1737
+ const presets = args["presets"] === void 0 ? existing?.presets ?? {} : readBooleanMap(args, "presets");
1738
+ next[key][name] = { default: fallback, presets };
1739
+ return { policy: await policy.save(next) };
1740
+ }
1741
+ async function runCatalogAction(ctx, args, exec) {
1742
+ const action = requireEnum(args, "action", CATALOG_ACTIONS);
1743
+ if (action === "tools") {
1744
+ const { tools, warnings } = collectOtherTools(ctx);
1745
+ return {
1746
+ tools: tools.map(({ parameters: _parameters, ...tool }) => tool),
1747
+ warnings
1748
+ };
1749
+ }
1750
+ if (action === "tool") {
1751
+ const name = requireString(args, "name");
1752
+ const { tools, warnings } = collectOtherTools(ctx);
1753
+ const tool = tools.find((candidate) => candidate.name === name);
1754
+ if (tool === void 0) throw new ToolError("not_found", `unknown tool "${name}"`);
1755
+ return { tool, warnings };
1756
+ }
1757
+ const presets = ctx.get("agentPresets");
1758
+ const list = await presets?.list() ?? [];
1759
+ const defaultId = presets?.defaultId;
1760
+ const current = exec.agent === void 0 ? void 0 : presetOfAgent(ctx, exec.agent);
1761
+ return {
1762
+ presets: list.map((preset) => ({ ...preset, isDefault: preset.id === defaultId })),
1763
+ ...defaultId === void 0 ? {} : { defaultId },
1764
+ ...current === void 0 ? {} : { currentPreset: current }
1765
+ };
1766
+ }
1767
+ async function runVariableAction(ctx, args) {
1768
+ const action = requireEnum(args, "action", VARIABLE_ACTIONS);
1769
+ if (action === "list") return await listVariables(ctx, "ai");
1770
+ const name = requireString(args, "name");
1771
+ if (action === "get") return { variable: await getVariable(ctx, name, "ai") };
1772
+ if (action === "delete") {
1773
+ await deleteVariable(ctx, name, "ai");
1774
+ return { deleted: name };
1775
+ }
1776
+ const input = { name };
1777
+ const label = readString(args, "label");
1778
+ const description = readString(args, "description");
1779
+ const value = readString(args, "value");
1780
+ const permissions = readObject(args, "permissions");
1781
+ if (label !== void 0) input.label = label;
1782
+ if (description !== void 0) input.description = description;
1783
+ if (value !== void 0) input.value = value;
1784
+ if (permissions !== void 0) {
1785
+ const actorOf = (key) => {
1786
+ const raw = permissions[key];
1787
+ if (typeof raw !== "object" || raw === null) return void 0;
1788
+ const out = {};
1789
+ for (const flag of ["read", "write", "delete"]) {
1790
+ const flagValue = Reflect.get(raw, flag);
1791
+ if (typeof flagValue === "boolean") out[flag] = flagValue;
1792
+ }
1793
+ return out;
1794
+ };
1795
+ const human = actorOf("human");
1796
+ const ai = actorOf("ai");
1797
+ input.permissions = {
1798
+ ...human === void 0 ? {} : { human },
1799
+ ...ai === void 0 ? {} : { ai }
1800
+ };
1801
+ }
1802
+ return { variable: await saveVariable(ctx, input, "ai") };
1803
+ }
1804
+ function actionSchema(variants) {
1805
+ return {
1806
+ type: "object",
1807
+ oneOf: variants.map((variant) => ({
1808
+ type: "object",
1809
+ additionalProperties: false,
1810
+ properties: {
1811
+ action: { type: "string", const: variant.action, description: variant.description },
1812
+ ...variant.properties
1813
+ },
1814
+ required: ["action", ...variant.required ?? []]
1815
+ }))
1816
+ };
1817
+ }
1818
+ var MCP_ENTRY_SCHEMA = {
1819
+ type: "object",
1820
+ additionalProperties: true,
1821
+ properties: {
1822
+ transport: { type: "string", enum: ["stdio", "streamable-http"] },
1823
+ command: { type: "string", description: "stdio executable; no shell expansion." },
1824
+ args: { type: "array", items: { type: "string" } },
1825
+ env: { type: "object", additionalProperties: true },
1826
+ cwd: { type: "string" },
1827
+ url: { type: "string", description: "streamable-http endpoint." },
1828
+ headers: { type: "object", additionalProperties: true },
1829
+ enabled: { type: "boolean" },
1830
+ toolCallTimeoutMs: { type: "number" },
1831
+ startupTimeoutMs: { type: "number" },
1832
+ closeTimeoutMs: { type: "number" },
1833
+ toolLoading: { type: "string", enum: ["eager", "on-demand"] },
1834
+ reconnect: {
1835
+ type: "object",
1836
+ additionalProperties: false,
1837
+ properties: {
1838
+ enabled: { type: "boolean" },
1839
+ initialDelayMs: { type: "number" },
1840
+ maxDelayMs: { type: "number" },
1841
+ maxAttempts: { type: "number" }
1842
+ }
1843
+ },
1844
+ oauth: { type: "object", additionalProperties: true }
1845
+ }
1846
+ };
1847
+ var SKILL_FIELDS = {
1848
+ description: { type: "string", description: "Frontmatter description." },
1849
+ whenToUse: { type: "string", description: "Optional routing guidance." },
1850
+ body: { type: "string", description: "Markdown body below the frontmatter." },
1851
+ disableModelInvocation: { type: "boolean", description: "Hide the skill from the model catalog." },
1852
+ userInvocable: { type: "boolean", description: "Expose the skill as a user slash command; defaults true." }
1853
+ };
1854
+ var SKILL_TARGET = {
1855
+ name: { type: "string", description: "Frontmatter skill name." },
1856
+ path: { type: "string", description: "Absolute SKILL.md path; use when names collide." }
1857
+ };
1858
+ var PRESET_OVERRIDES_SCHEMA = {
1859
+ type: "object",
1860
+ additionalProperties: { type: "boolean" },
1861
+ description: "Explicit per-preset overrides; omitted presets follow default."
1862
+ };
1863
+ var VARIABLE_PERMISSIONS_SCHEMA = {
1864
+ type: "object",
1865
+ additionalProperties: false,
1866
+ properties: {
1867
+ human: {
1868
+ type: "object",
1869
+ additionalProperties: false,
1870
+ properties: { read: { type: "boolean" }, write: { type: "boolean" }, delete: { type: "boolean" } }
1871
+ },
1872
+ ai: {
1873
+ type: "object",
1874
+ additionalProperties: false,
1875
+ properties: { read: { type: "boolean" }, write: { type: "boolean" }, delete: { type: "boolean" } }
1876
+ }
1877
+ }
1878
+ };
1879
+ function createToolManagerTools(ctx, policy) {
1880
+ return [
1881
+ {
1882
+ name: "mcp_manage",
1883
+ description: "Manage MCP servers in this profile. This is the only tool that creates, updates, deletes, enables, disables, tests, restarts, or labels MCP servers. `list` returns configured and plugin-provided servers with live status and tool names; `get` adds the stored entry and full tool schemas. Writes go through the shared settings queue, so the Host validates and rebuilds the connection without a restart. Plugin-provided servers are read-only except for test, restart, and label. Entry strings may embed `{{name}}` variables; the Host stores them as native credential templates.",
1884
+ parameters: actionSchema([
1885
+ { action: "list", description: "List configured and plugin-provided servers with status and tool names." },
1886
+ {
1887
+ action: "get",
1888
+ description: "Read one server with its entry, status, and tool schemas.",
1889
+ properties: { name: { type: "string" } },
1890
+ required: ["name"]
1891
+ },
1892
+ {
1893
+ action: "create",
1894
+ description: "Create a new configured server; fails if the name already exists.",
1895
+ properties: { name: { type: "string" }, entry: MCP_ENTRY_SCHEMA },
1896
+ required: ["name", "entry"]
1897
+ },
1898
+ {
1899
+ action: "update",
1900
+ description: "Patch an existing configured server; omitted entry fields keep their values.",
1901
+ properties: { name: { type: "string" }, entry: MCP_ENTRY_SCHEMA },
1902
+ required: ["name", "entry"]
1903
+ },
1904
+ {
1905
+ action: "delete",
1906
+ description: "Delete a configured server after explicit confirmation.",
1907
+ properties: {
1908
+ name: { type: "string" },
1909
+ confirm: { type: "boolean", description: "Must be true." }
1910
+ },
1911
+ required: ["name", "confirm"]
1912
+ },
1913
+ {
1914
+ action: "test",
1915
+ description: "Test one server connection without restarting it.",
1916
+ properties: { name: { type: "string" }, timeoutMs: { type: "number" } },
1917
+ required: ["name"]
1918
+ },
1919
+ {
1920
+ action: "restart",
1921
+ description: "Rebuild one connected server from its current entry.",
1922
+ properties: { name: { type: "string" } },
1923
+ required: ["name"]
1924
+ },
1925
+ {
1926
+ action: "enable",
1927
+ description: "Enable a configured server and rebuild its connection.",
1928
+ properties: { name: { type: "string" } },
1929
+ required: ["name"]
1930
+ },
1931
+ {
1932
+ action: "disable",
1933
+ description: "Disable a configured server and unregister its tools; the entry is kept.",
1934
+ properties: { name: { type: "string" } },
1935
+ required: ["name"]
1936
+ },
1937
+ {
1938
+ action: "set_icon",
1939
+ description: "Set or clear the short text/emoji label shown in the MCP list.",
1940
+ properties: {
1941
+ name: { type: "string" },
1942
+ icon: { type: "string", description: "1\u20138 code points; an empty string clears it." }
1943
+ },
1944
+ required: ["name", "icon"]
1945
+ }
1946
+ ]),
1947
+ output: { schema: {}, render: renderResult },
1948
+ async execute(rawArgs, exec) {
1949
+ return await runMcpAction(ctx, policy, argsRecord(rawArgs), exec);
1950
+ }
1951
+ },
1952
+ {
1953
+ name: "skill_manage",
1954
+ description: "Manage Agent Skill files in the writable skill roots. This tool owns Skill content and resource reads; scan-directory configuration lives in `skill_roots`. `list` discovers roots and summaries; `get` returns one complete document plus its resource tree; `read_resource` returns one non-SKILL.md file. `update` preserves unknown frontmatter; pass `content` to replace the whole file or form fields to rewrite only the owned keys. Runtime and bundled skills are read-only; delete requires explicit confirmation.",
1955
+ parameters: actionSchema([
1956
+ { action: "list", description: "List writable roots and one summary per skill." },
1957
+ {
1958
+ action: "get",
1959
+ description: "Read one full skill document, including resource entries.",
1960
+ properties: SKILL_TARGET
1961
+ },
1962
+ {
1963
+ action: "create",
1964
+ description: "Create a directory-bundle skill in one writable root.",
1965
+ properties: {
1966
+ rootKey: { type: "string", description: "Writable root key from list." },
1967
+ name: { type: "string" },
1968
+ ...SKILL_FIELDS
1969
+ },
1970
+ required: ["rootKey", "name", "description"]
1971
+ },
1972
+ {
1973
+ action: "update",
1974
+ description: "Update one skill by form fields or a raw document.",
1975
+ properties: {
1976
+ ...SKILL_TARGET,
1977
+ ...SKILL_FIELDS,
1978
+ content: { type: "string", description: "Complete file text; mutually exclusive with form fields." }
1979
+ }
1980
+ },
1981
+ {
1982
+ action: "delete",
1983
+ description: "Delete one skill or flat skill file after explicit confirmation.",
1984
+ properties: { ...SKILL_TARGET, confirm: { type: "boolean", description: "Must be true." } },
1985
+ required: ["confirm"]
1986
+ },
1987
+ {
1988
+ action: "read_resource",
1989
+ description: "Read one file below a skill directory (never executes it).",
1990
+ properties: {
1991
+ ...SKILL_TARGET,
1992
+ resource: { type: "string", description: "Relative path inside the skill directory." }
1993
+ },
1994
+ required: ["resource"]
1995
+ }
1996
+ ]),
1997
+ output: { schema: {}, render: renderResult },
1998
+ async execute(rawArgs) {
1999
+ return await runSkillAction(ctx, argsRecord(rawArgs));
2000
+ }
2001
+ },
2002
+ {
2003
+ name: "skill_roots",
2004
+ description: "Read or replace the custom directories scanned for Agent Skills. Built-in roots are fixed. These directories are discovery settings, not injection rules; use `visibility_manage` for those. Paths must be absolute and are capped at 20.",
2005
+ parameters: actionSchema([
2006
+ { action: "list", description: "List built-in and custom skill roots." },
2007
+ {
2008
+ action: "set",
2009
+ description: "Replace the complete custom-root list; [] clears it.",
2010
+ properties: {
2011
+ directories: { type: "array", items: { type: "string" } }
2012
+ },
2013
+ required: ["directories"]
2014
+ }
2015
+ ]),
2016
+ output: { schema: {}, render: renderResult },
2017
+ async execute(rawArgs) {
2018
+ return await runSkillRootsAction(argsRecord(rawArgs));
2019
+ }
2020
+ },
2021
+ {
2022
+ name: "visibility_manage",
2023
+ description: "Read or patch the Agent visibility policy. This tool only changes policy slices: one preset tool block, one preset skill block, or one MCP/Skill injection rule. It never edits registry definitions and never replaces the whole policy document. Use `catalog` to inspect what exists before writing rules; use `get` to inspect the current document.",
2024
+ parameters: actionSchema([
2025
+ { action: "get", description: "Read the complete normalized policy document." },
2026
+ {
2027
+ action: "set_mcp_injection",
2028
+ description: "Set one MCP server\u2019s default and per-preset injection rule.",
2029
+ properties: {
2030
+ server: { type: "string" },
2031
+ default: { type: "boolean" },
2032
+ presets: PRESET_OVERRIDES_SCHEMA
2033
+ },
2034
+ required: ["server", "default"]
2035
+ },
2036
+ {
2037
+ action: "set_skill_injection",
2038
+ description: "Set one skill\u2019s default and per-preset injection rule.",
2039
+ properties: {
2040
+ skill: { type: "string" },
2041
+ default: { type: "boolean" },
2042
+ presets: PRESET_OVERRIDES_SCHEMA
2043
+ },
2044
+ required: ["skill", "default"]
2045
+ },
2046
+ {
2047
+ action: "remove_injection",
2048
+ description: "Remove an MCP or Skill injection rule.",
2049
+ properties: {
2050
+ kind: { type: "string", enum: ["mcp", "skill"] },
2051
+ name: { type: "string" }
2052
+ },
2053
+ required: ["kind", "name"]
2054
+ }
2055
+ ]),
2056
+ output: { schema: {}, render: renderResult },
2057
+ async execute(rawArgs) {
2058
+ return await runVisibilityAction(policy, argsRecord(rawArgs));
2059
+ }
2060
+ },
2061
+ {
2062
+ name: "catalog",
2063
+ description: "Read-only projection of tools and Agent presets. `tools` lists every non-MCP registry tool; `tool` adds its argument schema; `presets` lists presets, the default, and the caller\u2019s current preset \u2014 use it to name presets for `visibility_manage`. This tool never writes; registry definitions are owned by plugins.",
2064
+ parameters: actionSchema([
2065
+ { action: "tools", description: "List every non-MCP registry tool without schemas." },
2066
+ {
2067
+ action: "tool",
2068
+ description: "Read one tool with its full argument schema.",
2069
+ properties: { name: { type: "string" } },
2070
+ required: ["name"]
2071
+ },
2072
+ { action: "presets", description: "List Agent presets, the default, and the caller\u2019s current preset." }
2073
+ ]),
2074
+ output: { schema: {}, render: renderResult },
2075
+ async execute(rawArgs, exec) {
2076
+ return await runCatalogAction(ctx, argsRecord(rawArgs), exec);
2077
+ }
2078
+ },
2079
+ {
2080
+ name: "variable_manage",
2081
+ description: "Manage variables: named strings the MCP forms reference as `{{name}}`. Values live in the Harness credential store, never in the MCP settings file; an MCP entry stores `${credential:NAME}` and the client resolves it at connect time. Each variable carries separate human/model permissions, and the model default is read=no, write=yes, delete=no: `list` and `get` therefore return metadata plus a mask, while `create`/`update` may still store a value. `value` is optional on update and keeps the stored value; an empty string clears it.",
2082
+ parameters: actionSchema([
2083
+ { action: "list", description: "List variables with metadata, masks, and permissions." },
2084
+ {
2085
+ action: "get",
2086
+ description: "Read one variable; the value appears only when the model may read it.",
2087
+ properties: { name: { type: "string" } },
2088
+ required: ["name"]
2089
+ },
2090
+ {
2091
+ action: "create",
2092
+ description: "Create a variable and optionally store its value.",
2093
+ properties: {
2094
+ name: { type: "string", description: "POSIX identifier; also the {{name}} token." },
2095
+ label: { type: "string" },
2096
+ description: { type: "string" },
2097
+ value: { type: "string", description: "Secret value; omit to declare it without a value." },
2098
+ permissions: VARIABLE_PERMISSIONS_SCHEMA
2099
+ },
2100
+ required: ["name"]
2101
+ },
2102
+ {
2103
+ action: "update",
2104
+ description: "Update one variable; omitted fields keep their values.",
2105
+ properties: {
2106
+ name: { type: "string" },
2107
+ label: { type: "string" },
2108
+ description: { type: "string" },
2109
+ value: { type: "string", description: "New value; empty string clears it." },
2110
+ permissions: VARIABLE_PERMISSIONS_SCHEMA
2111
+ },
2112
+ required: ["name"]
2113
+ },
2114
+ {
2115
+ action: "delete",
2116
+ description: "Delete a variable and its stored value.",
2117
+ properties: { name: { type: "string" } },
2118
+ required: ["name"]
2119
+ }
2120
+ ]),
2121
+ output: { schema: {}, render: renderResult },
2122
+ async execute(rawArgs) {
2123
+ return await runVariableAction(ctx, argsRecord(rawArgs));
2124
+ }
2125
+ }
2126
+ ];
2127
+ }
2128
+
2129
+ // src/host/mcp-server.ts
2130
+ var SUPPORTED_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set(["2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"]);
2131
+ var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
2132
+ var SERVER_INFO = { name: SERVER_NAME, version: "0.1.0" };
2133
+ var MAX_BODY_BYTES = 4e6;
2134
+ var SSE_HEARTBEAT_MS = 25e3;
2135
+ function success(id, result) {
2136
+ return { jsonrpc: "2.0", id, result };
2137
+ }
2138
+ function failure(id, code, message) {
2139
+ return { jsonrpc: "2.0", id, error: { code, message } };
2140
+ }
2141
+ function isRecord(value) {
2142
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2143
+ }
2144
+ function isLoopback(address) {
2145
+ return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
2146
+ }
2147
+ function messageOf2(error) {
2148
+ return error instanceof Error ? error.message : String(error);
2149
+ }
2150
+ async function readBody(req) {
2151
+ const chunks = [];
2152
+ let size = 0;
2153
+ for await (const chunk of req) {
2154
+ const buffer = chunk;
2155
+ size += buffer.byteLength;
2156
+ if (size > MAX_BODY_BYTES) throw new Error("request body is too large");
2157
+ chunks.push(buffer);
2158
+ }
2159
+ return Buffer.concat(chunks, size).toString("utf8");
2160
+ }
2161
+ function sendJson(res, status, payload, headers = {}) {
2162
+ res.statusCode = status;
2163
+ res.setHeader("content-type", "application/json; charset=utf-8");
2164
+ res.setHeader("cache-control", "no-store");
2165
+ for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
2166
+ res.end(JSON.stringify(payload));
2167
+ }
2168
+ var ToolManagerMcpServer = class {
2169
+ constructor(ctx, policy) {
2170
+ this.ctx = ctx;
2171
+ this.tools = createToolManagerTools(ctx, policy);
2172
+ }
2173
+ ctx;
2174
+ server;
2175
+ token = randomBytes(18).toString("base64url");
2176
+ tools;
2177
+ streams = /* @__PURE__ */ new Set();
2178
+ protocolVersion = DEFAULT_PROTOCOL_VERSION;
2179
+ sessionId;
2180
+ /** The path the MCP client must use; it contains the per-process token. */
2181
+ get path() {
2182
+ return `/mcp/${this.token}`;
2183
+ }
2184
+ /** Start on a random loopback port; returns the URL registered with the manager. */
2185
+ async start() {
2186
+ if (this.server !== void 0) throw new Error("MCP server is already started");
2187
+ const server = createServer((req, res) => {
2188
+ void this.handle(req, res).catch((error) => {
2189
+ if (!res.headersSent) sendJson(res, 500, failure(null, -32603, messageOf2(error)));
2190
+ else res.end();
2191
+ });
2192
+ });
2193
+ this.server = server;
2194
+ await new Promise((resolve, reject) => {
2195
+ const onError = (error) => {
2196
+ server.off("listening", onListening);
2197
+ reject(error);
2198
+ };
2199
+ const onListening = () => {
2200
+ server.off("error", onError);
2201
+ resolve();
2202
+ };
2203
+ server.once("error", onError);
2204
+ server.once("listening", onListening);
2205
+ server.listen(0, "127.0.0.1");
2206
+ });
2207
+ const address = server.address();
2208
+ return { port: address.port, url: `http://127.0.0.1:${address.port}${this.path}` };
2209
+ }
2210
+ /** End open streams and close the listener. */
2211
+ async close() {
2212
+ for (const stream of this.streams) {
2213
+ try {
2214
+ stream.end();
2215
+ } catch {
2216
+ }
2217
+ }
2218
+ this.streams.clear();
2219
+ const server = this.server;
2220
+ this.server = void 0;
2221
+ if (server === void 0) return;
2222
+ await new Promise((resolve) => {
2223
+ server.close(() => resolve());
2224
+ server.closeAllConnections?.();
2225
+ });
2226
+ }
2227
+ /** Dispatch one HTTP request. */
2228
+ async handle(req, res) {
2229
+ if (!isLoopback(req.socket.remoteAddress)) {
2230
+ sendJson(res, 403, failure(null, -32e3, "loopback access only"));
2231
+ return;
2232
+ }
2233
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
2234
+ if (url.pathname !== this.path) {
2235
+ sendJson(res, 404, failure(null, -32e3, "not found"));
2236
+ return;
2237
+ }
2238
+ if (req.method === "GET") {
2239
+ this.openStream(req, res);
2240
+ return;
2241
+ }
2242
+ if (req.method === "DELETE") {
2243
+ res.statusCode = 405;
2244
+ res.setHeader("allow", "POST, GET, DELETE");
2245
+ res.end();
2246
+ return;
2247
+ }
2248
+ if (req.method !== "POST") {
2249
+ res.statusCode = 405;
2250
+ res.setHeader("allow", "POST, GET, DELETE");
2251
+ res.end();
2252
+ return;
2253
+ }
2254
+ const contentType = String(req.headers["content-type"] ?? "");
2255
+ if (!contentType.toLowerCase().includes("application/json")) {
2256
+ sendJson(res, 415, failure(null, -32e3, "content-type must be application/json"));
2257
+ return;
2258
+ }
2259
+ let payload;
2260
+ try {
2261
+ payload = JSON.parse(await readBody(req));
2262
+ } catch (error) {
2263
+ sendJson(res, 400, failure(null, -32700, messageOf2(error)));
2264
+ return;
2265
+ }
2266
+ const messages = Array.isArray(payload) ? payload : [payload];
2267
+ const controller = new AbortController();
2268
+ res.once("close", () => controller.abort());
2269
+ const responses = [];
2270
+ for (const message of messages) {
2271
+ const response = await this.handleMessage(message, controller.signal);
2272
+ if (response !== void 0) responses.push(response);
2273
+ }
2274
+ if (responses.length === 0) {
2275
+ res.statusCode = 202;
2276
+ res.end();
2277
+ return;
2278
+ }
2279
+ const headers = { "mcp-protocol-version": this.protocolVersion };
2280
+ if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId;
2281
+ sendJson(res, 200, Array.isArray(payload) ? responses : responses[0], headers);
2282
+ }
2283
+ /** Keep a Streamable HTTP GET channel open for server-initiated messages. */
2284
+ openStream(req, res) {
2285
+ res.writeHead(200, {
2286
+ "content-type": "text/event-stream",
2287
+ "cache-control": "no-store",
2288
+ connection: "keep-alive"
2289
+ });
2290
+ res.write(": connected\n\n");
2291
+ this.streams.add(res);
2292
+ const timer = setInterval(() => {
2293
+ if (!res.writableEnded) res.write(": ping\n\n");
2294
+ }, SSE_HEARTBEAT_MS);
2295
+ timer.unref?.();
2296
+ req.once("close", () => {
2297
+ clearInterval(timer);
2298
+ this.streams.delete(res);
2299
+ try {
2300
+ res.end();
2301
+ } catch {
2302
+ }
2303
+ });
2304
+ }
2305
+ /** Answer one JSON-RPC message; notifications produce no response. */
2306
+ async handleMessage(message, signal) {
2307
+ if (!isRecord(message)) return failure(null, -32600, "invalid request");
2308
+ const request = message;
2309
+ const { id, method } = request;
2310
+ if (typeof method !== "string") return void 0;
2311
+ if (id === void 0) {
2312
+ return void 0;
2313
+ }
2314
+ if (method === "initialize") return this.initialize(id, request.params);
2315
+ if (method === "ping") return success(id, {});
2316
+ if (method === "tools/list") return success(id, { tools: this.toolList() });
2317
+ if (method === "tools/call") return await this.callTool(id, request.params, signal);
2318
+ if (method === "resources/list") return success(id, { resources: [] });
2319
+ if (method === "resources/templates/list") return success(id, { resourceTemplates: [] });
2320
+ if (method === "prompts/list") return success(id, { prompts: [] });
2321
+ return failure(id, -32601, `method not found: ${method}`);
2322
+ }
2323
+ /** Answer the MCP handshake and retain the negotiated protocol version. */
2324
+ initialize(id, params) {
2325
+ const offered = isRecord(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : "";
2326
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.has(offered) ? offered : DEFAULT_PROTOCOL_VERSION;
2327
+ this.protocolVersion = protocolVersion;
2328
+ this.sessionId = randomBytes(18).toString("base64url");
2329
+ return success(id, {
2330
+ protocolVersion,
2331
+ capabilities: { tools: {} },
2332
+ serverInfo: SERVER_INFO,
2333
+ instructions: "Manage this DeepSeek Harness profile: MCP servers, Agent Skill files and scan roots, per-preset visibility/injection policy, and read-only tool/preset catalogs."
2334
+ });
2335
+ }
2336
+ /** Project the management tools onto the MCP tools/list shape. */
2337
+ toolList() {
2338
+ return this.tools.map((tool) => ({
2339
+ name: tool.name,
2340
+ description: tool.description,
2341
+ inputSchema: tool.parameters
2342
+ }));
2343
+ }
2344
+ /** Execute one management tool and map its result to MCP content. */
2345
+ async callTool(id, params, signal) {
2346
+ if (!isRecord(params) || typeof params["name"] !== "string") {
2347
+ return failure(id, -32602, "tools/call requires a tool name");
2348
+ }
2349
+ const name = params["name"];
2350
+ const tool = this.tools.find((candidate) => candidate.name === name);
2351
+ if (tool === void 0) return failure(id, -32602, `unknown tool: ${name}`);
2352
+ const args = params["arguments"] === void 0 ? {} : params["arguments"];
2353
+ try {
2354
+ const value = await tool.execute(args, { signal });
2355
+ const content = tool.output.render(args, value).map((block) => ({ type: "text", text: block.text }));
2356
+ return success(id, { content });
2357
+ } catch (error) {
2358
+ const failure2 = error instanceof ToolError ? { ok: false, error: { code: error.code, message: error.message } } : { ok: false, error: { code: "internal", message: messageOf2(error) } };
2359
+ return success(id, { content: [{ type: "text", text: JSON.stringify(failure2) }], isError: true });
2360
+ }
2361
+ }
2362
+ };
2363
+ function attachMcpServer(ctx, policy) {
2364
+ ctx.inject(["mcpManager"], (child) => {
2365
+ const manager = child.mcpManager;
2366
+ if (manager === void 0 || typeof manager.register !== "function") return;
2367
+ const server = new ToolManagerMcpServer(ctx, policy);
2368
+ let disposeRegistration;
2369
+ let disposed = false;
2370
+ child.effect(
2371
+ () => () => {
2372
+ disposed = true;
2373
+ try {
2374
+ disposeRegistration?.();
2375
+ } catch {
2376
+ }
2377
+ void server.close();
2378
+ },
2379
+ "dsh-tool-manage: MCP server"
2380
+ );
2381
+ void server.start().then(({ url }) => {
2382
+ if (disposed) {
2383
+ void server.close();
2384
+ return;
2385
+ }
2386
+ let lastError;
2387
+ for (const name of [SERVER_NAME, `${SERVER_NAME}-local`]) {
2388
+ try {
2389
+ disposeRegistration = manager.register(name, {
2390
+ transport: "streamable-http",
2391
+ url,
2392
+ startupTimeoutMs: 1e4,
2393
+ toolLoading: "eager"
2394
+ });
2395
+ return;
2396
+ } catch (error) {
2397
+ lastError = error;
2398
+ }
2399
+ }
2400
+ ctx.logger?.warn(`dsh-tool-manage: could not register its MCP server: ${String(lastError)}`);
2401
+ void server.close();
2402
+ }).catch((error) => {
2403
+ ctx.logger?.warn(`dsh-tool-manage: could not start its MCP server: ${messageOf2(error)}`);
2404
+ void server.close();
2405
+ });
2406
+ });
2407
+ }
2408
+
2409
+ // src/host/policy.ts
2410
+ import { mkdir as mkdir4, readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
2411
+ import { homedir as homedir5 } from "os";
2412
+ import { dirname as dirname4 } from "path";
2413
+ var POLICY_VERSION = 5;
2414
+ var PRESET_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/;
2415
+ var MAX_PRESETS = 200;
2416
+ var MAX_MCP_SERVERS = 200;
2417
+ var SKILL_INJECTION_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2418
+ var MAX_ICON_CODE_POINTS = 8;
2419
+ var IMMUTABLE_TOOLS = /* @__PURE__ */ new Set(["run_code"]);
2420
+ function policyPath(environment = process.env, home = homedir5()) {
2421
+ return statePath("policy.json", environment, home);
2422
+ }
2423
+ function emptyPolicy() {
2424
+ return { version: POLICY_VERSION, mcp: {}, skillInjection: {}, icons: {} };
2425
+ }
2426
+ function normalizeMcpInjection(raw) {
2427
+ if (raw === void 0 || raw === null) return {};
2428
+ if (typeof raw !== "object" || Array.isArray(raw)) throw new Error('policy: "mcp" must be an object');
2429
+ const entries = Object.entries(raw);
2430
+ if (entries.length > MAX_MCP_SERVERS) throw new Error("policy: too many MCP servers");
2431
+ const out = {};
2432
+ for (const [server, value] of entries) {
2433
+ if (!MCP_SERVER_NAME.test(server)) throw new Error(`policy: invalid MCP server name "${server}"`);
2434
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2435
+ throw new Error(`policy: MCP server "${server}" must be an object`);
2436
+ }
2437
+ const record = value;
2438
+ const fallback = record["default"];
2439
+ if (fallback !== void 0 && typeof fallback !== "boolean") {
2440
+ throw new Error(`policy: MCP server "${server}" default must be a boolean`);
2441
+ }
2442
+ const presets = {};
2443
+ const rawPresets = record["presets"];
2444
+ if (rawPresets !== void 0 && rawPresets !== null) {
2445
+ if (typeof rawPresets !== "object" || Array.isArray(rawPresets)) {
2446
+ throw new Error(`policy: MCP server "${server}" presets must be an object`);
2447
+ }
2448
+ const presetEntries = Object.entries(rawPresets);
2449
+ if (presetEntries.length > MAX_PRESETS) throw new Error(`policy: MCP server "${server}" has too many presets`);
2450
+ for (const [presetId, enabled] of presetEntries) {
2451
+ if (!PRESET_ID_PATTERN.test(presetId)) {
2452
+ throw new Error(`policy: invalid preset id "${presetId}" on MCP server "${server}"`);
2453
+ }
2454
+ if (typeof enabled !== "boolean") {
2455
+ throw new Error(`policy: MCP server "${server}" preset "${presetId}" must be a boolean`);
2456
+ }
2457
+ presets[presetId] = enabled;
2458
+ }
2459
+ }
2460
+ out[server] = { default: fallback ?? true, presets };
2461
+ }
2462
+ return out;
2463
+ }
2464
+ function normalizeIcons(raw) {
2465
+ if (raw === void 0 || raw === null) return {};
2466
+ if (typeof raw !== "object" || Array.isArray(raw)) throw new Error('policy: "icons" must be an object');
2467
+ const entries = Object.entries(raw);
2468
+ if (entries.length > MAX_MCP_SERVERS) throw new Error("policy: too many MCP icons");
2469
+ const out = {};
2470
+ for (const [server, value] of entries) {
2471
+ if (!MCP_SERVER_NAME.test(server)) throw new Error(`policy: invalid MCP server name "${server}"`);
2472
+ if (typeof value !== "string") throw new Error(`policy: MCP icon "${server}" must be a string`);
2473
+ const glyph = value.trim();
2474
+ if (glyph === "") continue;
2475
+ if (Array.from(glyph).length > MAX_ICON_CODE_POINTS) {
2476
+ throw new Error(`policy: MCP icon "${server}" is too long`);
2477
+ }
2478
+ out[server] = glyph;
2479
+ }
2480
+ return out;
2481
+ }
2482
+ function normalizeSkillInjection(raw) {
2483
+ if (raw === void 0 || raw === null) return {};
2484
+ if (typeof raw !== "object" || Array.isArray(raw)) throw new Error('policy: "skillInjection" must be an object');
2485
+ const entries = Object.entries(raw);
2486
+ if (entries.length > MAX_MCP_SERVERS) throw new Error("policy: too many skill injection rules");
2487
+ const out = {};
2488
+ for (const [skill, value] of entries) {
2489
+ if (!SKILL_INJECTION_NAME.test(skill)) throw new Error(`policy: invalid skill name "${skill}"`);
2490
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2491
+ throw new Error(`policy: skill "${skill}" must be an object`);
2492
+ }
2493
+ const record = value;
2494
+ const fallback = record["default"];
2495
+ if (fallback !== void 0 && typeof fallback !== "boolean") {
2496
+ throw new Error(`policy: skill "${skill}" default must be a boolean`);
2497
+ }
2498
+ const presets = {};
2499
+ const rawPresets = record["presets"];
2500
+ if (rawPresets !== void 0 && rawPresets !== null) {
2501
+ if (typeof rawPresets !== "object" || Array.isArray(rawPresets)) {
2502
+ throw new Error(`policy: skill "${skill}" presets must be an object`);
2503
+ }
2504
+ for (const [presetId, enabled] of Object.entries(rawPresets)) {
2505
+ if (!PRESET_ID_PATTERN.test(presetId))
2506
+ throw new Error(`policy: invalid preset id "${presetId}" on skill "${skill}"`);
2507
+ if (typeof enabled !== "boolean")
2508
+ throw new Error(`policy: skill "${skill}" preset "${presetId}" must be a boolean`);
2509
+ presets[presetId] = enabled;
2510
+ }
2511
+ }
2512
+ out[skill] = { default: fallback ?? true, presets };
2513
+ }
2514
+ return out;
2515
+ }
2516
+ function normalizePolicy(input) {
2517
+ if (typeof input !== "object" || input === null) throw new Error("policy: expected an object");
2518
+ const record = input;
2519
+ const version = record["version"] ?? POLICY_VERSION;
2520
+ if (version !== 1 && version !== 3 && version !== 4 && version !== POLICY_VERSION) {
2521
+ throw new Error(`policy: unsupported version ${String(version)}`);
2522
+ }
2523
+ const carriesInjection = version === 4 || version === POLICY_VERSION;
2524
+ const mcp = carriesInjection ? normalizeMcpInjection(record["mcp"]) : {};
2525
+ const skillInjection = carriesInjection ? normalizeSkillInjection(record["skillInjection"]) : {};
2526
+ const icons = carriesInjection ? normalizeIcons(record["icons"]) : {};
2527
+ const legacyRule = mcp[LEGACY_SERVER_NAME];
2528
+ if (legacyRule !== void 0 && mcp[SERVER_NAME] === void 0) {
2529
+ mcp[SERVER_NAME] = legacyRule;
2530
+ delete mcp[LEGACY_SERVER_NAME];
2531
+ }
2532
+ const legacyIcon = icons[LEGACY_SERVER_NAME];
2533
+ if (legacyIcon !== void 0 && icons[SERVER_NAME] === void 0) {
2534
+ icons[SERVER_NAME] = legacyIcon;
2535
+ delete icons[LEGACY_SERVER_NAME];
2536
+ }
2537
+ return { version: POLICY_VERSION, mcp, skillInjection, icons };
2538
+ }
2539
+ function mcpInjectionDenied(policy, presetId, name) {
2540
+ if (presetId === void 0) return false;
2541
+ let hit;
2542
+ for (const [server, rule] of Object.entries(policy.mcp)) {
2543
+ if (!name.startsWith(`mcp__${server}__`)) continue;
2544
+ if (hit === void 0 || server.length > hit.server.length) hit = { server, rule };
2545
+ }
2546
+ if (hit === void 0) return false;
2547
+ return (hit.rule.presets[presetId] ?? hit.rule.default) === false;
2548
+ }
2549
+ function compileToolDeny(policy, presetId, toolNames) {
2550
+ return toolNames.filter((name) => !IMMUTABLE_TOOLS.has(name) && mcpInjectionDenied(policy, presetId, name)).sort();
2551
+ }
2552
+ function compileSkillHides(policy, presetId, skills) {
2553
+ return skills.filter((skill) => {
2554
+ if (presetId === void 0) return false;
2555
+ const rule = policy.skillInjection[skill.name];
2556
+ return rule !== void 0 && (rule.presets[presetId] ?? rule.default) === false;
2557
+ }).map((skill) => ({
2558
+ name: skill.name,
2559
+ description: skill.description,
2560
+ source: "runtime",
2561
+ modelInvocable: true
2562
+ })).sort((a, b) => a.name.localeCompare(b.name));
2563
+ }
2564
+ var McpPolicyController = class {
2565
+ constructor(host, path) {
2566
+ this.host = host;
2567
+ this.path = path;
2568
+ }
2569
+ host;
2570
+ path;
2571
+ policy = emptyPolicy();
2572
+ toolMasks = /* @__PURE__ */ new Map();
2573
+ toolSignatures = /* @__PURE__ */ new Map();
2574
+ skillMasks = /* @__PURE__ */ new Map();
2575
+ skillSignatures = /* @__PURE__ */ new Map();
2576
+ timer;
2577
+ defaultId;
2578
+ /** Load the document and start watching agents, presets, tools, and skills. */
2579
+ async start() {
2580
+ try {
2581
+ this.policy = normalizePolicy(JSON.parse(await readFile4(this.path, "utf8")));
2582
+ } catch {
2583
+ this.policy = emptyPolicy();
2584
+ }
2585
+ try {
2586
+ const presets = this.host.get("agentPresets");
2587
+ this.defaultId = presets?.defaultId;
2588
+ } catch {
2589
+ this.defaultId = void 0;
2590
+ }
2591
+ this.host.on("agent/created", (...args) => {
2592
+ const agent = args[0]?.agent;
2593
+ if (agent !== void 0) this.applyAgent(agent);
2594
+ });
2595
+ this.host.on("agent/disposed", (...args) => {
2596
+ const id = args[0]?.agent.id;
2597
+ if (id !== void 0) this.release(id);
2598
+ });
2599
+ this.host.on("agent-preset/selected", (...args) => {
2600
+ const sessionId = typeof args[0] === "string" ? args[0] : void 0;
2601
+ if (sessionId === void 0) return;
2602
+ const agent = this.agentById(sessionId);
2603
+ if (agent !== void 0) this.applyAgent(agent);
2604
+ });
2605
+ this.host.on("tools/change", () => this.schedule());
2606
+ this.host.on("skills/change", () => this.schedule());
2607
+ this.applyAll();
2608
+ }
2609
+ /** The current document, for the panel. */
2610
+ current() {
2611
+ return this.policy;
2612
+ }
2613
+ /** Persist a complete document and re-apply it to every live Agent. */
2614
+ async save(input) {
2615
+ const next = normalizePolicy(input);
2616
+ await mkdir4(dirname4(this.path), { recursive: true });
2617
+ await writeFile4(this.path, `${JSON.stringify(next, null, 2)}
2618
+ `, "utf8");
2619
+ this.policy = next;
2620
+ this.applyAll();
2621
+ return this.policy;
2622
+ }
2623
+ /** Stop the debounce timer (the Host owns the rest through effect scopes). */
2624
+ dispose() {
2625
+ if (this.timer !== void 0) clearTimeout(this.timer);
2626
+ this.timer = void 0;
2627
+ for (const id of [...this.toolMasks.keys()]) this.release(id);
2628
+ }
2629
+ schedule() {
2630
+ if (this.timer !== void 0) return;
2631
+ this.timer = setTimeout(() => {
2632
+ this.timer = void 0;
2633
+ this.applyAll();
2634
+ }, 40);
2635
+ this.timer.unref?.();
2636
+ }
2637
+ agentById(sessionId) {
2638
+ try {
2639
+ const agents = this.host.get("agents")?.list() ?? [];
2640
+ return agents.find((agent) => agent.id === sessionId);
2641
+ } catch {
2642
+ return void 0;
2643
+ }
2644
+ }
2645
+ /**
2646
+ * The preset the Agent currently runs under. A Session's creation header is
2647
+ * only the initial fact: a switch writes `agent-preset/selected`, which the
2648
+ * presets registry projects. Read that projection first.
2649
+ */
2650
+ presetOf(agent) {
2651
+ try {
2652
+ const presets = this.host.get("agentPresets");
2653
+ const selected = presets?.presetForSession?.(agent.session);
2654
+ if (typeof selected === "string" && selected !== "") return selected;
2655
+ } catch {
2656
+ }
2657
+ return agent.session.header.agentPreset;
2658
+ }
2659
+ globalToolNames() {
2660
+ try {
2661
+ const tools = this.host.get("tools");
2662
+ return (tools?.definitions() ?? []).map((definition) => definition.name);
2663
+ } catch {
2664
+ return [];
2665
+ }
2666
+ }
2667
+ applyAll() {
2668
+ const live = /* @__PURE__ */ new Set();
2669
+ let agents = [];
2670
+ try {
2671
+ agents = this.host.get("agents")?.list() ?? [];
2672
+ } catch {
2673
+ agents = [];
2674
+ }
2675
+ for (const agent of agents) {
2676
+ live.add(agent.id);
2677
+ this.applyAgent(agent);
2678
+ }
2679
+ for (const id of [...this.toolMasks.keys()]) {
2680
+ if (!live.has(id)) this.release(id);
2681
+ }
2682
+ for (const id of [...this.skillMasks.keys()]) {
2683
+ if (!live.has(id)) this.release(id);
2684
+ }
2685
+ }
2686
+ applyAgent(agent) {
2687
+ const preset = this.presetOf(agent) ?? this.defaultId;
2688
+ this.applyTools(agent, preset);
2689
+ void this.applySkills(agent, preset).catch(() => {
2690
+ });
2691
+ }
2692
+ applyTools(agent, preset) {
2693
+ const deny = compileToolDeny(this.policy, preset, this.globalToolNames());
2694
+ const signature = deny.join("\n");
2695
+ if (this.toolSignatures.get(agent.id) === signature) return;
2696
+ this.releaseTools(agent.id);
2697
+ this.toolSignatures.set(agent.id, signature);
2698
+ if (deny.length === 0) return;
2699
+ try {
2700
+ const dispose = agent.ctx.tools?.restrict({ deny });
2701
+ if (dispose !== void 0) this.toolMasks.set(agent.id, dispose);
2702
+ } catch {
2703
+ }
2704
+ }
2705
+ async applySkills(agent, preset) {
2706
+ const skills = agent.ctx.skills;
2707
+ if (skills === void 0) return;
2708
+ let visible = [];
2709
+ try {
2710
+ visible = await skills.list({ scope: agent, cwd: process.cwd() });
2711
+ } catch {
2712
+ return;
2713
+ }
2714
+ const hidden = compileSkillHides(this.policy, preset, visible);
2715
+ const signature = hidden.map((skill) => skill.name).join("\n");
2716
+ if (this.skillSignatures.get(agent.id) === signature) return;
2717
+ this.releaseSkills(agent.id);
2718
+ this.skillSignatures.set(agent.id, signature);
2719
+ const disposers = [];
2720
+ for (const skill of hidden) {
2721
+ try {
2722
+ const dispose = skills.register({
2723
+ name: skill.name,
2724
+ description: skill.description || "Hidden by the tool manager.",
2725
+ content: "",
2726
+ source: "runtime",
2727
+ invocation: { modelInvocable: false, userInvocable: false }
2728
+ });
2729
+ disposers.push(dispose);
2730
+ } catch {
2731
+ }
2732
+ }
2733
+ if (disposers.length > 0) this.skillMasks.set(agent.id, disposers);
2734
+ }
2735
+ release(id) {
2736
+ this.releaseTools(id);
2737
+ this.releaseSkills(id);
2738
+ this.toolSignatures.delete(id);
2739
+ this.skillSignatures.delete(id);
2740
+ }
2741
+ releaseTools(id) {
2742
+ const dispose = this.toolMasks.get(id);
2743
+ this.toolMasks.delete(id);
2744
+ if (dispose === void 0) return;
2745
+ try {
2746
+ dispose();
2747
+ } catch {
2748
+ }
2749
+ }
2750
+ releaseSkills(id) {
2751
+ const disposers = this.skillMasks.get(id);
2752
+ this.skillMasks.delete(id);
2753
+ if (disposers === void 0) return;
2754
+ for (const dispose of disposers) {
2755
+ try {
2756
+ dispose();
2757
+ } catch {
2758
+ }
2759
+ }
2760
+ }
2761
+ };
2762
+
2763
+ // src/host/routes.ts
2764
+ var BASE = `/${ROUTE_BASE}`;
2765
+ var SKILLS_PATH = `${BASE}/skills`;
2766
+ var SKILL_READ_PATH = `${BASE}/skill/read`;
2767
+ var SKILL_RESOURCE_PATH = `${BASE}/skill/resource`;
2768
+ var SKILL_ROOTS_PATH = `${BASE}/skill/roots`;
2769
+ var SKILL_SAVE_PATH = `${BASE}/skill/save`;
2770
+ var SKILL_CREATE_PATH = `${BASE}/skill/create`;
2771
+ var SKILL_DELETE_PATH = `${BASE}/skill/delete`;
2772
+ var MCP_TOOLS_PATH = `${BASE}/mcp/tools`;
2773
+ var PRESETS_PATH = `${BASE}/presets`;
2774
+ var POLICY_PATH = `${BASE}/policy`;
2775
+ var OTHER_TOOLS_PATH = `${BASE}/tools`;
2776
+ var VARIABLES_PATH = `${BASE}/variables`;
2777
+ var VARIABLE_SAVE_PATH = `${BASE}/variable/save`;
2778
+ var VARIABLE_DELETE_PATH = `${BASE}/variable/delete`;
2779
+ var MAX_BODY_BYTES2 = 4e6;
2780
+ function sendJson2(res, status, payload) {
2781
+ res.statusCode = status;
2782
+ res.setHeader("content-type", "application/json; charset=utf-8");
2783
+ res.setHeader("cache-control", "no-store");
2784
+ res.end(JSON.stringify(payload));
2785
+ }
2786
+ async function readJson(req) {
2787
+ const chunks = [];
2788
+ let size = 0;
2789
+ for await (const chunk of req) {
2790
+ const buffer = chunk;
2791
+ size += buffer.byteLength;
2792
+ if (size > MAX_BODY_BYTES2) {
2793
+ req.resume();
2794
+ return void 0;
2795
+ }
2796
+ chunks.push(buffer);
2797
+ }
2798
+ if (size === 0) return void 0;
2799
+ try {
2800
+ return JSON.parse(Buffer.concat(chunks, size).toString("utf8"));
2801
+ } catch {
2802
+ return void 0;
2803
+ }
2804
+ }
2805
+ function messageOf3(error) {
2806
+ return error instanceof Error ? error.message : String(error);
2807
+ }
2808
+ function stringOf(body, key) {
2809
+ if (typeof body !== "object" || body === null) return void 0;
2810
+ const value = Reflect.get(body, key);
2811
+ return typeof value === "string" ? value : void 0;
2812
+ }
2813
+ function attachToolManagerRoutes(ctx, policy) {
2814
+ ctx.inject(["webServer"], (child) => {
2815
+ const register = (path, handler) => {
2816
+ child.effect(
2817
+ () => child.webServer.register({
2818
+ kind: "exact",
2819
+ path,
2820
+ auth: "required",
2821
+ handler: async (req, res) => {
2822
+ try {
2823
+ await handler(req, res);
2824
+ } catch (error) {
2825
+ sendJson2(res, 400, { ok: false, error: messageOf3(error) });
2826
+ }
2827
+ }
2828
+ }),
2829
+ `dsh-tool-manage: ${path}`
2830
+ );
2831
+ };
2832
+ const requirePost = (req, res) => {
2833
+ if (req.method === "POST") return true;
2834
+ res.statusCode = 405;
2835
+ res.setHeader("allow", "POST");
2836
+ res.end();
2837
+ return false;
2838
+ };
2839
+ const requireGet = (req, res) => {
2840
+ if (req.method === "GET") return true;
2841
+ res.statusCode = 405;
2842
+ res.setHeader("allow", "GET");
2843
+ res.end();
2844
+ return false;
2845
+ };
2846
+ register(SKILLS_PATH, async (req, res) => {
2847
+ if (!requireGet(req, res)) return;
2848
+ const roots = await allSkillRoots();
2849
+ sendJson2(res, 200, { ok: true, ...await listSkills(skillRegistryOf(ctx), roots) });
2850
+ });
2851
+ register(SKILL_ROOTS_PATH, async (req, res) => {
2852
+ if (req.method === "GET") {
2853
+ const roots = await allSkillRoots();
2854
+ sendJson2(res, 200, {
2855
+ ok: true,
2856
+ roots,
2857
+ directories: roots.filter((root) => root.custom === true).map((root) => root.path)
2858
+ });
2859
+ return;
2860
+ }
2861
+ if (req.method !== "POST") {
2862
+ res.statusCode = 405;
2863
+ res.setHeader("allow", "GET, POST");
2864
+ res.end();
2865
+ return;
2866
+ }
2867
+ const body = await readJson(req);
2868
+ const directories = typeof body === "object" && body !== null ? Reflect.get(body, "directories") : void 0;
2869
+ await saveCustomSkillDirectories(directories);
2870
+ sendJson2(res, 200, { ok: true, roots: await allSkillRoots() });
2871
+ });
2872
+ register(SKILL_RESOURCE_PATH, async (req, res) => {
2873
+ if (!requirePost(req, res)) return;
2874
+ const body = await readJson(req);
2875
+ const path = stringOf(body, "path");
2876
+ const resource = stringOf(body, "resource");
2877
+ if (path === void 0 || resource === void 0) {
2878
+ sendJson2(res, 400, { ok: false, error: "\u7F3A\u5C11 path / resource" });
2879
+ return;
2880
+ }
2881
+ sendJson2(res, 200, {
2882
+ ok: true,
2883
+ resource: await readSkillResource(skillRegistryOf(ctx), path, resource, await allSkillRoots())
2884
+ });
2885
+ });
2886
+ register(SKILL_READ_PATH, async (req, res) => {
2887
+ if (!requirePost(req, res)) return;
2888
+ const body = await readJson(req);
2889
+ const path = stringOf(body, "path");
2890
+ if (path === void 0) {
2891
+ sendJson2(res, 400, { ok: false, error: "\u7F3A\u5C11 path" });
2892
+ return;
2893
+ }
2894
+ sendJson2(res, 200, {
2895
+ ok: true,
2896
+ skill: await readSkillDocument(skillRegistryOf(ctx), path, await allSkillRoots())
2897
+ });
2898
+ });
2899
+ register(SKILL_SAVE_PATH, async (req, res) => {
2900
+ if (!requirePost(req, res)) return;
2901
+ const body = await readJson(req);
2902
+ if (typeof body !== "object" || body === null) {
2903
+ sendJson2(res, 400, { ok: false, error: "\u8BF7\u6C42\u4F53\u65E0\u6548" });
2904
+ return;
2905
+ }
2906
+ const path = stringOf(body, "path");
2907
+ if (path === void 0) {
2908
+ sendJson2(res, 400, { ok: false, error: "\u7F3A\u5C11 path" });
2909
+ return;
2910
+ }
2911
+ const content = stringOf(body, "content");
2912
+ const fields = Reflect.get(body, "fields");
2913
+ const bodyText = stringOf(body, "body");
2914
+ const skill = await saveSkillDocument(
2915
+ skillRegistryOf(ctx),
2916
+ fields === void 0 ? { path, ...content === void 0 ? {} : { content } } : {
2917
+ path,
2918
+ fields,
2919
+ body: bodyText ?? ""
2920
+ },
2921
+ await allSkillRoots()
2922
+ );
2923
+ sendJson2(res, 200, { ok: true, skill });
2924
+ });
2925
+ register(SKILL_CREATE_PATH, async (req, res) => {
2926
+ if (!requirePost(req, res)) return;
2927
+ const body = await readJson(req);
2928
+ if (typeof body !== "object" || body === null) {
2929
+ sendJson2(res, 400, { ok: false, error: "\u8BF7\u6C42\u4F53\u65E0\u6548" });
2930
+ return;
2931
+ }
2932
+ const rootKey = stringOf(body, "rootKey");
2933
+ const name = stringOf(body, "name");
2934
+ const description = stringOf(body, "description");
2935
+ if (rootKey === void 0 || name === void 0 || description === void 0) {
2936
+ sendJson2(res, 400, { ok: false, error: "\u7F3A\u5C11 rootKey / name / description" });
2937
+ return;
2938
+ }
2939
+ const whenToUse = stringOf(body, "whenToUse");
2940
+ const bodyText = stringOf(body, "body");
2941
+ const skill = await createSkillDocument(
2942
+ skillRegistryOf(ctx),
2943
+ {
2944
+ rootKey,
2945
+ name,
2946
+ description,
2947
+ ...whenToUse === void 0 ? {} : { whenToUse },
2948
+ ...bodyText === void 0 ? {} : { body: bodyText },
2949
+ disableModelInvocation: Reflect.get(body, "disableModelInvocation") === true,
2950
+ userInvocable: Reflect.get(body, "userInvocable") !== false
2951
+ },
2952
+ await allSkillRoots()
2953
+ );
2954
+ sendJson2(res, 200, { ok: true, skill });
2955
+ });
2956
+ register(SKILL_DELETE_PATH, async (req, res) => {
2957
+ if (!requirePost(req, res)) return;
2958
+ const body = await readJson(req);
2959
+ const path = stringOf(body, "path");
2960
+ if (path === void 0) {
2961
+ sendJson2(res, 400, { ok: false, error: "\u7F3A\u5C11 path" });
2962
+ return;
2963
+ }
2964
+ await deleteSkillDocument(path, await allSkillRoots());
2965
+ sendJson2(res, 200, { ok: true });
2966
+ });
2967
+ register(VARIABLES_PATH, async (req, res) => {
2968
+ if (!requireGet(req, res)) return;
2969
+ sendJson2(res, 200, { ok: true, ...await listVariables(ctx, "human") });
2970
+ });
2971
+ register(VARIABLE_SAVE_PATH, async (req, res) => {
2972
+ if (!requirePost(req, res)) return;
2973
+ const body = await readJson(req);
2974
+ const name = stringOf(body, "name");
2975
+ if (name === void 0) {
2976
+ sendJson2(res, 400, { ok: false, error: "\u7F3A\u5C11 name" });
2977
+ return;
2978
+ }
2979
+ const record = typeof body === "object" && body !== null ? body : {};
2980
+ const variable = await saveVariable(
2981
+ ctx,
2982
+ {
2983
+ name,
2984
+ ...stringOf(body, "label") === void 0 ? {} : { label: stringOf(body, "label") },
2985
+ ...stringOf(body, "description") === void 0 ? {} : { description: stringOf(body, "description") },
2986
+ ...stringOf(body, "value") === void 0 ? {} : { value: stringOf(body, "value") },
2987
+ ...record["permissions"] === void 0 ? {} : { permissions: record["permissions"] }
2988
+ },
2989
+ "human"
2990
+ );
2991
+ sendJson2(res, 200, { ok: true, variable });
2992
+ });
2993
+ register(VARIABLE_DELETE_PATH, async (req, res) => {
2994
+ if (!requirePost(req, res)) return;
2995
+ const body = await readJson(req);
2996
+ const name = stringOf(body, "name");
2997
+ if (name === void 0) {
2998
+ sendJson2(res, 400, { ok: false, error: "\u7F3A\u5C11 name" });
2999
+ return;
3000
+ }
3001
+ await deleteVariable(ctx, name, "human");
3002
+ sendJson2(res, 200, { ok: true });
3003
+ });
3004
+ register(PRESETS_PATH, async (req, res) => {
3005
+ if (!requireGet(req, res)) return;
3006
+ const presets = ctx.get("agentPresets");
3007
+ const list = await presets?.list() ?? [];
3008
+ const defaultId = presets?.defaultId;
3009
+ sendJson2(res, 200, {
3010
+ ok: true,
3011
+ presets: list.map((preset) => ({ ...preset, isDefault: preset.id === defaultId })),
3012
+ ...defaultId === void 0 ? {} : { defaultId }
3013
+ });
3014
+ });
3015
+ register(POLICY_PATH, async (req, res) => {
3016
+ if (req.method === "GET") {
3017
+ sendJson2(res, 200, { ok: true, policy: policy.current() });
3018
+ return;
3019
+ }
3020
+ if (req.method !== "PUT") {
3021
+ res.statusCode = 405;
3022
+ res.setHeader("allow", "GET, PUT");
3023
+ res.end();
3024
+ return;
3025
+ }
3026
+ const body = await readJson(req);
3027
+ if (typeof body !== "object" || body === null) {
3028
+ sendJson2(res, 400, { ok: false, error: "\u8BF7\u6C42\u4F53\u65E0\u6548" });
3029
+ return;
3030
+ }
3031
+ sendJson2(res, 200, { ok: true, policy: await policy.save(Reflect.get(body, "policy")) });
3032
+ });
3033
+ register(MCP_TOOLS_PATH, async (req, res) => {
3034
+ if (!requireGet(req, res)) return;
3035
+ const value = ctx.get("tools");
3036
+ const tools = typeof value === "object" && value !== null && typeof Reflect.get(value, "definitions") === "function" ? value : void 0;
3037
+ sendJson2(res, 200, { ok: true, ...groupMcpTools(tools?.definitions() ?? []) });
3038
+ });
3039
+ register(OTHER_TOOLS_PATH, async (req, res) => {
3040
+ if (!requireGet(req, res)) return;
3041
+ const { tools, warnings } = collectOtherTools(ctx);
3042
+ sendJson2(res, 200, { ok: true, tools, warnings });
3043
+ });
3044
+ });
3045
+ }
3046
+
3047
+ // src/host/index.ts
3048
+ function apply(ctx) {
3049
+ const policy = new McpPolicyController(ctx, policyPath());
3050
+ ctx.effect(() => () => policy.dispose(), "dsh-tool-manage: policy controller");
3051
+ void policy.start().catch((error) => {
3052
+ ctx.logger?.warn(`dsh-tool-manage: policy controller failed to start: ${String(error)}`);
3053
+ });
3054
+ attachToolManagerRoutes(ctx, policy);
3055
+ attachMcpServer(ctx, policy);
3056
+ }
3057
+ export {
3058
+ McpPolicyController,
3059
+ POLICY_VERSION,
3060
+ ToolManagerMcpServer,
3061
+ apply,
3062
+ applySkillFields,
3063
+ attachMcpServer,
3064
+ collectOtherTools,
3065
+ compileSkillHides,
3066
+ compileToolDeny,
3067
+ createSkillContent,
3068
+ createSkillDocument,
3069
+ createToolManagerTools,
3070
+ defaultMcpEntry,
3071
+ defaultPermissions,
3072
+ defaultSkillRoots,
3073
+ deleteSkillDocument,
3074
+ deleteVariable,
3075
+ dshHome,
3076
+ emptyPolicy,
3077
+ entryToNative,
3078
+ entryToSugar,
3079
+ findMcpEntry,
3080
+ getVariable,
3081
+ groupMcpTools,
3082
+ isInside,
3083
+ isVariableName,
3084
+ listLocalSkills,
3085
+ listMcpServers,
3086
+ listSkills,
3087
+ listVariables,
3088
+ mcpToolName,
3089
+ mergeMcpEntry,
3090
+ normalizeMcpEntry,
3091
+ normalizePolicy,
3092
+ parseSkillDocument,
3093
+ parseYamlScalars,
3094
+ policyPath,
3095
+ probeMcpServer,
3096
+ readMcpConfig,
3097
+ readSkillDocument,
3098
+ removeMcpServer,
3099
+ restartMcpServer,
3100
+ saveSkillDocument,
3101
+ saveVariable,
3102
+ splitDocument,
3103
+ splitMcpToolName,
3104
+ stateDir,
3105
+ statePath,
3106
+ summarizeSkillFile,
3107
+ toNativeToken,
3108
+ toSugarToken,
3109
+ upsertMcpServer,
3110
+ variableNames,
3111
+ variablesPath
3112
+ };
3113
+ //# sourceMappingURL=index.js.map