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

middleware.ts

256 lines8.5 KB

1/**
2 * `withSkills` — portable Agent Skills as a chat middleware.
3 *
4 * All source resolution and catalog rendering happen once in `setup`; `onConfig`
5 * (which fires every agent iteration) only returns memoized values. Otherwise an
6 * S3-backed source would hit the network per loop turn and catalog reordering
7 * would break Anthropic's cache prefix mid-run.
8 */
9import {
10 createCapability,
11 defineChatMiddleware,
12 SkillLimitError,
13} from '@tanstack/ai'
14import { combineSources } from './combinators'
15import { renderCatalog } from './catalog'
16import { modelFamilyOf } from './types'
17import { createLoadSkillTool } from './tools/load-skill'
18import { READ_RESOURCE_TOOL_NAME } from './tools/read-resource'
19import type { DefinedChatMiddleware, StreamChunk, Tool } from '@tanstack/ai'
20import type { ModelFamily, SkillMetadata, SkillSource } from './types'
21​
22/** CUSTOM stream-event name carrying the catalog to the browser DevTools. */
23export const SKILLS_STATE_EVENT = 'skills:state'
24​
25export interface SkillsStateEventValue {
26 catalog: Array<{ name: string; description: string }>
27 activated: Array<string>
29​
30export interface SkillsOptions {
31 /** Override catalog rendering. Receives resolved metadata + the model family. */
32 renderCatalog?: (skills: Array<SkillMetadata>, family: ModelFamily) => string
33 /** Template with a required `{skills}` placeholder. Literal braces escape as `{{`/`}}`. */
34 instructionTemplate?: string
35 /** Hard cap on tier-1 catalog token spend. Default 4000. */
36 maxCatalogTokens?: number
37 /** `'error'` (default) or a reducer invoked when the cap is exceeded. */
38 onLimitExceeded?:
39 | 'error'
40 | ((skills: Array<SkillMetadata>, limit: number) => Array<SkillMetadata>)
41 /** Where the catalog goes. Default `'system'`. */
42 catalogPlacement?: 'system' | 'tool-description'
43 /** Require approval before load_skill / read_skill_resource. Default false. */
44 requireApproval?: boolean
46​
47interface SkillsRuntime {
48 skills: Array<SkillMetadata>
49 activated: Set<string>
50 source: SkillSource
51 family: ModelFamily
52 catalog: string
53 options: SkillsOptions
54 /** Built on first onConfig (needs config.tools to detect the resource tool). */
55 memo?: { prompt: { content: string } | undefined; tools: Array<Tool> }
56 stateChunkEmitted?: boolean
58​
59const SkillsCapability = createCapability<SkillsRuntime>()('skills')
60​
61/** ~4 chars/token — good enough to guard a runaway catalog. */
62const estimateTokens = (s: string) => Math.ceil(s.length / 4)
63​
64function fillTemplate(template: string, catalog: string): string {
65 // Escape `{{`/`}}` to sentinels, substitute `{skills}`, then restore braces.
66 const OPEN = '\u0000OPEN\u0000'
67 const CLOSE = '\u0000CLOSE\u0000'
68 return template
69 .split('{{')
70 .join(OPEN)
71 .split('}}')
72 .join(CLOSE)
73 .split('{skills}')
74 .join(catalog)
75 .split(OPEN)
76 .join('{')
77 .split(CLOSE)
78 .join('}')
80​
81/** True when a code_execution/shell tool in `tools` carries hosted skills. */
82function findNativeSkillTool(tools: Array<Tool>): string | undefined {
83 for (const tool of tools) {
84 const meta = tool.metadata as
85 | { skills?: Array<unknown>; environment?: { skills?: Array<unknown> } }
86 | undefined
87 if (tool.name === 'code_execution' && (meta?.skills?.length ?? 0) > 0) {
88 return 'code_execution'
89 }
90 if (tool.name === 'shell' && (meta?.environment?.skills?.length ?? 0) > 0) {
91 return 'shell'
92 }
93 }
94 return undefined
96​
97function activationInstructions(
98 catalog: string,
99 hasResourceTool: boolean,
100): string {
101 const resourceLine = hasResourceTool
102 ? 'To read a skill’s bundled resource files, call `read_skill_resource` with the skill name and the resource path.'
103 : 'Some skills may list resource files; they are not loadable in this configuration.'
104 return [
105 'You have access to a library of skills. When a task matches one, call the `load_skill` tool with its name to load its full instructions before proceeding.',
106 catalog,
107 resourceLine,
108 ].join('\n\n')
110​
111export function withSkills(
112 sources: SkillSource | Array<SkillSource>,
113 options: SkillsOptions = {},
114): DefinedChatMiddleware<
115 unknown,
116 readonly [],
117 readonly [typeof SkillsCapability]
118> {
119 if (options.instructionTemplate && options.renderCatalog) {
120 throw new Error(
121 '`instructionTemplate` and `renderCatalog` are mutually exclusive',
122 )
123 }
124 if (
125 options.instructionTemplate &&
126 !options.instructionTemplate.includes('{skills}')
127 ) {
128 throw new Error(
129 '`instructionTemplate` must contain a `{skills}` placeholder',
130 )
131 }
132​
133 return defineChatMiddleware({
134 name: 'skills',
135 provides: [SkillsCapability],
136​
137 async setup(ctx) {
138 const source = combineSources(sources)
139 let skills = await source.list()
140 const family = modelFamilyOf(ctx.provider)
141​
142 // Catalog token cap (spec §4.2).
143 const limit = options.maxCatalogTokens ?? 4000
144 const render = options.renderCatalog ?? renderCatalog
145 let catalog = render(skills, family)
146 if (estimateTokens(catalog) > limit) {
147 if (options.onLimitExceeded && options.onLimitExceeded !== 'error') {
148 skills = options.onLimitExceeded(skills, limit)
149 catalog = render(skills, family)
150 }
151 if (estimateTokens(catalog) > limit) {
152 throw new SkillLimitError({
153 provider: family,
154 path: 'portable',
155 limit: `maxCatalogTokens (${limit})`,
156 allowed: limit,
157 actual: estimateTokens(catalog),
158 offending: skills.map((s) => s.name),
159 })
160 }
161 }
162​
163 ctx.provide(SkillsCapability, {
164 skills,
165 activated: new Set<string>(),
166 source,
167 family,
168 catalog,
169 options,
170 })
171 },
172​
173 onConfig(ctx, config) {
174 const rt = ctx.get(SkillsCapability)
175 if (rt.skills.length === 0) return // empty catalog → no tools, no prompt
176​
177 // Native co-existence: portable + hosted skills don't compose (spec §6.1).
178 const native = findNativeSkillTool(config.tools)
179 if (native) {
180 throw new Error(
181 `withSkills (portable skills) cannot be combined with a "${native}" tool that carries hosted/native skills. ` +
182 'Use one delivery mode: remove the hosted skills, or drop withSkills.',
183 )
184 }
185​
186 if (!rt.memo) {
187 const hasResourceTool = config.tools.some(
188 (t) => t.name === READ_RESOURCE_TOOL_NAME,
189 )
190 const body =
191 options.instructionTemplate !== undefined
192 ? fillTemplate(options.instructionTemplate, rt.catalog)
193 : activationInstructions(rt.catalog, hasResourceTool)
194​
195 const loadTool = createLoadSkillTool({
196 source: rt.source,
197 skills: rt.skills,
198 activated: rt.activated,
199 requireApproval: options.requireApproval,
200 })
201​
202 const placement = options.catalogPlacement ?? 'system'
203 if (placement === 'tool-description') {
204 loadTool.description = `${loadTool.description}\n\n${body}`
205 rt.memo = { prompt: undefined, tools: [loadTool] }
206 } else {
207 rt.memo = { prompt: { content: body }, tools: [loadTool] }
208 }
209 }
210​
211 // onConfig fires every iteration and the engine feeds the merged config
212 // back in — so appending must be idempotent (add our prompt/tools only
213 // when not already present) or a second iteration duplicates them.
214 const prompt = rt.memo.prompt
215 const promptPresent =
216 !prompt ||
217 config.systemPrompts.some((p) =>
218 typeof p === 'string'
219 ? p === prompt.content
220 : p.content === prompt.content,
221 )
222 const existingNames = new Set(config.tools.map((t) => t.name))
223 const toolsToAdd = rt.memo.tools.filter((t) => !existingNames.has(t.name))
224​
225 return {
226 systemPrompts:
227 prompt && !promptPresent
228 ? [...config.systemPrompts, prompt]
229 : config.systemPrompts,
230 tools:
231 toolsToAdd.length > 0
232 ? [...config.tools, ...toolsToAdd]
233 : config.tools,
234 }
235 },
236​
237 onChunk(ctx, chunk) {
238 const rt = ctx.getOptional(SkillsCapability)
239 if (!rt || rt.stateChunkEmitted) return
240 rt.stateChunkEmitted = true
241 const custom: StreamChunk = {
242 type: 'CUSTOM',
243 name: SKILLS_STATE_EVENT,
244 value: {
245 catalog: rt.skills.map((s) => ({
246 name: s.name,
247 description: s.description,
248 })),
249 activated: [...rt.activated],
250 } satisfies SkillsStateEventValue,
251 timestamp: Date.now(),
252 }
253 return [chunk, custom]
254 },
255 })