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

plugin-owners.test.ts

238 lines8.1 KB

1import { describe, expect, it, vi } from 'vitest'
2import { memoryPersistence } from '@tanstack/ai-persistence'
3import { createCapability, defineAgent, toolDefinition } from '@tanstack/ai'
4import { AgentRegistry } from '../src/agents'
5import { defineCommand } from '../src/commands'
6import { configOption } from '../src/config'
7import { createExtensionPoint, createPluginEvent } from '../src/extensions'
8import { definePlugin, mountPlugins } from '../src/plugins'
9import { createHarnessHost, defineHarness } from '../src'
10import { mockAdapter, text } from './helpers'
11import type { MountedPlugins, PluginSetupContext } from '../src/plugins'
12​
13const env = () => ({
14 threadId: 't1',
15 registry: new AgentRegistry(),
16 harnessTools: [],
17 harnessProvides: [],
18})
19​
20const Rules = createExtensionPoint<string>('test/rules')
21​
22const agentNamed = (name: string) =>
23 defineAgent({ name, description: name, run: async () => name })
24​
25/** A plugin `id` that contributes one item of every kind, each named `id`. */
26function contributor(id: string) {
27 const capability = createCapability<string>()(`test/${id}-capability`)
28 const pick = () => undefined
29 const plugin = definePlugin({
30 name: id,
31 provides: [capability],
32 setup: ({ provide }) => {
33 provide(capability, `${id} value`)
34 return {
35 tools: [
36 toolDefinition({ name: `${id}_tool`, description: id }).server(
37 () => id,
38 ),
39 ],
40 prompts: [
41 `${id} prompt`,
42 { id: `${id}:context`, text: `${id} context`, placement: 'context' },
43 ],
44 middleware: [{ name: `${id}-middleware` }],
45 agentMiddleware: [{ name: `${id}-agent-middleware` }],
46 generationMiddleware: [{ name: `${id}-generation-middleware` }],
47 agents: [agentNamed(`${id}-agent`)],
48 subagents: [agentNamed(`${id}-subagent`)],
49 commands: {
50 [`${id}-command`]: defineCommand({ description: id, run: () => id }),
51 },
52 config: {
53 [`${id}-level`]: configOption.select({
54 options: ['low', 'high'],
55 default: 'low',
56 }),
57 },
58 contribute: [Rules.item(`${id} rule`)],
59 adapter: pick,
60 discoverTools: () => [],
61 prepareTools: ({ tools }) => tools,
62 }
63 },
64 })
65 return { plugin, capability, pick }
67​
68/** The name or value of every contribution in `mounted`. */
69function contents(mounted: MountedPlugins) {
70 const names = (items: ReadonlyArray<{ name?: string }>) =>
71 items.map((item) => item.name)
72 return {
73 plugins: mounted.owners.plugins.map((plugin) => plugin.name),
74 tools: names(mounted.tools),
75 prompts: mounted.prompts,
76 contextPrompts: mounted.contextPrompts.map((item) => item.text),
77 middleware: names(mounted.middleware),
78 agentMiddleware: names(mounted.agentMiddleware),
79 generationMiddleware: names(mounted.generationMiddleware),
80 agents: names(mounted.agents),
81 subagents: names(mounted.subagents),
82 commands: [...mounted.commands.keys()],
83 config: [...mounted.config.keys()],
84 rules: (mounted.extensions.get(Rules.name) ?? []).map((item) => item.value),
85 adapters: mounted.adapters,
86 discoverers: mounted.discoverers.map((item) => item.owner),
87 preparers: mounted.preparers.map((item) => item.owner),
88 capabilities: mounted.capabilityBridge?.provides ?? [],
89 }
91​
92describe('MountedPlugins.withoutOwners', () => {
93 it('removes every kind of contribution of a plugin and keeps the others', async () => {
94 const a = contributor('a')
95 const b = contributor('b')
96 const mounted = await mountPlugins([a.plugin, b.plugin], env())
97​
98 const kept = mounted.withoutOwners(['a'])
99​
100 expect(contents(kept)).toEqual({
101 plugins: ['b'],
102 tools: ['b_tool'],
103 prompts: ['b prompt'],
104 contextPrompts: ['b context'],
105 middleware: ['b-middleware'],
106 agentMiddleware: ['b-agent-middleware'],
107 generationMiddleware: ['b-generation-middleware'],
108 agents: ['b-agent'],
109 subagents: ['b-subagent'],
110 commands: ['b-command'],
111 config: ['b-level'],
112 rules: ['b rule'],
113 adapters: [b.pick],
114 discoverers: ['b'],
115 preparers: ['b'],
116 capabilities: [b.capability],
117 })
118 expect(kept.values.get(a.capability)).toBeUndefined()
119 expect(kept.values.get(b.capability)).toBe('b value')
120 // The mounted set itself keeps both plugins.
121 expect(contents(mounted).agents).toEqual(['a-agent', 'b-agent'])
122 expect(mounted.values.get(a.capability)).toBe('a value')
123 })
124​
125 it('removes an agent that a plugin set after the mount', async () => {
126 let saved: PluginSetupContext | undefined
127 const late = definePlugin({
128 name: 'late',
129 setup: (ctx) => {
130 saved = ctx
131 },
132 })
133 const mounted = await mountPlugins([late, contributor('b').plugin], env())
134 saved?.agents.set(agentNamed('late-subagent'), { subagent: true })
135​
136 expect(contents(mounted).subagents).toEqual(['b-subagent', 'late-subagent'])
137 expect(contents(mounted.withoutOwners(['late'])).subagents).toEqual([
138 'b-subagent',
139 ])
140 })
141​
142 it('reads the commands and agents that a kept plugin sets after the copy', async () => {
143 let saved: PluginSetupContext | undefined
144 const late = definePlugin({
145 name: 'late',
146 setup: (ctx) => {
147 saved = ctx
148 },
149 })
150 const mounted = await mountPlugins([late, contributor('b').plugin], env())
151 const kept = mounted.withoutOwners(['b'])
152​
153 saved?.commands.set(
154 'deploy',
155 defineCommand({ description: 'Deploy', run: () => 'deployed' }),
156 )
157 saved?.agents.set(agentNamed('late-subagent'), { subagent: true })
158​
159 expect(contents(kept).commands).toEqual(['deploy'])
160 expect(contents(kept).subagents).toEqual(['late-subagent'])
161 saved?.commands.delete('deploy')
162 expect(contents(kept).commands).toEqual([])
163 })
164​
165 it('refuses to remove a plugin whose capability a kept plugin requires', async () => {
166 const a = contributor('a')
167 const reader = definePlugin({
168 name: 'reader',
169 requires: [a.capability],
170 })
171 const mounted = await mountPlugins([a.plugin, reader], env())
172​
173 expect(() => mounted.withoutOwners(['a'])).toThrow(
174 'Cannot remove plugin a: plugin reader requires its capability "test/a-capability".',
175 )
176 expect(contents(mounted.withoutOwners(['a', 'reader'])).plugins).toEqual([])
177 })
178})
179​
180describe('ctx.on', () => {
181 it('leaves no abort listener on the plugin signal after off()', async () => {
182 let saved: PluginSetupContext | undefined
183 const listener = definePlugin({
184 name: 'listener',
185 setup: (ctx) => {
186 saved = ctx
187 },
188 })
189 await mountPlugins([listener], env())
190 if (!saved) throw new Error('setup did not run')
191 const signal = saved.resources.signal
192 const add = vi.spyOn(signal, 'addEventListener')
193 const removeListener = vi.spyOn(signal, 'removeEventListener')
194 const ping = createPluginEvent<string>('test/ping')
195​
196 for (let index = 0; index < 3; index++) {
197 saved.on(ping, () => {})()
198 }
199​
200 const added = add.mock.calls.map((call) => call[1])
201 const removed = removeListener.mock.calls.map((call) => call[1])
202 expect(added).toHaveLength(3)
203 expect(added.filter((item) => !removed.includes(item))).toEqual([])
204 })
205})
206​
207describe('a thread that removes a plugin', () => {
208 it('does not run an agent of that plugin by name', async () => {
209 const worker = defineAgent({
210 name: 'worker',
211 description: 'Works',
212 run: async () => 'worked',
213 })
214 const plugin = definePlugin({
215 name: 'test/workers',
216 setup: () => ({ agents: [worker] }),
217 })
218 const host = createHarnessHost({ persistence: memoryPersistence() })
219 const session = await host.open(
220 defineHarness({
221 name: 'test/plugin-owners',
222 adapter: mockAdapter(() => text('ok')).adapter,
223 plugins: () => [plugin],
224 }),
225 { threadId: 't' },
226 )
227 const byName = session.agent('worker')
228 expect(await byName?.run()).toBe('worked')
229​
230 await session.updateThreadSettings({
231 settings: { plugins: { remove: ['test/workers'] } },
232 })
233​
234 expect(session.agent('worker')).toBeUndefined()
235 await expect(byName?.start()).rejects.toThrow('Unknown agent: worker')
236 await host.close()
237 })
238})