cordis-tools.e2e.ts 8.1 KB

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