Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

load-skill.ts

96 lines2.6 KB

1/**
2 * `load_skill` — activates a skill by name and returns its (frontmatter-stripped)
3 * body plus a resource/script inventory. Result shape is frozen in phase 1;
4 * changing it later would churn every eval, snapshot, and devtools panel.
5 */
6import { toolDefinition } from '@tanstack/ai'
7import { z } from 'zod'
8import { stripFrontmatter } from '../parse'
9import type { Tool } from '@tanstack/ai'
10import type {
11 LoadSkillResult,
12 SkillMetadata,
13 SkillScriptRef,
14 SkillSource,
15} from '../types'
16​
17export const ALREADY_LOADED =
18 '(already loaded earlier in this conversation — reuse the prior content)'
19​
20const scriptSchema = z.object({
21 path: z.string(),
22 executable: z.literal(false),
23 reason: z.string().optional(),
24})
25​
26const resultSchema = z.object({
27 skill: z.string(),
28 content: z.string(),
29 resources: z.array(z.string()),
30 scripts: z.array(scriptSchema),
31 compatibility: z.string().optional(),
32})
33​
34export interface LoadSkillDeps {
35 source: SkillSource
36 skills: Array<SkillMetadata>
37 /** per-conversation activation set (dedupe). */
38 activated: Set<string>
39 requireApproval?: boolean
41​
42export function createLoadSkillTool(deps: LoadSkillDeps): Tool {
43 const names = deps.skills.map((s) => s.name)
44 const nameEnum = z.enum(names as [string, ...Array<string>])
45 const byName = new Map(deps.skills.map((s) => [s.name, s]))
46​
47 const handler = async ({
48 name,
49 }: {
50 name: string
51 }): Promise<LoadSkillResult> => {
52 if (deps.activated.has(name)) {
53 return {
54 skill: name,
55 content: ALREADY_LOADED,
56 resources: [],
57 scripts: [],
58 }
59 }
60 const raw = await deps.source.load(name)
61 const resources = (await deps.source.listResources?.(name)) ?? []
62 const scripts = ((await deps.source.listScripts?.(name)) ??
63 []) as Array<SkillScriptRef>
64 deps.activated.add(name)
65 const compatibility = byName.get(name)?.compatibility
66 return {
67 skill: name,
68 content: stripFrontmatter(raw),
69 resources,
70 scripts,
71 ...(compatibility && { compatibility }),
72 }
73 }
74​
75 const description =
76 'Activate an available skill by name. Returns its full instructions plus ' +
77 'a list of any bundled resources and scripts.'
78 const inputSchema = z.object({ name: nameEnum })
79​
80 if (deps.requireApproval) {
81 return toolDefinition({
82 name: 'load_skill',
83 description,
84 inputSchema,
85 outputSchema: resultSchema,
86 needsApproval: true,
87 approvalSchema: z.object({ approve: z.boolean() }),
88 }).server(handler)
89 }
90 return toolDefinition({
91 name: 'load_skill',
92 description,
93 inputSchema,
94 outputSchema: resultSchema,
95 }).server(handler)