request-reconstruction.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * Loop-level reconstructability: every request the loop sends is a pure function of the
  3. * session log — messages derive at the step/start boundary and the header is the latest
  4. * request/header snapshot. Each request extends its predecessor unless a logged compaction
  5. * replacement or header change explains the difference.
  6. */
  7. import { describe, expect, it } from 'vitest'
  8. import { Context } from 'cordis'
  9. import LlmService from '@deepseek-ai/dsh-llm'
  10. import type { GenerateOptions } from '@deepseek-ai/dsh-llm'
  11. import SessionStore, { Session, SessionId, foldRequestHeader } from '@deepseek-ai/dsh-session'
  12. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  13. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  14. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  15. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  16. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  17. async function harness(adapter: MockAdapter, persona = 'stable base') {
  18. const ctx = new Context()
  19. await ctx.plugin(LlmService)
  20. await ctx.plugin(SessionStore)
  21. await ctx.plugin(SystemPrompt, { persona })
  22. await ctx.plugin(ToolRegistry)
  23. await ctx.plugin(AgentRegistry)
  24. await ctx.plugin(AgentLoop, { agents: [] })
  25. ctx.llm.registerAdapter(['mock'], adapter)
  26. return ctx
  27. }
  28. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  29. return new Promise((resolve) => {
  30. const dispose = ctx.on('agent/status', (subject, status) => {
  31. if (subject === agent && status === 'idle') {
  32. dispose()
  33. resolve()
  34. }
  35. })
  36. })
  37. }
  38. function send(agent: Agent, text: string) {
  39. agent.send([{ type: 'text', text }])
  40. }
  41. /** Assert `previous` is a strict value-prefix of `current`. */
  42. function expectPrefixExtension(previous: GenerateOptions, current: GenerateOptions) {
  43. expect(current.messages.length).toBeGreaterThan(previous.messages.length)
  44. expect(current.messages.slice(0, previous.messages.length)).toEqual([...previous.messages])
  45. expect(current.system).toEqual(previous.system)
  46. expect(current.tools).toEqual(previous.tools)
  47. }
  48. function registerEcho(ctx: Context) {
  49. ctx.tools.register(defineTool({
  50. name: 'echo',
  51. description: 'echo back',
  52. parameters: { text: { type: 'string' } },
  53. async execute(args) {
  54. return [{ type: 'text', text: `echo: ${String(args.text)}` }]
  55. },
  56. }))
  57. }
  58. describe('request stability across the loop', () => {
  59. it('each step request within a turn append-extends the previous, frozen end to end', async () => {
  60. const adapter = new MockAdapter([
  61. toolCallResponse('c1', 'echo', { text: 'one' }, 'first'),
  62. toolCallResponse('c2', 'echo', { text: 'two' }, 'second'),
  63. textResponse('done'),
  64. ])
  65. const ctx = await harness(adapter)
  66. registerEcho(ctx)
  67. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  68. send(agent, 'go')
  69. await waitForIdle(ctx, agent)
  70. expect(adapter.requests).toHaveLength(3)
  71. expectPrefixExtension(adapter.requests[0]!, adapter.requests[1]!)
  72. expectPrefixExtension(adapter.requests[1]!, adapter.requests[2]!)
  73. for (const request of adapter.requests) {
  74. expect(Object.isFrozen(request)).toBe(true)
  75. expect(Object.isFrozen(request.messages)).toBe(true)
  76. }
  77. // One anchoring header snapshot; no further header events (nothing changed).
  78. const headerEvents = agent.session.events.filter(e => e.type === 'request/header')
  79. expect(headerEvents).toHaveLength(1)
  80. expect(headerEvents[0]?.type === 'request/header' && headerEvents[0].data.reason).toBe('initial')
  81. })
  82. it('a later turn append-extends the previous turn (one conversation, one log)', async () => {
  83. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  84. const ctx = await harness(adapter)
  85. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  86. send(agent, 'first')
  87. await waitForIdle(ctx, agent)
  88. send(agent, 'second')
  89. await waitForIdle(ctx, agent)
  90. expect(adapter.requests).toHaveLength(2)
  91. expectPrefixExtension(adapter.requests[0]!, adapter.requests[1]!)
  92. })
  93. it('a compaction replace rewrites the resend, and the log explains it', async () => {
  94. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  95. const ctx = await harness(adapter)
  96. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  97. send(agent, 'first')
  98. await waitForIdle(ctx, agent)
  99. // A pre-step listener compacts turn 1's history before turn 2's step —
  100. // the sanctioned surface rewrite, landing OUTSIDE the step.
  101. const preStep = ctx.on('agent/pre-step', () => {
  102. preStep()
  103. const session = agent.session
  104. const nodes = session.surface.nodes
  105. session.append('context/message', {
  106. content: [{ type: 'text', text: '[summary of turn 1]' }],
  107. source: { kind: 'plugin', plugin: 'test-compact' },
  108. }, {
  109. surfaceOp: { op: 'replace', start: nodes[0]!, end: nodes[1]! },
  110. sourceEventSeqs: [nodes[0]!, nodes[1]!],
  111. })
  112. })
  113. send(agent, 'second')
  114. await waitForIdle(ctx, agent)
  115. const second = adapter.requests[1]!
  116. // The rewritten history: summary replaces turn 1's user+assistant pair.
  117. expect(second.messages[0]!.content.some(b => b.type === 'text' && b.text.includes('[summary of turn 1]'))).toBe(true)
  118. // No header event beyond the anchor: the replace is itself in the log.
  119. expect(agent.session.events.filter(e => e.type === 'request/header')).toHaveLength(1)
  120. })
  121. it('a real system-prompt change is a full changed-header snapshot; a stable prompt logs nothing', async () => {
  122. const adapter = new MockAdapter([textResponse('one'), textResponse('two'), textResponse('three')])
  123. const ctx = await harness(adapter)
  124. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  125. send(agent, 'first')
  126. await waitForIdle(ctx, agent)
  127. send(agent, 'second')
  128. await waitForIdle(ctx, agent)
  129. // Identical assembly re-rendered per step is NOT a change.
  130. expect(agent.session.events.filter(e => e.type === 'request/header')).toHaveLength(1)
  131. ctx.systemPrompt.section({ name: 'extra', order: 2, text: 'new guidance' })
  132. send(agent, 'third')
  133. await waitForIdle(ctx, agent)
  134. const snapshots = agent.session.events.filter(e => e.type === 'request/header')
  135. expect(snapshots).toHaveLength(2)
  136. expect(snapshots[1]?.data.reason).toBe('change')
  137. expect(adapter.requests[2]!.system).toContain('new guidance')
  138. // History is preserved across the change — only the header moved.
  139. expect(adapter.requests[2]!.messages.length).toBeGreaterThan(adapter.requests[1]!.messages.length)
  140. })
  141. it('an inject() during the agent/request waterfall joins the NEXT request (the step/start boundary)', async () => {
  142. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  143. const ctx = await harness(adapter)
  144. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  145. let injected = false
  146. ctx.on('agent/request', async (_agent, _turn, _step, _config, next) => {
  147. if (!injected) {
  148. injected = true
  149. agent.inject([{ type: 'text', text: '[late context]' }], { source: { kind: 'plugin', plugin: 'test' } })
  150. }
  151. return next()
  152. })
  153. send(agent, 'first')
  154. await waitForIdle(ctx, agent)
  155. const first = adapter.requests[0]!
  156. // The inject landed in the log after the boundary: not in THIS request…
  157. expect(first.messages.some(m => m.content.some(b => b.type === 'text' && b.text.includes('[late context]')))).toBe(false)
  158. expect(agent.session.events.some(e => e.type === 'context/message')).toBe(true)
  159. send(agent, 'second')
  160. await waitForIdle(ctx, agent)
  161. // …but in the next one, at its logged position.
  162. const second = adapter.requests[1]!
  163. expect(second.messages.some(m => m.content.some(b => b.type === 'text' && b.text.includes('[late context]')))).toBe(true)
  164. })
  165. it('a mutation attempt on the frozen request content throws into the step (loud, not silent)', async () => {
  166. const adapter = new MockAdapter([textResponse('one')])
  167. const ctx = await harness(adapter)
  168. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  169. const errors: Error[] = []
  170. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  171. ctx.on('llm/stream', (options, next) => {
  172. // The historical failure mode this design kills: a listener rewriting
  173. // request content in place. The freeze turns it into a loud error.
  174. options.messages.push({ role: 'user', content: [{ type: 'text', text: 'sneaky' }] })
  175. return next()
  176. })
  177. send(agent, 'go')
  178. await waitForIdle(ctx, agent)
  179. expect(errors).toHaveLength(1)
  180. expect(errors[0]!.message).toMatch(/not extensible|frozen|read only|readonly/i)
  181. })
  182. it('a fresh loop instance over a seeded log anchors with a resume snapshot and stays cache-aligned', async () => {
  183. const adapter = new MockAdapter([textResponse('one')])
  184. const ctx = await harness(adapter)
  185. const agent = ctx.agentLoop.create(SessionId('gen1'), { provider: 'mock', model: 'mock' })
  186. send(agent, 'first')
  187. await waitForIdle(ctx, agent)
  188. // Second generation: a new agent whose session is seeded with the first
  189. // one's full log (the resume/fork path).
  190. const adapter2 = new MockAdapter([textResponse('two')])
  191. const ctx2 = await harness(adapter2)
  192. const handle = await ctx2.agents.create({
  193. sessionId: SessionId('gen2-session'),
  194. seed: [...agent.session.events],
  195. agentOptions: { provider: 'mock', model: 'mock' },
  196. })
  197. const agent2 = handle.agent
  198. send(agent2, 'second')
  199. await waitForIdle(ctx2, agent2)
  200. const snapshots = agent2.session.events.filter(e => e.type === 'request/header')
  201. expect(snapshots).toHaveLength(2)
  202. expect(snapshots[1]?.type === 'request/header' && snapshots[1].data.reason).toBe('resume')
  203. // Identical header across the restart: byte-identical continuation.
  204. expect(adapter2.requests[0]!.system).toEqual(adapter.requests[0]!.system)
  205. expectPrefixExtension(adapter.requests[0]!, adapter2.requests[0]!)
  206. })
  207. it('a delegating listener cannot mutate the seed through next() — the fold stays log-true', async () => {
  208. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  209. const ctx = await harness(adapter)
  210. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  211. ctx.on('agent/request', async (_agent, _turn, _step, _config, next) => {
  212. const config = await next()
  213. // next() resolves the SAME frozen seed — in-place shaping after
  214. // delegation is unrepresentable, so a "mutate what next() returned"
  215. // listener cannot desync the log from the request (nor reach the
  216. // session's cached header fold, which is deep-cloned away and itself
  217. // frozen).
  218. expect(Object.isFrozen(config)).toBe(true)
  219. expect(() => { (config as { temperature?: number }).temperature = 0.9 }).toThrow(TypeError)
  220. return config
  221. })
  222. send(agent, 'first')
  223. await waitForIdle(ctx, agent)
  224. send(agent, 'second')
  225. await waitForIdle(ctx, agent)
  226. // No changed snapshot was logged (nothing really changed), and the session's own
  227. // fold is immutable state.
  228. expect(agent.session.events.filter(e => e.type === 'request/header')).toHaveLength(1)
  229. expect(Object.isFrozen(agent.session.requestHeader())).toBe(true)
  230. expect(adapter.requests[1]!.temperature).toBeUndefined()
  231. })
  232. it('THEOREM: every request rebuilds byte-equal from the session log alone', async () => {
  233. const adapter = new MockAdapter([
  234. toolCallResponse('c1', 'echo', { text: 'one' }, 'calling'),
  235. textResponse('done'),
  236. textResponse('after change'),
  237. ])
  238. const ctx = await harness(adapter)
  239. registerEcho(ctx)
  240. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  241. send(agent, 'go')
  242. await waitForIdle(ctx, agent)
  243. ctx.systemPrompt.section({ name: 'extra', order: 2, text: 'now with guidance' })
  244. ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => ({ ...config, temperature: 0.5, maxTokens: 99, stop: ['<END>'] }))
  245. send(agent, 'again')
  246. await waitForIdle(ctx, agent)
  247. expect(adapter.requests).toHaveLength(3)
  248. const events = agent.session.events
  249. const stepStarts = events.filter(e => e.type === 'step/start')
  250. expect(stepStarts).toHaveLength(3)
  251. adapter.requests.forEach((request, index) => {
  252. const stepStart = stepStarts[index]!
  253. // Messages: the derivation over the log prefix strictly before this
  254. // step's step/start — rebuilt here through a completely fresh Session.
  255. const rebuilt = new Session(SessionId(`rebuild-${index}`), structuredClone(events.slice(0, stepStart.seq)))
  256. expect(structuredClone(request.messages)).toEqual(rebuilt.deriveMessages())
  257. // Header: the latest request/header snapshot up to this step's dispatch
  258. // (its header event sits between step/start and the first chunk).
  259. const firstChunk = events.find(e => e.type === 'assistant/chunk' && e.seq > stepStart.seq)!
  260. const header = foldRequestHeader(events.slice(0, firstChunk.seq))!
  261. expect(request.model).toBe(header.config.model)
  262. expect(request.system).toEqual(header.system)
  263. expect(structuredClone(request.tools ?? [])).toEqual(structuredClone(header.tools ?? []))
  264. expect(request.temperature).toBe(header.config.temperature)
  265. expect(request.maxTokens).toBe(header.config.maxTokens)
  266. expect(request.stop).toEqual(header.config.stop)
  267. })
  268. })
  269. })