import { readFile } from "node:fs/promises"; import { dirname } from "node:path"; import { Type } from "typebox"; import { SKILL_PRECEDENCE_NOTE, truncateHead, type ExtensionAPI, type ResolvedSkillInfo, type SkillInvocationState } from "@selesai/code"; import type { Skill } from "../../core/skills.ts"; export const SKILLS_INDEX_INSTRUCTION = "Skills are reusable procedures. Use skill_show without a name to list them, or pass query to filter names and descriptions. Pass an exact listed name to load its instructions before applying it. skill_show is not declared: call it from a codemode script as tools.skill_show({ query }) or tools.skill_show({ name }) and return the result. References in a loaded skill are relative to its directory. Tool discovery is separate: use tool_search or codemode searchTools()."; /** The custom message that tells the model the user opened skills for this turn. */ export const SKILL_REQUEST_MESSAGE_TYPE = "skill-request"; /** At most this many skills are listed inline when skill_show is unavailable. */ export const MAX_INLINE_SKILL_LISTING = 50; /** Where the model is allowed to look right now. Undefined means the host has no gate (older host): everything eligible. */ export type SkillVisibility = ((name: string) => boolean) | undefined; /** The host owns trust and settings filtering. Never scan additional directories. */ export function eligibleSkills(skills: readonly ResolvedSkillInfo[], visible?: SkillVisibility): ResolvedSkillInfo[] { const seen = new Set(); return skills.filter((skill) => { if (skill.disableModelInvocation || seen.has(skill.name)) return false; if (visible && !visible(skill.name)) return false; seen.add(skill.name); return true; }); } /** The visibility a skill-invocation state grants: auto mode or an open turn sees everything. */ export function skillVisibility(state: SkillInvocationState | undefined): SkillVisibility { if (!state || state.mode === "auto" || state.open) return undefined; const always = new Set(state.alwaysAvailable); return (name) => always.has(name); } /** An excluded show tool must not strand the model behind an unusable synthetic index. */ export function compactSkillIndex(skills: Skill[], showAvailable: boolean): Skill[] { if (!showAvailable || skills.length === 0) return skills; return [{ name: "skills-index", description: SKILLS_INDEX_INSTRUCTION, filePath: "", baseDir: "", sourceInfo: { path: "", source: "builtin", scope: "user", origin: "top-level" }, disableModelInvocation: false, }]; } export interface SkillShowArgs { name?: string; query?: string; limit?: number; } function escapeAttribute(value: string): string { return value.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); } function escapeText(value: string): string { return value.replace(/&/g, "&").replace(//g, ">"); } export type SkillShowDetails = | { loaded: true; complete: boolean; skill: string; filePath: string } | { loaded: false; entries: Array<{ name: string; description: string }>; total: number; truncated: boolean }; export interface SkillShowResult { content: Array<{ type: "text"; text: string }>; details: SkillShowDetails; } const CLOSED_GUIDANCE = "Skills are user-invoked in this session: the user has not asked for a skill in this message. Do not load one on your own; continue with the request as written. The user can open skills by saying \"skill\" or naming one with $name."; /** List metadata or load one exact resolved skill; no classification or tool activation. */ export async function showSkill( skills: readonly ResolvedSkillInfo[], args: SkillShowArgs, signal?: AbortSignal, visible?: SkillVisibility, ): Promise { signal?.throwIfAborted(); const eligible = eligibleSkills(skills, visible); if (args.name !== undefined) { const skill = eligible.find((entry) => entry.name === args.name); if (!skill) { const gated = visible !== undefined && eligibleSkills(skills).some((entry) => entry.name === args.name); throw new Error(gated ? `Skill "${args.name}" is not available this turn. ${CLOSED_GUIDANCE}` : `Unknown or model-ineligible skill "${args.name}". Use skill_show without a name to list eligible skills.`); } const body = await readFile(skill.filePath, { encoding: "utf8", signal }); const output = truncateHead(body); const guidance = output.truncated ? `Instructions are incomplete (50KB/2000-line limit). Read the remaining instructions from ${skill.filePath} before applying this skill.` : "The full instructions are embedded below; do not read the file again."; return { content: [{ type: "text" as const, text: `\n${guidance}\nReferences are relative to ${dirname(skill.filePath)}.\n${SKILL_PRECEDENCE_NOTE}\n\n${output.content}\n` }], details: { loaded: true, complete: !output.truncated, skill: skill.name, filePath: skill.filePath }, }; } const terms = (args.query ?? "").toLocaleLowerCase().split(/\s+/u).filter(Boolean); const matches = eligible.filter((skill) => { const text = `${skill.name} ${skill.description}`.toLocaleLowerCase(); return terms.every((term) => text.includes(term)); }); const limit = Math.max(1, Math.min(50, Math.floor(args.limit ?? 20))); const entries = matches.slice(0, limit).map(({ name, description }) => ({ name, description })); const listing = entries.map((entry) => `${entry.name} — ${entry.description}`).join("\n"); const output = truncateHead(listing); const empty = visible !== undefined && eligible.length === 0 ? CLOSED_GUIDANCE : "No eligible skills match."; return { content: [{ type: "text" as const, text: matches.length === 0 ? empty : `${output.content}\n\n${entries.length} of ${matches.length} matches. Pass an exact name to load instructions.${matches.length > entries.length || output.truncated ? " Narrow query to see remaining matches." : ""}` }], details: { loaded: false, entries, total: matches.length, truncated: output.truncated || matches.length > entries.length }, }; } /** * The notice for a turn whose user message opened skills in explicit mode. With skill_show * reachable it points there; otherwise it lists the skills with their files for the read tool. */ export function skillRequestNotice(input: { requested: readonly string[]; showAvailable: boolean; skills: readonly ResolvedSkillInfo[]; }): string { const lines = [ "", "The user asked for a skill in this message, so model-invocable skills are available for this turn only.", ]; if (input.requested.length > 0) { lines.push(`The user named: ${input.requested.map((name) => `\`${name}\``).join(", ")}. Named skills are already embedded inline when their instructions appear above; do not load them again.`); } if (input.showAvailable) { lines.push("List skills with skill_show({ query }) and load one with skill_show({ name }). skill_show is not declared: call it from a codemode script as tools.skill_show(...)."); } else { const eligible = eligibleSkills(input.skills); lines.push("Load a skill by reading its file with the read tool when it fits the request:"); for (const skill of eligible.slice(0, MAX_INLINE_SKILL_LISTING)) { lines.push(`- ${escapeText(skill.name)} — ${escapeText(skill.description)} (${escapeText(skill.filePath)})`); } if (eligible.length > MAX_INLINE_SKILL_LISTING) lines.push(`(${eligible.length - MAX_INLINE_SKILL_LISTING} more not listed.)`); } lines.push(SKILL_PRECEDENCE_NOTE, ""); return lines.join("\n"); } /** Older hosts have no skill-invocation API: treat them as auto mode (the previous behavior). */ function invocationState(pi: ExtensionAPI): SkillInvocationState | undefined { return typeof pi.getSkillInvocation === "function" ? pi.getSkillInvocation() : undefined; } export default function skillsIndexExtension(pi: ExtensionAPI): void { const showAvailable = () => { const active = pi.getActiveTools(); return active.includes("skill_show") || active.includes("codemode"); }; pi.registerTool({ name: "skill_show", label: "Skills", // ponytail: deferred keeps the declaration out of context; reached via codemode (tools.skill_show). exposure: "deferred", description: "List or filter the resolved skill index, or load one skill's instructions by exact name. Omit name to list; query filters names/descriptions using all supplied words. Output is limited to 50KB or 2000 lines; incomplete instructions must be read from the returned file path before use. Does not discover or activate tools.", promptSnippet: "List reusable procedures or load one skill's instructions", promptGuidelines: ["Use skill_show for the skills-index entry; is a synthetic index, not a file to read."], parameters: Type.Object({ name: Type.Optional(Type.String({ minLength: 1, description: "Exact listed skill name to load." })), query: Type.Optional(Type.String({ minLength: 1, description: "Filter names/descriptions when listing." })), limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 50, description: "Maximum listed matches (default 20)." })), }), execute: async (_id, args, signal) => showSkill(pi.getResolvedSkills(), args, signal, skillVisibility(invocationState(pi))), }); /** Set by a user-typed prompt, consumed by its run's before_agent_start: one notice per request. */ let pendingUserTurn = false; pi.on("input", (event) => { pendingUserTurn = event.source !== "extension" && event.streamingBehavior === undefined; }); // Runtime APIs are bound at session_start. The callback reads the current loadout, // so later explicit exclusions restore the ordinary index rather than hide skills. // skill_show is deferred, so it is reachable when declared or when codemode can call it. pi.on("session_start", () => { pendingUserTurn = false; pi.setSkillsIndexFilter((skills) => compactSkillIndex(skills, showAvailable())); }); pi.on("before_agent_start", (event) => { if (event.messageType !== "user") return; const pending = pendingUserTurn; pendingUserTurn = false; if (!pending) return; const state = invocationState(pi); // Auto mode already advertises every skill; a closed turn has nothing to announce. if (!state || state.mode === "auto" || !state.open) return; return { message: { customType: SKILL_REQUEST_MESSAGE_TYPE, content: skillRequestNotice({ requested: state.requested, showAvailable: showAvailable(), skills: pi.getResolvedSkills() }), display: false, details: { requested: state.requested }, }, }; }); }