loader-composition.spec.ts 4.7 KB

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