loader-composition.spec.ts 4.5 KB

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