model-surface.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import { Buffer } from 'node:buffer'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import AgentRegistry from '@deepseek-ai/dsh-agent'
  4. import type { Agent } from '@deepseek-ai/dsh-agent'
  5. import { createToolResultMessage, ToolCallId } from '@deepseek-ai/dsh-llm'
  6. import { createScope, scopeOf, type ScopeKey } from '@deepseek-ai/dsh-scope'
  7. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  8. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  9. import ToolRuntime from '@deepseek-ai/dsh-tools'
  10. import { describe, expect, it, vi } from 'vitest'
  11. import * as VisualizerClient from '../src/client.ts'
  12. import VisualizerService from '../src/index.ts'
  13. import * as VisualizerModel from '../src/model.ts'
  14. import { visualizerSystemPrompt } from '../src/prompt.ts'
  15. const SIGNAL = new AbortController().signal
  16. const SCOPED_BASES = new WeakMap<Context, Context>()
  17. async function captureScopedBase(ctx: Context): Promise<void> {
  18. await ctx.plugin(Object.assign((inner: Context) => {
  19. SCOPED_BASES.set(ctx, inner)
  20. }, { inject: ['systemPrompt', 'tools'] }))
  21. }
  22. async function mount() {
  23. const ctx = new Context()
  24. await ctx.plugin(AgentRegistry)
  25. await ctx.plugin(SystemPrompt)
  26. await ctx.plugin(ToolRuntime)
  27. const authorityFiber = await ctx.plugin(VisualizerService)
  28. await captureScopedBase(ctx)
  29. const base = SCOPED_BASES.get(ctx)
  30. if (base === undefined) throw new Error('missing scoped test base')
  31. const presetKey: ScopeKey = { agentPreset: 'surface' }
  32. const presetScope = createScope(base, presetKey)
  33. const modelFiber = await presetScope.ctx.plugin(VisualizerModel)
  34. const agent = recordedAgent(ctx, 'surface-agent', undefined, undefined, presetKey)
  35. ctx.agents.register(agent)
  36. return { ctx, authorityFiber, modelFiber, presetScope, agent }
  37. }
  38. async function modelFace(ctx: Context, agent: Agent) {
  39. const prompt = await ctx.systemPrompt.assemble({ agent, scope: agent })
  40. const names = ['widget_guidelines', 'show_widget']
  41. .filter(name => ctx.tools.get(name, agent) !== undefined)
  42. const guidance = await ctx.tools.execute({
  43. signal: SIGNAL,
  44. callId: ToolCallId('snapshot-guidance'),
  45. name: 'widget_guidelines',
  46. arguments: { modules: ['diagram', 'mockup', 'interactive', 'chart', 'illustration'] },
  47. agent,
  48. })
  49. const receipt = await ctx.tools.execute({
  50. signal: SIGNAL,
  51. callId: ToolCallId('snapshot-widget'),
  52. name: 'show_widget',
  53. arguments: {
  54. title: 'Snapshot',
  55. widget_code: '<button>Choose</button>',
  56. },
  57. agent,
  58. })
  59. return {
  60. prompt: prompt.sections.find(section => section.name === 'tool:visualizer')?.text,
  61. tools: Object.fromEntries(names.map((name) => {
  62. const tool = ctx.tools.get(name, agent)
  63. if (tool === undefined) throw new Error(`missing Visualizer tool ${name}`)
  64. return [name, { description: tool.description, parameters: tool.parameters, output: tool.output.schema }]
  65. })),
  66. results: { guidance: guidance.content, show_widget: receipt.content },
  67. }
  68. }
  69. function recordedAgent(
  70. ctx: Context,
  71. id: string,
  72. followup: Agent['followup'] = vi.fn<Agent['followup']>(),
  73. source = '<button>Choose</button><script></script>',
  74. presetParent?: ScopeKey,
  75. ): Agent {
  76. const session = Session.create(SessionId(id))
  77. session.append('turn/start', { turn: 1 })
  78. session.append('step/start', { turn: 1, step: 1 })
  79. const call = session.append('tool/call', {
  80. turn: 1,
  81. step: 1,
  82. callId: ToolCallId('widget'),
  83. name: 'show_widget',
  84. arguments: JSON.stringify({ title: 'Choice', widget_code: source }),
  85. })
  86. session.append('tool/result', {
  87. turn: 1,
  88. step: 1,
  89. message: createToolResultMessage({ callId: ToolCallId('widget'), content: [], isError: false }),
  90. meta: { kind: /^<svg(?=[\s/>])/i.test(source.trimStart()) ? 'svg' : 'html' },
  91. }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] })
  92. const agent = { id: session.id, session, ctx, followup } as unknown as Agent
  93. const scope = createScope(
  94. SCOPED_BASES.get(ctx) ?? ctx,
  95. agent,
  96. presetParent === undefined ? undefined : { parent: presetParent },
  97. )
  98. Object.assign(agent, { ctx: scope.ctx.extend({ agent }) })
  99. return agent
  100. }
  101. describe('Visualizer model surface', () => {
  102. it('ships one neutral SVG and HTML model surface when mounted', async () => {
  103. const { ctx, agent } = await mount()
  104. expect(await modelFace(ctx, agent)).toMatchSnapshot()
  105. const prompt = await ctx.systemPrompt.assemble({ agent, scope: agent })
  106. expect(prompt.sections.find(section => section.name === 'tool:visualizer')?.text)
  107. .toBe(visualizerSystemPrompt())
  108. const guidance = ctx.tools.get('widget_guidelines', agent)!
  109. const show = ctx.tools.get('show_widget', agent)!
  110. expect(ctx.tools.schemas()).toEqual([])
  111. const mockupGuidelines = await ctx.tools.execute({
  112. signal: SIGNAL,
  113. callId: ToolCallId('mockup'),
  114. name: 'widget_guidelines',
  115. arguments: { modules: ['mockup'] },
  116. agent,
  117. })
  118. const mockupGuidelineText = mockupGuidelines.content
  119. .flatMap(item => item.type === 'text' ? [item.text] : [])
  120. .join('\n')
  121. expect(mockupGuidelineText).toContain('native controls')
  122. const interactiveGuidelines = await ctx.tools.execute({
  123. signal: SIGNAL,
  124. callId: ToolCallId('interactive'),
  125. name: 'widget_guidelines',
  126. arguments: { modules: ['interactive'] },
  127. agent,
  128. })
  129. const interactiveGuidelineText = interactiveGuidelines.content
  130. .flatMap(item => item.type === 'text' ? [item.text] : [])
  131. .join('\n')
  132. expect(interactiveGuidelineText).toContain('window.dshWidget.sendPrompt')
  133. expect(interactiveGuidelineText).toContain('Call show_widget next')
  134. expect(visualizerSystemPrompt()).toContain('choose presentation details yourself')
  135. expect(visualizerSystemPrompt()).toContain('use no file, shell, editing, or preview step')
  136. expect(interactiveGuidelineText).toContain('one primary control per value')
  137. expect(interactiveGuidelineText).toContain('Give every control a clear label')
  138. expect(interactiveGuidelineText).not.toContain('window.dshWidget.onInit')
  139. expect(interactiveGuidelineText).not.toContain('window.dshWidget.reportState')
  140. expect(guidance.parameters).toEqual({
  141. type: 'object',
  142. properties: {
  143. modules: {
  144. type: 'array',
  145. items: { type: 'string', enum: ['diagram', 'mockup', 'interactive', 'chart', 'illustration'] },
  146. description: 'Choose every module that fits the requested result. diagram: a fixed view of nodes and relationships. chart: quantitative data. illustration: a scene or image. interactive: an adjustable calculation, simulation, or animated demonstration. mockup: a product surface shown to explain one interaction.',
  147. },
  148. },
  149. required: ['modules'],
  150. })
  151. expect(show.description)
  152. .toBe('Render one temporary inline graphic or interactive widget from conversation content or completed tool results. Source beginning with <svg uses SVG; anything else uses HTML. Pass one small, complete source in this call; validation occurs after submission.')
  153. const staticReceipt = show.output.render?.(
  154. { title: 'Static', widget_code: '<svg></svg>' },
  155. { kind: 'svg' },
  156. )[0]
  157. expect(staticReceipt?.type === 'text' ? staticReceipt.text : '')
  158. .toBe('Widget "Static" accepted (svg). It is final for this response; finish with brief supporting prose.')
  159. expect((show.output.schema as { properties: { kind: { enum: string[] } } }).properties.kind.enum)
  160. .toEqual(['svg', 'html'])
  161. const sourceDescription = JSON.stringify(show.parameters)
  162. expect(sourceDescription).toContain('For HTML: one fragment')
  163. expect(sourceDescription).toContain('inline <style>')
  164. expect(sourceDescription).toContain('<canvas> using 2D or WebGL')
  165. expect(sourceDescription).toContain('inline <script>')
  166. expect(sourceDescription).toContain('For SVG: raw SVG')
  167. expect(sourceDescription).toContain(
  168. 'Keep the widget self-contained: include all required styles, scripts, data, and assets in the source',
  169. )
  170. expect(sourceDescription).not.toContain('load and follow the interactive widget_guidelines module')
  171. expect(sourceDescription).not.toContain('window.dshWidget')
  172. })
  173. it('applies the fixed per-Agent prompt rate in the preset scope', async () => {
  174. const { ctx, presetScope, agent } = await mount()
  175. expect((await ctx.systemPrompt.assemble()).contexts).toEqual([])
  176. const presetKey = scopeOf(presetScope.ctx)
  177. if (presetKey === undefined) throw new Error('missing preset scope key')
  178. expect((await ctx.systemPrompt.assemble({ scope: presetKey })).contexts).toEqual([])
  179. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).contexts).toEqual([])
  180. for (let index = 0; index < 4; index += 1) {
  181. ctx.visualizer.remoteSendPrompt(agent, {
  182. resultSeq: 3, text: `follow-up ${index}`,
  183. })
  184. }
  185. expect(() => {
  186. ctx.visualizer.remoteSendPrompt(agent, { resultSeq: 3, text: 'one too many' })
  187. }).toThrow('Agent widget follow-up rate limit reached')
  188. })
  189. it('keeps Host authority model-empty and exposes ./model only through its preset standing scope', async () => {
  190. const { ctx, agent } = await mount()
  191. const bare = recordedAgent(ctx, 'bare-agent')
  192. ctx.agents.register(bare)
  193. expect(Object.keys(VisualizerClient)).toEqual([])
  194. expect(ctx.tools.schemas()).toEqual([])
  195. expect(ctx.tools.schemas(agent).map(tool => tool.name).sort())
  196. .toEqual(['show_widget', 'widget_guidelines'])
  197. expect(ctx.tools.schemas(bare)).toEqual([])
  198. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).sections
  199. .some(section => section.name === 'tool:visualizer')).toBe(true)
  200. expect((await ctx.systemPrompt.assemble({ agent: bare, scope: bare })).sections
  201. .some(section => section.name === 'tool:visualizer')).toBe(false)
  202. })
  203. it('withdraws the inherited router when a child filter hides the feature tools', async () => {
  204. const { ctx, presetScope } = await mount()
  205. const presetKey = scopeOf(presetScope.ctx)
  206. if (presetKey === undefined) throw new Error('missing preset scope key')
  207. const child = recordedAgent(ctx, 'filtered-child', undefined, undefined, presetKey)
  208. ctx.agents.register(child)
  209. const visible = await ctx.systemPrompt.assemble({ agent: child, scope: child })
  210. expect(visible.sections.find(section => section.name === 'tool:visualizer')?.text)
  211. .toBe(visualizerSystemPrompt())
  212. expect(visible.contexts).toEqual([])
  213. child.ctx.tools.restrict({ allow: [] })
  214. expect(ctx.tools.schemas(child)).toEqual([])
  215. const hidden = await ctx.systemPrompt.assemble({ agent: child, scope: child })
  216. expect(hidden.sections.find(section => section.name === 'tool:visualizer')?.text).toBe('')
  217. expect(hidden.contexts).toEqual([])
  218. })
  219. it('keeps the show_widget contract satisfiable when a child filter hides widget_guidelines', async () => {
  220. const { ctx, presetScope } = await mount()
  221. const presetKey = scopeOf(presetScope.ctx)
  222. if (presetKey === undefined) throw new Error('missing preset scope key')
  223. const child = recordedAgent(ctx, 'show-only-child', undefined, undefined, presetKey)
  224. ctx.agents.register(child)
  225. child.ctx.tools.restrict({ allow: ['show_widget'] })
  226. expect(ctx.tools.schemas(child).map(tool => tool.name)).toEqual(['show_widget'])
  227. expect(ctx.tools.get('widget_guidelines', child)).toBeUndefined()
  228. expect(ctx.tools.get('show_widget', child)?.description).not.toContain('widget_guidelines')
  229. const prompt = await ctx.systemPrompt.assemble({ agent: child, scope: child })
  230. expect(prompt.sections.find(section => section.name === 'tool:visualizer')?.text)
  231. .toBe(visualizerSystemPrompt())
  232. })
  233. it('omits delivery guidance when a child filter hides show_widget', async () => {
  234. const { ctx, presetScope } = await mount()
  235. const presetKey = scopeOf(presetScope.ctx)
  236. if (presetKey === undefined) throw new Error('missing preset scope key')
  237. const child = recordedAgent(ctx, 'guidelines-only-child', undefined, undefined, presetKey)
  238. ctx.agents.register(child)
  239. child.ctx.tools.restrict({ allow: ['widget_guidelines'] })
  240. expect(ctx.tools.schemas(child).map(tool => tool.name)).toEqual(['widget_guidelines'])
  241. const result = await ctx.tools.execute({
  242. signal: SIGNAL,
  243. callId: ToolCallId('filtered-guidance'),
  244. name: 'widget_guidelines',
  245. arguments: { modules: ['diagram'] },
  246. agent: child,
  247. })
  248. const text = result.content.flatMap(item => item.type === 'text' ? [item.text] : []).join('\n')
  249. expect(text).toContain('## Foundation')
  250. expect(text).not.toContain('show_widget')
  251. const prompt = await ctx.systemPrompt.assemble({ agent: child, scope: child })
  252. expect(prompt.sections.find(section => section.name === 'tool:visualizer')?.text).toBe('')
  253. })
  254. it('rejects installing the model surface on the unscoped Host root', async () => {
  255. const ctx = new Context()
  256. await ctx.plugin(AgentRegistry)
  257. await ctx.plugin(SystemPrompt)
  258. await ctx.plugin(ToolRuntime)
  259. await ctx.plugin(VisualizerService)
  260. expect(() => { ctx.visualizer.installModelSurface(ctx) })
  261. .toThrow('tool-visualizer: the model contribution requires a scoped context without an Agent')
  262. expect(ctx.tools.schemas()).toEqual([])
  263. expect((await ctx.systemPrompt.assemble()).sections
  264. .some(section => section.name === 'tool:visualizer')).toBe(false)
  265. await ctx.fiber.dispose()
  266. })
  267. it('rejects installing the model surface in one Agent\'s own scope', async () => {
  268. const ctx = new Context()
  269. await ctx.plugin(AgentRegistry)
  270. await ctx.plugin(SystemPrompt)
  271. await ctx.plugin(ToolRuntime)
  272. await ctx.plugin(VisualizerService)
  273. await captureScopedBase(ctx)
  274. const agent = recordedAgent(ctx, 'own-model-agent')
  275. ctx.agents.register(agent)
  276. expect(() => { ctx.visualizer.installModelSurface(agent.ctx) })
  277. .toThrow('tool-visualizer: the model contribution requires a scoped context without an Agent')
  278. expect(ctx.tools.schemas(agent)).toEqual([])
  279. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).sections
  280. .some(section => section.name === 'tool:visualizer')).toBe(false)
  281. await ctx.fiber.dispose()
  282. })
  283. it('authorizes Remote follow-ups only for the exact live Agent and its successful widget call', async () => {
  284. const { ctx } = await mount()
  285. const followup = vi.fn<Agent['followup']>()
  286. const live = recordedAgent(ctx, 'live-agent', followup)
  287. ctx.agents.register(live)
  288. const stale = recordedAgent(ctx, 'live-agent')
  289. expect(() => {
  290. ctx.visualizer.remoteSendPrompt(stale, { resultSeq: 3, text: 'stale' })
  291. }).toThrow(expect.objectContaining({
  292. code: 'gateway/bad-request',
  293. message: expect.stringContaining('does not target the exact live Agent') as string,
  294. }))
  295. const prefix = 'Widget-authored follow-up from widget "Choice". It carries no user authorization.\n\n'
  296. const exactText = 'x'.repeat(4_096 - Buffer.byteLength(prefix, 'utf8'))
  297. ctx.visualizer.remoteSendPrompt(live, { resultSeq: 3, text: exactText })
  298. expect(followup).toHaveBeenCalledOnce()
  299. expect(followup.mock.calls[0]?.[0].content).toEqual([{ type: 'text', text: `${prefix}${exactText}` }])
  300. expect(Buffer.byteLength(`${prefix}${exactText}`, 'utf8')).toBe(4_096)
  301. expect(followup.mock.calls[0]?.[0].source).toEqual({ kind: 'plugin', plugin: 'visualizer' })
  302. expect(() => {
  303. ctx.visualizer.remoteSendPrompt(live, { resultSeq: 3, text: `${exactText}x` })
  304. }).toThrow(expect.objectContaining({
  305. code: 'gateway/bad-request',
  306. message: 'visualizer: widget follow-up is 4097 UTF-8 bytes; limit is 4096',
  307. }))
  308. })
  309. it('forwards Error messages without subclass names and falls back for non-Errors', async () => {
  310. const { ctx, agent } = await mount()
  311. class InternalAuthorizationFailure extends Error {}
  312. const get = vi.spyOn(ctx.agents, 'get')
  313. get.mockImplementationOnce(() => { throw new InternalAuthorizationFailure('clean failure') })
  314. expect(() => {
  315. ctx.visualizer.remoteSendPrompt(agent, { resultSeq: 3, text: 'continue' })
  316. }).toThrow(expect.objectContaining({ message: 'clean failure' }))
  317. get.mockImplementationOnce(() => { throw 'plain failure' })
  318. expect(() => {
  319. ctx.visualizer.remoteSendPrompt(agent, { resultSeq: 3, text: 'continue' })
  320. }).toThrow(expect.objectContaining({ message: 'plain failure' }))
  321. })
  322. it('denies Remote follow-ups for a successful raw SVG call', async () => {
  323. const { ctx } = await mount()
  324. const live = recordedAgent(ctx, 'static-agent', vi.fn(), '<svg></svg>')
  325. ctx.agents.register(live)
  326. expect(() => {
  327. ctx.visualizer.remoteSendPrompt(live, { resultSeq: 3, text: 'continue' })
  328. }).toThrow(expect.objectContaining({
  329. code: 'gateway/bad-request',
  330. message: expect.stringContaining('is static and cannot send follow-ups') as string,
  331. }))
  332. })
  333. it('enforces the renderer byte boundary and does not echo widget source', async () => {
  334. const { ctx, agent } = await mount()
  335. const exactSource = 'x'.repeat(131_072)
  336. const exact = await ctx.tools.execute({
  337. signal: SIGNAL,
  338. callId: ToolCallId('exact'),
  339. name: 'show_widget',
  340. arguments: { title: '图', widget_code: exactSource },
  341. agent,
  342. })
  343. expect(exact.isError).toBe(false)
  344. expect(exact.content.map(block => block.type === 'text' ? block.text : '').join('')).not.toContain(exactSource)
  345. const oversized = await ctx.tools.execute({
  346. signal: SIGNAL,
  347. callId: ToolCallId('oversized'),
  348. name: 'show_widget',
  349. arguments: { title: '图', widget_code: `${exactSource}x` },
  350. agent,
  351. })
  352. expect(oversized.isError).toBe(true)
  353. expect(oversized.content).toEqual([{
  354. type: 'text',
  355. text: 'Error: visualizer: widget_code is 131073 UTF-8 bytes; limit is 131072',
  356. }])
  357. })
  358. it('rejects an empty interactive fragment', async () => {
  359. const { ctx, agent } = await mount()
  360. const result = await ctx.tools.execute({
  361. signal: SIGNAL,
  362. callId: ToolCallId('empty'),
  363. name: 'show_widget',
  364. arguments: { title: 'Empty', widget_code: ' ' },
  365. agent,
  366. })
  367. expect(result).toMatchObject({ isError: true })
  368. expect(result.content).toEqual([{ type: 'text', text: 'Error: visualizer: widget_code must be non-empty' }])
  369. })
  370. it('validates every widget argument boundary and detects source kinds case-insensitively', async () => {
  371. const { ctx, agent } = await mount()
  372. const execute = async (title: string, widget_code: string) => await ctx.tools.execute({
  373. signal: SIGNAL, callId: ToolCallId(`case-${title.length}-${widget_code.length}`),
  374. name: 'show_widget', arguments: { title, widget_code }, agent,
  375. })
  376. const errorText = async (title: string, source: string): Promise<string> => {
  377. const block = (await execute(title, source)).content[0]
  378. return block?.type === 'text' ? block.text : ''
  379. }
  380. expect(await errorText(' ', '<svg></svg>')).toContain('title must be non-empty')
  381. expect(await errorText('汉'.repeat(86), '<svg></svg>')).toContain('title is 258 UTF-8 bytes')
  382. expect(await errorText('A', '<html></html>')).toContain('document wrappers')
  383. expect(await errorText('A', '<html/>')).toContain('document wrappers')
  384. expect(await errorText('A', '<body/>')).toContain('document wrappers')
  385. expect(await errorText('A', '<!--note--><html lang="en">')).toContain('document wrappers')
  386. expect(await errorText('A', '```html\n<html></html>\n```')).toContain('raw source without Markdown code fences')
  387. expect(await errorText('A', '```html\n \n```')).toContain('raw source without Markdown code fences')
  388. expect(await errorText('A', '```html5\n<button>A</button>\n```')).toContain('raw source without Markdown code fences')
  389. expect(await errorText('A', '````html\n<button>A</button>\n````')).toContain('raw source without Markdown code fences')
  390. expect(await errorText('A', '~~~html\n<button>A</button>\n~~~')).toContain('raw source without Markdown code fences')
  391. expect(await execute('A', '<svgx></svgx>')).toMatchObject({ isError: false, meta: { kind: 'html' } })
  392. expect(await execute('A', ' <SVG></SVG>')).toMatchObject({ isError: false, meta: { kind: 'svg' } })
  393. expect(await execute('A', '<svg/>')).toMatchObject({ isError: false, meta: { kind: 'svg' } })
  394. expect(await errorText('A', '```svg\n<svg viewBox="0 0 2 1"></svg>\n```'))
  395. .toContain('raw source without Markdown code fences')
  396. expect(await errorText('A', '```html\n<button>A</button>\n```'))
  397. .toContain('raw source without Markdown code fences')
  398. })
  399. it('accepts interactive HTML and exercises every tool presentation surface', async () => {
  400. const { ctx, agent } = await mount()
  401. const guidance = ctx.tools.get('widget_guidelines', agent)!
  402. const show = ctx.tools.get('show_widget', agent)!
  403. expect(guidance.isConcurrencySafe?.({ modules: ['chart'] })).toBe(true)
  404. expect(guidance.presentCall?.({ modules: ['chart'] })).toMatchObject({ title: 'Load widget guidance: chart' })
  405. expect(guidance.output.render?.({ modules: ['chart'] }, 'rules')).toEqual([{ type: 'text', text: 'rules' }])
  406. expect(show.isConcurrencySafe?.({ title: 'Demo', widget_code: '<button>A</button>' })).toBe(true)
  407. expect(show.presentCall?.({ title: 'Demo', widget_code: '<button>A</button>' })).toMatchObject({ title: 'Widget: Demo' })
  408. expect(show.output.render?.({ title: 'Demo', widget_code: '<button>A</button>' }, { kind: 'html' }))
  409. .toEqual([{
  410. type: 'text',
  411. text: 'Widget "Demo" accepted (html). It is final for this response; finish with brief supporting prose.',
  412. }])
  413. expect(show.output.presentationMeta?.({ title: 'Demo', widget_code: '<button>A</button>' }, { kind: 'html' }))
  414. .toEqual({ kind: 'html' })
  415. const html = await ctx.tools.execute({
  416. signal: SIGNAL, callId: ToolCallId('html'), name: 'show_widget',
  417. arguments: { title: 'Demo', widget_code: '<button>A</button>' }, agent,
  418. })
  419. expect(html).toMatchObject({ isError: false, meta: { kind: 'html' } })
  420. })
  421. it('removes tools and prompt with the ./model fiber while keeping Host authority', async () => {
  422. const { ctx, modelFiber, agent } = await mount()
  423. expect(ctx.tools.get('show_widget', agent)).toBeDefined()
  424. await modelFiber.dispose()
  425. expect(ctx.tools.get('show_widget', agent)).toBeUndefined()
  426. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).sections
  427. .some(section => section.name === 'tool:visualizer')).toBe(false)
  428. expect(ctx.get('visualizer') !== undefined).toBe(true)
  429. })
  430. it('withdraws the ./model contribution when its Host authority disappears', async () => {
  431. const { ctx, authorityFiber, modelFiber, agent } = await mount()
  432. expect(ctx.tools.get('show_widget', agent)).toBeDefined()
  433. await authorityFiber.dispose()
  434. await vi.waitFor(() => { expect(ctx.tools.get('show_widget', agent)).toBeUndefined() })
  435. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).sections
  436. .some(section => section.name === 'tool:visualizer')).toBe(false)
  437. await modelFiber.dispose()
  438. })
  439. })