@hcstar/dsh-tool-manage 0.0.0-stage → 0.0.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host/mcp-server.ts","../src/shared/identity.ts","../src/shared/variables.ts","../src/shared/mcp.ts","../src/host/mcp-tools.ts","../src/host/tool-kit.ts","../src/host/mcp-config.ts","../src/host/other-tools.ts","../src/host/skills.ts","../src/host/frontmatter.ts","../src/host/skill-roots.ts","../src/host/state.ts","../src/host/variables.ts","../src/host/agent-tools.ts","../src/host/policy.ts","../src/host/routes.ts","../src/host/index.ts"],"sourcesContent":["/**\n * The plugin's own MCP server.\n *\n * The panel and the agent should manage the same things through the same\n * protocol, and the MCP page should list this plugin like any other server.\n * A separate stdio process would lose `ctx.settings`, `ctx.mcpManager`, and\n * the live registry, so the server runs inside the Host on a random loopback\n * port and speaks the Streamable HTTP transport. The plugin then registers the\n * URL with `ctx.mcpManager`, which connects the normal MCP client and publishes\n * the tools as `mcp__dsh-tool-manage__*`.\n *\n * A random path token keeps the loopback endpoint from being addressable by a\n * process that did not receive the URL from the manager; the socket binds to\n * 127.0.0.1 only.\n */\nimport { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport type { AddressInfo } from 'node:net'\n\nimport { SERVER_NAME } from '../shared/identity.js'\nimport type { HostContext } from './context.js'\nimport type { McpPolicyController } from './policy.js'\nimport { createToolManagerTools } from './agent-tools.js'\nimport { ToolError, type ToolDefinitionFace } from './tool-kit.js'\n\n/** Protocol versions this minimal server echoes back when the client offers one. */\nconst SUPPORTED_PROTOCOL_VERSIONS = new Set(['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'])\n/** Fallback version when the client offers something we do not know. */\nconst DEFAULT_PROTOCOL_VERSION = '2025-06-18'\n/** The advertised MCP server identity. */\nconst SERVER_INFO = { name: SERVER_NAME, version: '0.1.0' } as const\n/** Requests are small tool calls; a body larger than this is a client mistake. */\nconst MAX_BODY_BYTES = 4_000_000\n/** How often an idle SSE channel emits a comment to keep intermediaries awake. */\nconst SSE_HEARTBEAT_MS = 25_000\n\n/** One JSON-RPC request shape as far as this server needs to read it. */\ninterface JsonRpcMessage {\n jsonrpc?: unknown\n id?: unknown\n method?: unknown\n params?: unknown\n}\n\n/** A JSON-RPC success envelope. */\nfunction success(id: unknown, result: unknown): Record<string, unknown> {\n return { jsonrpc: '2.0', id, result }\n}\n\n/** A JSON-RPC error envelope. */\nfunction failure(id: unknown, code: number, message: string): Record<string, unknown> {\n return { jsonrpc: '2.0', id, error: { code, message } }\n}\n\n/** Whether a value is a plain data object. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Whether a socket address is loopback. */\nfunction isLoopback(address: string | undefined): boolean {\n return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'\n}\n\n/** A short message without a stack. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Read a bounded request body. */\nasync function readBody(req: IncomingMessage): Promise<string> {\n const chunks: Buffer[] = []\n let size = 0\n for await (const chunk of req) {\n const buffer = chunk as Buffer\n size += buffer.byteLength\n if (size > MAX_BODY_BYTES) throw new Error('request body is too large')\n chunks.push(buffer)\n }\n return Buffer.concat(chunks, size).toString('utf8')\n}\n\n/** Write one JSON response. */\nfunction sendJson(res: ServerResponse, status: number, payload: unknown, headers: Record<string, string> = {}): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n for (const [name, value] of Object.entries(headers)) res.setHeader(name, value)\n res.end(JSON.stringify(payload))\n}\n\n/** The Host-internal MCP server for the tool manager. */\nexport class ToolManagerMcpServer {\n private server: Server | undefined\n private readonly token = randomBytes(18).toString('base64url')\n private readonly tools: ToolDefinitionFace[]\n private readonly streams = new Set<ServerResponse>()\n private protocolVersion = DEFAULT_PROTOCOL_VERSION\n private sessionId: string | undefined\n\n constructor(\n private readonly ctx: HostContext,\n policy: McpPolicyController,\n ) {\n this.tools = createToolManagerTools(ctx, policy)\n }\n\n /** The path the MCP client must use; it contains the per-process token. */\n get path(): string {\n return `/mcp/${this.token}`\n }\n\n /** Start on a random loopback port; returns the URL registered with the manager. */\n async start(): Promise<{ port: number; url: string }> {\n if (this.server !== undefined) throw new Error('MCP server is already started')\n const server = createServer((req, res) => {\n void this.handle(req, res).catch((error: unknown) => {\n if (!res.headersSent) sendJson(res, 500, failure(null, -32603, messageOf(error)))\n else res.end()\n })\n })\n this.server = server\n await new Promise<void>((resolve, reject) => {\n const onError = (error: Error): void => {\n server.off('listening', onListening)\n reject(error)\n }\n const onListening = (): void => {\n server.off('error', onError)\n resolve()\n }\n server.once('error', onError)\n server.once('listening', onListening)\n server.listen(0, '127.0.0.1')\n })\n const address = server.address() as AddressInfo\n return { port: address.port, url: `http://127.0.0.1:${address.port}${this.path}` }\n }\n\n /** End open streams and close the listener. */\n async close(): Promise<void> {\n for (const stream of this.streams) {\n try {\n stream.end()\n } catch {\n // The peer already closed the stream.\n }\n }\n this.streams.clear()\n const server = this.server\n this.server = undefined\n if (server === undefined) return\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n server.closeAllConnections?.()\n })\n }\n\n /** Dispatch one HTTP request. */\n private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n if (!isLoopback(req.socket.remoteAddress)) {\n sendJson(res, 403, failure(null, -32000, 'loopback access only'))\n return\n }\n const url = new URL(req.url ?? '/', 'http://127.0.0.1')\n if (url.pathname !== this.path) {\n sendJson(res, 404, failure(null, -32000, 'not found'))\n return\n }\n if (req.method === 'GET') {\n this.openStream(req, res)\n return\n }\n if (req.method === 'DELETE') {\n res.statusCode = 405\n res.setHeader('allow', 'POST, GET, DELETE')\n res.end()\n return\n }\n if (req.method !== 'POST') {\n res.statusCode = 405\n res.setHeader('allow', 'POST, GET, DELETE')\n res.end()\n return\n }\n const contentType = String(req.headers['content-type'] ?? '')\n if (!contentType.toLowerCase().includes('application/json')) {\n sendJson(res, 415, failure(null, -32000, 'content-type must be application/json'))\n return\n }\n let payload: unknown\n try {\n payload = JSON.parse(await readBody(req))\n } catch (error) {\n sendJson(res, 400, failure(null, -32700, messageOf(error)))\n return\n }\n const messages = Array.isArray(payload) ? payload : [payload]\n const controller = new AbortController()\n res.once('close', () => controller.abort())\n const responses: unknown[] = []\n for (const message of messages) {\n const response = await this.handleMessage(message, controller.signal)\n if (response !== undefined) responses.push(response)\n }\n if (responses.length === 0) {\n res.statusCode = 202\n res.end()\n return\n }\n const headers: Record<string, string> = { 'mcp-protocol-version': this.protocolVersion }\n if (this.sessionId !== undefined) headers['mcp-session-id'] = this.sessionId\n sendJson(res, 200, Array.isArray(payload) ? responses : responses[0], headers)\n }\n\n /** Keep a Streamable HTTP GET channel open for server-initiated messages. */\n private openStream(req: IncomingMessage, res: ServerResponse): void {\n res.writeHead(200, {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-store',\n connection: 'keep-alive',\n })\n res.write(': connected\\n\\n')\n this.streams.add(res)\n const timer = setInterval(() => {\n if (!res.writableEnded) res.write(': ping\\n\\n')\n }, SSE_HEARTBEAT_MS)\n timer.unref?.()\n req.once('close', () => {\n clearInterval(timer)\n this.streams.delete(res)\n try {\n res.end()\n } catch {\n // Already ended.\n }\n })\n }\n\n /** Answer one JSON-RPC message; notifications produce no response. */\n private async handleMessage(message: unknown, signal: AbortSignal): Promise<unknown | undefined> {\n if (!isRecord(message)) return failure(null, -32600, 'invalid request')\n const request = message as JsonRpcMessage\n const { id, method } = request\n if (typeof method !== 'string') return undefined\n if (id === undefined) {\n // notifications/initialized, notifications/cancelled, progress, ...\n return undefined\n }\n if (method === 'initialize') return this.initialize(id, request.params)\n if (method === 'ping') return success(id, {})\n if (method === 'tools/list') return success(id, { tools: this.toolList() })\n if (method === 'tools/call') return await this.callTool(id, request.params, signal)\n if (method === 'resources/list') return success(id, { resources: [] })\n if (method === 'resources/templates/list') return success(id, { resourceTemplates: [] })\n if (method === 'prompts/list') return success(id, { prompts: [] })\n return failure(id, -32601, `method not found: ${method}`)\n }\n\n /** Answer the MCP handshake and retain the negotiated protocol version. */\n private initialize(id: unknown, params: unknown): unknown {\n const offered = isRecord(params) && typeof params['protocolVersion'] === 'string' ? params['protocolVersion'] : ''\n const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.has(offered) ? offered : DEFAULT_PROTOCOL_VERSION\n this.protocolVersion = protocolVersion\n this.sessionId = randomBytes(18).toString('base64url')\n return success(id, {\n protocolVersion,\n capabilities: { tools: {} },\n serverInfo: SERVER_INFO,\n instructions:\n 'Manage this DeepSeek Harness profile: MCP servers, Agent Skill files and scan roots, per-preset visibility/injection policy, and read-only tool/preset catalogs.',\n })\n }\n\n /** Project the management tools onto the MCP tools/list shape. */\n private toolList(): Record<string, unknown>[] {\n return this.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.parameters,\n }))\n }\n\n /** Execute one management tool and map its result to MCP content. */\n private async callTool(id: unknown, params: unknown, signal: AbortSignal): Promise<unknown> {\n if (!isRecord(params) || typeof params['name'] !== 'string') {\n return failure(id, -32602, 'tools/call requires a tool name')\n }\n const name = params['name']\n const tool = this.tools.find((candidate) => candidate.name === name)\n if (tool === undefined) return failure(id, -32602, `unknown tool: ${name}`)\n const args = params['arguments'] === undefined ? {} : params['arguments']\n try {\n const value = await tool.execute(args, { signal })\n const content = tool.output.render(args, value).map((block) => ({ type: 'text', text: block.text }))\n return success(id, { content })\n } catch (error) {\n const failure =\n error instanceof ToolError\n ? { ok: false, error: { code: error.code, message: error.message } }\n : { ok: false, error: { code: 'internal', message: messageOf(error) } }\n return success(id, { content: [{ type: 'text', text: JSON.stringify(failure) }], isError: true })\n }\n }\n}\n\n/**\n * Start the in-Host MCP server and register it with the MCP manager.\n *\n * Registration makes the server visible on the MCP page as a plugin-provided\n * entry and publishes its tools as `mcp__<serverName>__*`. A profile that has\n * no MCP manager simply gets no server: the panel's routes still work.\n */\nexport function attachMcpServer(ctx: HostContext, policy: McpPolicyController): void {\n ctx.inject(['mcpManager'], (child) => {\n const manager = child.mcpManager\n if (manager === undefined || typeof manager.register !== 'function') return\n const server = new ToolManagerMcpServer(ctx, policy)\n let disposeRegistration: (() => void) | undefined\n let disposed = false\n child.effect(\n () => () => {\n disposed = true\n try {\n disposeRegistration?.()\n } catch {\n // The manager already released the registration.\n }\n void server.close()\n },\n 'dsh-tool-manage: MCP server',\n )\n void server\n .start()\n .then(({ url }) => {\n if (disposed) {\n void server.close()\n return\n }\n let lastError: unknown\n for (const name of [SERVER_NAME, `${SERVER_NAME}-local`]) {\n try {\n disposeRegistration = manager.register(name, {\n transport: 'streamable-http',\n url,\n startupTimeoutMs: 10_000,\n toolLoading: 'eager',\n })\n return\n } catch (error) {\n lastError = error\n }\n }\n ctx.logger?.warn(`dsh-tool-manage: could not register its MCP server: ${String(lastError)}`)\n void server.close()\n })\n .catch((error: unknown) => {\n ctx.logger?.warn(`dsh-tool-manage: could not start its MCP server: ${messageOf(error)}`)\n void server.close()\n })\n })\n}\n","/**\n * Identities shared by the Host half and the browser bundle.\n *\n * The package name is the client module id; this file owns the *runtime* names\n * that are not derived from the manifest: the self-registered MCP server (which\n * also prefixes every model-facing tool), the Host route prefix, and the panel\n * id shared by the sidebar entry and the panel it opens.\n */\n\n/** The server name this plugin registers with the MCP manager; tools become `mcp__<name>__*`. */\nexport const SERVER_NAME = 'dsh-tool-manage'\n\n/** The pre-rename server name; policy documents written before the rename use it as a key. */\nexport const LEGACY_SERVER_NAME = 'tool-manager'\n\n/** HTTP route prefix shared by the Host routes and the browser client. */\nexport const ROUTE_BASE = 'dsh-tool-manage'\n\n/** The id shared by the sidebar entry and the main panel it opens. */\nexport const PANEL_ID = 'dsh-tool-manage'\n","/**\n * `{{name}}` tokens and their `${credential:NAME}` translation.\n *\n * The panel and the model speak `{{name}}`: short, readable, and safe to embed\n * inside a longer string such as `Bearer {{token}}`. The MCP client resolves\n * only `${credential:NAME}` at connection time, so the Host rewrites one form\n * into the other at the storage boundary. Rewriting is per token and\n * conditional: a token whose name no variable declares stays literal text,\n * which makes a half-typed template harmless and keeps `Bearer {{x}}` working\n * once `x` exists.\n */\n\n/** A variable name is a POSIX identifier: it doubles as the credential reference. */\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/** `{{name}}` with optional inner spaces; the group is the candidate name. */\nconst SUGAR_TOKEN = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g\n\n/** The native credential template the MCP client expands. */\nconst NATIVE_TOKEN = /\\$\\{credential:([A-Za-z_][A-Za-z0-9_]*)\\}/g\n\n/** Whether a raw string could name a variable at all (and thus a credential ref). */\nexport function isVariableName(value: string): boolean {\n return VARIABLE_NAME.test(value)\n}\n\n/** The fields of an MCP entry whose strings the MCP client expands at connect time. */\nexport interface TemplatedEntry {\n command?: string\n args?: string[]\n cwd?: string\n url?: string\n env?: Record<string, string>\n headers?: Record<string, string>\n}\n\n/** Apply one string mapping to every template-capable field of an entry. */\nexport function mapEntryStrings<T extends TemplatedEntry>(entry: T, map: (value: string) => string): T {\n const next: T = { ...entry }\n if (typeof entry.command === 'string') next.command = map(entry.command)\n if (Array.isArray(entry.args)) next.args = entry.args.map(map)\n if (typeof entry.cwd === 'string') next.cwd = map(entry.cwd)\n if (typeof entry.url === 'string') next.url = map(entry.url)\n if (entry.env !== undefined) {\n next.env = Object.fromEntries(Object.entries(entry.env).map(([key, value]) => [key, map(value)]))\n }\n if (entry.headers !== undefined) {\n next.headers = Object.fromEntries(Object.entries(entry.headers).map(([key, value]) => [key, map(value)]))\n }\n return next\n}\n\n/**\n * Rewrite every `{{name}}` the store knows into `${credential:NAME}`.\n * @param value - any configuration string, possibly with tokens inside a longer text.\n * @param known - whether the store declares that variable.\n * @returns the native template string; unknown tokens are preserved verbatim.\n */\nexport function toNativeToken(value: string, known: (name: string) => boolean): string {\n return value.replace(SUGAR_TOKEN, (match, name: string) =>\n isVariableName(name) && known(name) ? `\\${credential:${name}}` : match,\n )\n}\n\n/**\n * Rewrite every `${credential:NAME}` that a variable declares back into `{{NAME}}` for display.\n * @param value - stored configuration string.\n * @param known - whether the store declares that variable.\n * @returns the readable form; native templates this plugin does not own stay as they are.\n */\nexport function toSugarToken(value: string, known: (name: string) => boolean): string {\n return value.replace(NATIVE_TOKEN, (match, name: string) => (known(name) ? `{{${name}}}` : match))\n}\n\n/**\n * Names referenced as `{{name}}` anywhere in an entry, in first-seen order.\n * Only names the store declares count, so a stray `{{foo}}` never becomes a reference.\n * @param entry - template-capable entry fields.\n * @param known - whether the store declares that variable.\n */\nexport function entryVariableRefs(entry: TemplatedEntry, known: (name: string) => boolean): string[] {\n const found: string[] = []\n const scan = (value: string): void => {\n for (const match of value.matchAll(SUGAR_TOKEN)) {\n const name = match[1]\n if (name !== undefined && isVariableName(name) && known(name) && !found.includes(name)) found.push(name)\n }\n }\n mapEntryStrings(entry, (value) => {\n scan(value)\n return value\n })\n return found\n}\n","/**\n * MCP server entry rules shared by the browser form and the Host tools.\n *\n * The panel and the agent tools edit the same `mcp-manager` config, so the\n * default entry and the cross-transport cleanup must not drift apart. Both\n * callers import this module; the manager still owns the final validation.\n */\nimport type { McpReconnectConfig, McpServerEntry, McpTransport } from './contracts.js'\n\n/** `dsh-mcp-manager`'s key rule for a server name. */\nexport const MCP_SERVER_NAME = /^[A-Za-z0-9_-]{1,32}$/\n\n/** Default reconnect policy a new entry starts from. */\nexport const DEFAULT_RECONNECT: McpReconnectConfig = {\n enabled: true,\n initialDelayMs: 500,\n maxDelayMs: 30_000,\n maxAttempts: 10,\n}\n\n/** A fresh stdio entry with the manager's schema defaults. */\nexport function defaultMcpEntry(): McpServerEntry {\n return {\n transport: 'stdio',\n command: '',\n args: [],\n env: {},\n cwd: '',\n url: '',\n headers: {},\n enabled: true,\n startupTimeoutMs: 30_000,\n reconnect: { ...DEFAULT_RECONNECT },\n }\n}\n\n/** Whether a transport value is one the manager accepts. */\nexport function isMcpTransport(value: unknown): value is McpTransport {\n return value === 'stdio' || value === 'streamable-http'\n}\n\n/** Copy an entry without sharing nested arrays or objects. */\nexport function cloneMcpEntry(entry: McpServerEntry): McpServerEntry {\n return structuredClone(entry)\n}\n\n/** Drop cross-transport fields and empty optional numbers before writing. */\nexport function normalizeMcpEntry(entry: McpServerEntry): McpServerEntry {\n const next = cloneMcpEntry(entry)\n if (next.transport === 'stdio') {\n next.url = ''\n next.headers = {}\n } else {\n next.command = ''\n next.args = []\n next.env = {}\n next.cwd = ''\n }\n next.args = next.args.filter((arg) => arg !== '')\n if (next.toolCallTimeoutMs === undefined || !Number.isFinite(next.toolCallTimeoutMs) || next.toolCallTimeoutMs <= 0) {\n delete next.toolCallTimeoutMs\n }\n if (next.closeTimeoutMs !== undefined && (!Number.isFinite(next.closeTimeoutMs) || next.closeTimeoutMs <= 0)) {\n delete next.closeTimeoutMs\n }\n if (!Number.isFinite(next.startupTimeoutMs) || next.startupTimeoutMs <= 0) next.startupTimeoutMs = 30_000\n return next\n}\n","/**\n * MCP tool-name helpers shared by the tool route and the injection policy.\n *\n * A public MCP tool is `mcp__<server>__<tool>`; the server segment is the\n * manager's `serverName`, which may itself contain underscores, so parsing and\n * formatting stay in one place.\n */\nimport type { McpToolInfo, McpToolsResult } from '../shared/contracts.js'\n\n/** The public-name prefix every MCP tool carries. */\nexport const MCP_TOOL_PREFIX = 'mcp__'\n\n/** Split one public MCP tool name into its server and raw tool segments. */\nexport function splitMcpToolName(name: string): { server: string; tool: string } | undefined {\n if (!name.startsWith(MCP_TOOL_PREFIX)) return undefined\n const rest = name.slice(MCP_TOOL_PREFIX.length)\n const separator = rest.indexOf('__')\n if (separator <= 0) return undefined\n const server = rest.slice(0, separator)\n const tool = rest.slice(separator + 2)\n if (tool === '') return undefined\n return { server, tool }\n}\n\n/** Build the public tool name for one server and raw tool. */\nexport function mcpToolName(server: string, tool: string): string {\n return `${MCP_TOOL_PREFIX}${server}__${tool}`\n}\n\n/** Group the host's MCP tool definitions by server name. */\nexport function groupMcpTools(\n definitions: readonly { name: string; description: string; parameters: Record<string, unknown> }[],\n): McpToolsResult {\n const servers: Record<string, McpToolInfo[]> = {}\n for (const definition of definitions) {\n const parsed = splitMcpToolName(definition.name)\n if (parsed === undefined) continue\n const list = servers[parsed.server] ?? []\n list.push({ name: parsed.tool, description: definition.description, parameters: definition.parameters })\n servers[parsed.server] = list\n }\n for (const list of Object.values(servers)) list.sort((left, right) => left.name.localeCompare(right.name))\n return { servers }\n}\n","/**\n * Minimal model-facing tool scaffolding for the Host half.\n *\n * The plugin ships no `@deepseek-ai/*` runtime import: a profile install\n * resolves the plugin from the profile directory, where the Harness packages\n * are not necessarily visible. These definitions therefore speak the registry's\n * plain `ToolDefinition` shape directly. The helpers only narrow arguments and\n * render canonical JSON; the registry and the executor pipeline own the rest.\n */\n\n/** One model-facing text block. */\nexport interface ToolTextBlock {\n type: 'text'\n text: string\n}\n\n/** The execution facts the tool bodies use. */\nexport interface ToolRunContextFace {\n /** Caller-owned cancellation. */\n signal: AbortSignal\n /** The Agent on whose behalf the call runs, when the executor supplies one. */\n agent?: unknown\n}\n\n/** The subset of `ToolDefinition` this plugin builds. */\nexport interface ToolDefinitionFace {\n name: string\n description: string\n parameters: Record<string, unknown>\n output: {\n schema: Record<string, unknown>\n render(args: unknown, value: unknown): ToolTextBlock[]\n }\n execute(args: unknown, exec: ToolRunContextFace): Promise<unknown>\n}\n\n/** Whether a value is a plain data object. */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const prototype = Object.getPrototypeOf(value) as unknown\n return prototype === Object.prototype || prototype === null ? (value as Record<string, unknown>) : undefined\n}\n\n/** Narrow the call arguments to their implicit object root. */\nexport function argsRecord(args: unknown): Record<string, unknown> {\n const record = asRecord(args)\n if (record === undefined) throw new Error('arguments must be a JSON object')\n return record\n}\n\n/** Read one optional string argument. */\nexport function readString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key]\n if (value === undefined) return undefined\n if (typeof value !== 'string') throw new Error(`argument \"${key}\" must be a string`)\n return value\n}\n\n/** Read one required string argument. */\nexport function requireString(record: Record<string, unknown>, key: string): string {\n const value = readString(record, key)\n if (value === undefined || value.trim() === '') throw new Error(`argument \"${key}\" is required`)\n return value\n}\n\n/** Read one optional enum argument. */\nexport function readEnum<const T extends string>(\n record: Record<string, unknown>,\n key: string,\n values: readonly T[],\n): T | undefined {\n const value = record[key]\n if (value === undefined) return undefined\n if (typeof value !== 'string' || !(values as readonly string[]).includes(value)) {\n throw new Error(`argument \"${key}\" must be one of ${values.join(', ')}`)\n }\n return value as T\n}\n\n/** Read one required enum argument. */\nexport function requireEnum<const T extends string>(\n record: Record<string, unknown>,\n key: string,\n values: readonly T[],\n): T {\n const value = readEnum(record, key, values)\n if (value === undefined) throw new Error(`argument \"${key}\" is required`)\n return value\n}\n\n/** Read one optional boolean argument. */\nexport function readBoolean(record: Record<string, unknown>, key: string): boolean | undefined {\n const value = record[key]\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new Error(`argument \"${key}\" must be a boolean`)\n return value\n}\n\n/** Read one optional finite number argument. */\nexport function readNumber(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key]\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`argument \"${key}\" must be a finite number`)\n return value\n}\n\n/** Read one optional string array argument. */\nexport function readStringArray(record: Record<string, unknown>, key: string): string[] | undefined {\n const value = record[key]\n if (value === undefined) return undefined\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {\n throw new Error(`argument \"${key}\" must be an array of strings`)\n }\n return value as string[]\n}\n\n/** Read one optional string map argument. */\nexport function readStringMap(record: Record<string, unknown>, key: string): Record<string, string> | undefined {\n const value = record[key]\n if (value === undefined) return undefined\n const map = asRecord(value)\n if (map === undefined) throw new Error(`argument \"${key}\" must be an object of strings`)\n const out: Record<string, string> = {}\n for (const [entryKey, entryValue] of Object.entries(map)) {\n if (typeof entryValue !== 'string') throw new Error(`argument \"${key}.${entryKey}\" must be a string`)\n out[entryKey] = entryValue\n }\n return out\n}\n\n/** Read one optional object argument. */\nexport function readObject(record: Record<string, unknown>, key: string): Record<string, unknown> | undefined {\n const value = record[key]\n if (value === undefined) return undefined\n const object = asRecord(value)\n if (object === undefined) throw new Error(`argument \"${key}\" must be an object`)\n return object\n}\n\n/** Render a canonical value as the model-facing text block. */\nexport function renderJson(value: unknown): ToolTextBlock[] {\n const text = JSON.stringify(value, null, 2)\n return [{ type: 'text', text: text === undefined ? 'null' : text }]\n}\n\n/** A tool failure with a stable machine-readable code. */\nexport class ToolError extends Error {\n /** Stable code the caller can branch on. */\n readonly code: string\n\n constructor(code: string, message: string) {\n super(message)\n this.name = 'ToolError'\n this.code = code\n }\n}\n\n/** Require an explicit confirmation for a destructive action. */\nexport function requireConfirm(record: Record<string, unknown>, action: string): void {\n if (record['confirm'] !== true) {\n throw new ToolError('confirmation_required', `${action} requires \"confirm\": true`)\n }\n}\n","/**\n * Host-side administration of the `mcp-manager` server fleet.\n *\n * The browser edits the same entries through the settings form service; this\n * module reads and writes the one stored copy in the profile patch. It never\n * keeps its own list: a write goes through `ctx.settings.replace`, so the\n * manager validates the entry and rebuilds the connection, and a concurrent\n * edit surfaces as a revision conflict rather than a lost update.\n */\nimport type { McpServerEntry, McpServerMap, McpServerView, McpToolInfo } from '../shared/contracts.js'\nimport {\n DEFAULT_RECONNECT,\n MCP_SERVER_NAME,\n defaultMcpEntry,\n isMcpTransport,\n normalizeMcpEntry,\n} from '../shared/mcp.js'\nimport type { HostContext } from './context.js'\nimport { groupMcpTools } from './mcp-tools.js'\nimport { asRecord } from './tool-kit.js'\n\n/** One settings descriptor as the Host settings service returns it. */\ninterface SettingsDescriptorFace {\n ns: string\n value?: unknown\n revision: number\n}\n\n/** The Host settings surface this module writes through. */\nexport interface SettingsFace {\n describe(options?: { redactSecrets?: boolean }): SettingsDescriptorFace[]\n replace(ns: string, section: object, expectedRevision?: number): Promise<void>\n}\n\n/** The MCP manager surface read for statuses, probes, and restarts. */\nexport interface McpManagerFace {\n config?: { servers?: { get(): McpServerMap } }\n list?(): readonly McpServerView[]\n probe?(name: string, options?: { signal?: AbortSignal; timeoutMs?: number }): Promise<unknown>\n restart?(name: string): Promise<void>\n}\n\n/** One configured server plus the runtime facts the tools can prove. */\nexport interface McpServerSummary {\n name: string\n /** Whether the entry belongs to the stored `mcp-manager` config. */\n configured: boolean\n /** Whether a plugin registered the entry for its own lifetime. */\n registered: boolean\n enabled: boolean\n transport: string\n /** `command` for stdio, `url` for streamable-http. */\n endpoint: string\n status?: unknown\n tools: string[]\n}\n\n/** The stored `mcp-manager` config plus the revision a later write must match. */\nexport interface McpConfigSnapshot {\n ns: string\n revision: number\n servers: McpServerMap\n}\n\n/** Read the settings descriptor for the `mcp-manager` row. */\nfunction settingsOf(ctx: HostContext): SettingsFace | undefined {\n const value = ctx.get('settings')\n if (typeof value !== 'object' || value === null) return undefined\n return typeof Reflect.get(value, 'describe') === 'function' ? (value as SettingsFace) : undefined\n}\n\n/** Read the MCP manager when the composition mounts one. */\nfunction managerOf(ctx: HostContext): McpManagerFace | undefined {\n const value = ctx.get('mcpManager')\n if (typeof value !== 'object' || value === null) return undefined\n return value as McpManagerFace\n}\n\n/**\n * Read the stored server map and its revision.\n *\n * The row id is `mcp-manager` in every shipped profile; a renamed row is found\n * by the shape of its projected value instead.\n */\nexport function readMcpConfig(ctx: HostContext): McpConfigSnapshot | undefined {\n const settings = settingsOf(ctx)\n if (settings === undefined) return undefined\n try {\n const descriptors = settings.describe()\n const exact = descriptors.find((descriptor) => descriptor.ns === 'mcp-manager')\n const shaped = descriptors.find((descriptor) => {\n const value = asRecord(descriptor.value)\n return value !== undefined && asRecord(value['servers']) !== undefined\n })\n const descriptor = exact ?? shaped\n if (descriptor === undefined) return undefined\n const value = asRecord(descriptor.value)\n const servers = value === undefined ? {} : (asRecord(value['servers']) ?? {})\n return { ns: descriptor.ns, revision: descriptor.revision, servers: servers as McpServerMap }\n } catch {\n return undefined\n }\n}\n\n/** The live configured map, used for reads when settings is unavailable. */\nexport function liveMcpServers(ctx: HostContext): McpServerMap {\n try {\n return managerOf(ctx)?.config?.servers?.get() ?? {}\n } catch {\n return {}\n }\n}\n\n/** List configured, registered, and retained servers with their tool names. */\nexport function listMcpServers(ctx: HostContext): { servers: McpServerSummary[]; warnings: string[] } {\n const warnings: string[] = []\n const snapshot = readMcpConfig(ctx)\n const servers = snapshot?.servers ?? liveMcpServers(ctx)\n const manager = managerOf(ctx)\n let views: readonly McpServerView[] = []\n if (manager?.list !== undefined) {\n try {\n views = manager.list()\n } catch (error) {\n warnings.push(`读取 MCP 运行状态失败:${messageOf(error)}`)\n }\n }\n let tools: Record<string, McpToolInfo[]> = {}\n try {\n const registry = ctx.get('tools') as\n | {\n definitions(\n scope?: unknown,\n ): readonly { name: string; description: string; parameters: Record<string, unknown> }[]\n }\n | undefined\n tools = groupMcpTools(registry?.definitions() ?? []).servers\n } catch (error) {\n warnings.push(`读取 MCP 工具失败:${messageOf(error)}`)\n }\n const viewByName = new Map(views.map((view) => [view.name, view]))\n const names = new Set<string>([...Object.keys(servers), ...viewByName.keys()])\n const out: McpServerSummary[] = []\n for (const name of [...names].sort((left, right) => left.localeCompare(right))) {\n const entry = servers[name]\n const view = viewByName.get(name)\n out.push({\n name,\n configured: entry !== undefined,\n registered: entry === undefined && view !== undefined,\n enabled: entry?.enabled ?? true,\n transport: entry?.transport ?? 'unknown',\n endpoint: entry === undefined ? '' : entry.transport === 'stdio' ? entry.command : entry.url,\n ...(view === undefined ? {} : { status: view.status }),\n tools: (tools[name] ?? []).map((tool) => tool.name),\n })\n }\n return { servers: out, warnings }\n}\n\n/** Read one server's stored entry, or undefined when it is only registered. */\nexport function findMcpEntry(ctx: HostContext, name: string): McpServerEntry | undefined {\n return (readMcpConfig(ctx)?.servers ?? liveMcpServers(ctx))[name]\n}\n\n/** Drop cross-transport fields, fill defaults, and validate the name. */\nexport function mergeMcpEntry(base: McpServerEntry | undefined, patch: Record<string, unknown>): McpServerEntry {\n const source = base ?? defaultMcpEntry()\n const transport = patch['transport'] === undefined ? source.transport : patch['transport']\n if (!isMcpTransport(transport)) throw new Error('entry.transport must be \"stdio\" or \"streamable-http\"')\n const reconnectSource = source.reconnect ?? DEFAULT_RECONNECT\n const reconnectPatch = asRecord(patch['reconnect'])\n const reconnect = {\n enabled: readBoolean(reconnectPatch, 'enabled') ?? reconnectSource.enabled,\n initialDelayMs: readPositive(reconnectPatch, 'initialDelayMs') ?? reconnectSource.initialDelayMs,\n maxDelayMs: readPositive(reconnectPatch, 'maxDelayMs') ?? reconnectSource.maxDelayMs,\n maxAttempts: readPositive(reconnectPatch, 'maxAttempts') ?? reconnectSource.maxAttempts,\n }\n const toolCallTimeoutMs = optionalPositive(patch, 'toolCallTimeoutMs', source.toolCallTimeoutMs)\n const closeTimeoutMs = optionalPositive(patch, 'closeTimeoutMs', source.closeTimeoutMs)\n const toolLoading = patch['toolLoading'] ?? source.toolLoading\n if (toolLoading !== undefined && toolLoading !== 'eager' && toolLoading !== 'on-demand') {\n throw new Error('entry.toolLoading must be \"eager\" or \"on-demand\"')\n }\n const oauth = patch['oauth'] === undefined ? source.oauth : asRecord(patch['oauth'])\n const next = normalizeMcpEntry({\n transport,\n command: readString(patch, 'command') ?? source.command,\n args: readStringArray(patch, 'args') ?? source.args,\n env: readStringMap(patch, 'env') ?? source.env,\n cwd: readString(patch, 'cwd') ?? source.cwd,\n url: readString(patch, 'url') ?? source.url,\n headers: readStringMap(patch, 'headers') ?? source.headers,\n enabled: readBoolean(patch, 'enabled') ?? source.enabled,\n startupTimeoutMs: readPositive(patch, 'startupTimeoutMs') ?? source.startupTimeoutMs,\n ...(toolCallTimeoutMs === undefined ? {} : { toolCallTimeoutMs }),\n ...(closeTimeoutMs === undefined ? {} : { closeTimeoutMs }),\n reconnect,\n ...(toolLoading === undefined ? {} : { toolLoading }),\n ...(oauth === undefined ? {} : { oauth }),\n })\n if (next.transport === 'stdio' && next.command.trim() === '') {\n throw new Error('a stdio server requires a non-empty command')\n }\n if (next.transport === 'streamable-http' && next.url.trim() === '') {\n throw new Error('a streamable-http server requires a non-empty url')\n }\n return next\n}\n\n/** Whether a settings write lost the revision race. */\nfunction isConflict(error: unknown): boolean {\n return typeof error === 'object' && error !== null && Reflect.get(error, 'code') === 'SETTINGS_CONFLICT'\n}\n\n/**\n * Apply a mutation to the stored map, retrying once after a revision conflict.\n * @param ctx - Host services.\n * @param mutate - pure change from the current map to the next map.\n * @returns the map actually stored.\n */\nasync function writeMcpServers(\n ctx: HostContext,\n mutate: (servers: McpServerMap) => McpServerMap,\n): Promise<McpServerMap> {\n const settings = settingsOf(ctx)\n if (settings === undefined) throw new Error('settings service is unavailable; MCP servers cannot be saved')\n let lastError: unknown\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const snapshot = readMcpConfig(ctx)\n if (snapshot === undefined) throw new Error('mcp-manager settings row is unavailable')\n const next = mutate(snapshot.servers)\n try {\n await settings.replace(snapshot.ns, { servers: next }, snapshot.revision)\n return next\n } catch (error) {\n lastError = error\n if (attempt > 0 || !isConflict(error)) throw error\n }\n }\n throw lastError instanceof Error ? lastError : new Error(String(lastError))\n}\n\n/** Create or update one configured server; registered servers are read-only. */\nexport async function upsertMcpServer(\n ctx: HostContext,\n name: string,\n patch: Record<string, unknown>,\n): Promise<McpServerEntry> {\n if (!MCP_SERVER_NAME.test(name)) {\n throw new Error('server name must match /^[A-Za-z0-9_-]{1,32}$/')\n }\n const manager = managerOf(ctx)\n if (manager?.list !== undefined) {\n const view = manager.list().find((candidate) => candidate.name === name)\n if (view !== undefined && !view.configured) {\n throw new Error(`server \"${name}\" is contributed by a plugin and cannot be edited here`)\n }\n }\n let entry: McpServerEntry | undefined\n await writeMcpServers(ctx, (servers) => {\n entry = mergeMcpEntry(servers[name], patch)\n return { ...servers, [name]: entry }\n })\n return entry as McpServerEntry\n}\n\n/** Remove one configured server. */\nexport async function removeMcpServer(ctx: HostContext, name: string): Promise<void> {\n const snapshot = readMcpConfig(ctx)\n if (snapshot === undefined) {\n throw new Error('settings service is unavailable; MCP servers cannot be removed')\n }\n if (!Object.hasOwn(snapshot.servers, name)) {\n const view = managerOf(ctx)\n ?.list?.()\n .find((candidate) => candidate.name === name)\n if (view !== undefined) throw new Error(`server \"${name}\" is contributed by a plugin and cannot be removed here`)\n throw new Error(`unknown MCP server \"${name}\"`)\n }\n await writeMcpServers(ctx, (servers) => {\n const next = { ...servers }\n delete next[name]\n return next\n })\n}\n\n/** Probe one configured or registered server without touching its live instance. */\nexport async function probeMcpServer(\n ctx: HostContext,\n name: string,\n options: { signal?: AbortSignal; timeoutMs?: number },\n): Promise<unknown> {\n const manager = managerOf(ctx)\n if (manager?.probe === undefined) throw new Error('mcpManager service is unavailable; the server cannot be probed')\n return await manager.probe(name, {\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n })\n}\n\n/** Rebuild one server from its current entry. */\nexport async function restartMcpServer(ctx: HostContext, name: string): Promise<void> {\n const manager = managerOf(ctx)\n if (manager?.restart === undefined)\n throw new Error('mcpManager service is unavailable; the server cannot be restarted')\n await manager.restart(name)\n}\n\n/** One server's tools with full parameter schemas, for a focused read. */\nexport function mcpServerTools(ctx: HostContext, name: string): McpToolInfo[] {\n try {\n const registry = ctx.get('tools') as\n | {\n definitions(\n scope?: unknown,\n ): readonly { name: string; description: string; parameters: Record<string, unknown> }[]\n }\n | undefined\n return groupMcpTools(registry?.definitions() ?? []).servers[name] ?? []\n } catch {\n return []\n }\n}\n\n/** Read one optional string patch field. */\nfunction readString(patch: Record<string, unknown>, key: string): string | undefined {\n const value = patch[key]\n if (value === undefined) return undefined\n if (typeof value !== 'string') throw new Error(`entry.${key} must be a string`)\n return value\n}\n\n/** Read one optional boolean patch field. */\nfunction readBoolean(patch: Record<string, unknown> | undefined, key: string): boolean | undefined {\n if (patch === undefined) return undefined\n const value = patch[key]\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new Error(`entry.${key} must be a boolean`)\n return value\n}\n\n/** Read one optional positive number patch field. */\nfunction readPositive(patch: Record<string, unknown> | undefined, key: string): number | undefined {\n if (patch === undefined) return undefined\n const value = patch[key]\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new Error(`entry.${key} must be a positive finite number`)\n }\n return value\n}\n\n/** Read one optional number field where an explicit null clears the value. */\nfunction optionalPositive(\n patch: Record<string, unknown>,\n key: string,\n fallback: number | undefined,\n): number | undefined {\n if (!Object.hasOwn(patch, key)) return fallback\n const value = patch[key]\n if (value === null) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new Error(`entry.${key} must be a positive finite number or null`)\n }\n return value\n}\n\n/** Read one optional string array patch field. */\nfunction readStringArray(patch: Record<string, unknown>, key: string): string[] | undefined {\n const value = patch[key]\n if (value === undefined) return undefined\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {\n throw new Error(`entry.${key} must be an array of strings`)\n }\n return value as string[]\n}\n\n/** Read one optional string map patch field. */\nfunction readStringMap(patch: Record<string, unknown>, key: string): Record<string, string> | undefined {\n const value = patch[key]\n if (value === undefined) return undefined\n const map = asRecord(value)\n if (map === undefined) throw new Error(`entry.${key} must be an object of strings`)\n const out: Record<string, string> = {}\n for (const [entryKey, entryValue] of Object.entries(map)) {\n if (typeof entryValue !== 'string') throw new Error(`entry.${key}.${entryKey} must be a string`)\n out[entryKey] = entryValue\n }\n return out\n}\n\n/** A short error message without a stack. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * Read every non-MCP tool the Host currently exposes.\n *\n * The registry has no owner metadata per definition, so the collector reports\n * what it can prove: the name, the model-facing description and schema, whether\n * the Host global plane defines it, and which live preset scopes can see it.\n * MCP tools belong to the MCP tab and are filtered out here.\n */\nimport type { OtherToolInfo, OtherToolsResult } from '../shared/contracts.js'\nimport { MCP_TOOL_PREFIX } from './mcp-tools.js'\n\n/** Bound the answer so a pathological registry cannot flood the panel. */\nconst MAX_TOOLS = 500\n\ninterface ToolLike {\n name: string\n description: string\n parameters: Record<string, unknown>\n}\n\ninterface ToolsFace {\n definitions(scope?: unknown): readonly ToolLike[]\n}\n\ninterface AgentLike {\n session: unknown\n ctx: { tools?: ToolsFace }\n}\n\n/** The Host services this collector reads. */\nexport interface OtherToolsHost {\n get(name: string): unknown\n on?(event: string, listener: (payload: unknown) => void): () => void\n}\n\n/** Read one agent's preset, preferring the committed projection over the header. */\nfunction presetOf(host: OtherToolsHost, agent: AgentLike): string | undefined {\n try {\n const registry = host.get('agentPresets') as\n { presetForSession?(session: unknown): string | null; defaultId?: string } | undefined\n const selected = registry?.presetForSession?.(agent.session)\n if (typeof selected === 'string' && selected !== '') return selected\n } catch {\n // Fall through to the structural header.\n }\n const header = (agent.session as { header?: { agentPreset?: unknown } } | undefined)?.header?.agentPreset\n return typeof header === 'string' && header !== '' ? header : undefined\n}\n\n/** Merge one definition into the accumulating map. */\nfunction remember(\n map: Map<string, OtherToolInfo>,\n definition: ToolLike,\n preset: string | undefined,\n global: boolean,\n): void {\n if (definition.name.startsWith(MCP_TOOL_PREFIX)) return\n if (definition.name === 'run_code') return\n const existing = map.get(definition.name)\n if (existing === undefined) {\n map.set(definition.name, {\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n global,\n presets: preset === undefined ? [] : [preset],\n })\n return\n }\n if (global) existing.global = true\n if (preset !== undefined && !existing.presets.includes(preset)) existing.presets.push(preset)\n}\n\n/**\n * Collect the non-MCP tool catalog.\n * @param host - the plugin Host context.\n * @returns sorted tools plus non-fatal read problems.\n */\nexport function collectOtherTools(host: OtherToolsHost): OtherToolsResult {\n const map = new Map<string, OtherToolInfo>()\n const warnings: string[] = []\n\n try {\n const tools = host.get('tools') as ToolsFace | undefined\n for (const definition of tools?.definitions() ?? []) remember(map, definition, undefined, true)\n } catch (error) {\n warnings.push(`全局工具注册表读取失败:${error instanceof Error ? error.message : String(error)}`)\n }\n\n let agents: readonly AgentLike[] = []\n try {\n agents = (host.get('agents') as { list(): readonly AgentLike[] } | undefined)?.list() ?? []\n } catch {\n agents = []\n }\n for (const agent of agents) {\n const preset = presetOf(host, agent)\n try {\n const tools = agent.ctx.tools\n for (const definition of tools?.definitions() ?? []) remember(map, definition, preset, false)\n } catch {\n // A disposing Agent scope contributes nothing; the global pass still ran.\n }\n }\n\n const tools = [...map.values()].sort((left, right) => left.name.localeCompare(right.name)).slice(0, MAX_TOOLS)\n if (map.size > MAX_TOOLS) warnings.push(`工具数量超过 ${String(MAX_TOOLS)},只展示前 ${String(MAX_TOOLS)} 个。`)\n return { tools, warnings }\n}\n","/**\n * Agent Skills discovery and editing on the Host.\n *\n * The browser never sees a filesystem path it may write: every operation\n * re-resolves the requested file against the scanned roots, and a write is\n * accepted only for `<root>/<skill>/SKILL.md` or `<root>/<skill>.md` under a\n * writable root. Runtime-provided skills (bundled, preset, plugin) are listed\n * read-only alongside the files.\n */\nimport { homedir } from 'node:os'\nimport { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'\nimport { mkdir, readFile, readdir, realpath, rm, stat, unlink, writeFile } from 'node:fs/promises'\n\nimport type {\n SkillCreateRequest,\n SkillDocumentInfo,\n SkillFieldsInput,\n SkillListResult,\n SkillResourceInfo,\n SkillResourceContent,\n SkillRootInfo,\n SkillSaveRequest,\n SkillSummaryInfo,\n} from '../shared/contracts.js'\n\nimport { SKILL_NAME_PATTERN, applySkillFields, createSkillContent, parseSkillDocument } from './frontmatter.js'\n\n/** The skill registry face this plugin reads; declared locally to stay runtime-free. */\nexport interface SkillRegistryFace {\n list(options?: { cwd?: string; signal?: AbortSignal }): Promise<readonly RuntimeSkillSummary[]>\n}\n\n/** Resolve the optional runtime skill registry without requiring the service. */\nexport function skillRegistryOf(host: { get(name: string): unknown }): SkillRegistryFace | undefined {\n const value = host.get('skills')\n if (typeof value !== 'object' || value === null) return undefined\n const list = Reflect.get(value, 'list')\n return typeof list === 'function' ? (value as SkillRegistryFace) : undefined\n}\n\n/** One runtime skill summary, matching `@deepseek-ai/dsh-skill`'s public shape. */\nexport interface RuntimeSkillSummary {\n name: string\n description: string\n whenToUse?: string\n path?: string\n source: string\n provider: string\n invocation: { modelInvocable: boolean; userInvocable: boolean }\n}\n\n/** The instruction-file content cap; a skill is documentation, not a dataset. */\nconst MAX_SKILL_BYTES = 1_000_000\n\n/** Where the manager looks for skills, in display order. */\nexport function defaultSkillRoots(environment: NodeJS.ProcessEnv = process.env, home = homedir()): SkillRootInfo[] {\n const dshHome = environment.DSH_HOME?.trim() || join(home, '.dsh')\n const agentsHome = environment.DSH_AGENTS_HOME?.trim() || join(home, '.agents')\n return [\n { key: 'user-dsh', label: 'DSH 全局', path: join(dshHome, 'skills'), writable: true, exists: false },\n { key: 'user-agents', label: '共享 Agent', path: join(agentsHome, 'skills'), writable: true, exists: false },\n ]\n}\n\n/** Result of scanning one root. */\ninterface RootScan {\n skills: SkillSummaryInfo[]\n warnings: string[]\n}\n\n/** One entry in a skill directory, recursively flattened for the wire. */\nconst MAX_RESOURCE_ENTRIES = 300\n\nasync function walkResources(\n directory: string,\n base: string,\n prefix: string,\n depth: number,\n out: SkillResourceInfo[],\n): Promise<void> {\n if (out.length >= MAX_RESOURCE_ENTRIES || depth > 8) return\n let entries\n try {\n entries = await readdir(join(directory, ...prefix.split('/').filter(Boolean)), { withFileTypes: true })\n } catch {\n return\n }\n entries.sort((left, right) => {\n const leftDir = left.isDirectory() ? 0 : 1\n const rightDir = right.isDirectory() ? 0 : 1\n return leftDir - rightDir || left.name.localeCompare(right.name)\n })\n for (const entry of entries) {\n if (out.length >= MAX_RESOURCE_ENTRIES) return\n if (entry.name === 'SKILL.md' || entry.name.startsWith('.')) continue\n if (entry.isSymbolicLink()) continue\n const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`\n if (entry.isDirectory()) {\n out.push({ name: entry.name, path: relative, bytes: 0, directory: true })\n await walkResources(directory, base, relative, depth + 1, out)\n continue\n }\n try {\n const info = await stat(join(base, ...relative.split('/')))\n out.push({ name: entry.name, path: relative, bytes: info.size, directory: false })\n } catch {\n out.push({ name: entry.name, path: relative, bytes: 0, directory: false })\n }\n }\n}\n\n/** Read every file and directory below one skill directory. */\nasync function listResources(directory: string): Promise<SkillResourceInfo[]> {\n const out: SkillResourceInfo[] = []\n await walkResources(directory, directory, '', 0, out)\n return out\n}\n\n/** Build a summary from one instruction file plus its owning root. */\nexport async function summarizeSkillFile(\n filePath: string,\n root: SkillRootInfo,\n fallbackName: string,\n directory?: string,\n): Promise<SkillSummaryInfo> {\n const [raw, info] = await Promise.all([readFile(filePath, 'utf8'), stat(filePath)])\n const parsed = parseSkillDocument(raw, fallbackName)\n const resources = directory === undefined ? [] : await listResources(directory)\n return {\n name: parsed.name,\n description: parsed.description,\n ...(parsed.whenToUse === undefined ? {} : { whenToUse: parsed.whenToUse }),\n path: filePath,\n ...(directory === undefined ? {} : { dir: directory }),\n source: root.key,\n sourceLabel: root.label,\n rootKey: root.key,\n writable: root.writable,\n valid: parsed.valid,\n ...(parsed.issue === undefined ? {} : { issue: parsed.issue }),\n modelInvocable: !parsed.disableModelInvocation,\n userInvocable: parsed.userInvocable,\n bytes: info.size,\n resources,\n }\n}\n\n/** Scan one root for directory bundles and flat `.md` files. */\nasync function scanRoot(root: SkillRootInfo): Promise<RootScan> {\n const warnings: string[] = []\n let entries\n try {\n entries = await readdir(root.path, { withFileTypes: true })\n } catch (error) {\n const code = (error as { code?: unknown }).code\n if (code !== 'ENOENT' && code !== 'ENOTDIR') warnings.push(`${root.label}(${root.path})无法读取`)\n return { skills: [], warnings }\n }\n const skills: SkillSummaryInfo[] = []\n for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {\n if (entry.name.startsWith('.')) continue\n if (entry.isDirectory()) {\n const file = join(root.path, entry.name, 'SKILL.md')\n try {\n const info = await stat(file)\n if (!info.isFile()) continue\n skills.push(await summarizeSkillFile(file, root, entry.name, join(root.path, entry.name)))\n } catch (error) {\n if ((error as { code?: unknown }).code !== 'ENOENT') warnings.push(`${entry.name}/SKILL.md 无法读取`)\n }\n continue\n }\n if (!entry.name.endsWith('.md')) continue\n const file = join(root.path, entry.name)\n try {\n skills.push(await summarizeSkillFile(file, root, basename(entry.name, '.md')))\n } catch {\n warnings.push(`${entry.name} 无法读取`)\n }\n }\n return { skills, warnings }\n}\n\n/** Human label for a runtime provider, falling back to the source key. */\nfunction runtimeLabel(summary: RuntimeSkillSummary): string {\n if (summary.provider.startsWith('dsh-') && summary.provider.includes('office')) return '内置 Office'\n if (summary.source === 'bundled') return '内置 Skills'\n return '运行时技能'\n}\n\n/** Read runtime skills through the registry, tolerating an absent service. */\nasync function runtimeSkills(\n registry: SkillRegistryFace | undefined,\n): Promise<{ skills: SkillSummaryInfo[]; warning?: string }> {\n if (registry === undefined) return { skills: [] }\n try {\n const list = await registry.list()\n const skills: SkillSummaryInfo[] = []\n for (const summary of list) {\n if (summary.path === undefined) continue\n let bytes = 0\n try {\n bytes = (await stat(summary.path)).size\n } catch {\n continue\n }\n skills.push({\n name: summary.name,\n description: summary.description,\n ...(summary.whenToUse === undefined ? {} : { whenToUse: summary.whenToUse }),\n path: summary.path,\n source: summary.source,\n sourceLabel: runtimeLabel(summary),\n writable: false,\n valid: true,\n modelInvocable: summary.invocation.modelInvocable,\n userInvocable: summary.invocation.userInvocable,\n bytes,\n resources: [],\n })\n }\n return { skills }\n } catch {\n return { skills: [], warning: '读取运行时技能目录失败' }\n }\n}\n\n/** Whether `candidate` is inside `root` (both already resolved). */\nexport function isInside(root: string, candidate: string): boolean {\n const rel = relative(root, candidate)\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))\n}\n\n/**\n * List every skill found in the writable roots, without merging runtime\n * providers. The skill tools address files, so they need this projection even\n * when a runtime provider would shadow a same-name file in the panel list.\n */\nexport async function listLocalSkills(roots: SkillRootInfo[] = defaultSkillRoots()): Promise<SkillListResult> {\n const warnings: string[] = []\n const byName = new Map<string, SkillSummaryInfo>()\n const order: string[] = []\n for (const root of roots) {\n try {\n root.exists = (await stat(root.path)).isDirectory()\n } catch {\n root.exists = false\n }\n const scan = await scanRoot(root)\n warnings.push(...scan.warnings)\n for (const skill of scan.skills) {\n if (!byName.has(skill.name)) order.push(skill.name)\n byName.set(skill.name, skill)\n }\n }\n const rank = new Map(roots.map((root, index) => [root.key, index]))\n const skills = order\n .map((name) => byName.get(name))\n .filter((skill): skill is SkillSummaryInfo => skill !== undefined)\n .sort((left, right) => {\n const leftRank = rank.get(left.rootKey ?? '') ?? roots.length\n const rightRank = rank.get(right.rootKey ?? '') ?? roots.length\n if (leftRank !== rightRank) return leftRank - rightRank\n return left.name.localeCompare(right.name)\n })\n return { roots, skills, warnings }\n}\n\n/**\n * List every skill the manager can show.\n * @param registry - the runtime skill registry when the Host composition provides one.\n */\nexport async function listSkills(\n registry: SkillRegistryFace | undefined,\n roots: SkillRootInfo[] = defaultSkillRoots(),\n): Promise<SkillListResult> {\n const local = await listLocalSkills(roots)\n const warnings = [...local.warnings]\n const byName = new Map(local.skills.map((skill) => [skill.name, skill]))\n const order = local.skills.map((skill) => skill.name)\n const runtime = await runtimeSkills(registry)\n warnings.push(...(runtime.warning === undefined ? [] : [runtime.warning]))\n for (const skill of runtime.skills) {\n if (byName.has(skill.name)) {\n warnings.push(`技能 ${skill.name} 被运行时提供者覆盖,列表中显示只读版本`)\n } else {\n order.push(skill.name)\n }\n byName.set(skill.name, skill)\n }\n const rank = new Map(local.roots.map((root, index) => [root.key, index]))\n const skills = order\n .map((name) => byName.get(name))\n .filter((skill): skill is SkillSummaryInfo => skill !== undefined)\n .sort((left, right) => {\n const leftRank = rank.get(left.rootKey ?? '') ?? local.roots.length\n const rightRank = rank.get(right.rootKey ?? '') ?? local.roots.length\n if (leftRank !== rightRank) return leftRank - rightRank\n return left.name.localeCompare(right.name)\n })\n return { roots: local.roots, skills, warnings }\n}\n\n/** A resolved instruction file and the root that owns it. */\ninterface ResolvedSkillFile {\n root: SkillRootInfo\n file: string\n directory?: string\n}\n\n/** Resolve a requested file to a skill instruction file under a scanned root. */\nasync function resolveSkillFile(\n requested: string,\n roots: SkillRootInfo[] = defaultSkillRoots(),\n): Promise<ResolvedSkillFile | undefined> {\n for (const root of roots) {\n let realRoot: string\n try {\n realRoot = await realpath(root.path)\n } catch {\n continue\n }\n let file: string\n try {\n file = await realpath(requested)\n } catch {\n continue\n }\n if (!isInside(realRoot, file)) continue\n const parts = relative(realRoot, file).split(sep)\n if (parts.length === 2 && parts[1] === 'SKILL.md') {\n const directory = dirname(file)\n try {\n if (!(await stat(directory)).isDirectory()) continue\n } catch {\n continue\n }\n return { root, file, directory }\n }\n if (parts.length === 1 && parts[0] !== undefined && parts[0].endsWith('.md')) {\n return { root, file }\n }\n }\n return undefined\n}\n\n/** Whether a path is one of the runtime skills' instruction files. */\nasync function isRuntimeSkillFile(path: string, registry: SkillRegistryFace | undefined): Promise<boolean> {\n if (registry === undefined) return false\n try {\n const list = await registry.list()\n let real: string\n try {\n real = await realpath(path)\n } catch {\n return false\n }\n for (const summary of list) {\n if (summary.path === undefined) continue\n try {\n if ((await realpath(summary.path)) === real) return true\n } catch {\n continue\n }\n }\n } catch {\n return false\n }\n return false\n}\n\n/** Read one skill file, including its complete content. */\nexport async function readSkillDocument(\n registry: SkillRegistryFace | undefined,\n path: string,\n roots: SkillRootInfo[] = defaultSkillRoots(),\n): Promise<SkillDocumentInfo> {\n const local = await resolveSkillFile(path, roots)\n if (local !== undefined) {\n const fallback = local.directory === undefined ? basename(local.file, '.md') : basename(local.directory)\n const summary = await summarizeSkillFile(local.file, local.root, fallback, local.directory)\n const content = await readFile(local.file, 'utf8')\n if (Buffer.byteLength(content, 'utf8') > MAX_SKILL_BYTES) throw new Error('技能文件超过 1 MB')\n const parsed = parseSkillDocument(content, fallback)\n return { ...summary, content, body: parsed.body }\n }\n if (await isRuntimeSkillFile(path, registry)) {\n const content = await readFile(path, 'utf8')\n const fallback = basename(dirname(path))\n const parsed = parseSkillDocument(content, fallback)\n return {\n name: parsed.name,\n description: parsed.description,\n ...(parsed.whenToUse === undefined ? {} : { whenToUse: parsed.whenToUse }),\n path,\n source: 'runtime',\n sourceLabel: '运行时技能',\n writable: false,\n valid: parsed.valid,\n ...(parsed.issue === undefined ? {} : { issue: parsed.issue }),\n modelInvocable: !parsed.disableModelInvocation,\n userInvocable: parsed.userInvocable,\n bytes: Buffer.byteLength(content, 'utf8'),\n resources: [],\n content,\n body: parsed.body,\n }\n }\n throw new Error('该技能文件不在可管理的目录中')\n}\n\n/**\n * Save one skill file in form mode or raw mode.\n * @param registry - runtime registry for read-back.\n * @param request - path plus either form fields or complete content.\n */\nexport async function saveSkillDocument(\n registry: SkillRegistryFace | undefined,\n request: SkillSaveRequest,\n roots: SkillRootInfo[] = defaultSkillRoots(),\n): Promise<SkillDocumentInfo> {\n const resolved = await resolveSkillFile(request.path, roots)\n if (resolved === undefined) throw new Error('该技能文件不在可管理的目录中')\n if (!resolved.root.writable) throw new Error('该目录是只读的')\n const current = await readFile(resolved.file, 'utf8')\n let next: string\n if (request.content !== undefined) {\n if (Buffer.byteLength(request.content, 'utf8') > MAX_SKILL_BYTES) throw new Error('技能文件超过 1 MB')\n next = request.content\n } else {\n if (request.fields === undefined) throw new Error('缺少要保存的字段')\n const fields = validateFields(request.fields)\n next = applySkillFields(current, fields, request.body ?? '')\n if (Buffer.byteLength(next, 'utf8') > MAX_SKILL_BYTES) throw new Error('技能文件超过 1 MB')\n }\n await writeFile(resolved.file, next, 'utf8')\n return await readSkillDocument(registry, resolved.file, roots)\n}\n\n/** Reject form values the provider would refuse to load. */\nfunction validateFields(fields: SkillFieldsInput): SkillFieldsInput {\n const name = fields.name.trim()\n if (!SKILL_NAME_PATTERN.test(name)) throw new Error('技能名必须是小写 kebab-case(例如 my-skill)')\n const description = fields.description.trim()\n if (description === '') throw new Error('描述不能为空')\n return { ...fields, name, description, whenToUse: fields.whenToUse.trim() }\n}\n\n/** Create a directory-bundle skill in one writable root. */\nexport async function createSkillDocument(\n registry: SkillRegistryFace | undefined,\n request: SkillCreateRequest,\n roots: SkillRootInfo[] = defaultSkillRoots(),\n): Promise<SkillDocumentInfo> {\n const fields = validateFields({\n name: request.name,\n description: request.description,\n whenToUse: request.whenToUse ?? '',\n disableModelInvocation: request.disableModelInvocation === true,\n userInvocable: request.userInvocable !== false,\n })\n const root = roots.find((candidate) => candidate.key === request.rootKey)\n if (root === undefined || !root.writable) throw new Error('目标目录不可写')\n await mkdir(root.path, { recursive: true })\n const realRoot = await realpath(root.path)\n const flat = join(realRoot, `${fields.name}.md`)\n try {\n await stat(flat)\n throw new Error(`已存在同名技能文件 ${fields.name}.md`)\n } catch (error) {\n if ((error as { code?: unknown }).code !== 'ENOENT') throw error\n }\n const directory = join(realRoot, fields.name)\n try {\n await stat(directory)\n throw new Error(`已存在同名技能目录 ${fields.name}/`)\n } catch (error) {\n if ((error as { code?: unknown }).code !== 'ENOENT') throw error\n }\n const requestedBody = request.body?.trim() ?? ''\n const body = requestedBody === '' ? `# ${fields.name}\\n` : requestedBody\n const content = createSkillContent({ ...fields, body })\n await mkdir(directory)\n try {\n await writeFile(join(directory, 'SKILL.md'), content, 'utf8')\n } catch (error) {\n await rm(directory, { recursive: true, force: true })\n throw error\n }\n return await readSkillDocument(registry, join(directory, 'SKILL.md'), roots)\n}\n\n/** Delete a skill directory bundle or flat skill file. */\nexport async function deleteSkillDocument(path: string, roots: SkillRootInfo[] = defaultSkillRoots()): Promise<void> {\n const resolved = await resolveSkillFile(path, roots)\n if (resolved === undefined) throw new Error('该技能文件不在可管理的目录中')\n if (!resolved.root.writable) throw new Error('该目录是只读的')\n if (resolved.directory === undefined) {\n await unlink(resolved.file)\n return\n }\n const realRoot = await realpath(resolved.root.path)\n if (dirname(resolved.directory) !== realRoot) throw new Error('拒绝删除非技能目录')\n await rm(resolved.directory, { recursive: true, force: false })\n}\n\n/** Read one file below a directory-bundle skill, with traversal and size guards. */\nexport async function readSkillResource(\n registry: SkillRegistryFace | undefined,\n skillPath: string,\n resource: string,\n roots: SkillRootInfo[] = defaultSkillRoots(),\n): Promise<SkillResourceContent> {\n const resolved = await resolveSkillFile(skillPath, roots)\n if (resolved === undefined || resolved.directory === undefined) {\n throw new Error('该技能没有可浏览的目录')\n }\n const parts = resource.split('/')\n if (resource.trim() === '' || isAbsolute(resource) || parts.some((part) => part === '..' || part === '')) {\n throw new Error('资源路径无效')\n }\n let realDir: string\n let file: string\n try {\n realDir = await realpath(resolved.directory)\n file = await realpath(join(resolved.directory, ...parts))\n } catch {\n throw new Error('资源文件不存在')\n }\n if (!isInside(realDir, file)) throw new Error('资源文件不在技能目录中')\n const info = await stat(file)\n if (!info.isFile()) throw new Error('该路径不是文件')\n if (info.size > MAX_SKILL_BYTES) throw new Error('资源文件超过 1 MB')\n const buffer = await readFile(file)\n const binary = buffer.includes(0)\n return {\n path: resource,\n bytes: info.size,\n ...(binary ? {} : { content: buffer.toString('utf8') }),\n binary,\n }\n}\n","/**\n * Skill file envelope handling.\n *\n * A skill file is YAML frontmatter plus a Markdown body. The manager edits a\n * handful of routing fields, so it parses the small scalar subset those fields\n * use and rewrites only the keys it owns; unrelated frontmatter (metadata,\n * license, unknown plugin keys) survives a form save byte-for-byte.\n *\n * This module is deliberately dependency-free: the browser-side tests import\n * the built artifact, and the Host half must not pull a YAML package into the\n * plugin bundle just to read four keys.\n */\nimport type { SkillFieldsInput } from '../shared/contracts.js'\n\n/** The provider's skill-name rule; a file whose name fails it never loads. */\nexport const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\n/** Parsed view of one skill file. */\nexport interface ParsedSkillDocument {\n name: string\n description: string\n whenToUse?: string\n disableModelInvocation: boolean\n userInvocable: boolean\n body: string\n valid: boolean\n issue?: string\n}\n\n/** A frontmatter document split at its closing delimiter. */\nexport interface SplitDocument {\n yamlLines: string[]\n body: string\n}\n\n/** One top-level YAML entry and the lines it occupies. */\ninterface YamlEntry {\n key: string | null\n lines: string[]\n}\n\nconst TOP_KEY = /^([A-Za-z0-9_-]+):(.*)$/\n\n/** Normalize line endings and remove a UTF-8 BOM without touching content. */\nfunction normalize(raw: string): string {\n return raw.replace(/^\\uFEFF/, '').replace(/\\r\\n?/g, '\\n')\n}\n\n/**\n * Split a skill file into its frontmatter lines and body.\n * @param raw - complete file text.\n * @returns the split document, or undefined when the envelope is absent.\n */\nexport function splitDocument(raw: string): SplitDocument | undefined {\n const text = normalize(raw)\n const lines = text.split('\\n')\n if (lines[0] !== '---') return undefined\n let close = -1\n for (let index = 1; index < lines.length; index += 1) {\n if (lines[index] === '---') {\n close = index\n break\n }\n }\n if (close < 0) return undefined\n return { yamlLines: lines.slice(1, close), body: lines.slice(close + 1).join('\\n') }\n}\n\n/** Parse one YAML scalar the way the routing fields need it. */\nexport function parseScalar(raw: string): unknown {\n const value = raw.trim()\n if (value === '') return ''\n if (value === 'true') return true\n if (value === 'false') return false\n if (value === 'null' || value === '~') return null\n if (value.startsWith('\"')) {\n try {\n return JSON.parse(value)\n } catch {\n return value.replace(/^\"|\"$/g, '').replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, '\\\\')\n }\n }\n if (value.startsWith(\"'\")) {\n return value.replace(/^'|'$/g, '').replace(/''/g, \"'\")\n }\n const comment = value.indexOf(' #')\n return comment < 0 ? value : value.slice(0, comment).trim()\n}\n\n/** Parse the top-level scalar entries used by the form editor. */\nexport function parseYamlScalars(lines: readonly string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index] ?? ''\n const match = TOP_KEY.exec(line)\n if (match === null) continue\n const key = match[1]\n if (key === undefined) continue\n let value = (match[2] ?? '').trim()\n const blockScalar = value === '' || value.startsWith('|') || value.startsWith('>')\n if (!blockScalar) {\n out[key] = parseScalar(value)\n continue\n }\n const block: string[] = []\n let cursor = index + 1\n for (; cursor < lines.length; cursor += 1) {\n const candidate = lines[cursor] ?? ''\n if (candidate === '') {\n block.push('')\n continue\n }\n if (!/^\\s/.test(candidate)) break\n block.push(candidate)\n }\n index = cursor - 1\n if (block.length === 0) {\n out[key] = ''\n continue\n }\n const indents = block.filter((entry) => entry.trim() !== '').map((entry) => /^\\s*/.exec(entry)?.[0].length ?? 0)\n const indent = indents.length === 0 ? 0 : Math.min(...indents)\n const dedented = block.map((entry) => entry.slice(Math.min(indent, entry.length)))\n value = value.startsWith('>')\n ? dedented\n .join(' ')\n .replace(/[ \\t]+/g, ' ')\n .trim()\n : dedented.join('\\n').replace(/\\n+$/, '')\n out[key] = value\n }\n return out\n}\n\n/** Read a non-empty string field, or undefined. */\nfunction stringField(data: Record<string, unknown>, key: string): string | undefined {\n const value = data[key]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/** Read an optional boolean field, flagging a malformed value. */\nfunction booleanField(data: Record<string, unknown>, key: string): boolean | undefined | 'invalid' {\n const value = data[key]\n if (value === undefined || value === null) return undefined\n if (typeof value === 'boolean') return value\n return 'invalid'\n}\n\n/**\n * Parse a complete skill file into the view the manager renders.\n * @param raw - file text.\n * @param fallbackName - directory or file stem used when the frontmatter lacks a name.\n * @returns parsed fields plus a validity verdict the manager surfaces instead of hiding bad files.\n */\nexport function parseSkillDocument(raw: string, fallbackName: string): ParsedSkillDocument {\n const split = splitDocument(raw)\n if (split === undefined) {\n return {\n name: fallbackName,\n description: '',\n disableModelInvocation: false,\n userInvocable: true,\n body: normalize(raw).replace(/^\\n+/, ''),\n valid: false,\n issue: '缺少 YAML frontmatter(文件必须以 --- 开头并闭合)',\n }\n }\n const data = parseYamlScalars(split.yamlLines)\n const declaredName = stringField(data, 'name')\n const description = stringField(data, 'description')\n const whenToUse = stringField(data, 'whenToUse')\n const modelFlag = booleanField(data, 'disable-model-invocation')\n const userFlag = booleanField(data, 'user-invocable')\n const issues: string[] = []\n if (declaredName === undefined) issues.push('缺少 name')\n else if (!SKILL_NAME_PATTERN.test(declaredName)) issues.push(`name \"${declaredName}\" 不是 kebab-case`)\n if (description === undefined) issues.push('缺少 description')\n if (modelFlag === 'invalid') issues.push('disable-model-invocation 必须是布尔值')\n if (userFlag === 'invalid') issues.push('user-invocable 必须是布尔值')\n return {\n name: declaredName ?? fallbackName,\n description: description ?? '',\n ...(whenToUse === undefined ? {} : { whenToUse }),\n disableModelInvocation: modelFlag === true,\n userInvocable: userFlag !== false,\n body: split.body.replace(/^\\n+/, '').replace(/\\s+$/, '\\n'),\n valid: issues.length === 0,\n ...(issues.length === 0 ? {} : { issue: issues.join(';') }),\n }\n}\n\n/** Quote a string as a single-line YAML double-quoted scalar. */\nfunction quote(value: string): string {\n return JSON.stringify(value)\n}\n\n/** Split YAML lines into top-level entries, preserving each entry's raw lines. */\nfunction entriesOf(lines: readonly string[]): YamlEntry[] {\n const entries: YamlEntry[] = []\n for (const line of lines) {\n const match = TOP_KEY.exec(line)\n if (match !== null) {\n const key = match[1]\n entries.push({ key: key === undefined ? null : key, lines: [line] })\n continue\n }\n const last = entries[entries.length - 1]\n if (last === undefined) entries.push({ key: null, lines: [line] })\n else last.lines.push(line)\n }\n return entries\n}\n\n/** Frontmatter keys the form owns; every other key is preserved verbatim. */\nconst MANAGED_KEYS = new Set(['name', 'description', 'whenToUse', 'disable-model-invocation', 'user-invocable'])\n\n/** The canonical field lines a form save writes, omitting defaults. */\nfunction fieldLines(fields: SkillFieldsInput): Array<[string, string]> {\n const lines: Array<[string, string]> = []\n lines.push(['name', quote(fields.name)])\n lines.push(['description', quote(fields.description)])\n if (fields.whenToUse.trim() !== '') lines.push(['whenToUse', quote(fields.whenToUse.trim())])\n if (fields.disableModelInvocation) lines.push(['disable-model-invocation', 'true'])\n if (!fields.userInvocable) lines.push(['user-invocable', 'false'])\n return lines\n}\n\n/**\n * Rewrite the manager-owned frontmatter fields and the body.\n *\n * Unknown keys and their indented blocks survive; an owned key that becomes\n * empty is removed, which keeps files in the shape the provider documents.\n * @param raw - current file text.\n * @param fields - form values.\n * @param body - new Markdown body.\n * @returns complete replacement file text.\n */\nexport function applySkillFields(raw: string, fields: SkillFieldsInput, body: string): string {\n const split = splitDocument(raw)\n if (split === undefined) return createSkillContent({ ...fields, body })\n const owned = new Map(fieldLines(fields))\n const entries = entriesOf(split.yamlLines)\n const emitted = new Set<string>()\n const next: string[] = []\n for (const entry of entries) {\n // Unknown keys and their indented blocks survive verbatim. An owned key is replaced by the\n // canonical line, or dropped when the form value became empty (its default).\n if (entry.key === null || !MANAGED_KEYS.has(entry.key)) {\n next.push(...entry.lines)\n continue\n }\n if (emitted.has(entry.key)) continue\n emitted.add(entry.key)\n const line = owned.get(entry.key)\n if (line !== undefined) next.push(`${entry.key}: ${line}`)\n }\n for (const [key, line] of owned) {\n if (!emitted.has(key)) next.push(`${key}: ${line}`)\n }\n return envelope(next, body)\n}\n\n/** Build a canonical skill file from scratch. */\nexport function createSkillContent(input: SkillFieldsInput & { body: string }): string {\n return envelope(\n fieldLines(input).map(([key, line]) => `${key}: ${line}`),\n input.body,\n )\n}\n\n/** Join frontmatter lines and a body into one file with a stable trailing newline. */\nfunction envelope(lines: readonly string[], body: string): string {\n const cleanBody = body.replace(/^\\n+/, '').replace(/\\s+$/, '')\n return `---\\n${lines.join('\\n')}\\n---\\n\\n${cleanBody === '' ? '' : `${cleanBody}\\n`}`\n}\n","/**\n * Custom skill scan directories.\n *\n * Built-in roots are fixed by DSH; a user can add absolute directories that the\n * panel treats like the built-in writable roots. The list lives in the\n * dsh-tool-manage state directory, not in the visibility policy: it is a discovery\n * setting, not a per-preset rule.\n */\nimport { createHash } from 'node:crypto'\nimport { mkdir, readFile, stat, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { basename, dirname, isAbsolute, normalize } from 'node:path'\n\nimport type { SkillRootInfo } from '../shared/contracts.js'\nimport { defaultSkillRoots } from './skills.js'\nimport { statePath } from './state.js'\n\n/** Bound the configured list. */\nconst MAX_CUSTOM_ROOTS = 20\n\n/** Stable key for a custom path; survives reordering. */\nfunction customKey(path: string): string {\n return `custom:${createHash('sha1').update(path).digest('hex').slice(0, 10)}`\n}\n\n/** Resolve the settings file under `$DSH_HOME/dsh-tool-manage`. */\nexport function skillRootsPath(environment: NodeJS.ProcessEnv = process.env, home = homedir()): string {\n return statePath('skill-roots.json', environment, home)\n}\n\n/** Normalize one user-supplied absolute directory. */\nfunction normalizeDirectory(input: unknown): string {\n if (typeof input !== 'string') throw new Error('扫描目录必须是字符串')\n const value = input.trim()\n if (value === '') throw new Error('扫描目录不能为空')\n if (!isAbsolute(value)) throw new Error(`扫描目录必须是绝对路径:${value}`)\n const normalized = normalize(value)\n if (normalized === '/' || normalized === '') throw new Error('不能把文件系统根目录作为扫描目录')\n return normalized\n}\n\n/** Read the configured directories, tolerating a missing or damaged file. */\nexport async function readCustomSkillDirectories(): Promise<string[]> {\n let raw: string\n try {\n raw = await readFile(skillRootsPath(), 'utf8')\n } catch {\n return []\n }\n try {\n const parsed: unknown = JSON.parse(raw)\n if (typeof parsed !== 'object' || parsed === null) return []\n const list = Reflect.get(parsed, 'directories')\n if (!Array.isArray(list)) return []\n const out: string[] = []\n for (const entry of list) {\n try {\n const path = normalizeDirectory(entry)\n if (!out.includes(path)) out.push(path)\n } catch {\n // Ignore one bad entry rather than losing every configured root.\n }\n }\n return out.slice(0, MAX_CUSTOM_ROOTS)\n } catch {\n return []\n }\n}\n\n/** Fill the volatile `exists` flag without changing the stable identity. */\nasync function withExists(root: SkillRootInfo): Promise<SkillRootInfo> {\n return {\n ...root,\n exists: await stat(root.path)\n .then((info) => info.isDirectory())\n .catch(() => false),\n }\n}\n\n/** All roots: built-ins in display order, then custom directories. */\nexport async function allSkillRoots(): Promise<SkillRootInfo[]> {\n const custom = await readCustomSkillDirectories()\n const builtIns = await Promise.all(defaultSkillRoots().map(withExists))\n const customRoots = await Promise.all(\n custom.map(async (path) =>\n withExists({\n key: customKey(path),\n label: basename(path) || path,\n path,\n writable: true,\n exists: false,\n custom: true,\n }),\n ),\n )\n return [...builtIns, ...customRoots]\n}\n\n/** Persist the custom list. Unknown fields are discarded. */\nexport async function saveCustomSkillDirectories(input: unknown): Promise<string[]> {\n if (!Array.isArray(input)) throw new Error('directories 必须是数组')\n const out: string[] = []\n for (const entry of input) {\n const path = normalizeDirectory(entry)\n if (!out.includes(path)) out.push(path)\n if (out.length > MAX_CUSTOM_ROOTS) throw new Error(`最多配置 ${String(MAX_CUSTOM_ROOTS)} 个扫描目录`)\n }\n const file = skillRootsPath()\n await mkdir(dirname(file), { recursive: true })\n await writeFile(file, `${JSON.stringify({ version: 1, directories: out }, null, 2)}\\n`, 'utf8')\n return out\n}\n","/**\n * This plugin's on-disk state directory.\n *\n * Policy, variable metadata and custom skill roots all live under one\n * `$DSH_HOME/<plugin>` directory. The directory was renamed with the package;\n * the first access moves the old `tool-manager` directory so an upgrade keeps\n * the user's injection policy, variables and scan roots instead of silently\n * starting from empty state.\n */\nimport { existsSync, mkdirSync, renameSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\n/** Resolve `$DSH_HOME` the same way every state file does. */\nexport function dshHome(environment: NodeJS.ProcessEnv = process.env, home = homedir()): string {\n return environment.DSH_HOME?.trim() || join(home, '.dsh')\n}\n\n/** Resolve the state directory, migrating the pre-rename name once. */\nexport function stateDir(environment: NodeJS.ProcessEnv = process.env, home = homedir()): string {\n const root = dshHome(environment, home)\n const next = join(root, 'dsh-tool-manage')\n const previous = join(root, 'tool-manager')\n if (existsSync(next) || !existsSync(previous)) return next\n try {\n mkdirSync(root, { recursive: true })\n renameSync(previous, next)\n return next\n } catch {\n // A concurrent process may have moved it first; otherwise keep using the\n // old directory rather than dropping the user's state on the floor.\n return existsSync(next) ? next : previous\n }\n}\n\n/** Resolve one file inside the state directory. */\nexport function statePath(name: string, environment: NodeJS.ProcessEnv = process.env, home = homedir()): string {\n return join(stateDir(environment, home), name)\n}\n","/**\n * Variables: named strings the MCP forms can reference as `{{name}}`.\n *\n * Two halves, deliberately kept apart:\n *\n * - **Values** live in the Harness credential store (`ctx.credentials`), which\n * owns `$DSH_HOME/.credentials.yaml` at `0600` with atomic, locked writes. An\n * MCP entry stores only `${credential:NAME}`, and the MCP client resolves it\n * at connection time — so a secret is never copied into a settings file.\n * - **Metadata** (label, description, who created it, and the human/AI\n * read-write-delete permissions) lives in `$DSH_HOME/dsh-tool-manage/variables.json`,\n * which holds no value at all.\n *\n * Permissions are enforced by this module for every caller that goes through\n * it: the panel routes act as `human`, the model's MCP tools act as `ai`. They\n * bound what each surface may read or change; they are not a sandbox against\n * a shell that can open the credential file directly.\n */\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname } from 'node:path'\n\nimport type {\n VariableActor,\n VariablePermissions,\n VariableSaveRequest,\n VariableSource,\n VariableSummaryInfo,\n} from '../shared/contracts.js'\nimport {\n isVariableName,\n mapEntryStrings,\n toNativeToken,\n toSugarToken,\n type TemplatedEntry,\n} from '../shared/variables.js'\nimport { statePath } from './state.js'\n\n/** The one metadata document version this build writes. */\nconst DOCUMENT_VERSION = 1\n/** Bound every free text field so a broken client cannot bloat the file. */\nconst MAX_NAME = 100\nconst MAX_LABEL = 200\nconst MAX_DESCRIPTION = 2000\n/** Mask shown when a value exists but the actor may not read it. */\nconst FALLBACK_MASK = '••••••'\n\n/** One variable's metadata; the value itself is in the credential store. */\ninterface VariableRecord {\n label: string\n description: string\n source: VariableSource\n permissions: Record<VariableActor, VariablePermissions>\n createdAt: string\n updatedAt: string\n}\n\n/** The metadata document. */\ninterface VariableDocument {\n version: 1\n variables: Record<string, VariableRecord>\n}\n\n/** The slice of the credential provider this module calls. */\nexport interface CredentialsFace {\n resolve(ref: string): Promise<{ value: string; source: string } | undefined>\n describe(ref: string): Promise<{ configured: boolean; source?: string; writable: boolean; masked?: string }>\n set(ref: string, value: string): Promise<void>\n unset(ref: string): Promise<void>\n}\n\n/** Services this module reaches. */\ninterface VariableHost {\n get(name: string): unknown\n}\n\n/** Resolve the metadata file under `$DSH_HOME`. */\nexport function variablesPath(environment: NodeJS.ProcessEnv = process.env, home = homedir()): string {\n return statePath('variables.json', environment, home)\n}\n\n/** What a newly created variable allows: the owner keeps everything, the model may rotate but not read or delete. */\nexport function defaultPermissions(): Record<VariableActor, VariablePermissions> {\n return {\n human: { read: true, write: true, delete: true },\n ai: { read: false, write: true, delete: false },\n }\n}\n\n/** A document with no variables. */\nfunction emptyDocument(): VariableDocument {\n return { version: DOCUMENT_VERSION, variables: {} }\n}\n\n/** Read the credential provider, or undefined when the composition mounts none. */\nexport function credentialsOf(host: VariableHost): CredentialsFace | undefined {\n const value = host.get('credentials')\n if (typeof value !== 'object' || value === null) return undefined\n if (typeof Reflect.get(value, 'set') !== 'function') return undefined\n return value as CredentialsFace\n}\n\n/** Copy one permission set, filling absent flags from the defaults. */\nfunction normalizePermissions(raw: unknown): Record<VariableActor, VariablePermissions> {\n const base = defaultPermissions()\n if (typeof raw !== 'object' || raw === null) return base\n const pick = (actor: VariableActor): VariablePermissions => {\n const source = Reflect.get(raw, actor)\n if (typeof source !== 'object' || source === null) return base[actor]\n const flag = (key: keyof VariablePermissions): boolean => {\n const value = Reflect.get(source, key)\n return typeof value === 'boolean' ? value : base[actor][key]\n }\n return { read: flag('read'), write: flag('write'), delete: flag('delete') }\n }\n return { human: pick('human'), ai: pick('ai') }\n}\n\n/** Validate and copy one stored record. */\nfunction normalizeRecord(raw: unknown, name: string): VariableRecord {\n if (typeof raw !== 'object' || raw === null) throw new Error(`variables: \"${name}\" is not an object`)\n const record = raw as Record<string, unknown>\n const source = record['source']\n if (source !== 'plugin' && source !== 'manual' && source !== 'ai') {\n throw new Error(`variables: \"${name}\" has an invalid source`)\n }\n const createdAt = typeof record['createdAt'] === 'string' ? record['createdAt'] : new Date(0).toISOString()\n const updatedAt = typeof record['updatedAt'] === 'string' ? record['updatedAt'] : createdAt\n return {\n label: typeof record['label'] === 'string' ? record['label'].slice(0, MAX_LABEL) : '',\n description: typeof record['description'] === 'string' ? record['description'].slice(0, MAX_DESCRIPTION) : '',\n source,\n permissions: normalizePermissions(record['permissions']),\n createdAt,\n updatedAt,\n }\n}\n\n/** Read the metadata document; a missing file is an empty one. */\nexport async function readVariableDocument(path = variablesPath()): Promise<VariableDocument> {\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (error) {\n if (typeof error === 'object' && error !== null && Reflect.get(error, 'code') === 'ENOENT') return emptyDocument()\n throw error\n }\n const parsed: unknown = JSON.parse(text)\n if (typeof parsed !== 'object' || parsed === null) throw new Error('variables: the document is not an object')\n const variables = Reflect.get(parsed, 'variables')\n if (typeof variables !== 'object' || variables === null) return emptyDocument()\n const out: Record<string, VariableRecord> = {}\n for (const [name, record] of Object.entries(variables as Record<string, unknown>)) {\n if (!isVariableName(name)) continue\n out[name] = normalizeRecord(record, name)\n }\n return { version: DOCUMENT_VERSION, variables: out }\n}\n\n/** Replace the metadata document atomically. */\nasync function writeVariableDocument(document: VariableDocument, path = variablesPath()): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n const temporary = `${path}.${String(process.pid)}.tmp`\n await writeFile(temporary, `${JSON.stringify(document, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 })\n await rename(temporary, path)\n}\n\n/** In-process write queue: metadata updates are read-modify-write, so they must not interleave. */\nlet writeTail: Promise<unknown> = Promise.resolve()\n\n/** Run one mutation exclusively. */\nfunction serialized<T>(work: () => Promise<T>): Promise<T> {\n const next = writeTail.then(work, work)\n writeTail = next.catch(() => undefined)\n return next\n}\n\n/** The names the document declares, for token rewriting. */\nexport async function variableNames(): Promise<(name: string) => boolean> {\n const document = await readVariableDocument()\n const known = new Set(Object.keys(document.variables))\n return (name: string) => known.has(name)\n}\n\n/**\n * Rewrite `{{name}}` tokens a variable declares into native templates.\n * @param entry - an MCP entry's template-capable fields.\n * @returns the same shape with native templates; unknown tokens are untouched.\n */\nexport async function entryToNative<T extends TemplatedEntry>(entry: T): Promise<T> {\n const known = await variableNames()\n return mapEntryStrings(entry, (value) => toNativeToken(value, known))\n}\n\n/**\n * Rewrite native templates this plugin owns back into `{{name}}` for display.\n * @param entry - a stored MCP entry.\n */\nexport async function entryToSugar<T extends TemplatedEntry>(entry: T): Promise<T> {\n const known = await variableNames()\n return mapEntryStrings(entry, (value) => toSugarToken(value, known))\n}\n\n/** The effective permissions for one actor. */\nfunction permissionsFor(record: VariableRecord | undefined, actor: VariableActor): VariablePermissions {\n const permissions = record?.permissions ?? defaultPermissions()\n return { ...permissions[actor] }\n}\n\n/** Build one wire row for an actor; the value is resolved only when the actor may read it. */\nasync function summarize(\n credentials: CredentialsFace | undefined,\n name: string,\n record: VariableRecord,\n actor: VariableActor,\n): Promise<VariableSummaryInfo> {\n const can = permissionsFor(record, actor)\n let configured = false\n let masked = FALLBACK_MASK\n let value: string | undefined\n if (credentials !== undefined) {\n try {\n const info = await credentials.describe(name)\n configured = info.configured\n if (typeof info.masked === 'string' && info.masked !== '') masked = info.masked\n if (can.read && info.configured) value = (await credentials.resolve(name))?.value\n } catch {\n // A store failure leaves the row masked rather than failing the whole list.\n }\n }\n return {\n name,\n label: record.label,\n description: record.description,\n source: record.source,\n configured,\n masked,\n ...(value === undefined ? {} : { value }),\n permissions: { human: { ...record.permissions.human }, ai: { ...record.permissions.ai } },\n can,\n createdAt: record.createdAt,\n updatedAt: record.updatedAt,\n }\n}\n\n/**\n * List every variable for one actor.\n * @param host - services the module reaches.\n * @param actor - who is asking; decides the value and the effective permissions.\n */\nexport async function listVariables(\n host: VariableHost,\n actor: VariableActor,\n): Promise<{ variables: VariableSummaryInfo[]; warnings: string[] }> {\n const document = await readVariableDocument()\n const credentials = credentialsOf(host)\n const warnings: string[] = []\n if (credentials === undefined) warnings.push('凭据服务不可用:变量值无法读取或保存')\n const rows: VariableSummaryInfo[] = []\n for (const name of Object.keys(document.variables).sort((left, right) => left.localeCompare(right))) {\n const record = document.variables[name]\n if (record === undefined) continue\n rows.push(await summarize(credentials, name, record, actor))\n }\n return { variables: rows, warnings }\n}\n\n/**\n * Read one variable for one actor, requiring only that it exists.\n * @param host - services the module reaches.\n * @param name - the variable name.\n * @param actor - who is asking.\n */\nexport async function getVariable(\n host: VariableHost,\n name: string,\n actor: VariableActor,\n): Promise<VariableSummaryInfo> {\n const document = await readVariableDocument()\n const record = document.variables[name]\n if (record === undefined) throw new Error(`变量 \"${name}\" 不存在`)\n return await summarize(credentialsOf(host), name, record, actor)\n}\n\n/** Reject a field that is too long or empty where it must not be. */\nfunction bounded(value: string, limit: number, field: string): string {\n if (value.length > limit) throw new Error(`${field} 超过 ${String(limit)} 个字符`)\n return value\n}\n\n/**\n * Create or update one variable.\n *\n * Creating requires the credential reference to be free: silently overwriting a\n * reference another surface already stores would change that surface's\n * credentials. Editing changes only what was sent and never resurrects a value.\n * @param host - services the module reaches.\n * @param input - the requested fields.\n * @param actor - who is writing; decides the permission checks and the source.\n */\nexport async function saveVariable(\n host: VariableHost,\n input: VariableSaveRequest,\n actor: VariableActor,\n): Promise<VariableSummaryInfo> {\n const name = typeof input.name === 'string' ? input.name.trim() : ''\n if (!isVariableName(name)) throw new Error('变量名必须是 POSIX 标识符:字母或下划线开头,只含字母、数字、下划线')\n bounded(name, MAX_NAME, '变量名')\n const credentials = credentialsOf(host)\n if (credentials === undefined) throw new Error('凭据服务不可用:变量无法保存')\n\n return await serialized(async () => {\n const document = await readVariableDocument()\n const existing = document.variables[name]\n const can = permissionsFor(existing, actor)\n if (existing !== undefined && !can.write) throw new Error(`当前身份没有修改变量 \"${name}\" 的权限`)\n\n if (existing === undefined && (await credentials.describe(name)).configured) {\n throw new Error(`凭据 \"${name}\" 已被其他来源使用;请换一个变量名`)\n }\n\n const now = new Date().toISOString()\n const record: VariableRecord = existing ?? {\n label: '',\n description: '',\n source: actor === 'ai' ? 'ai' : 'manual',\n permissions: defaultPermissions(),\n createdAt: now,\n updatedAt: now,\n }\n if (typeof input.label === 'string') record.label = bounded(input.label.trim(), MAX_LABEL, '显示名')\n if (typeof input.description === 'string') {\n record.description = bounded(input.description.trim(), MAX_DESCRIPTION, '描述')\n }\n if (input.permissions !== undefined) {\n record.permissions = normalizePermissions({\n human: { ...record.permissions.human, ...(input.permissions.human ?? {}) },\n ai: { ...record.permissions.ai, ...(input.permissions.ai ?? {}) },\n })\n }\n record.updatedAt = now\n\n if (typeof input.value === 'string') {\n if (input.value.length > 0) await credentials.set(name, input.value)\n else await credentials.unset(name)\n }\n\n document.variables[name] = record\n await writeVariableDocument(document)\n return await summarize(credentials, name, record, actor)\n })\n}\n\n/**\n * Remove one variable and its stored value.\n * @param host - services the module reaches.\n * @param name - the variable name.\n * @param actor - who is deleting; requires the delete permission.\n */\nexport async function deleteVariable(host: VariableHost, name: string, actor: VariableActor): Promise<void> {\n await serialized(async () => {\n const document = await readVariableDocument()\n const record = document.variables[name]\n if (record === undefined) throw new Error(`变量 \"${name}\" 不存在`)\n if (!permissionsFor(record, actor).delete) throw new Error(`当前身份没有删除变量 \"${name}\" 的权限`)\n const credentials = credentialsOf(host)\n if (credentials !== undefined) await credentials.unset(name)\n delete document.variables[name]\n await writeVariableDocument(document)\n })\n}\n","/**\n * Model-facing management tools, split by resource domain.\n *\n * The UI and the agent operate on the same storage: skills are files under the\n * writable roots, MCP entries are the `mcp-manager` row's config, the preset\n * policy is `policy.json`, and the registry projections are read-only. Keeping\n * one tool per resource domain avoids a dozen near-empty CRUD tools: each tool\n * takes an `action` and returns the same shapes the routes return.\n */\nimport type {\n AgentPresetInfo,\n InjectionPolicy,\n SkillDocumentInfo,\n SkillSummaryInfo,\n McpServerEntry,\n VariableActor,\n VariablePermissions,\n VariableSaveRequest,\n} from '../shared/contracts.js'\nimport { toSugarToken } from '../shared/variables.js'\nimport type { HostContext } from './context.js'\nimport {\n findMcpEntry,\n listMcpServers,\n mcpServerTools,\n probeMcpServer,\n removeMcpServer,\n restartMcpServer,\n upsertMcpServer,\n} from './mcp-config.js'\nimport { collectOtherTools } from './other-tools.js'\nimport type { McpPolicyController } from './policy.js'\nimport {\n createSkillDocument,\n deleteSkillDocument,\n listLocalSkills,\n listSkills,\n readSkillDocument,\n readSkillResource,\n saveSkillDocument,\n skillRegistryOf,\n} from './skills.js'\nimport { allSkillRoots, saveCustomSkillDirectories } from './skill-roots.js'\nimport {\n deleteVariable,\n entryToNative,\n entryToSugar,\n getVariable,\n listVariables,\n saveVariable,\n variableNames,\n} from './variables.js'\nimport {\n argsRecord,\n readBoolean,\n readNumber,\n readObject,\n readString,\n readStringArray,\n renderJson,\n requireConfirm,\n requireEnum,\n requireString,\n ToolError,\n type ToolDefinitionFace,\n type ToolRunContextFace,\n type ToolTextBlock,\n} from './tool-kit.js'\n\n/** `output.render` receives `(arguments, value)`; only the canonical value is rendered. */\nfunction renderResult(_args: unknown, value: unknown): ToolTextBlock[] {\n return renderJson(value)\n}\n\nconst SKILL_ACTIONS = ['list', 'get', 'create', 'update', 'delete', 'read_resource'] as const\nconst SKILL_ROOT_ACTIONS = ['list', 'set'] as const\nconst MCP_ACTIONS = [\n 'list',\n 'get',\n 'create',\n 'update',\n 'delete',\n 'test',\n 'restart',\n 'enable',\n 'disable',\n 'set_icon',\n] as const\nconst VISIBILITY_ACTIONS = ['get', 'set_mcp_injection', 'set_skill_injection', 'remove_injection'] as const\nconst CATALOG_ACTIONS = ['tools', 'tool', 'presets'] as const\nconst VARIABLE_ACTIONS = ['list', 'get', 'create', 'update', 'delete'] as const\n\n/** One resolved writable-or-readonly skill file. */\ninterface ResolvedSkill {\n path: string\n writable: boolean\n}\n\n/** Read an optional preset override map of booleans. */\nfunction readBooleanMap(record: Record<string, unknown>, key: string): Record<string, boolean> {\n const value = record[key]\n if (value === undefined) return {}\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ToolError('invalid_argument', `\"${key}\" must be an object of booleans`)\n }\n const out: Record<string, boolean> = {}\n for (const [name, enabled] of Object.entries(value)) {\n if (typeof enabled !== 'boolean') {\n throw new ToolError('invalid_argument', `\"${key}.${name}\" must be a boolean`)\n }\n out[name] = enabled\n }\n return out\n}\n\n/** The preset an Agent currently runs under, preferring the committed projection. */\nfunction presetOfAgent(ctx: HostContext, agent: unknown): string | undefined {\n const session = (agent as { session?: unknown } | undefined)?.session\n try {\n const presets = ctx.get('agentPresets') as { presetForSession?(session: unknown): string | null } | undefined\n const selected = presets?.presetForSession?.(session)\n if (typeof selected === 'string' && selected !== '') return selected\n } catch {\n // Fall through to the durable header.\n }\n const header = (session as { header?: { agentPreset?: unknown } } | undefined)?.header?.agentPreset\n return typeof header === 'string' && header !== '' ? header : undefined\n}\n\n/** Find one skill file by path or by frontmatter name; local files win over runtime ones. */\nasync function resolveSkill(\n ctx: HostContext,\n options: { name?: string; path?: string; writable: boolean },\n roots: Awaited<ReturnType<typeof allSkillRoots>>,\n): Promise<ResolvedSkill> {\n const registry = skillRegistryOf(ctx)\n if (options.path !== undefined) {\n const document = await readSkillDocument(registry, options.path, roots)\n if (options.writable && !document.writable) throw new Error('this skill file is not writable')\n return { path: document.path ?? options.path, writable: document.writable }\n }\n const name = options.name\n if (name === undefined || name.trim() === '') throw new Error('provide \"name\" or \"path\"')\n const local = await listLocalSkills(roots)\n const candidates = local.skills.filter((skill) => skill.name === name && skill.path !== undefined)\n const localMatch = candidates.find((skill) => skill.writable) ?? candidates[0]\n if (localMatch?.path !== undefined) {\n if (options.writable && !localMatch.writable) throw new Error(`skill \"${name}\" is read-only`)\n return { path: localMatch.path, writable: localMatch.writable }\n }\n const all = await listSkills(registry, roots)\n const runtimeMatch = all.skills.find((skill) => skill.name === name && skill.path !== undefined)\n if (runtimeMatch?.path === undefined) throw new Error(`unknown skill \"${name}\"`)\n if (options.writable) throw new Error(`skill \"${name}\" is provided at runtime and is read-only`)\n return { path: runtimeMatch.path, writable: false }\n}\n\n/** Keep the list payload compact: resource names, not per-file sizes. */\nfunction summarizeSkill(skill: SkillSummaryInfo): Record<string, unknown> {\n const truncated = skill.description.length > 240\n return {\n name: skill.name,\n description: truncated ? `${skill.description.slice(0, 237)}…` : skill.description,\n ...(truncated ? { descriptionTruncated: true } : {}),\n ...(skill.path === undefined ? {} : { path: skill.path }),\n ...(skill.dir === undefined ? {} : { dir: skill.dir }),\n source: skill.source,\n sourceLabel: skill.sourceLabel,\n ...(skill.rootKey === undefined ? {} : { rootKey: skill.rootKey }),\n writable: skill.writable,\n valid: skill.valid,\n ...(skill.issue === undefined ? {} : { issue: skill.issue }),\n modelInvocable: skill.modelInvocable,\n userInvocable: skill.userInvocable,\n bytes: skill.bytes,\n resources: skill.resources.map((resource) => resource.name),\n }\n}\n\n/** Run one `skill_manage` action. */\nasync function runSkillAction(ctx: HostContext, args: Record<string, unknown>): Promise<unknown> {\n const action = requireEnum(args, 'action', SKILL_ACTIONS)\n const registry = skillRegistryOf(ctx)\n const roots = await allSkillRoots()\n if (action === 'list') {\n const result = await listSkills(registry, roots)\n return {\n roots: result.roots,\n skills: result.skills.map(summarizeSkill),\n warnings: result.warnings,\n }\n }\n if (action === 'get') {\n const resolved = await resolveSkill(\n ctx,\n {\n ...(readString(args, 'name') === undefined ? {} : { name: readString(args, 'name') }),\n ...(readString(args, 'path') === undefined ? {} : { path: readString(args, 'path') }),\n writable: false,\n },\n roots,\n )\n const document: SkillDocumentInfo = await readSkillDocument(registry, resolved.path, roots)\n return { skill: document }\n }\n if (action === 'read_resource') {\n const resolved = await resolveSkill(\n ctx,\n {\n ...(readString(args, 'name') === undefined ? {} : { name: readString(args, 'name') }),\n ...(readString(args, 'path') === undefined ? {} : { path: readString(args, 'path') }),\n writable: false,\n },\n roots,\n )\n return { resource: await readSkillResource(registry, resolved.path, requireString(args, 'resource'), roots) }\n }\n if (action === 'create') {\n const rootKey = requireString(args, 'rootKey')\n const name = requireString(args, 'name')\n const description = requireString(args, 'description')\n const document = await createSkillDocument(\n registry,\n {\n rootKey,\n name,\n description,\n ...(readString(args, 'whenToUse') === undefined ? {} : { whenToUse: readString(args, 'whenToUse') }),\n ...(readString(args, 'body') === undefined ? {} : { body: readString(args, 'body') }),\n disableModelInvocation: readBoolean(args, 'disableModelInvocation') === true,\n userInvocable: readBoolean(args, 'userInvocable') !== false,\n },\n roots,\n )\n return { skill: document }\n }\n if (action === 'update') {\n const resolved = await resolveSkill(\n ctx,\n {\n ...(readString(args, 'name') === undefined ? {} : { name: readString(args, 'name') }),\n ...(readString(args, 'path') === undefined ? {} : { path: readString(args, 'path') }),\n writable: true,\n },\n roots,\n )\n const content = readString(args, 'content')\n const fields = {\n description: readString(args, 'description'),\n whenToUse: readString(args, 'whenToUse'),\n body: readString(args, 'body'),\n disableModelInvocation: readBoolean(args, 'disableModelInvocation'),\n userInvocable: readBoolean(args, 'userInvocable'),\n }\n const provided = Object.values(fields).some((value) => value !== undefined)\n if (content !== undefined && provided) throw new Error('provide \"content\" or form fields, not both')\n if (content === undefined && !provided) throw new Error('update requires \"content\" or at least one form field')\n if (content !== undefined) {\n return { skill: await saveSkillDocument(registry, { path: resolved.path, content }, roots) }\n }\n const current = await readSkillDocument(registry, resolved.path, roots)\n return {\n skill: await saveSkillDocument(\n registry,\n {\n path: resolved.path,\n fields: {\n name: current.valid ? current.name : (readString(args, 'name') ?? current.name),\n description: fields.description ?? current.description,\n whenToUse: fields.whenToUse ?? current.whenToUse ?? '',\n disableModelInvocation: fields.disableModelInvocation ?? !current.modelInvocable,\n userInvocable: fields.userInvocable ?? current.userInvocable,\n },\n body: fields.body ?? current.body,\n },\n roots,\n ),\n }\n }\n requireConfirm(args, 'delete')\n const resolved = await resolveSkill(\n ctx,\n {\n ...(readString(args, 'name') === undefined ? {} : { name: readString(args, 'name') }),\n ...(readString(args, 'path') === undefined ? {} : { path: readString(args, 'path') }),\n writable: true,\n },\n roots,\n )\n await deleteSkillDocument(resolved.path, roots)\n return { deleted: resolved.path }\n}\n\n/** List one server's live view or fail with a stable code. */\nfunction requireServer(\n ctx: HostContext,\n name: string,\n options: { configured?: boolean } = {},\n): ReturnType<typeof listMcpServers>['servers'][number] {\n const server = listMcpServers(ctx).servers.find((candidate) => candidate.name === name)\n if (server === undefined) throw new ToolError('not_found', `unknown MCP server \"${name}\"`)\n if (options.configured === true && !server.configured) {\n throw new ToolError('read_only', `server \"${name}\" is plugin-provided and cannot be edited here`)\n }\n return server\n}\n\n/** Render one stored entry for a model caller: templates this plugin owns become `{{name}}`. */\nasync function displayEntry(entry: McpServerEntry | undefined): Promise<McpServerEntry | undefined> {\n return entry === undefined ? undefined : await entryToSugar(entry)\n}\n\n/** Run one `mcp_manage` action. */\nasync function runMcpAction(\n ctx: HostContext,\n policy: McpPolicyController,\n args: Record<string, unknown>,\n exec: ToolRunContextFace,\n): Promise<unknown> {\n const action = requireEnum(args, 'action', MCP_ACTIONS)\n if (action === 'list') {\n const known = await variableNames()\n const listed = listMcpServers(ctx)\n return {\n ...listed,\n servers: listed.servers.map((server) => ({ ...server, endpoint: toSugarToken(server.endpoint, known) })),\n }\n }\n const name = requireString(args, 'name')\n if (action === 'get') {\n const server = requireServer(ctx, name)\n return {\n server: {\n ...server,\n ...(server.configured ? { entry: await displayEntry(findMcpEntry(ctx, name)) } : {}),\n },\n tools: mcpServerTools(ctx, name),\n }\n }\n if (action === 'create') {\n const entry = readObject(args, 'entry')\n if (entry === undefined) throw new ToolError('invalid_argument', 'create requires \"entry\"')\n const existing = listMcpServers(ctx).servers.find((candidate) => candidate.name === name)\n if (existing?.configured === true) throw new ToolError('conflict', `MCP server \"${name}\" already exists`)\n if (existing?.registered === true) throw new ToolError('read_only', `server \"${name}\" is plugin-provided`)\n return { name, entry: await displayEntry(await upsertMcpServer(ctx, name, await entryToNative(entry))) }\n }\n if (action === 'update') {\n requireServer(ctx, name, { configured: true })\n const patch = readObject(args, 'entry')\n if (patch === undefined || Object.keys(patch).length === 0) {\n throw new ToolError('invalid_argument', 'update requires a non-empty \"entry\" patch')\n }\n return { name, entry: await displayEntry(await upsertMcpServer(ctx, name, await entryToNative(patch))) }\n }\n if (action === 'delete') {\n requireConfirm(args, 'delete')\n await removeMcpServer(ctx, name)\n return { deleted: name }\n }\n if (action === 'test') {\n requireServer(ctx, name)\n const timeoutMs = readNumber(args, 'timeoutMs')\n return {\n name,\n result: await probeMcpServer(ctx, name, {\n signal: exec.signal,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n }),\n }\n }\n if (action === 'restart') {\n requireServer(ctx, name)\n await restartMcpServer(ctx, name)\n return { restarted: name }\n }\n if (action === 'enable' || action === 'disable') {\n requireServer(ctx, name, { configured: true })\n const enabled = action === 'enable'\n return { name, enabled, entry: await upsertMcpServer(ctx, name, { enabled }) }\n }\n // set_icon\n requireServer(ctx, name)\n const icon = readString(args, 'icon')\n if (icon === undefined) throw new ToolError('invalid_argument', 'set_icon requires \"icon\" (empty clears it)')\n const current = policy.current()\n const icons = { ...current.icons }\n const next = icon.trim()\n if (next === '') delete icons[name]\n else icons[name] = next\n const saved = await policy.save({ ...current, icons })\n return { name, icon: next === '' ? null : next, policy: saved }\n}\n\n/** Run one `skill_roots` action. */\nasync function runSkillRootsAction(args: Record<string, unknown>): Promise<unknown> {\n const action = requireEnum(args, 'action', SKILL_ROOT_ACTIONS)\n if (action === 'set') {\n const directories = readStringArray(args, 'directories')\n if (directories === undefined) throw new ToolError('invalid_argument', 'set requires \"directories\"')\n await saveCustomSkillDirectories(directories)\n }\n return { roots: await allSkillRoots() }\n}\n\n/** Run one `visibility_manage` action. */\nasync function runVisibilityAction(policy: McpPolicyController, args: Record<string, unknown>): Promise<unknown> {\n const action = requireEnum(args, 'action', VISIBILITY_ACTIONS)\n if (action === 'get') return { policy: policy.current() }\n const next = JSON.parse(JSON.stringify(policy.current())) as InjectionPolicy\n if (action === 'remove_injection') {\n const kind = requireEnum(args, 'kind', ['mcp', 'skill'] as const)\n const name = requireString(args, 'name')\n if (kind === 'mcp') delete next.mcp[name]\n else delete next.skillInjection[name]\n return { policy: await policy.save(next) }\n }\n const key = action === 'set_mcp_injection' ? 'mcp' : 'skillInjection'\n const name = requireString(args, action === 'set_mcp_injection' ? 'server' : 'skill')\n const fallback = readBoolean(args, 'default')\n if (fallback === undefined) throw new ToolError('invalid_argument', 'argument \"default\" is required')\n const existing = next[key][name]\n const presets = args['presets'] === undefined ? (existing?.presets ?? {}) : readBooleanMap(args, 'presets')\n next[key][name] = { default: fallback, presets }\n return { policy: await policy.save(next) }\n}\n\n/** Run one `catalog` action. */\nasync function runCatalogAction(\n ctx: HostContext,\n args: Record<string, unknown>,\n exec: ToolRunContextFace,\n): Promise<unknown> {\n const action = requireEnum(args, 'action', CATALOG_ACTIONS)\n if (action === 'tools') {\n const { tools, warnings } = collectOtherTools(ctx)\n return {\n tools: tools.map(({ parameters: _parameters, ...tool }) => tool),\n warnings,\n }\n }\n if (action === 'tool') {\n const name = requireString(args, 'name')\n const { tools, warnings } = collectOtherTools(ctx)\n const tool = tools.find((candidate) => candidate.name === name)\n if (tool === undefined) throw new ToolError('not_found', `unknown tool \"${name}\"`)\n return { tool, warnings }\n }\n const presets = ctx.get('agentPresets') as HostContext['agentPresets']\n const list: AgentPresetInfo[] = (await presets?.list()) ?? []\n const defaultId = presets?.defaultId\n const current = exec.agent === undefined ? undefined : presetOfAgent(ctx, exec.agent)\n return {\n presets: list.map((preset) => ({ ...preset, isDefault: preset.id === defaultId })),\n ...(defaultId === undefined ? {} : { defaultId }),\n ...(current === undefined ? {} : { currentPreset: current }),\n }\n}\n\n/** Run one `variable_manage` action as the model. */\nasync function runVariableAction(ctx: HostContext, args: Record<string, unknown>): Promise<unknown> {\n const action = requireEnum(args, 'action', VARIABLE_ACTIONS)\n if (action === 'list') return await listVariables(ctx, 'ai')\n const name = requireString(args, 'name')\n if (action === 'get') return { variable: await getVariable(ctx, name, 'ai') }\n if (action === 'delete') {\n await deleteVariable(ctx, name, 'ai')\n return { deleted: name }\n }\n const input: VariableSaveRequest = { name }\n const label = readString(args, 'label')\n const description = readString(args, 'description')\n const value = readString(args, 'value')\n const permissions = readObject(args, 'permissions')\n if (label !== undefined) input.label = label\n if (description !== undefined) input.description = description\n if (value !== undefined) input.value = value\n if (permissions !== undefined) {\n const actorOf = (key: VariableActor): Partial<VariablePermissions> | undefined => {\n const raw = permissions[key]\n if (typeof raw !== 'object' || raw === null) return undefined\n const out: Partial<VariablePermissions> = {}\n for (const flag of ['read', 'write', 'delete'] as const) {\n const flagValue = Reflect.get(raw, flag)\n if (typeof flagValue === 'boolean') out[flag] = flagValue\n }\n return out\n }\n const human = actorOf('human')\n const ai = actorOf('ai')\n input.permissions = {\n ...(human === undefined ? {} : { human }),\n ...(ai === undefined ? {} : { ai }),\n }\n }\n return { variable: await saveVariable(ctx, input, 'ai') }\n}\n\n/** One action variant in a tool's `oneOf` input schema. */\ninterface ActionVariant {\n action: string\n description: string\n properties?: Record<string, unknown>\n required?: readonly string[]\n}\n\n/** Build an action-discriminated input schema; every branch declares its own required fields. */\nfunction actionSchema(variants: readonly ActionVariant[]): Record<string, unknown> {\n return {\n type: 'object',\n oneOf: variants.map((variant) => ({\n type: 'object',\n additionalProperties: false,\n properties: {\n action: { type: 'string', const: variant.action, description: variant.description },\n ...variant.properties,\n },\n required: ['action', ...(variant.required ?? [])],\n })),\n }\n}\n\n/** The MCP entry patch accepted by create/update. */\nconst MCP_ENTRY_SCHEMA: Record<string, unknown> = {\n type: 'object',\n additionalProperties: true,\n properties: {\n transport: { type: 'string', enum: ['stdio', 'streamable-http'] },\n command: { type: 'string', description: 'stdio executable; no shell expansion.' },\n args: { type: 'array', items: { type: 'string' } },\n env: { type: 'object', additionalProperties: true },\n cwd: { type: 'string' },\n url: { type: 'string', description: 'streamable-http endpoint.' },\n headers: { type: 'object', additionalProperties: true },\n enabled: { type: 'boolean' },\n toolCallTimeoutMs: { type: 'number' },\n startupTimeoutMs: { type: 'number' },\n closeTimeoutMs: { type: 'number' },\n toolLoading: { type: 'string', enum: ['eager', 'on-demand'] },\n reconnect: {\n type: 'object',\n additionalProperties: false,\n properties: {\n enabled: { type: 'boolean' },\n initialDelayMs: { type: 'number' },\n maxDelayMs: { type: 'number' },\n maxAttempts: { type: 'number' },\n },\n },\n oauth: { type: 'object', additionalProperties: true },\n },\n}\n\n/** Skill frontmatter fields accepted by create/update. */\nconst SKILL_FIELDS: Record<string, unknown> = {\n description: { type: 'string', description: 'Frontmatter description.' },\n whenToUse: { type: 'string', description: 'Optional routing guidance.' },\n body: { type: 'string', description: 'Markdown body below the frontmatter.' },\n disableModelInvocation: { type: 'boolean', description: 'Hide the skill from the model catalog.' },\n userInvocable: { type: 'boolean', description: 'Expose the skill as a user slash command; defaults true.' },\n}\n\n/** Name/path target shared by skill reads and writes. */\nconst SKILL_TARGET: Record<string, unknown> = {\n name: { type: 'string', description: 'Frontmatter skill name.' },\n path: { type: 'string', description: 'Absolute SKILL.md path; use when names collide.' },\n}\n\n/** Booleans keyed by preset id for one injection rule. */\nconst PRESET_OVERRIDES_SCHEMA: Record<string, unknown> = {\n type: 'object',\n additionalProperties: { type: 'boolean' },\n description: 'Explicit per-preset overrides; omitted presets follow default.',\n}\n\n/** Permission flags one actor may change for a variable. */\nconst VARIABLE_PERMISSIONS_SCHEMA: Record<string, unknown> = {\n type: 'object',\n additionalProperties: false,\n properties: {\n human: {\n type: 'object',\n additionalProperties: false,\n properties: { read: { type: 'boolean' }, write: { type: 'boolean' }, delete: { type: 'boolean' } },\n },\n ai: {\n type: 'object',\n additionalProperties: false,\n properties: { read: { type: 'boolean' }, write: { type: 'boolean' }, delete: { type: 'boolean' } },\n },\n },\n}\n\n/** The six model-facing tool definitions this plugin exposes. */\nexport function createToolManagerTools(ctx: HostContext, policy: McpPolicyController): ToolDefinitionFace[] {\n return [\n {\n name: 'mcp_manage',\n description:\n 'Manage MCP servers in this profile. This is the only tool that creates, updates, deletes, enables, disables, tests, restarts, or labels MCP servers. ' +\n '`list` returns configured and plugin-provided servers with live status and tool names; `get` adds the stored entry and full tool schemas. ' +\n 'Writes go through the shared settings queue, so the Host validates and rebuilds the connection without a restart. ' +\n 'Plugin-provided servers are read-only except for test, restart, and label. ' +\n 'Entry strings may embed `{{name}}` variables; the Host stores them as native credential templates.',\n parameters: actionSchema([\n { action: 'list', description: 'List configured and plugin-provided servers with status and tool names.' },\n {\n action: 'get',\n description: 'Read one server with its entry, status, and tool schemas.',\n properties: { name: { type: 'string' } },\n required: ['name'],\n },\n {\n action: 'create',\n description: 'Create a new configured server; fails if the name already exists.',\n properties: { name: { type: 'string' }, entry: MCP_ENTRY_SCHEMA },\n required: ['name', 'entry'],\n },\n {\n action: 'update',\n description: 'Patch an existing configured server; omitted entry fields keep their values.',\n properties: { name: { type: 'string' }, entry: MCP_ENTRY_SCHEMA },\n required: ['name', 'entry'],\n },\n {\n action: 'delete',\n description: 'Delete a configured server after explicit confirmation.',\n properties: {\n name: { type: 'string' },\n confirm: { type: 'boolean', description: 'Must be true.' },\n },\n required: ['name', 'confirm'],\n },\n {\n action: 'test',\n description: 'Test one server connection without restarting it.',\n properties: { name: { type: 'string' }, timeoutMs: { type: 'number' } },\n required: ['name'],\n },\n {\n action: 'restart',\n description: 'Rebuild one connected server from its current entry.',\n properties: { name: { type: 'string' } },\n required: ['name'],\n },\n {\n action: 'enable',\n description: 'Enable a configured server and rebuild its connection.',\n properties: { name: { type: 'string' } },\n required: ['name'],\n },\n {\n action: 'disable',\n description: 'Disable a configured server and unregister its tools; the entry is kept.',\n properties: { name: { type: 'string' } },\n required: ['name'],\n },\n {\n action: 'set_icon',\n description: 'Set or clear the short text/emoji label shown in the MCP list.',\n properties: {\n name: { type: 'string' },\n icon: { type: 'string', description: '1–8 code points; an empty string clears it.' },\n },\n required: ['name', 'icon'],\n },\n ]),\n output: { schema: {}, render: renderResult },\n async execute(rawArgs, exec) {\n return await runMcpAction(ctx, policy, argsRecord(rawArgs), exec)\n },\n },\n {\n name: 'skill_manage',\n description:\n 'Manage Agent Skill files in the writable skill roots. This tool owns Skill content and resource reads; scan-directory configuration lives in `skill_roots`. ' +\n '`list` discovers roots and summaries; `get` returns one complete document plus its resource tree; `read_resource` returns one non-SKILL.md file. ' +\n '`update` preserves unknown frontmatter; pass `content` to replace the whole file or form fields to rewrite only the owned keys. ' +\n 'Runtime and bundled skills are read-only; delete requires explicit confirmation.',\n parameters: actionSchema([\n { action: 'list', description: 'List writable roots and one summary per skill.' },\n {\n action: 'get',\n description: 'Read one full skill document, including resource entries.',\n properties: SKILL_TARGET,\n },\n {\n action: 'create',\n description: 'Create a directory-bundle skill in one writable root.',\n properties: {\n rootKey: { type: 'string', description: 'Writable root key from list.' },\n name: { type: 'string' },\n ...SKILL_FIELDS,\n },\n required: ['rootKey', 'name', 'description'],\n },\n {\n action: 'update',\n description: 'Update one skill by form fields or a raw document.',\n properties: {\n ...SKILL_TARGET,\n ...SKILL_FIELDS,\n content: { type: 'string', description: 'Complete file text; mutually exclusive with form fields.' },\n },\n },\n {\n action: 'delete',\n description: 'Delete one skill or flat skill file after explicit confirmation.',\n properties: { ...SKILL_TARGET, confirm: { type: 'boolean', description: 'Must be true.' } },\n required: ['confirm'],\n },\n {\n action: 'read_resource',\n description: 'Read one file below a skill directory (never executes it).',\n properties: {\n ...SKILL_TARGET,\n resource: { type: 'string', description: 'Relative path inside the skill directory.' },\n },\n required: ['resource'],\n },\n ]),\n output: { schema: {}, render: renderResult },\n async execute(rawArgs) {\n return await runSkillAction(ctx, argsRecord(rawArgs))\n },\n },\n {\n name: 'skill_roots',\n description:\n 'Read or replace the custom directories scanned for Agent Skills. Built-in roots are fixed. ' +\n 'These directories are discovery settings, not injection rules; use `visibility_manage` for those. ' +\n 'Paths must be absolute and are capped at 20.',\n parameters: actionSchema([\n { action: 'list', description: 'List built-in and custom skill roots.' },\n {\n action: 'set',\n description: 'Replace the complete custom-root list; [] clears it.',\n properties: {\n directories: { type: 'array', items: { type: 'string' } },\n },\n required: ['directories'],\n },\n ]),\n output: { schema: {}, render: renderResult },\n async execute(rawArgs) {\n return await runSkillRootsAction(argsRecord(rawArgs))\n },\n },\n {\n name: 'visibility_manage',\n description:\n '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. ' +\n 'It never edits registry definitions and never replaces the whole policy document. ' +\n 'Use `catalog` to inspect what exists before writing rules; use `get` to inspect the current document.',\n parameters: actionSchema([\n { action: 'get', description: 'Read the complete normalized policy document.' },\n {\n action: 'set_mcp_injection',\n description: 'Set one MCP server’s default and per-preset injection rule.',\n properties: {\n server: { type: 'string' },\n default: { type: 'boolean' },\n presets: PRESET_OVERRIDES_SCHEMA,\n },\n required: ['server', 'default'],\n },\n {\n action: 'set_skill_injection',\n description: 'Set one skill’s default and per-preset injection rule.',\n properties: {\n skill: { type: 'string' },\n default: { type: 'boolean' },\n presets: PRESET_OVERRIDES_SCHEMA,\n },\n required: ['skill', 'default'],\n },\n {\n action: 'remove_injection',\n description: 'Remove an MCP or Skill injection rule.',\n properties: {\n kind: { type: 'string', enum: ['mcp', 'skill'] },\n name: { type: 'string' },\n },\n required: ['kind', 'name'],\n },\n ]),\n output: { schema: {}, render: renderResult },\n async execute(rawArgs) {\n return await runVisibilityAction(policy, argsRecord(rawArgs))\n },\n },\n {\n name: 'catalog',\n description:\n 'Read-only projection of tools and Agent presets. `tools` lists every non-MCP registry tool; `tool` adds its argument schema; ' +\n '`presets` lists presets, the default, and the caller’s current preset — use it to name presets for `visibility_manage`. ' +\n 'This tool never writes; registry definitions are owned by plugins.',\n parameters: actionSchema([\n { action: 'tools', description: 'List every non-MCP registry tool without schemas.' },\n {\n action: 'tool',\n description: 'Read one tool with its full argument schema.',\n properties: { name: { type: 'string' } },\n required: ['name'],\n },\n { action: 'presets', description: 'List Agent presets, the default, and the caller’s current preset.' },\n ]),\n output: { schema: {}, render: renderResult },\n async execute(rawArgs, exec) {\n return await runCatalogAction(ctx, argsRecord(rawArgs), exec)\n },\n },\n {\n name: 'variable_manage',\n description:\n 'Manage variables: named strings the MCP forms reference as `{{name}}`. Values live in the Harness credential store, ' +\n 'never in the MCP settings file; an MCP entry stores `${credential:NAME}` and the client resolves it at connect time. ' +\n 'Each variable carries separate human/model permissions, and the model default is read=no, write=yes, delete=no: ' +\n '`list` and `get` therefore return metadata plus a mask, while `create`/`update` may still store a value. ' +\n '`value` is optional on update and keeps the stored value; an empty string clears it.',\n parameters: actionSchema([\n { action: 'list', description: 'List variables with metadata, masks, and permissions.' },\n {\n action: 'get',\n description: 'Read one variable; the value appears only when the model may read it.',\n properties: { name: { type: 'string' } },\n required: ['name'],\n },\n {\n action: 'create',\n description: 'Create a variable and optionally store its value.',\n properties: {\n name: { type: 'string', description: 'POSIX identifier; also the {{name}} token.' },\n label: { type: 'string' },\n description: { type: 'string' },\n value: { type: 'string', description: 'Secret value; omit to declare it without a value.' },\n permissions: VARIABLE_PERMISSIONS_SCHEMA,\n },\n required: ['name'],\n },\n {\n action: 'update',\n description: 'Update one variable; omitted fields keep their values.',\n properties: {\n name: { type: 'string' },\n label: { type: 'string' },\n description: { type: 'string' },\n value: { type: 'string', description: 'New value; empty string clears it.' },\n permissions: VARIABLE_PERMISSIONS_SCHEMA,\n },\n required: ['name'],\n },\n {\n action: 'delete',\n description: 'Delete a variable and its stored value.',\n properties: { name: { type: 'string' } },\n required: ['name'],\n },\n ]),\n output: { schema: {}, render: renderResult },\n async execute(rawArgs) {\n return await runVariableAction(ctx, argsRecord(rawArgs))\n },\n },\n ]\n}\n","/**\n * Injection policy for MCP servers and skills.\n *\n * DSH keeps one registry per scope chain (global -> preset -> agent). A third\n * party cannot move another plugin's registration, but it can narrow what one\n * live Agent inherits: `agent.ctx.tools.restrict({ deny })` masks global tools,\n * and a same-name `agent.ctx.skills.register(...)` shadow with both invocation\n * flags off removes a skill from that Agent's model catalog. This module owns\n * the document and the per-Agent application.\n *\n * Version 5 carries only the injection rules: each MCP server and each skill\n * declares a default plus per-preset overrides, edited beside that resource.\n * The older preset-wide tool/skill mask lists are gone with the preset page.\n */\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname } from 'node:path'\n\nimport type { InjectionPolicy, McpInjectionRule } from '../shared/contracts.js'\nimport { LEGACY_SERVER_NAME, SERVER_NAME } from '../shared/identity.js'\nimport { MCP_SERVER_NAME } from '../shared/mcp.js'\nimport { statePath } from './state.js'\n\n/** The one policy document version this build writes. */\nexport const POLICY_VERSION = 5\n/** Preset ids stay readable and bounded; they are session-facing identities. */\nconst PRESET_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/\n/** Bound the document so a broken client cannot make it enormous. */\nconst MAX_PRESETS = 200\nconst MAX_MCP_SERVERS = 200\n/** Skill names follow kebab-case; the policy key is the same identity. */\nconst SKILL_INJECTION_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n/** Icon glyphs stay short; count code points so emoji fit. */\nconst MAX_ICON_CODE_POINTS = 8\n/** Reserved transport tools reject restriction at the registry boundary. */\nconst IMMUTABLE_TOOLS = new Set(['run_code'])\n\n/** The skill surface one Agent exposes to the mask. */\nexport interface PolicySkill {\n name: string\n description: string\n invocation?: { modelInvocable?: boolean }\n}\n\n/** The Agent surface the policy reads and narrows. */\nexport interface PolicyAgent {\n id: string\n session: { header: { agentPreset?: string } }\n ctx: {\n tools?: { restrict(filter: { deny?: readonly string[] }): () => void }\n skills?: {\n list(options: { scope?: unknown; cwd?: string }): Promise<readonly PolicySkill[]>\n register(skill: {\n name: string\n description: string\n content: string\n source: string\n invocation: { modelInvocable: boolean; userInvocable: boolean }\n }): () => void\n }\n }\n}\n\n/** The preset registry face used to read a Session's committed selection. */\ninterface PresetRegistry {\n readonly defaultId?: string\n presetForSession?(session: unknown): string | null\n}\n\n/** The Host services the policy uses. */\nexport interface PolicyHost {\n on(event: string, listener: (...args: unknown[]) => void): () => void\n get(name: string): unknown\n}\n\n/** Resolve the policy file under `$DSH_HOME`. */\nexport function policyPath(environment: NodeJS.ProcessEnv = process.env, home = homedir()): string {\n return statePath('policy.json', environment, home)\n}\n\n/** A document with no narrowing: every preset sees everything. */\nexport function emptyPolicy(): InjectionPolicy {\n return { version: POLICY_VERSION, mcp: {}, skillInjection: {}, icons: {} }\n}\n\n/** Validate the per-MCP injection map. */\nfunction normalizeMcpInjection(raw: unknown): Record<string, McpInjectionRule> {\n if (raw === undefined || raw === null) return {}\n if (typeof raw !== 'object' || Array.isArray(raw)) throw new Error('policy: \"mcp\" must be an object')\n const entries = Object.entries(raw as Record<string, unknown>)\n if (entries.length > MAX_MCP_SERVERS) throw new Error('policy: too many MCP servers')\n const out: Record<string, McpInjectionRule> = {}\n for (const [server, value] of entries) {\n if (!MCP_SERVER_NAME.test(server)) throw new Error(`policy: invalid MCP server name \"${server}\"`)\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`policy: MCP server \"${server}\" must be an object`)\n }\n const record = value as Record<string, unknown>\n const fallback = record['default']\n if (fallback !== undefined && typeof fallback !== 'boolean') {\n throw new Error(`policy: MCP server \"${server}\" default must be a boolean`)\n }\n const presets: Record<string, boolean> = {}\n const rawPresets = record['presets']\n if (rawPresets !== undefined && rawPresets !== null) {\n if (typeof rawPresets !== 'object' || Array.isArray(rawPresets)) {\n throw new Error(`policy: MCP server \"${server}\" presets must be an object`)\n }\n const presetEntries = Object.entries(rawPresets as Record<string, unknown>)\n if (presetEntries.length > MAX_PRESETS) throw new Error(`policy: MCP server \"${server}\" has too many presets`)\n for (const [presetId, enabled] of presetEntries) {\n if (!PRESET_ID_PATTERN.test(presetId)) {\n throw new Error(`policy: invalid preset id \"${presetId}\" on MCP server \"${server}\"`)\n }\n if (typeof enabled !== 'boolean') {\n throw new Error(`policy: MCP server \"${server}\" preset \"${presetId}\" must be a boolean`)\n }\n presets[presetId] = enabled\n }\n }\n out[server] = { default: fallback ?? true, presets }\n }\n return out\n}\n\n/** Validate the optional per-server text glyph map. */\nfunction normalizeIcons(raw: unknown): Record<string, string> {\n if (raw === undefined || raw === null) return {}\n if (typeof raw !== 'object' || Array.isArray(raw)) throw new Error('policy: \"icons\" must be an object')\n const entries = Object.entries(raw as Record<string, unknown>)\n if (entries.length > MAX_MCP_SERVERS) throw new Error('policy: too many MCP icons')\n const out: Record<string, string> = {}\n for (const [server, value] of entries) {\n if (!MCP_SERVER_NAME.test(server)) throw new Error(`policy: invalid MCP server name \"${server}\"`)\n if (typeof value !== 'string') throw new Error(`policy: MCP icon \"${server}\" must be a string`)\n const glyph = value.trim()\n if (glyph === '') continue\n if (Array.from(glyph).length > MAX_ICON_CODE_POINTS) {\n throw new Error(`policy: MCP icon \"${server}\" is too long`)\n }\n out[server] = glyph\n }\n return out\n}\n\n/** Validate the per-skill injection map. */\nfunction normalizeSkillInjection(raw: unknown): Record<string, McpInjectionRule> {\n if (raw === undefined || raw === null) return {}\n if (typeof raw !== 'object' || Array.isArray(raw)) throw new Error('policy: \"skillInjection\" must be an object')\n const entries = Object.entries(raw as Record<string, unknown>)\n if (entries.length > MAX_MCP_SERVERS) throw new Error('policy: too many skill injection rules')\n const out: Record<string, McpInjectionRule> = {}\n for (const [skill, value] of entries) {\n if (!SKILL_INJECTION_NAME.test(skill)) throw new Error(`policy: invalid skill name \"${skill}\"`)\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`policy: skill \"${skill}\" must be an object`)\n }\n const record = value as Record<string, unknown>\n const fallback = record['default']\n if (fallback !== undefined && typeof fallback !== 'boolean') {\n throw new Error(`policy: skill \"${skill}\" default must be a boolean`)\n }\n const presets: Record<string, boolean> = {}\n const rawPresets = record['presets']\n if (rawPresets !== undefined && rawPresets !== null) {\n if (typeof rawPresets !== 'object' || Array.isArray(rawPresets)) {\n throw new Error(`policy: skill \"${skill}\" presets must be an object`)\n }\n for (const [presetId, enabled] of Object.entries(rawPresets as Record<string, unknown>)) {\n if (!PRESET_ID_PATTERN.test(presetId))\n throw new Error(`policy: invalid preset id \"${presetId}\" on skill \"${skill}\"`)\n if (typeof enabled !== 'boolean')\n throw new Error(`policy: skill \"${skill}\" preset \"${presetId}\" must be a boolean`)\n presets[presetId] = enabled\n }\n }\n out[skill] = { default: fallback ?? true, presets }\n }\n return out\n}\n\n/** Validate and copy a whole policy document, accepting every shipped version. */\nexport function normalizePolicy(input: unknown): InjectionPolicy {\n if (typeof input !== 'object' || input === null) throw new Error('policy: expected an object')\n const record = input as Record<string, unknown>\n const version = record['version'] ?? POLICY_VERSION\n if (version !== 1 && version !== 3 && version !== 4 && version !== POLICY_VERSION) {\n throw new Error(`policy: unsupported version ${String(version)}`)\n }\n // Versions before 4 kept the injection maps elsewhere; the preset masks they\n // also carried have no replacement, so a migration simply drops them.\n const carriesInjection = version === 4 || version === POLICY_VERSION\n const mcp = carriesInjection ? normalizeMcpInjection(record['mcp']) : {}\n const skillInjection = carriesInjection ? normalizeSkillInjection(record['skillInjection']) : {}\n const icons = carriesInjection ? normalizeIcons(record['icons']) : {}\n // The plugin's own server was renamed with the package; carry the user's\n // injection rule and icon over instead of resetting them to defaults.\n const legacyRule = mcp[LEGACY_SERVER_NAME]\n if (legacyRule !== undefined && mcp[SERVER_NAME] === undefined) {\n mcp[SERVER_NAME] = legacyRule\n delete mcp[LEGACY_SERVER_NAME]\n }\n const legacyIcon = icons[LEGACY_SERVER_NAME]\n if (legacyIcon !== undefined && icons[SERVER_NAME] === undefined) {\n icons[SERVER_NAME] = legacyIcon\n delete icons[LEGACY_SERVER_NAME]\n }\n return { version: POLICY_VERSION, mcp, skillInjection, icons }\n}\n\n/** Whether the MCP server owning `name` is switched off for this preset. */\nfunction mcpInjectionDenied(policy: InjectionPolicy, presetId: string | undefined, name: string): boolean {\n if (presetId === undefined) return false\n let hit: { server: string; rule: McpInjectionRule } | undefined\n for (const [server, rule] of Object.entries(policy.mcp)) {\n if (!name.startsWith(`mcp__${server}__`)) continue\n // Prefer the longest server name when one key is a prefix of another.\n if (hit === undefined || server.length > hit.server.length) hit = { server, rule }\n }\n if (hit === undefined) return false\n return (hit.rule.presets[presetId] ?? hit.rule.default) === false\n}\n\n/** Compute the global tool names one preset must not see. */\nexport function compileToolDeny(\n policy: InjectionPolicy,\n presetId: string | undefined,\n toolNames: readonly string[],\n): string[] {\n return toolNames.filter((name) => !IMMUTABLE_TOOLS.has(name) && mcpInjectionDenied(policy, presetId, name)).sort()\n}\n\n/** One skill the policy hides: enough to shadow it in the Agent's catalog. */\nexport interface HiddenSkill {\n name: string\n description: string\n source: string\n modelInvocable: boolean\n}\n\n/**\n * Compute the skills one preset must keep out of its model catalog. Every\n * visible name participates, including a skill this controller already\n * shadowed: excluding shadows would flip the desired set on every re-apply and\n * loop through `skills/change`.\n */\nexport function compileSkillHides(\n policy: InjectionPolicy,\n presetId: string | undefined,\n skills: readonly PolicySkill[],\n): HiddenSkill[] {\n return skills\n .filter((skill) => {\n if (presetId === undefined) return false\n const rule = policy.skillInjection[skill.name]\n return rule !== undefined && (rule.presets[presetId] ?? rule.default) === false\n })\n .map((skill) => ({\n name: skill.name,\n description: skill.description,\n source: 'runtime',\n modelInvocable: true,\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n}\n\n/** Live narrowing of the tool registry and skill catalog, one set per Agent. */\nexport class McpPolicyController {\n private policy: InjectionPolicy = emptyPolicy()\n private readonly toolMasks = new Map<string, () => void>()\n private readonly toolSignatures = new Map<string, string>()\n private readonly skillMasks = new Map<string, (() => void)[]>()\n private readonly skillSignatures = new Map<string, string>()\n private timer: ReturnType<typeof setTimeout> | undefined\n private defaultId: string | undefined\n\n constructor(\n private readonly host: PolicyHost,\n private readonly path: string,\n ) {}\n\n /** Load the document and start watching agents, presets, tools, and skills. */\n async start(): Promise<void> {\n try {\n this.policy = normalizePolicy(JSON.parse(await readFile(this.path, 'utf8')))\n } catch {\n this.policy = emptyPolicy()\n }\n try {\n const presets = this.host.get('agentPresets') as PresetRegistry | undefined\n this.defaultId = presets?.defaultId\n } catch {\n this.defaultId = undefined\n }\n this.host.on('agent/created', (...args) => {\n const agent = (args[0] as { agent: PolicyAgent } | undefined)?.agent\n if (agent !== undefined) this.applyAgent(agent)\n })\n this.host.on('agent/disposed', (...args) => {\n const id = (args[0] as { agent: PolicyAgent } | undefined)?.agent.id\n if (id !== undefined) this.release(id)\n })\n this.host.on('agent-preset/selected', (...args) => {\n const sessionId = typeof args[0] === 'string' ? args[0] : undefined\n if (sessionId === undefined) return\n const agent = this.agentById(sessionId)\n if (agent !== undefined) this.applyAgent(agent)\n })\n this.host.on('tools/change', () => this.schedule())\n this.host.on('skills/change', () => this.schedule())\n this.applyAll()\n }\n\n /** The current document, for the panel. */\n current(): InjectionPolicy {\n return this.policy\n }\n\n /** Persist a complete document and re-apply it to every live Agent. */\n async save(input: unknown): Promise<InjectionPolicy> {\n const next = normalizePolicy(input)\n await mkdir(dirname(this.path), { recursive: true })\n await writeFile(this.path, `${JSON.stringify(next, null, 2)}\\n`, 'utf8')\n this.policy = next\n this.applyAll()\n return this.policy\n }\n\n /** Stop the debounce timer (the Host owns the rest through effect scopes). */\n dispose(): void {\n if (this.timer !== undefined) clearTimeout(this.timer)\n this.timer = undefined\n for (const id of [...this.toolMasks.keys()]) this.release(id)\n }\n\n private schedule(): void {\n if (this.timer !== undefined) return\n this.timer = setTimeout(() => {\n this.timer = undefined\n this.applyAll()\n }, 40)\n this.timer.unref?.()\n }\n\n private agentById(sessionId: string): PolicyAgent | undefined {\n try {\n const agents = (this.host.get('agents') as { list(): readonly PolicyAgent[] } | undefined)?.list() ?? []\n return agents.find((agent) => agent.id === sessionId)\n } catch {\n return undefined\n }\n }\n\n /**\n * The preset the Agent currently runs under. A Session's creation header is\n * only the initial fact: a switch writes `agent-preset/selected`, which the\n * presets registry projects. Read that projection first.\n */\n private presetOf(agent: PolicyAgent): string | undefined {\n try {\n const presets = this.host.get('agentPresets') as PresetRegistry | undefined\n const selected = presets?.presetForSession?.(agent.session)\n if (typeof selected === 'string' && selected !== '') return selected\n } catch {\n // Fall through to the durable creation header.\n }\n return agent.session.header.agentPreset\n }\n\n private globalToolNames(): readonly string[] {\n try {\n const tools = this.host.get('tools') as { definitions(scope?: unknown): readonly { name: string }[] } | undefined\n return (tools?.definitions() ?? []).map((definition) => definition.name)\n } catch {\n return []\n }\n }\n\n private applyAll(): void {\n const live = new Set<string>()\n let agents: readonly PolicyAgent[] = []\n try {\n agents = (this.host.get('agents') as { list(): readonly PolicyAgent[] } | undefined)?.list() ?? []\n } catch {\n agents = []\n }\n for (const agent of agents) {\n live.add(agent.id)\n this.applyAgent(agent)\n }\n for (const id of [...this.toolMasks.keys()]) {\n if (!live.has(id)) this.release(id)\n }\n for (const id of [...this.skillMasks.keys()]) {\n if (!live.has(id)) this.release(id)\n }\n }\n\n private applyAgent(agent: PolicyAgent): void {\n const preset = this.presetOf(agent) ?? this.defaultId\n this.applyTools(agent, preset)\n void this.applySkills(agent, preset).catch(() => {\n // Skill discovery is optional; a failing provider leaves the mask as is.\n })\n }\n\n private applyTools(agent: PolicyAgent, preset: string | undefined): void {\n const deny = compileToolDeny(this.policy, preset, this.globalToolNames())\n const signature = deny.join('\\n')\n if (this.toolSignatures.get(agent.id) === signature) return\n this.releaseTools(agent.id)\n this.toolSignatures.set(agent.id, signature)\n if (deny.length === 0) return\n try {\n const dispose = agent.ctx.tools?.restrict({ deny })\n if (dispose !== undefined) this.toolMasks.set(agent.id, dispose)\n } catch {\n // A scope that cannot be narrowed (already disposing) contributes nothing.\n }\n }\n\n private async applySkills(agent: PolicyAgent, preset: string | undefined): Promise<void> {\n const skills = agent.ctx.skills\n if (skills === undefined) return\n let visible: readonly PolicySkill[] = []\n try {\n visible = await skills.list({ scope: agent, cwd: process.cwd() })\n } catch {\n return\n }\n const hidden = compileSkillHides(this.policy, preset, visible)\n const signature = hidden.map((skill) => skill.name).join('\\n')\n if (this.skillSignatures.get(agent.id) === signature) return\n this.releaseSkills(agent.id)\n this.skillSignatures.set(agent.id, signature)\n const disposers: (() => void)[] = []\n for (const skill of hidden) {\n try {\n const dispose = skills.register({\n name: skill.name,\n description: skill.description || 'Hidden by the tool manager.',\n content: '',\n source: 'runtime',\n invocation: { modelInvocable: false, userInvocable: false },\n })\n disposers.push(dispose)\n } catch {\n // A duplicate name in the same layer is already hidden or immutable.\n }\n }\n if (disposers.length > 0) this.skillMasks.set(agent.id, disposers)\n }\n\n private release(id: string): void {\n this.releaseTools(id)\n this.releaseSkills(id)\n this.toolSignatures.delete(id)\n this.skillSignatures.delete(id)\n }\n\n private releaseTools(id: string): void {\n const dispose = this.toolMasks.get(id)\n this.toolMasks.delete(id)\n if (dispose === undefined) return\n try {\n dispose()\n } catch {\n // Already disposed with the Agent scope.\n }\n }\n\n private releaseSkills(id: string): void {\n const disposers = this.skillMasks.get(id)\n this.skillMasks.delete(id)\n if (disposers === undefined) return\n for (const dispose of disposers) {\n try {\n dispose()\n } catch {\n // Already disposed with the Agent scope.\n }\n }\n }\n}\n","/**\n * Host routes for the tool manager.\n *\n * Skills live on the Host's filesystem, so the browser asks the Host; MCP tool\n * metadata lives in the Host's tool registry, so it does too. Every route is\n * admitted by the web server's `required` policy (browser token plus Host/Origin\n * trust) and speaks bounded JSON.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { ROUTE_BASE } from '../shared/identity.js'\nimport type { HostContext } from './context.js'\nimport type { McpPolicyController } from './policy.js'\nimport {\n createSkillDocument,\n deleteSkillDocument,\n listSkills,\n readSkillDocument,\n readSkillResource,\n saveSkillDocument,\n skillRegistryOf,\n} from './skills.js'\nimport { groupMcpTools } from './mcp-tools.js'\nimport { collectOtherTools } from './other-tools.js'\nimport { deleteVariable, listVariables, saveVariable } from './variables.js'\nimport { allSkillRoots, saveCustomSkillDirectories } from './skill-roots.js'\n\n/** Base path of the skill collection. */\nconst BASE = `/${ROUTE_BASE}`\n\nexport const SKILLS_PATH = `${BASE}/skills`\n/** Read one skill file. */\nexport const SKILL_READ_PATH = `${BASE}/skill/read`\n/** Read one resource below a skill directory. */\nexport const SKILL_RESOURCE_PATH = `${BASE}/skill/resource`\n/** Configure custom skill scan directories. */\nexport const SKILL_ROOTS_PATH = `${BASE}/skill/roots`\n/** Save one skill file. */\nexport const SKILL_SAVE_PATH = `${BASE}/skill/save`\n/** Create one skill. */\nexport const SKILL_CREATE_PATH = `${BASE}/skill/create`\n/** Delete one skill. */\nexport const SKILL_DELETE_PATH = `${BASE}/skill/delete`\n/** Aggregated MCP tool metadata. */\nexport const MCP_TOOLS_PATH = `${BASE}/mcp/tools`\n/** The Agent preset roster. */\nexport const PRESETS_PATH = `${BASE}/presets`\n/** The per-preset visibility policy document. */\nexport const POLICY_PATH = `${BASE}/policy`\n/** Non-MCP tools the Host registry exposes (plugins, presets, core). */\nexport const OTHER_TOOLS_PATH = `${BASE}/tools`\n/** The variable collection. */\nexport const VARIABLES_PATH = `${BASE}/variables`\n/** Create or update one variable. */\nexport const VARIABLE_SAVE_PATH = `${BASE}/variable/save`\n/** Remove one variable. */\nexport const VARIABLE_DELETE_PATH = `${BASE}/variable/delete`\n\n/** Read cap: a skill is a document, and an 8 MB body is already generous. */\nconst MAX_BODY_BYTES = 4_000_000\n\n/** The tools service face this route reads. */\ninterface ToolsFace {\n definitions(): readonly {\n name: string\n description: string\n parameters: Record<string, unknown>\n }[]\n}\n\n/** Answer with JSON and no caching. */\nfunction sendJson(res: ServerResponse, status: number, payload: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.end(JSON.stringify(payload))\n}\n\n/** Read a bounded JSON body; undefined when it is absent, oversized, or not JSON. */\nasync function readJson(req: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = []\n let size = 0\n for await (const chunk of req) {\n const buffer = chunk as Buffer\n size += buffer.byteLength\n if (size > MAX_BODY_BYTES) {\n req.resume()\n return undefined\n }\n chunks.push(buffer)\n }\n if (size === 0) return undefined\n try {\n return JSON.parse(Buffer.concat(chunks, size).toString('utf8'))\n } catch {\n return undefined\n }\n}\n\n/** A short, user-facing message that never leaks a stack. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Read a string field from an unknown request body. */\nfunction stringOf(body: unknown, key: string): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined\n const value = Reflect.get(body, key)\n return typeof value === 'string' ? value : undefined\n}\n\n/** Register every dsh-tool-manage route on the Host web server. */\nexport function attachToolManagerRoutes(ctx: HostContext, policy: McpPolicyController): void {\n ctx.inject(['webServer'], (child) => {\n const register = (path: string, handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>): void => {\n child.effect(\n () =>\n child.webServer.register({\n kind: 'exact',\n path,\n auth: 'required',\n handler: async (req, res) => {\n try {\n await handler(req, res)\n } catch (error) {\n sendJson(res, 400, { ok: false, error: messageOf(error) })\n }\n },\n }),\n `dsh-tool-manage: ${path}`,\n )\n }\n\n const requirePost = (req: IncomingMessage, res: ServerResponse): boolean => {\n if (req.method === 'POST') return true\n res.statusCode = 405\n res.setHeader('allow', 'POST')\n res.end()\n return false\n }\n const requireGet = (req: IncomingMessage, res: ServerResponse): boolean => {\n if (req.method === 'GET') return true\n res.statusCode = 405\n res.setHeader('allow', 'GET')\n res.end()\n return false\n }\n\n register(SKILLS_PATH, async (req, res) => {\n if (!requireGet(req, res)) return\n const roots = await allSkillRoots()\n sendJson(res, 200, { ok: true, ...(await listSkills(skillRegistryOf(ctx), roots)) })\n })\n\n register(SKILL_ROOTS_PATH, async (req, res) => {\n if (req.method === 'GET') {\n const roots = await allSkillRoots()\n sendJson(res, 200, {\n ok: true,\n roots,\n directories: roots.filter((root) => root.custom === true).map((root) => root.path),\n })\n return\n }\n if (req.method !== 'POST') {\n res.statusCode = 405\n res.setHeader('allow', 'GET, POST')\n res.end()\n return\n }\n const body = await readJson(req)\n const directories = typeof body === 'object' && body !== null ? Reflect.get(body, 'directories') : undefined\n await saveCustomSkillDirectories(directories)\n sendJson(res, 200, { ok: true, roots: await allSkillRoots() })\n })\n\n register(SKILL_RESOURCE_PATH, async (req, res) => {\n if (!requirePost(req, res)) return\n const body = await readJson(req)\n const path = stringOf(body, 'path')\n const resource = stringOf(body, 'resource')\n if (path === undefined || resource === undefined) {\n sendJson(res, 400, { ok: false, error: '缺少 path / resource' })\n return\n }\n sendJson(res, 200, {\n ok: true,\n resource: await readSkillResource(skillRegistryOf(ctx), path, resource, await allSkillRoots()),\n })\n })\n\n register(SKILL_READ_PATH, async (req, res) => {\n if (!requirePost(req, res)) return\n const body = await readJson(req)\n const path = stringOf(body, 'path')\n if (path === undefined) {\n sendJson(res, 400, { ok: false, error: '缺少 path' })\n return\n }\n sendJson(res, 200, {\n ok: true,\n skill: await readSkillDocument(skillRegistryOf(ctx), path, await allSkillRoots()),\n })\n })\n\n register(SKILL_SAVE_PATH, async (req, res) => {\n if (!requirePost(req, res)) return\n const body = await readJson(req)\n if (typeof body !== 'object' || body === null) {\n sendJson(res, 400, { ok: false, error: '请求体无效' })\n return\n }\n const path = stringOf(body, 'path')\n if (path === undefined) {\n sendJson(res, 400, { ok: false, error: '缺少 path' })\n return\n }\n const content = stringOf(body, 'content')\n const fields = Reflect.get(body, 'fields')\n const bodyText = stringOf(body, 'body')\n const skill = await saveSkillDocument(\n skillRegistryOf(ctx),\n fields === undefined\n ? { path, ...(content === undefined ? {} : { content }) }\n : {\n path,\n fields: fields as {\n name: string\n description: string\n whenToUse: string\n disableModelInvocation: boolean\n userInvocable: boolean\n },\n body: bodyText ?? '',\n },\n await allSkillRoots(),\n )\n sendJson(res, 200, { ok: true, skill })\n })\n\n register(SKILL_CREATE_PATH, async (req, res) => {\n if (!requirePost(req, res)) return\n const body = await readJson(req)\n if (typeof body !== 'object' || body === null) {\n sendJson(res, 400, { ok: false, error: '请求体无效' })\n return\n }\n const rootKey = stringOf(body, 'rootKey')\n const name = stringOf(body, 'name')\n const description = stringOf(body, 'description')\n if (rootKey === undefined || name === undefined || description === undefined) {\n sendJson(res, 400, { ok: false, error: '缺少 rootKey / name / description' })\n return\n }\n const whenToUse = stringOf(body, 'whenToUse')\n const bodyText = stringOf(body, 'body')\n const skill = await createSkillDocument(\n skillRegistryOf(ctx),\n {\n rootKey,\n name,\n description,\n ...(whenToUse === undefined ? {} : { whenToUse }),\n ...(bodyText === undefined ? {} : { body: bodyText }),\n disableModelInvocation: Reflect.get(body, 'disableModelInvocation') === true,\n userInvocable: Reflect.get(body, 'userInvocable') !== false,\n },\n await allSkillRoots(),\n )\n sendJson(res, 200, { ok: true, skill })\n })\n\n register(SKILL_DELETE_PATH, async (req, res) => {\n if (!requirePost(req, res)) return\n const body = await readJson(req)\n const path = stringOf(body, 'path')\n if (path === undefined) {\n sendJson(res, 400, { ok: false, error: '缺少 path' })\n return\n }\n await deleteSkillDocument(path, await allSkillRoots())\n sendJson(res, 200, { ok: true })\n })\n\n register(VARIABLES_PATH, async (req, res) => {\n if (!requireGet(req, res)) return\n sendJson(res, 200, { ok: true, ...(await listVariables(ctx, 'human')) })\n })\n\n register(VARIABLE_SAVE_PATH, async (req, res) => {\n if (!requirePost(req, res)) return\n const body = await readJson(req)\n const name = stringOf(body, 'name')\n if (name === undefined) {\n sendJson(res, 400, { ok: false, error: '缺少 name' })\n return\n }\n const record = typeof body === 'object' && body !== null ? (body as Record<string, unknown>) : {}\n const variable = await saveVariable(\n ctx,\n {\n name,\n ...(stringOf(body, 'label') === undefined ? {} : { label: stringOf(body, 'label') }),\n ...(stringOf(body, 'description') === undefined ? {} : { description: stringOf(body, 'description') }),\n ...(stringOf(body, 'value') === undefined ? {} : { value: stringOf(body, 'value') }),\n ...(record['permissions'] === undefined\n ? {}\n : { permissions: record['permissions'] as Parameters<typeof saveVariable>[1]['permissions'] }),\n },\n 'human',\n )\n sendJson(res, 200, { ok: true, variable })\n })\n\n register(VARIABLE_DELETE_PATH, async (req, res) => {\n if (!requirePost(req, res)) return\n const body = await readJson(req)\n const name = stringOf(body, 'name')\n if (name === undefined) {\n sendJson(res, 400, { ok: false, error: '缺少 name' })\n return\n }\n await deleteVariable(ctx, name, 'human')\n sendJson(res, 200, { ok: true })\n })\n\n register(PRESETS_PATH, async (req, res) => {\n if (!requireGet(req, res)) return\n const presets = ctx.get('agentPresets') as HostContext['agentPresets']\n const list = (await presets?.list()) ?? []\n const defaultId = presets?.defaultId\n sendJson(res, 200, {\n ok: true,\n presets: list.map((preset) => ({ ...preset, isDefault: preset.id === defaultId })),\n ...(defaultId === undefined ? {} : { defaultId }),\n })\n })\n\n register(POLICY_PATH, async (req, res) => {\n if (req.method === 'GET') {\n sendJson(res, 200, { ok: true, policy: policy.current() })\n return\n }\n if (req.method !== 'PUT') {\n res.statusCode = 405\n res.setHeader('allow', 'GET, PUT')\n res.end()\n return\n }\n const body = await readJson(req)\n if (typeof body !== 'object' || body === null) {\n sendJson(res, 400, { ok: false, error: '请求体无效' })\n return\n }\n sendJson(res, 200, { ok: true, policy: await policy.save(Reflect.get(body, 'policy')) })\n })\n\n register(MCP_TOOLS_PATH, async (req, res) => {\n if (!requireGet(req, res)) return\n const value = ctx.get('tools')\n const tools =\n typeof value === 'object' && value !== null && typeof Reflect.get(value, 'definitions') === 'function'\n ? (value as ToolsFace)\n : undefined\n sendJson(res, 200, { ok: true, ...groupMcpTools(tools?.definitions() ?? []) })\n })\n register(OTHER_TOOLS_PATH, async (req, res) => {\n if (!requireGet(req, res)) return\n const { tools, warnings } = collectOtherTools(ctx)\n sendJson(res, 200, { ok: true, tools, warnings })\n })\n })\n}\n","/**\n * dsh-tool-manage — Host half.\n *\n * One Loader row with no configuration of its own. It adds the management\n * routes the browser panel calls: skill discovery/read/save/create/delete on\n * the global skill roots, MCP tool metadata, variables, the preset roster, and\n * the MCP/skill injection policy. MCP server entries themselves stay in the\n * `mcp-manager` row's volatile Config, which the panel edits through the\n * settings service — this plugin never keeps a second copy.\n *\n * @module @hcstar/dsh-tool-manage\n */\nimport type { HostContext } from './context.js'\nimport { attachMcpServer } from './mcp-server.js'\nimport { McpPolicyController, policyPath } from './policy.js'\nimport { attachToolManagerRoutes } from './routes.js'\n\n/** Register the management routes; headless compositions without a web server simply get none. */\nexport function apply(ctx: HostContext): void {\n const policy = new McpPolicyController(ctx, policyPath())\n ctx.effect(() => () => policy.dispose(), 'dsh-tool-manage: policy controller')\n void policy.start().catch((error: unknown) => {\n ctx.logger?.warn(`dsh-tool-manage: policy controller failed to start: ${String(error)}`)\n })\n attachToolManagerRoutes(ctx, policy)\n attachMcpServer(ctx, policy)\n}\n\nexport {\n parseSkillDocument,\n applySkillFields,\n createSkillContent,\n parseYamlScalars,\n splitDocument,\n} from './frontmatter.js'\nexport {\n createSkillDocument,\n defaultSkillRoots,\n deleteSkillDocument,\n isInside,\n listLocalSkills,\n listSkills,\n readSkillDocument,\n saveSkillDocument,\n summarizeSkillFile,\n} from './skills.js'\nexport { createToolManagerTools } from './agent-tools.js'\nexport { attachMcpServer, ToolManagerMcpServer } from './mcp-server.js'\nexport { dshHome, stateDir, statePath } from './state.js'\nexport {\n findMcpEntry,\n listMcpServers,\n mergeMcpEntry,\n probeMcpServer,\n readMcpConfig,\n removeMcpServer,\n restartMcpServer,\n upsertMcpServer,\n} from './mcp-config.js'\nexport { defaultMcpEntry, normalizeMcpEntry } from '../shared/mcp.js'\nexport { groupMcpTools, mcpToolName, splitMcpToolName } from './mcp-tools.js'\nexport { collectOtherTools } from './other-tools.js'\nexport {\n defaultPermissions,\n deleteVariable,\n entryToNative,\n entryToSugar,\n getVariable,\n listVariables,\n saveVariable,\n variableNames,\n variablesPath,\n} from './variables.js'\nexport { isVariableName, toNativeToken, toSugarToken } from '../shared/variables.js'\nexport {\n compileSkillHides,\n compileToolDeny,\n emptyPolicy,\n McpPolicyController,\n normalizePolicy,\n POLICY_VERSION,\n policyPath,\n} from './policy.js'\n"],"mappings":";AAeA,SAAS,mBAAmB;AAC5B,SAAS,oBAA4E;;;ACN9E,IAAM,cAAc;AAGpB,IAAM,qBAAqB;AAG3B,IAAM,aAAa;;;ACH1B,IAAM,gBAAgB;AAGtB,IAAM,cAAc;AAGpB,IAAM,eAAe;AAGd,SAAS,eAAe,OAAwB;AACrD,SAAO,cAAc,KAAK,KAAK;AACjC;AAaO,SAAS,gBAA0C,OAAU,KAAmC;AACr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E,CAAC;AAAA,IAC/E,CAAC;AACD,aAAS,kBAAkB,OAAO,KAAK,QAAQ;AAC7C,UAAI,CAAC,WAAW,KAAK,GAAG,EAAG;AAC3B,YAAM,EAAE,OAAO,SAAS,IAAI,kBAAkB,GAAG;AACjD,MAAAA,UAAS,KAAK,KAAK,EAAE,IAAI,MAAM,OAAO,SAAS,CAAC;AAAA,IAClD,CAAC;AAAA,EACH,CAAC;AACH;;;AClWO,SAAS,MAAM,KAAwB;AAC5C,QAAM,SAAS,IAAI,oBAAoB,KAAK,WAAW,CAAC;AACxD,MAAI,OAAO,MAAM,MAAM,OAAO,QAAQ,GAAG,oCAAoC;AAC7E,OAAK,OAAO,MAAM,EAAE,MAAM,CAAC,UAAmB;AAC5C,QAAI,QAAQ,KAAK,uDAAuD,OAAO,KAAK,CAAC,EAAE;AAAA,EACzF,CAAC;AACD,0BAAwB,KAAK,MAAM;AACnC,kBAAgB,KAAK,MAAM;AAC7B;","names":["descriptor","value","readBoolean","readString","readStringArray","tools","dshHome","relative","file","mkdir","readFile","stat","writeFile","homedir","basename","dirname","isAbsolute","normalize","homedir","join","homedir","isAbsolute","normalize","readFile","stat","basename","mkdir","dirname","writeFile","mkdir","readFile","writeFile","homedir","dirname","homedir","readFile","mkdir","dirname","writeFile","resolved","name","messageOf","failure","mkdir","readFile","writeFile","homedir","dirname","homedir","readFile","mkdir","dirname","writeFile","MAX_BODY_BYTES","sendJson","messageOf"]}