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

plugin-agents.test.ts

198 lines6.0 KB

1import { describe, expect, it } from 'vitest'
2import { z } from 'zod'
3import { defineAgent, toolDefinition } from '@tanstack/ai'
4import { memoryPersistence } from '@tanstack/ai-persistence'
5import {
6 createHarnessHost,
7 createPluginEvent,
8 defineCommand,
9 defineHarness,
10 definePlugin,
11} from '../src'
12import { AgentRegistry } from '../src/agents'
13import { mountPlugins } from '../src/plugins'
14import { mockAdapter, text, toolCall } from './helpers'
15import type { AgentActions, HarnessRunContext } from '../src'
16​
17const painter = defineAgent({
18 name: 'painter',
19 description: 'Paints',
20 produces: 'image',
21 inputSchema: z.object({ subject: z.string() }),
22 run: async (ctx) => `a painting of ${ctx.input.subject}`,
23})
24​
25describe('ctx.agents inside a session', () => {
26 it('lists, gets, finds, and starts agents', async () => {
27 const director = definePlugin({
28 name: 'test/director',
29 setup: (ctx) => ({
30 commands: {
31 survey: defineCommand({
32 description: 'Look at the agents',
33 run: () => ({
34 names: ctx.agents.list().map((agent) => agent.name),
35 byName: ctx.agents.get('painter')?.description,
36 byOutput: ctx.agents.find({ produces: 'image' })?.name,
37 none: ctx.agents.find({ produces: 'video' }),
38 }),
39 }),
40 paint: defineCommand({
41 description: 'Start the painter by name, then by value',
42 run: async () => [
43 await ctx.agents.start('painter', { subject: 'rain' }),
44 await ctx.agents.start(
45 painter,
46 { subject: 'sun' },
47 { startTurnWhenDone: false },
48 ),
49 ],
50 }),
51 },
52 }),
53 })
54 const host = createHarnessHost({ persistence: memoryPersistence() })
55 const session = await host.open(
56 defineHarness({
57 name: 'test/agents',
58 adapter: mockAdapter([]).adapter,
59 agents: [painter],
60 plugins: () => [director],
61 }),
62 {
63 threadId: 't',
64 },
65 )
66 expect(await session.runCommand({ name: 'survey' })).toEqual({
67 names: ['painter'],
68 byName: 'Paints',
69 byOutput: 'painter',
70 none: undefined,
71 })
72 expect(await session.runCommand({ name: 'paint' })).toEqual([
73 'a painting of rain',
74 'a painting of sun',
75 ])
76 await host.close()
77 })
78​
79 it('throws for a parent that names no running agent run of this session', async () => {
80 const host = createHarnessHost({ persistence: memoryPersistence() })
81 const harness = defineHarness({
82 name: 'test/agents',
83 adapter: mockAdapter([]).adapter,
84 agents: [painter],
85 })
86 const session = await host.open(harness, { threadId: 't' })
87 const other = await host.open(harness, { threadId: 't2' })
88 const ended = session.agents.painter.start(
89 { subject: 'rain' },
90 { addResultNote: false },
91 )
92 await ended
93 const foreign = other.agents.painter.start(
94 { subject: 'sun' },
95 { addResultNote: false },
96 )
97 await foreign
98​
99 for (const runId of ['unknown-run', ended.id, foreign.id]) {
100 expect(() =>
101 session.agents.painter.start(
102 { subject: 'snow' },
103 { addResultNote: false, parent: { runId } },
104 ),
105 ).toThrow(
106 `parent names no running agent run of this session (${runId}). Pass parent: null for a root run.`,
107 )
108 }
109 await host.close()
110 })
111​
112 it('starts a top-level run for a parent that is a running turn', async () => {
113 let agents: AgentActions | undefined
114 const director = definePlugin({
115 name: 'test/director',
116 setup: (ctx) => {
117 agents = ctx.agents
118 },
119 })
120 const paint = toolDefinition({
121 name: 'paint',
122 description: 'Paints from a tool of the main model',
123 inputSchema: z.object({}),
124 }).server<HarnessRunContext>(async (_args, ctx) =>
125 agents?.run(painter, { subject: 'fog' }, { parent: ctx.context.run }),
126 )
127 const host = createHarnessHost({ persistence: memoryPersistence() })
128 const session = await host.open(
129 defineHarness({
130 name: 'test/agents',
131 adapter: mockAdapter([
132 () => toolCall('paint', {}),
133 () => text('Painted.'),
134 ]).adapter,
135 agents: [painter],
136 tools: [paint],
137 plugins: () => [director],
138 }),
139 { threadId: 't' },
140 )
141​
142 expect((await session.send('paint fog')).text).toBe('Painted.')
143 const [run] = session.agentRuns()
144 expect(run).toMatchObject({ status: 'completed' })
145 expect(run?.parentRunId).toBeUndefined()
146 await host.close()
147 })
148})
149​
150describe('plugin services outside a session', () => {
151 it('ignores events and config, and refuses session-only services', async () => {
152 const ping = createPluginEvent<number>('test/ping')
153 let checks: Record<string, unknown> = {}
154 const probe = definePlugin({
155 name: 'test/probe',
156 setup: (ctx) => {
157 const stop = ctx.on(ping, () => {})
158 stop()
159 ctx.emit(ping, 1)
160 const refused = (call: () => unknown) => {
161 try {
162 call()
163 return 'ran'
164 } catch (error) {
165 return error instanceof Error ? error.message : String(error)
166 }
167 }
168 checks = {
169 config: ctx.config.get('anything'),
170 state: refused(() => ctx.state({})),
171 credentials: refused(() => ctx.credentials.get('x')),
172 session: refused(() => ctx.session.snapshot()),
173 run: refused(() => ctx.agents.run('painter')),
174 start: refused(() => ctx.agents.start('painter')),
175 group: refused(() => ctx.agents.group({}, () => [])),
176 }
177 return {}
178 },
179 })
180 await mountPlugins([probe], {
181 threadId: 't',
182 registry: new AgentRegistry(),
183 harnessTools: [],
184 harnessProvides: [],
185 })
186 expect(checks.config).toBeUndefined()
187 for (const key of [
188 'state',
189 'credentials',
190 'session',
191 'run',
192 'start',
193 'group',
194 ]) {
195 expect(checks[key]).toContain('only available inside a harness session')
196 }
197 })
198})