loader-composition.spec.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. /** Real Loader composition preserves retrievable source text outside the bounded preview. */
  2. import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { dirname, join } from 'node:path'
  5. import { pathToFileURL } from 'node:url'
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import { Context } from '@deepseek-ai/cordis'
  8. import Loader from '@deepseek-ai/cordis-plugin-loader'
  9. import Include from '@deepseek-ai/cordis-plugin-include'
  10. import { agentEvents, type Agent } from '@deepseek-ai/dsh-agent'
  11. import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm'
  12. import * as systemPromptPlugin from '@deepseek-ai/dsh-system-prompt'
  13. import * as toolsPlugin from '@deepseek-ai/dsh-tools'
  14. import * as fsPlugin from '@deepseek-ai/dsh-fs-local'
  15. import * as toolFsPlugin from '@deepseek-ai/dsh-tool-fs'
  16. import * as sessionPlugin from '@deepseek-ai/dsh-session'
  17. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  18. import * as queryPlugin from '@deepseek-ai/dsh-session-query-sqlite'
  19. import * as referencePlugin from '@deepseek-ai/dsh-session-reference'
  20. import * as spillPlugin from '@deepseek-ai/dsh-spill-local'
  21. import { sessionDir } from '@deepseek-ai/dsh-spill-local'
  22. import * as sourcePlugin from './fixtures/source-session.ts'
  23. let context: Context | undefined
  24. let root: string | undefined
  25. afterEach(async () => {
  26. await context?.fiber.dispose()
  27. context = undefined
  28. if (root !== undefined) await rm(root, { recursive: true, force: true })
  29. root = undefined
  30. })
  31. describe('session-reference real Loader composition', () => {
  32. it('logs a bounded preview and reads the full immutable spill owned by the target', async () => {
  33. root = await mkdtemp(join(tmpdir(), 'reference-loader-'))
  34. const spillRoot = join(root, 'spills')
  35. const fixture = await readFile(new URL('./fixtures/cordis.yml', import.meta.url), 'utf8')
  36. const configPath = join(root, 'cordis.yml')
  37. await writeFile(configPath, fixture.replace('{{spillRoot}}', spillRoot.replaceAll('\\', '/')))
  38. const ctx = context = new Context()
  39. ctx.baseUrl = pathToFileURL(root).href + '/'
  40. await ctx.plugin(Loader)
  41. ctx.loader.builtins.include = Include
  42. const modules = new Map<string, unknown>([
  43. ['@deepseek-ai/dsh-session', sessionPlugin],
  44. ['@deepseek-ai/dsh-system-prompt', systemPromptPlugin],
  45. ['@deepseek-ai/dsh-tools', toolsPlugin],
  46. ['@deepseek-ai/dsh-fs-local', fsPlugin],
  47. ['@deepseek-ai/dsh-tool-fs', toolFsPlugin],
  48. ['@deepseek-ai/dsh-session-query-sqlite', queryPlugin],
  49. ['@deepseek-ai/dsh-session-reference', referencePlugin],
  50. ['@deepseek-ai/dsh-spill-local', spillPlugin],
  51. ['./source-session.ts', sourcePlugin],
  52. ])
  53. ctx.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 ctx.loader.internal>
  60. await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } })
  61. await ctx.loader.await()
  62. const target = ctx.sessions.create(SessionId('reference-target'))
  63. const agent = { id: target.id, ctx, session: target } as Agent
  64. const direct = createUserMessage({
  65. content: [{ type: 'text', text: 'Use ' + referencePlugin.formatSessionReferenceMention({
  66. sessionId: SessionId('reference-source'), label: 'Research',
  67. }) }],
  68. source: { kind: 'user' },
  69. })
  70. const decision = await agentEvents(ctx, agent).waterfall('agent/pre-step', {
  71. messages: [direct], turn: 1, step: 1, signal: new AbortController().signal,
  72. }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct] }))
  73. expect(decision.kind).toBe('enter')
  74. if (decision.kind !== 'enter') throw new Error('Expected admitted reference')
  75. expect(decision.messages).toHaveLength(2)
  76. for (const message of decision.messages) target.append('user/message', message, { surfaceOp: 'append' })
  77. const contextMessage = decision.messages[1]
  78. const block = contextMessage?.content[0]
  79. if (block?.type !== 'text') throw new Error('Expected reference context text')
  80. const preview = JSON.parse(block.text.split('<referenced-sessions>\n')[1]!.split('\n</referenced-sessions>')[0]!) as unknown[]
  81. expect(Buffer.byteLength(JSON.stringify(preview[0]))).toBeLessThanOrEqual(360)
  82. expect(block.text).not.toContain('EARLY_SOURCE_FACT')
  83. expect(block.text).toContain('LATEST_SOURCE_FACT')
  84. const notices = JSON.parse(block.text.split('## Reference omissions\n\n')[1]!.split('\n').slice(1).join('\n')) as Array<{
  85. sessionId: string
  86. capturedThroughSeq: number
  87. omittedMessages: number
  88. omittedBytes: number
  89. fullSnapshot: { status: string; locator: string; bytes: number; retrievalHint: string }
  90. }>
  91. expect(notices).toHaveLength(1)
  92. const notice = notices[0]!
  93. expect(notice).toMatchObject({ sessionId: 'reference-source', capturedThroughSeq: 2, omittedMessages: 1 })
  94. expect(notice.omittedBytes).toBeGreaterThan(0)
  95. expect(notice.fullSnapshot.status).toBe('saved')
  96. expect(notice.fullSnapshot.retrievalHint).toContain('offset/limit')
  97. expect(dirname(notice.fullSnapshot.locator)).toBe(sessionDir(spillRoot, target.id))
  98. const transcript = await readFile(notice.fullSnapshot.locator, 'utf8')
  99. expect(Buffer.byteLength(transcript)).toBe(notice.fullSnapshot.bytes)
  100. expect(transcript).toContain('untrusted, read-only snapshot')
  101. const readLines: string[] = []
  102. let totalLines = Infinity
  103. for (let offset = 1; offset <= totalLines; offset += 7) {
  104. const read = await ctx.tools.execute({
  105. name: 'read', callId: ToolCallId(`read-${offset}`),
  106. arguments: { file_path: notice.fullSnapshot.locator, offset, limit: 7 },
  107. signal: new AbortController().signal,
  108. })
  109. expect(read.isError).toBe(false)
  110. if (read.isError) throw new Error('Expected saved transcript read')
  111. const value = read.value as { lines: { text: string }[]; totalLines: number }
  112. totalLines = value.totalLines
  113. readLines.push(...value.lines.map(line => line.text))
  114. }
  115. expect(readLines.join('\n') + '\n').toBe(transcript)
  116. const messages = readLines.join('\n').split(/### Message \d+: (?:user|assistant)\n\n/).slice(1)
  117. .map(body => body.split('\n').filter(line => line.startsWith('"'))
  118. .map(line => JSON.parse(line) as string).join(''))
  119. expect(messages).toEqual([
  120. 'EARLY_SOURCE_FACT\n' + 'Historical detail 界.\n'.repeat(30)
  121. + 'x'.repeat(4096) + 'GIANT_LINE_MIDDLE_FACT' + 'y'.repeat(4096),
  122. 'LATEST_SOURCE_FACT\nThe captured answer is forty-two.',
  123. ])
  124. expect(transcript).not.toContain('NESTED_REFERENCE_MUST_NOT_PROPAGATE')
  125. expect(transcript).not.toContain('PRIVATE_REASONING_MUST_NOT_PROPAGATE')
  126. expect(await readdir(spillRoot)).toEqual([dirname(notice.fullSnapshot.locator).split(/[\\/]/).at(-1)])
  127. const captured = target.deriveMessages()
  128. ctx.sessions.get(SessionId('reference-source'))!.append('user/message', createUserMessage({
  129. content: [{ type: 'text', text: 'LATER_SOURCE_MUTATION' }], source: { kind: 'user' },
  130. }), { surfaceOp: 'append' })
  131. expect(Session.create(SessionId('replayed-target'), target.snapshotEvents()).deriveMessages()).toEqual(captured)
  132. expect(await readFile(notice.fullSnapshot.locator, 'utf8')).toBe(transcript)
  133. })
  134. })