model-surface.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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('External resources are blocked; inline everything')
  168. expect(sourceDescription).not.toContain('load and follow the interactive widget_guidelines module')
  169. expect(sourceDescription).not.toContain('window.dshWidget')
  170. })
  171. it('applies the fixed per-Agent prompt rate in the preset scope', async () => {
  172. const { ctx, presetScope, agent } = await mount()
  173. expect((await ctx.systemPrompt.assemble()).contexts).toEqual([])
  174. const presetKey = scopeOf(presetScope.ctx)
  175. if (presetKey === undefined) throw new Error('missing preset scope key')
  176. expect((await ctx.systemPrompt.assemble({ scope: presetKey })).contexts).toEqual([])
  177. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).contexts).toEqual([])
  178. for (let index = 0; index < 4; index += 1) {
  179. ctx.visualizer.remoteSendPrompt(agent, {
  180. resultSeq: 3, text: `follow-up ${index}`,
  181. })
  182. }
  183. expect(() => {
  184. ctx.visualizer.remoteSendPrompt(agent, { resultSeq: 3, text: 'one too many' })
  185. }).toThrow('Agent widget follow-up rate limit reached')
  186. })
  187. it('keeps Host authority model-empty and exposes ./model only through its preset standing scope', async () => {
  188. const { ctx, agent } = await mount()
  189. const bare = recordedAgent(ctx, 'bare-agent')
  190. ctx.agents.register(bare)
  191. expect(Object.keys(VisualizerClient)).toEqual([])
  192. expect(ctx.tools.schemas()).toEqual([])
  193. expect(ctx.tools.schemas(agent).map(tool => tool.name).sort())
  194. .toEqual(['show_widget', 'widget_guidelines'])
  195. expect(ctx.tools.schemas(bare)).toEqual([])
  196. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).sections
  197. .some(section => section.name === 'tool:visualizer')).toBe(true)
  198. expect((await ctx.systemPrompt.assemble({ agent: bare, scope: bare })).sections
  199. .some(section => section.name === 'tool:visualizer')).toBe(false)
  200. })
  201. it('withdraws the inherited router when a child filter hides the feature tools', async () => {
  202. const { ctx, presetScope } = await mount()
  203. const presetKey = scopeOf(presetScope.ctx)
  204. if (presetKey === undefined) throw new Error('missing preset scope key')
  205. const child = recordedAgent(ctx, 'filtered-child', undefined, undefined, presetKey)
  206. ctx.agents.register(child)
  207. const visible = await ctx.systemPrompt.assemble({ agent: child, scope: child })
  208. expect(visible.sections.find(section => section.name === 'tool:visualizer')?.text)
  209. .toBe(visualizerSystemPrompt())
  210. expect(visible.contexts).toEqual([])
  211. child.ctx.tools.restrict({ allow: [] })
  212. expect(ctx.tools.schemas(child)).toEqual([])
  213. const hidden = await ctx.systemPrompt.assemble({ agent: child, scope: child })
  214. expect(hidden.sections.find(section => section.name === 'tool:visualizer')?.text).toBe('')
  215. expect(hidden.contexts).toEqual([])
  216. })
  217. it('keeps the show_widget contract satisfiable when a child filter hides widget_guidelines', async () => {
  218. const { ctx, presetScope } = await mount()
  219. const presetKey = scopeOf(presetScope.ctx)
  220. if (presetKey === undefined) throw new Error('missing preset scope key')
  221. const child = recordedAgent(ctx, 'show-only-child', undefined, undefined, presetKey)
  222. ctx.agents.register(child)
  223. child.ctx.tools.restrict({ allow: ['show_widget'] })
  224. expect(ctx.tools.schemas(child).map(tool => tool.name)).toEqual(['show_widget'])
  225. expect(ctx.tools.get('widget_guidelines', child)).toBeUndefined()
  226. expect(ctx.tools.get('show_widget', child)?.description).not.toContain('widget_guidelines')
  227. const prompt = await ctx.systemPrompt.assemble({ agent: child, scope: child })
  228. expect(prompt.sections.find(section => section.name === 'tool:visualizer')?.text)
  229. .toBe(visualizerSystemPrompt())
  230. })
  231. it('omits delivery guidance when a child filter hides show_widget', async () => {
  232. const { ctx, presetScope } = await mount()
  233. const presetKey = scopeOf(presetScope.ctx)
  234. if (presetKey === undefined) throw new Error('missing preset scope key')
  235. const child = recordedAgent(ctx, 'guidelines-only-child', undefined, undefined, presetKey)
  236. ctx.agents.register(child)
  237. child.ctx.tools.restrict({ allow: ['widget_guidelines'] })
  238. expect(ctx.tools.schemas(child).map(tool => tool.name)).toEqual(['widget_guidelines'])
  239. const result = await ctx.tools.execute({
  240. signal: SIGNAL,
  241. callId: ToolCallId('filtered-guidance'),
  242. name: 'widget_guidelines',
  243. arguments: { modules: ['diagram'] },
  244. agent: child,
  245. })
  246. const text = result.content.flatMap(item => item.type === 'text' ? [item.text] : []).join('\n')
  247. expect(text).toContain('## Foundation')
  248. expect(text).not.toContain('show_widget')
  249. const prompt = await ctx.systemPrompt.assemble({ agent: child, scope: child })
  250. expect(prompt.sections.find(section => section.name === 'tool:visualizer')?.text).toBe('')
  251. })
  252. it('rejects installing the model surface on the unscoped Host root', async () => {
  253. const ctx = new Context()
  254. await ctx.plugin(AgentRegistry)
  255. await ctx.plugin(SystemPrompt)
  256. await ctx.plugin(ToolRuntime)
  257. await ctx.plugin(VisualizerService)
  258. expect(() => { ctx.visualizer.installModelSurface(ctx) })
  259. .toThrow('tool-visualizer: the model contribution requires a scoped context without an Agent')
  260. expect(ctx.tools.schemas()).toEqual([])
  261. expect((await ctx.systemPrompt.assemble()).sections
  262. .some(section => section.name === 'tool:visualizer')).toBe(false)
  263. await ctx.fiber.dispose()
  264. })
  265. it('rejects installing the model surface in one Agent\'s own scope', async () => {
  266. const ctx = new Context()
  267. await ctx.plugin(AgentRegistry)
  268. await ctx.plugin(SystemPrompt)
  269. await ctx.plugin(ToolRuntime)
  270. await ctx.plugin(VisualizerService)
  271. await captureScopedBase(ctx)
  272. const agent = recordedAgent(ctx, 'own-model-agent')
  273. ctx.agents.register(agent)
  274. expect(() => { ctx.visualizer.installModelSurface(agent.ctx) })
  275. .toThrow('tool-visualizer: the model contribution requires a scoped context without an Agent')
  276. expect(ctx.tools.schemas(agent)).toEqual([])
  277. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).sections
  278. .some(section => section.name === 'tool:visualizer')).toBe(false)
  279. await ctx.fiber.dispose()
  280. })
  281. it('authorizes Remote follow-ups only for the exact live Agent and its successful widget call', async () => {
  282. const { ctx } = await mount()
  283. const followup = vi.fn<Agent['followup']>()
  284. const live = recordedAgent(ctx, 'live-agent', followup)
  285. ctx.agents.register(live)
  286. const stale = recordedAgent(ctx, 'live-agent')
  287. expect(() => {
  288. ctx.visualizer.remoteSendPrompt(stale, { resultSeq: 3, text: 'stale' })
  289. }).toThrow(expect.objectContaining({
  290. code: 'gateway/bad-request',
  291. message: expect.stringContaining('does not target the exact live Agent') as string,
  292. }))
  293. const prefix = 'Widget-authored follow-up from widget "Choice". It carries no user authorization.\n\n'
  294. const exactText = 'x'.repeat(4_096 - Buffer.byteLength(prefix, 'utf8'))
  295. ctx.visualizer.remoteSendPrompt(live, { resultSeq: 3, text: exactText })
  296. expect(followup).toHaveBeenCalledOnce()
  297. expect(followup.mock.calls[0]?.[0].content).toEqual([{ type: 'text', text: `${prefix}${exactText}` }])
  298. expect(Buffer.byteLength(`${prefix}${exactText}`, 'utf8')).toBe(4_096)
  299. expect(followup.mock.calls[0]?.[0].source).toEqual({ kind: 'plugin', plugin: 'visualizer' })
  300. expect(() => {
  301. ctx.visualizer.remoteSendPrompt(live, { resultSeq: 3, text: `${exactText}x` })
  302. }).toThrow(expect.objectContaining({
  303. code: 'gateway/bad-request',
  304. message: 'visualizer: widget follow-up is 4097 UTF-8 bytes; limit is 4096',
  305. }))
  306. })
  307. it('forwards Error messages without subclass names and falls back for non-Errors', async () => {
  308. const { ctx, agent } = await mount()
  309. class InternalAuthorizationFailure extends Error {}
  310. const get = vi.spyOn(ctx.agents, 'get')
  311. get.mockImplementationOnce(() => { throw new InternalAuthorizationFailure('clean failure') })
  312. expect(() => {
  313. ctx.visualizer.remoteSendPrompt(agent, { resultSeq: 3, text: 'continue' })
  314. }).toThrow(expect.objectContaining({ message: 'clean failure' }))
  315. get.mockImplementationOnce(() => { throw 'plain failure' })
  316. expect(() => {
  317. ctx.visualizer.remoteSendPrompt(agent, { resultSeq: 3, text: 'continue' })
  318. }).toThrow(expect.objectContaining({ message: 'plain failure' }))
  319. })
  320. it('denies Remote follow-ups for a successful raw SVG call', async () => {
  321. const { ctx } = await mount()
  322. const live = recordedAgent(ctx, 'static-agent', vi.fn(), '<svg></svg>')
  323. ctx.agents.register(live)
  324. expect(() => {
  325. ctx.visualizer.remoteSendPrompt(live, { resultSeq: 3, text: 'continue' })
  326. }).toThrow(expect.objectContaining({
  327. code: 'gateway/bad-request',
  328. message: expect.stringContaining('is static and cannot send follow-ups') as string,
  329. }))
  330. })
  331. it('enforces the renderer byte boundary and does not echo widget source', async () => {
  332. const { ctx, agent } = await mount()
  333. const exactSource = 'x'.repeat(131_072)
  334. const exact = await ctx.tools.execute({
  335. signal: SIGNAL,
  336. callId: ToolCallId('exact'),
  337. name: 'show_widget',
  338. arguments: { title: '图', widget_code: exactSource },
  339. agent,
  340. })
  341. expect(exact.isError).toBe(false)
  342. expect(exact.content.map(block => block.type === 'text' ? block.text : '').join('')).not.toContain(exactSource)
  343. const oversized = await ctx.tools.execute({
  344. signal: SIGNAL,
  345. callId: ToolCallId('oversized'),
  346. name: 'show_widget',
  347. arguments: { title: '图', widget_code: `${exactSource}x` },
  348. agent,
  349. })
  350. expect(oversized.isError).toBe(true)
  351. expect(oversized.content).toEqual([{
  352. type: 'text',
  353. text: 'Error: visualizer: widget_code is 131073 UTF-8 bytes; limit is 131072',
  354. }])
  355. })
  356. it('rejects an empty interactive fragment', async () => {
  357. const { ctx, agent } = await mount()
  358. const result = await ctx.tools.execute({
  359. signal: SIGNAL,
  360. callId: ToolCallId('empty'),
  361. name: 'show_widget',
  362. arguments: { title: 'Empty', widget_code: ' ' },
  363. agent,
  364. })
  365. expect(result).toMatchObject({ isError: true })
  366. expect(result.content).toEqual([{ type: 'text', text: 'Error: visualizer: widget_code must be non-empty' }])
  367. })
  368. it('validates every widget argument boundary and detects source kinds case-insensitively', async () => {
  369. const { ctx, agent } = await mount()
  370. const execute = async (title: string, widget_code: string) => await ctx.tools.execute({
  371. signal: SIGNAL, callId: ToolCallId(`case-${title.length}-${widget_code.length}`),
  372. name: 'show_widget', arguments: { title, widget_code }, agent,
  373. })
  374. const errorText = async (title: string, source: string): Promise<string> => {
  375. const block = (await execute(title, source)).content[0]
  376. return block?.type === 'text' ? block.text : ''
  377. }
  378. expect(await errorText(' ', '<svg></svg>')).toContain('title must be non-empty')
  379. expect(await errorText('汉'.repeat(86), '<svg></svg>')).toContain('title is 258 UTF-8 bytes')
  380. expect(await errorText('A', '<html></html>')).toContain('document wrappers')
  381. expect(await errorText('A', '<html/>')).toContain('document wrappers')
  382. expect(await errorText('A', '<body/>')).toContain('document wrappers')
  383. expect(await errorText('A', '<!--note--><html lang="en">')).toContain('document wrappers')
  384. expect(await errorText('A', '```html\n<html></html>\n```')).toContain('raw source without Markdown code fences')
  385. expect(await errorText('A', '```html\n \n```')).toContain('raw source without Markdown code fences')
  386. expect(await errorText('A', '```html5\n<button>A</button>\n```')).toContain('raw source without Markdown code fences')
  387. expect(await errorText('A', '````html\n<button>A</button>\n````')).toContain('raw source without Markdown code fences')
  388. expect(await errorText('A', '~~~html\n<button>A</button>\n~~~')).toContain('raw source without Markdown code fences')
  389. expect(await execute('A', '<svgx></svgx>')).toMatchObject({ isError: false, meta: { kind: 'html' } })
  390. expect(await execute('A', ' <SVG></SVG>')).toMatchObject({ isError: false, meta: { kind: 'svg' } })
  391. expect(await execute('A', '<svg/>')).toMatchObject({ isError: false, meta: { kind: 'svg' } })
  392. expect(await errorText('A', '```svg\n<svg viewBox="0 0 2 1"></svg>\n```'))
  393. .toContain('raw source without Markdown code fences')
  394. expect(await errorText('A', '```html\n<button>A</button>\n```'))
  395. .toContain('raw source without Markdown code fences')
  396. })
  397. it('accepts interactive HTML and exercises every tool presentation surface', async () => {
  398. const { ctx, agent } = await mount()
  399. const guidance = ctx.tools.get('widget_guidelines', agent)!
  400. const show = ctx.tools.get('show_widget', agent)!
  401. expect(guidance.isConcurrencySafe?.({ modules: ['chart'] })).toBe(true)
  402. expect(guidance.presentCall?.({ modules: ['chart'] })).toMatchObject({ title: 'Load widget guidance: chart' })
  403. expect(guidance.output.render?.({ modules: ['chart'] }, 'rules')).toEqual([{ type: 'text', text: 'rules' }])
  404. expect(show.isConcurrencySafe?.({ title: 'Demo', widget_code: '<button>A</button>' })).toBe(true)
  405. expect(show.presentCall?.({ title: 'Demo', widget_code: '<button>A</button>' })).toMatchObject({ title: 'Widget: Demo' })
  406. expect(show.output.render?.({ title: 'Demo', widget_code: '<button>A</button>' }, { kind: 'html' }))
  407. .toEqual([{
  408. type: 'text',
  409. text: 'Widget "Demo" accepted (html). It is final for this response; finish with brief supporting prose.',
  410. }])
  411. expect(show.output.presentationMeta?.({ title: 'Demo', widget_code: '<button>A</button>' }, { kind: 'html' }))
  412. .toEqual({ kind: 'html' })
  413. const html = await ctx.tools.execute({
  414. signal: SIGNAL, callId: ToolCallId('html'), name: 'show_widget',
  415. arguments: { title: 'Demo', widget_code: '<button>A</button>' }, agent,
  416. })
  417. expect(html).toMatchObject({ isError: false, meta: { kind: 'html' } })
  418. })
  419. it('removes tools and prompt with the ./model fiber while keeping Host authority', async () => {
  420. const { ctx, modelFiber, agent } = await mount()
  421. expect(ctx.tools.get('show_widget', agent)).toBeDefined()
  422. await modelFiber.dispose()
  423. expect(ctx.tools.get('show_widget', agent)).toBeUndefined()
  424. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).sections
  425. .some(section => section.name === 'tool:visualizer')).toBe(false)
  426. expect(ctx.get('visualizer') !== undefined).toBe(true)
  427. })
  428. it('withdraws the ./model contribution when its Host authority disappears', async () => {
  429. const { ctx, authorityFiber, modelFiber, agent } = await mount()
  430. expect(ctx.tools.get('show_widget', agent)).toBeDefined()
  431. await authorityFiber.dispose()
  432. await vi.waitFor(() => { expect(ctx.tools.get('show_widget', agent)).toBeUndefined() })
  433. expect((await ctx.systemPrompt.assemble({ agent, scope: agent })).sections
  434. .some(section => section.name === 'tool:visualizer')).toBe(false)
  435. await modelFiber.dispose()
  436. })
  437. })