import { createHash } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { z } from 'zod'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { discoverSkills, resolveSkillCandidates, } from '../../skills/catalog.js'; import { toToolParameters } from '../../utils/zodToJson.js'; const MAX_SKILL_BYTES = 256 * 1024; const schema = z.object({ name: z .string() .min(1) .max(200) .regex(/^[^/\\]+$/), arguments: z.string().max(20_000).optional(), sourceId: z .string() .regex(/^[a-f0-9]{64}$/) .optional() .describe('同名歧义时使用 SearchSkills 返回的 sourceId'), }); type Input = z.infer; async function call( input: Input, context: ToolCallContext, ): Promise { const found = resolveSkillCandidates( await discoverSkills(context.cwd, context), input.name, input.sourceId, ); if (!found.length) return { ok: false, error: `没有找到名称精确匹配的 Skill:${input.name}` }; if (found.length > 1) return { ok: false, error: `Skill 名称有歧义:${input.name}。请选择 sourceId 后重试。\n${JSON.stringify(found.map(({ sourceId, sourceDir }) => ({ sourceId, sourceDir })))}`, }; const available = context.availableToolNames?.(); const missing = available && found[0]!.requiresTools?.filter(name => !available.has(name)); if (missing?.length) return { ok: false, error: `Skill ${input.name} 当前缺少工具:${missing.join(', ')}。不能通过技能扩大执行权限。` }; // Search roots are ordered: project skill intentionally overrides the bundled skill. const path = join(found[0]!.sourceDir, 'SKILL.md'); const content = await readFile(path); if (content.length > MAX_SKILL_BYTES) return { ok: false, error: `Skill 指令过大(${content.length} > ${MAX_SKILL_BYTES} bytes),拒绝加载半份指令。`, }; const hash = createHash('sha256').update(content).digest('hex'); // Loading in another node/session does not mean these instructions are in // this model's context. Always return the complete, current instructions. return { ok: true, content: `Skill: ${input.name}\nRoot: ${join(path, '..')}\nSHA-256: ${hash}${input.arguments ? `\nUser arguments: ${input.arguments}` : ''}\n\n${content.toString('utf8')}`, }; } export const skillTool: Tool = { name: 'Skill', description: 'Loads one installed Skill by exact name and returns its complete SKILL.md instructions, root directory and content hash. Use this instead of manually locating SKILL.md.', inputSchema: schema, parameters: toToolParameters(schema), maxResultSizeChars: MAX_SKILL_BYTES + 24_000, isReadOnly: true, isConcurrencySafe: true, call: async () => ({ ok: false, error: 'Skill requires runtime context' }), callWithContext: (input, _signal, context) => call(input, context), };