cordis-tools.e2e.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import type { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import { cordisHarness, waitForIdle } from './harness.ts'
  5. import { SessionId } from '@deepseek-ai/dsh-session'
  6. /**
  7. * With-key smoke for the self-referential cordis tools: a REAL model drives
  8. * cordis_mount/cordis_unmount against the live context the test observes.
  9. * World-verified, not self-reported: the mounted listener must actually WRITE
  10. * its tagged console line, the self-made tool must actually EXIST in the
  11. * registry and appear as a real `tool/call`, the cross-mount service must
  12. * actually LAND in the reflect store. Key-gated (see vitest.e2e.config.ts).
  13. */
  14. let ctx: Context | undefined
  15. afterEach(async () => {
  16. vi.restoreAllMocks()
  17. // Always dispose the harness, even on failure/retry/timeout: agent-loop
  18. // teardown stops the loop, and disposing the tree unwinds every dynamic
  19. // mount the model left behind.
  20. await ctx?.fiber.dispose()
  21. ctx = undefined
  22. })
  23. /** The tagged write-through lines (`[cordis:dyn-n] …`) captured by a console spy. */
  24. function taggedCalls(log: { mock: { calls: unknown[][] } }): unknown[][] {
  25. return log.mock.calls.filter(call => typeof call[0] === 'string' && /^\[cordis:dyn-\d+\]$/.test(call[0]))
  26. }
  27. /** Model-facing text of one tool result, concatenated. */
  28. function resultText(result: { content: { type: string; text?: string }[] }): string {
  29. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  30. }
  31. describe.skipIf(!process.env.DEEPSEEK_API_KEY)('cordis tools: a real model modifies its own runtime', () => {
  32. it('mounts a status listener whose tagged output actually fires, then unmounts it', async () => {
  33. ctx = await cordisHarness()
  34. const log = vi.spyOn(console, 'log').mockImplementation(() => {})
  35. const agent = ctx.agentLoop.create(SessionId('cordis-e2e-listener'), { provider: 'deepseek', model: 'deepseek-v4-flash' })
  36. agent.send([{
  37. type: 'text',
  38. text: 'Use cordis_mount to mount a plugin that listens to the \'agent/status\' '
  39. + 'cordis event and logs every change with console.log. Reply "mounted" once done.',
  40. }])
  41. await waitForIdle(ctx, agent)
  42. // The WORLD check: the turn's own running→idle transition must have driven
  43. // the mounted listener through the tagged sandbox console.
  44. expect(taggedCalls(log).length).toBeGreaterThan(0)
  45. const mid = await ctx.tools.execute({
  46. callId: CallId('verify-mounted'), name: 'cordis_inspect', arguments: { what: 'dynamic' },
  47. })
  48. expect(resultText(mid)).toContain('dyn-')
  49. agent.send([{ type: 'text', text: 'Now unmount the plugin you just mounted.' }])
  50. await waitForIdle(ctx, agent)
  51. const after = await ctx.tools.execute({
  52. callId: CallId('verify-unmounted'), name: 'cordis_inspect', arguments: { what: 'dynamic' },
  53. })
  54. expect(resultText(after)).toContain('(no dynamic plugins mounted)')
  55. }, 120_000)
  56. it('builds itself a reverse_text tool and actually calls it', async () => {
  57. ctx = await cordisHarness()
  58. const agent = ctx.agentLoop.create(SessionId('cordis-e2e-selftool'), { provider: 'deepseek', model: 'deepseek-v4-flash' })
  59. agent.send([{
  60. type: 'text',
  61. text: 'Give yourself a new tool: use cordis_mount to mount a plugin with '
  62. + 'inject ["tools"] that calls harness.registerTool(ctx, harness.defineTool({...})) '
  63. + 'to register a tool named reverse_text with one required string parameter '
  64. + '"text", returning the text reversed. Then CALL reverse_text with the '
  65. + 'exact text "harness" and report its exact output.',
  66. }])
  67. await waitForIdle(ctx, agent)
  68. // World checks: the tool exists in the registry, was invoked as a real tool call, and its
  69. // RESULT (the self-made execute actually running) is the reversed string. Model prose is only
  70. // self-report and is deliberately not asserted.
  71. expect(ctx.tools.get('reverse_text')).toBeDefined()
  72. const events = [...agent.session.events]
  73. const calls = events.filter(event => event.type === 'tool/call')
  74. expect(calls.some(event => event.data.name === 'cordis_mount')).toBe(true)
  75. const reverseCalls = calls.filter(event => event.data.name === 'reverse_text')
  76. expect(reverseCalls.length).toBeGreaterThan(0)
  77. const reverseResults = events
  78. .filter(event => event.type === 'tool/result')
  79. .filter(event => reverseCalls.some(call => call.data.callId === event.data.callId))
  80. .flatMap(event => event.data.content.filter(block => block.type === 'text').map(block => block.text))
  81. // On failure, surface what the model actually mounted and what the tool
  82. // returned — an e2e failing at a distance is undebuggable without it.
  83. const mountCode = calls
  84. .filter(event => event.data.name === 'cordis_mount')
  85. .map(event => event.data.arguments)
  86. .join('\n---\n')
  87. const trace = events.map((event) => {
  88. switch (event.type) {
  89. case 'tool/call': return `tool/call:${event.data.name}`
  90. case 'tool/result': return `tool/result:${event.data.isError ? 'ERR:' + JSON.stringify(event.data.content).slice(0, 200) : 'ok'}`
  91. case 'turn/end': return `turn/end:${JSON.stringify(event.data.reason)}`
  92. default: return event.type
  93. }
  94. }).join('\n')
  95. expect(
  96. reverseResults.some(text => text.includes('ssenrah')),
  97. `no reversed output in reverse_text results.\nresults: ${JSON.stringify(reverseResults)}\nmount code: ${mountCode}\ntrace:\n${trace}`,
  98. ).toBe(true)
  99. }, 120_000)
  100. it('composes two mounts through provide/inject, and unmounting the provider parks the consumer', async () => {
  101. ctx = await cordisHarness()
  102. const agent = ctx.agentLoop.create(SessionId('cordis-e2e-compose'), { provider: 'deepseek', model: 'deepseek-v4-flash' })
  103. agent.send([{
  104. type: 'text',
  105. text: 'Mount TWO separate plugins with cordis_mount. First a provider: apply calls '
  106. + 'ctx.provide(\'shouter\', { shout: (s) => s.toUpperCase() }). Second a consumer with '
  107. + 'inject ["shouter", "tools"] that registers (via harness.registerTool + harness.defineTool) '
  108. + 'a tool named shout_text with one required string parameter "text" whose execute returns '
  109. + 'ctx.shouter.shout(args.text) as a text content block. Then CALL shout_text with "quiet" '
  110. + 'and report the exact output.',
  111. }])
  112. await waitForIdle(ctx, agent)
  113. // World checks: the service is really in the store, the tool really ran.
  114. expect(ctx.get('shouter')).toBeDefined()
  115. expect(ctx.tools.get('shout_text')).toBeDefined()
  116. const events = [...agent.session.events]
  117. const shoutCalls = events
  118. .filter(event => event.type === 'tool/call')
  119. .filter(event => event.data.name === 'shout_text')
  120. expect(shoutCalls.length).toBeGreaterThan(0)
  121. const shoutResults = events
  122. .filter(event => event.type === 'tool/result')
  123. .filter(event => shoutCalls.some(call => call.data.callId === event.data.callId))
  124. .flatMap(event => event.data.content.filter(block => block.type === 'text').map(block => block.text))
  125. expect(shoutResults.some(text => text.includes('QUIET'))).toBe(true)
  126. agent.send([{ type: 'text', text: 'Now unmount ONLY the provider plugin (the one that provided shouter).' }])
  127. await waitForIdle(ctx, agent)
  128. // The consumer must have been parked by cordis itself: service gone,
  129. // dependent tool unregistered, dynamic table naming the missing service.
  130. expect(ctx.get('shouter')).toBeUndefined()
  131. expect(ctx.tools.get('shout_text')).toBeUndefined()
  132. const after = await ctx.tools.execute({
  133. callId: CallId('verify-parked'), name: 'cordis_inspect', arguments: { what: 'dynamic' },
  134. })
  135. expect(resultText(after)).toContain('waiting for: shouter')
  136. }, 120_000)
  137. })