loader-composition.spec.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import { mkdtemp, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { pathToFileURL } from 'node:url'
  5. import { afterEach, describe, expect, it } from 'vitest'
  6. import { Context } from 'cordis'
  7. import Loader from '@cordisjs/plugin-loader'
  8. import Include from '@cordisjs/plugin-include'
  9. import AgentRegistry from '@deepseek-ai/dsh-agent'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  12. import LlmService, { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm'
  13. import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  14. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  15. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  16. import ToolRegistry from '@deepseek-ai/dsh-tools'
  17. import * as retry from '../src/index.ts'
  18. let root: string | undefined
  19. let context: Context | undefined
  20. class TransientOnceAdapter extends LlmAdapter {
  21. requests = 0
  22. async * stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  23. this.requests += 1
  24. if (this.requests === 1) throw new LlmError('temporary outage', 'SERVER')
  25. yield { type: 'block-start', index: 0, blockType: 'text' }
  26. yield { type: 'text-delta', index: 0, text: 'recovered' }
  27. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'recovered' } }
  28. yield { type: 'finish', reason: { kind: 'stop' } }
  29. }
  30. }
  31. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  32. return new Promise((resolve) => {
  33. const dispose = ctx.on('agent/status', (subject, status) => {
  34. if (subject === agent && status === 'idle') {
  35. dispose()
  36. resolve()
  37. }
  38. })
  39. })
  40. }
  41. afterEach(async () => {
  42. await context?.fiber.dispose()
  43. context = undefined
  44. if (root !== undefined) await rm(root, { recursive: true, force: true })
  45. root = undefined
  46. })
  47. async function loadYaml(lines: readonly string[]): Promise<Context> {
  48. root = await mkdtemp(join(tmpdir(), 'dsh-llm-retry-loader-'))
  49. const configPath = join(root, 'cordis.yml')
  50. await writeFile(configPath, [...lines, ''].join('\n'))
  51. context = new Context()
  52. context.baseUrl = pathToFileURL(root).href + '/'
  53. await context.plugin(Loader)
  54. context.loader.builtins.include = Include
  55. const modules = new Map<string, unknown>([
  56. ['@deepseek-ai/dsh-llm', LlmService],
  57. ['@deepseek-ai/dsh-session', SessionStore],
  58. ['@deepseek-ai/dsh-system-prompt', SystemPrompt],
  59. ['@deepseek-ai/dsh-tools', ToolRegistry],
  60. ['@deepseek-ai/dsh-agent', AgentRegistry],
  61. ['@deepseek-ai/dsh-llm-retry', retry],
  62. ['@deepseek-ai/dsh-agent-loop', AgentLoop],
  63. ])
  64. context.loader.internal = {
  65. version: 'v2',
  66. async import(specifier: string) {
  67. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  68. return modules.get(specifier)
  69. },
  70. } as unknown as NonNullable<typeof context.loader.internal>
  71. await context.loader.create({
  72. name: 'cordis:include',
  73. config: { path: pathToFileURL(configPath).href },
  74. })
  75. await context.loader.await()
  76. return context
  77. }
  78. describe('real Loader composition', () => {
  79. it('loads the flat policy and records recovery through the shipping loop', async () => {
  80. const loaded = await loadYaml([
  81. "- name: '@deepseek-ai/dsh-llm'",
  82. "- name: '@deepseek-ai/dsh-session'",
  83. "- name: '@deepseek-ai/dsh-system-prompt'",
  84. "- name: '@deepseek-ai/dsh-tools'",
  85. "- name: '@deepseek-ai/dsh-agent'",
  86. "- name: '@deepseek-ai/dsh-llm-retry'",
  87. ' config:',
  88. ' maxTransientRetries: 1',
  89. ' initialDelayMs: 1',
  90. ' maxDelayMs: 1',
  91. ' jitterRatio: 0',
  92. ' retryableCodes: [RATE_LIMIT, SERVER]',
  93. "- name: '@deepseek-ai/dsh-agent-loop'",
  94. ])
  95. const unloaded = [...loaded.loader.entries()]
  96. .filter(entry => entry.fiber === undefined && !entry.disabled)
  97. .map(entry => entry.options.name)
  98. expect(unloaded).toEqual([])
  99. expect(loaded.agents).toBeInstanceOf(AgentRegistry)
  100. const adapter = new TransientOnceAdapter()
  101. loaded.llm.registerAdapter(['mock'], adapter)
  102. const agent = loaded.agentLoop.create(SessionId('loader-retry'), { provider: 'mock', model: 'mock' })
  103. const idle = waitForIdle(loaded, agent)
  104. agent.send([{ type: 'text', text: 'recover' }])
  105. await idle
  106. expect(adapter.requests).toBe(2)
  107. expect(agent.session.events.filter(event => event.type === 'llm/retry')).toHaveLength(1)
  108. expect(agent.session.deriveMessages().at(-1)).toMatchObject({
  109. role: 'assistant',
  110. content: [{ type: 'text', text: 'recovered' }],
  111. })
  112. })
  113. })