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

combinators.ts

224 lines6.7 KB

1/**
2 * Source combinators (spec §3.3). Sources compose in practice: org skills +
3 * project skills + tenant skills. `aggregate` concatenates, `dedupe` resolves
4 * collisions, `filter` hides, `cache` memoizes.
5 */
6import { stableHash } from './util'
7import type { SkillMetadata, SkillScriptRef, SkillSource } from './types'
8​
9export type FilterContext = Record<string, unknown>
10export type FilterPredicate = (
11 skill: SkillMetadata,
12 ctx?: FilterContext,
13) => boolean
14​
15/** Forward a source's optional `revision`, preserving `undefined` when absent. */
16function forwardRevision(
17 source: SkillSource,
18): (() => Promise<string>) | undefined {
19 const rev = source.revision
20 return rev ? () => rev() : undefined
22​
23/** Route a delegating method to the first source that lists `name`. */
24async function ownerOf(
25 sources: Array<SkillSource>,
26 name: string,
27): Promise<SkillSource> {
28 for (const source of sources) {
29 const list = await source.list()
30 if (list.some((s) => s.name === name)) return source
31 }
32 throw new Error(`no source provides a skill named "${name}"`)
34​
35async function combinedRevision(
36 sources: Array<SkillSource>,
37): Promise<string | undefined> {
38 const revs = await Promise.all(
39 sources.map((s) => s.revision?.() ?? Promise.resolve(undefined)),
40 )
41 if (revs.some((r) => r === undefined)) return undefined
42 return stableHash(revs.join('|'))
44​
45/** Concatenate sources in registration order. No dedupe. */
46export function aggregate(sources: Array<SkillSource>): SkillSource {
47 // Only expose revision() when every child does — a partial revision would
48 // report "unchanged" while an unversioned child mutated underneath.
49 const allVersioned = sources.every((s) => s.revision)
50 return {
51 ...(allVersioned && {
52 revision: async () => (await combinedRevision(sources)) ?? '',
53 }),
54 list: async () => {
55 const lists = await Promise.all(sources.map((s) => s.list()))
56 return lists.flat()
57 },
58 load: async (name) => (await ownerOf(sources, name)).load(name),
59 listResources: async (name) => {
60 const owner = await ownerOf(sources, name)
61 return owner.listResources?.(name) ?? []
62 },
63 readResource: async (name, path) => {
64 const owner = await ownerOf(sources, name)
65 if (!owner.readResource) {
66 throw new Error(`skill "${name}" does not support resources`)
67 }
68 return owner.readResource(name, path)
69 },
70 listScripts: async (name) => {
71 const owner = await ownerOf(sources, name)
72 return (owner.listScripts?.(name) ?? []) as Array<SkillScriptRef>
73 },
74 readScript: async (name, path) => {
75 const owner = await ownerOf(sources, name)
76 if (!owner.readScript) {
77 throw new Error(`skill "${name}" does not support scripts`)
78 }
79 return owner.readScript(name, path)
80 },
81 }
83​
84/** First occurrence of a name wins; warns on collision. */
85export function dedupe(
86 source: SkillSource,
87 onCollision: (name: string) => void = (name) =>
88 console.warn(`[ai-skills] duplicate skill "${name}" — first one wins`),
89): SkillSource {
90 return {
91 ...source,
92 revision: forwardRevision(source),
93 list: async () => {
94 const seen = new Set<string>()
95 const out: Array<SkillMetadata> = []
96 for (const skill of await source.list()) {
97 if (seen.has(skill.name)) {
98 onCollision(skill.name)
99 continue
100 }
101 seen.add(skill.name)
102 out.push(skill)
103 }
104 return out
105 },
106 }
108​
109/** Hide skills the predicate rejects. Filtered skills never reach the catalog. */
110export function filter(
111 source: SkillSource,
112 predicate: FilterPredicate,
113 ctx?: FilterContext,
114): SkillSource {
115 const list = async () =>
116 (await source.list()).filter((s) => predicate(s, ctx))
117 const assertVisible = async (name: string) => {
118 const skills = await list()
119 if (!skills.some((s) => s.name === name)) {
120 throw new Error(`no skill named "${name}"`)
121 }
122 }
123 return {
124 ...source,
125 revision: forwardRevision(source),
126 list,
127 load: async (name) => {
128 await assertVisible(name)
129 return source.load(name)
130 },
131 listResources: source.listResources
132 ? async (name) => {
133 await assertVisible(name)
134 return source.listResources?.(name) ?? []
135 }
136 : undefined,
137 readResource: source.readResource
138 ? async (name, path) => {
139 await assertVisible(name)
140 const read = source.readResource
141 if (!read) {
142 throw new Error(`skill "${name}" does not support resources`)
143 }
144 return read(name, path)
145 }
146 : undefined,
147 listScripts: source.listScripts
148 ? async (name) => {
149 await assertVisible(name)
150 return (source.listScripts?.(name) ?? []) as Array<SkillScriptRef>
151 }
152 : undefined,
153 readScript: source.readScript
154 ? async (name, path) => {
155 await assertVisible(name)
156 const read = source.readScript
157 if (!read) {
158 throw new Error(`skill "${name}" does not support scripts`)
159 }
160 return read(name, path)
161 }
162 : undefined,
163 }
165​
166/**
167 * Memoize `list()`/`load()`. Concurrent `list()` calls share one underlying
168 * fetch. `refreshInterval` (ms) expires the memo; omit for forever.
169 *
170 * Never auto-applied by the middleware — caching a tenant-scoped source in a
171 * shared bucket would replay one tenant's skills for another. Opt in explicitly.
172 */
173export function cache(
174 source: SkillSource,
175 opts: { refreshInterval?: number } = {},
176): SkillSource {
177 let listPromise: Promise<Array<SkillMetadata>> | undefined
178 let listAt = 0
179 const loads = new Map<string, Promise<string>>()
180​
181 const now = () => (opts.refreshInterval ? Date.now() : 0)
182 const fresh = () =>
183 opts.refreshInterval === undefined || now() - listAt < opts.refreshInterval
184​
185 return {
186 ...source,
187 revision: forwardRevision(source),
188 list: () => {
189 if (!listPromise || !fresh()) {
190 listAt = now()
191 loads.clear()
192 listPromise = source.list().catch((err) => {
193 listPromise = undefined // don't cache failures
194 throw err
195 })
196 }
197 return listPromise
198 },
199 load: (name) => {
200 let p = loads.get(name)
201 if (!p) {
202 p = source.load(name).catch((err) => {
203 loads.delete(name)
204 throw err
205 })
206 loads.set(name, p)
207 }
208 return p
209 },
210 }
212​
213/**
214 * Combine the sources handed to the middleware. An array is deduped and
215 * aggregated; a single bare source is used as-is (never auto-wrapped).
216 */
217export function combineSources(
218 sources: SkillSource | Array<SkillSource>,
219): SkillSource {
220 if (!Array.isArray(sources)) return sources
221 const [first] = sources
222 if (sources.length === 1 && first) return first
223 return dedupe(aggregate(sources))