Open History to see the last commit
1/**
2 * `inlineSkill` — an edge-safe {@link SkillSource} for a single skill defined
3 * next to app code, in a DB row, or per-session/per-tenant. Resource values may
4 * be thunks, evaluated at read time.
5 */
6import { stableHash } from '../util'
7import { validateSkill } from '../validate'
8import type { SkillMetadata, SkillSource } from '../types'
9
10export interface InlineSkillConfig {
11 name: string
12 description: string
13 instructions: string
14 resources?: Record<string, string | (() => string | Promise<string>)>
15 compatibility?: string
16}
17
18export function inlineSkill(config: InlineSkillConfig): SkillSource {
19 const metadata: SkillMetadata = {
20 name: config.name,
21 description: config.description,
22 ...(config.compatibility && { compatibility: config.compatibility }),
23 }
24 const lint = validateSkill(metadata)
25 if (!lint.ok) {
26 throw new Error(
27 `inlineSkill "${config.name}": ${lint.issues.map((i) => i.message).join('; ')}`,
28 )
29 }
30 const resourcePaths = Object.keys(config.resources ?? {})
31 const revision = stableHash(
32 JSON.stringify({
33 metadata,
34 instructions: config.instructions,
35 resources: resourcePaths,
36 }),
37 )
38
39 const assertName = (name: string) => {
40 if (name !== config.name) {
41 throw new Error(`inlineSkill has no skill named "${name}"`)
42 }
43 }
44
45 return {
46 revision: () => Promise.resolve(revision),
47 list: () => Promise.resolve([metadata]),
48 // Async so an unknown-name throw surfaces as a rejected promise.
49 load: async (name) => {
50 assertName(name)
51 return config.instructions
52 },
53 listResources: async (name) => {
54 assertName(name)
55 return resourcePaths
56 },
57 readResource: async (name, path) => {
58 assertName(name)
59 const value = config.resources?.[path]
60 if (value === undefined) {
61 throw new Error(`skill "${name}" has no resource "${path}"`)
62 }
63 return typeof value === 'function' ? await value() : value
64 },
65 }
66}