time-context.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import { createUserMessage, CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  5. import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  6. import { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  7. import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent'
  8. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  9. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  10. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  11. import * as timeContext from '@deepseek-ai/dsh-time-context'
  12. import type { Config } from '@deepseek-ai/dsh-time-context'
  13. const BASE = Date.parse('2026-07-14T00:00:00.000Z')
  14. const ORIGINAL_TIME_ZONE = process.env['TZ']
  15. const SIGNAL = new AbortController().signal
  16. beforeEach(() => {
  17. process.env['TZ'] = 'UTC'
  18. vi.useFakeTimers()
  19. vi.setSystemTime(BASE)
  20. })
  21. afterEach(() => {
  22. vi.restoreAllMocks()
  23. vi.useRealTimers()
  24. if (ORIGINAL_TIME_ZONE === undefined) delete process.env['TZ']
  25. else process.env['TZ'] = ORIGINAL_TIME_ZONE
  26. })
  27. async function mount(config: Config = {}) {
  28. const ctx = new Context()
  29. await ctx.plugin(AgentRegistry)
  30. const fiber = await ctx.plugin(timeContext, config)
  31. return { ctx, fiber }
  32. }
  33. function sessionAgent(session: Session, id = 'agent'): Agent {
  34. return {
  35. id: SessionId(id),
  36. options: {},
  37. session,
  38. status: 'running',
  39. acceptsNextStep: true,
  40. ctx: new Context(),
  41. followup: () => {},
  42. steer: () => {},
  43. inject(input) {
  44. session.append('user/message', input, { surfaceOp: 'append' })
  45. },
  46. send: () => {},
  47. cancel() {},
  48. whenIdle: () => Promise.resolve(),
  49. }
  50. }
  51. function openMessageTurn(session: Session, turn: number): void {
  52. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  53. session.append('user/message', createUserMessage({
  54. content: [{ type: 'text', text: `turn ${turn}` }],
  55. source: { kind: 'user' },
  56. }), { surfaceOp: 'append' })
  57. }
  58. function contextTexts(session: Session): string[] {
  59. const texts: string[] = []
  60. for (const event of session.events) {
  61. if (event.type === 'user/message'
  62. && event.data.source.kind === 'plugin'
  63. && event.data.source.plugin === 'time-context') {
  64. texts.push(event.data.content.find(block => block.type === 'text')?.text ?? '')
  65. }
  66. }
  67. return texts
  68. }
  69. async function fire(
  70. ctx: Context,
  71. agent: Agent,
  72. turn: number,
  73. step: number,
  74. signal: AbortSignal = SIGNAL,
  75. ): Promise<void> {
  76. await agentEvents(ctx, agent).serial('agent/step', turn, step, signal)
  77. }
  78. function textResponse(text: string): StreamChunk[] {
  79. return [
  80. { type: 'block-start', index: 0, blockType: 'text' },
  81. { type: 'block-end', index: 0, block: { type: 'text', text } },
  82. { type: 'finish', reason: { kind: 'stop' } },
  83. ]
  84. }
  85. function toolCallResponse(): StreamChunk[] {
  86. return [
  87. { type: 'block-start', index: 0, blockType: 'tool-call' },
  88. {
  89. type: 'block-end',
  90. index: 0,
  91. block: { type: 'tool-call', id: CallId('tick-1'), name: 'tick', arguments: '{}' },
  92. },
  93. { type: 'finish', reason: { kind: 'tool-calls' } },
  94. ]
  95. }
  96. class ScriptedAdapter extends LlmAdapter {
  97. readonly requests: GenerateOptions[] = []
  98. constructor(private readonly script: StreamChunk[][]) {
  99. super()
  100. }
  101. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  102. this.requests.push(options)
  103. const chunks = this.script.shift()
  104. if (chunks === undefined) throw new Error('ScriptedAdapter: script exhausted')
  105. for (const chunk of chunks) yield chunk
  106. }
  107. }
  108. async function loopHarness(adapter: ScriptedAdapter, config: Config = {}): Promise<Context> {
  109. const ctx = new Context()
  110. await mountAgentLoopTestDependencies(ctx)
  111. await ctx.plugin(AgentLoop, { agents: [] })
  112. await ctx.plugin(timeContext, config)
  113. ctx.llm.registerAdapter(['mock'], adapter)
  114. return ctx
  115. }
  116. function requestText(request: GenerateOptions): string {
  117. return request.messages
  118. .flatMap(message => message.content)
  119. .filter(block => block.type === 'text')
  120. .map(block => block.text)
  121. .join('\n')
  122. }
  123. describe('durable step context', () => {
  124. it('records turn, step, zoned time, and the preceding model-visible message baseline', async () => {
  125. const { ctx } = await mount({ timeZone: 'Asia/Shanghai' })
  126. const session = new Session(SessionId('first'))
  127. openMessageTurn(session, 1)
  128. vi.setSystemTime(BASE + 90_061_000)
  129. await fire(ctx, sessionAgent(session), 1, 1)
  130. expect(contextTexts(session)).toEqual([
  131. 'Time sampled while preparing turn 1, step 1: 2026-07-15T09:01:01+08:00[Asia/Shanghai]\n'
  132. + 'Elapsed since the preceding model-visible message: 1d 1h 1m 1s.',
  133. ])
  134. const event = session.events.at(-1)
  135. expect(event?.type).toBe('user/message')
  136. if (event?.type !== 'user/message') throw new Error('missing time context')
  137. expect(event.data.source).toEqual({ kind: 'plugin', plugin: 'time-context' })
  138. expect(event.surfaceOp).toBe('append')
  139. })
  140. it('reports an unavailable first-step baseline when no model-visible message precedes it', async () => {
  141. const { ctx } = await mount()
  142. const session = new Session(SessionId('unavailable'))
  143. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  144. await fire(ctx, sessionAgent(session), 1, 1)
  145. expect(contextTexts(session)[0]).toContain(
  146. 'Elapsed since the preceding model-visible message: unavailable.',
  147. )
  148. })
  149. it.each([
  150. ['omitted interval', {}],
  151. ['zero interval', { refreshIntervalMs: 0 }],
  152. ] as const)('uses the preceding durable step-context timestamp after step one with %s', async (_label, config) => {
  153. const { ctx } = await mount(config)
  154. const session = new Session(SessionId('later-step'))
  155. const agent = sessionAgent(session)
  156. openMessageTurn(session, 3)
  157. await fire(ctx, agent, 3, 1)
  158. vi.setSystemTime(BASE + 61_000)
  159. await fire(ctx, agent, 3, 2)
  160. expect(contextTexts(session)[1]).toBe(
  161. 'Time sampled while preparing turn 3, step 2: 2026-07-14T00:01:01+00:00[UTC]\n'
  162. + 'Elapsed since the preceding step context: 1m 1s.',
  163. )
  164. })
  165. it('reports an unavailable later-step baseline at the matching turn boundary', async () => {
  166. const { ctx } = await mount()
  167. const session = new Session(SessionId('later-step-boundary'))
  168. openMessageTurn(session, 4)
  169. await fire(ctx, sessionAgent(session), 4, 2)
  170. expect(contextTexts(session)[0]).toContain(
  171. 'Elapsed since the preceding step context: unavailable.',
  172. )
  173. })
  174. it('reports an unavailable later-step baseline when event lookup is exhausted', async () => {
  175. const { ctx } = await mount()
  176. const session = new Session(SessionId('later-step-exhausted'))
  177. await fire(ctx, sessionAgent(session), 1, 2)
  178. expect(contextTexts(session)[0]).toContain(
  179. 'Elapsed since the preceding step context: unavailable.',
  180. )
  181. })
  182. it('injects after backward wall-clock movement and clamps elapsed time to zero', async () => {
  183. const { ctx } = await mount({ refreshIntervalMs: 60_000 })
  184. const session = new Session(SessionId('backward'))
  185. const agent = sessionAgent(session)
  186. openMessageTurn(session, 1)
  187. await fire(ctx, agent, 1, 1)
  188. vi.setSystemTime(BASE - 5_000)
  189. await fire(ctx, agent, 1, 2)
  190. expect(contextTexts(session)).toHaveLength(2)
  191. expect(contextTexts(session)[1]).toContain('Elapsed since the preceding step context: 0s.')
  192. })
  193. it('uses a shadowed durable injection after resume and injects at the exact threshold', async () => {
  194. const { ctx } = await mount({ refreshIntervalMs: 1_000 })
  195. const original = new Session(SessionId('seed-source'))
  196. openMessageTurn(original, 1)
  197. await fire(ctx, sessionAgent(original), 1, 1)
  198. const user = original.events.find(event => event.type === 'user/message' && event.data.source.kind === 'user')
  199. const reading = original.events.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  200. if (user === undefined || reading === undefined) throw new Error('missing source surface events')
  201. original.append('user/message', createUserMessage({
  202. content: [{ type: 'text', text: 'compacted history' }],
  203. source: { kind: 'plugin', plugin: 'compact-basic' },
  204. }), {
  205. surfaceOp: { op: 'replace', start: user.seq, end: reading.seq },
  206. sourceEventSeqs: [user.seq, reading.seq],
  207. })
  208. original.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  209. expect(JSON.stringify(original.deriveMessages())).not.toContain('Time sampled while preparing')
  210. const resumed = new Session(SessionId('resumed'), [...original.events])
  211. const resumedAgent = sessionAgent(resumed)
  212. vi.setSystemTime(BASE + 999)
  213. openMessageTurn(resumed, 2)
  214. const beforeSkip = resumed.events.length
  215. await fire(ctx, resumedAgent, 2, 1)
  216. expect(resumed.events).toHaveLength(beforeSkip)
  217. expect(contextTexts(resumed)).toHaveLength(1)
  218. vi.setSystemTime(BASE + 1_000)
  219. await fire(ctx, resumedAgent, 2, 2)
  220. expect(contextTexts(resumed)).toHaveLength(2)
  221. expect(contextTexts(resumed)[1]).toContain(
  222. 'Elapsed since the preceding step context: unavailable.',
  223. )
  224. })
  225. it('applies a positive interval across turns without sharing state between sessions', async () => {
  226. const { ctx } = await mount({ refreshIntervalMs: 1_000 })
  227. const first = new Session(SessionId('interval-first'))
  228. const firstAgent = sessionAgent(first, 'first-agent')
  229. openMessageTurn(first, 1)
  230. await fire(ctx, firstAgent, 1, 1)
  231. first.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  232. vi.setSystemTime(BASE + 500)
  233. openMessageTurn(first, 2)
  234. const beforeSkip = first.events.length
  235. await fire(ctx, firstAgent, 2, 1)
  236. const independent = new Session(SessionId('interval-independent'))
  237. openMessageTurn(independent, 1)
  238. await fire(ctx, sessionAgent(independent, 'independent-agent'), 1, 1)
  239. expect(first.events).toHaveLength(beforeSkip)
  240. expect(contextTexts(first)).toHaveLength(1)
  241. expect(contextTexts(independent)).toHaveLength(1)
  242. })
  243. it('runs before ordinary pre-step listeners and skips an already-aborted step', async () => {
  244. const { ctx } = await mount()
  245. const session = new Session(SessionId('ordering'))
  246. const agent = sessionAgent(session)
  247. openMessageTurn(session, 1)
  248. let ordinarySawContext = false
  249. ctx.on('agent/step', (subject) => {
  250. ordinarySawContext = subject.session.events.some(event => event.type === 'user/message')
  251. })
  252. await fire(ctx, agent, 1, 1)
  253. const abort = new AbortController()
  254. abort.abort()
  255. await fire(ctx, agent, 1, 2, abort.signal)
  256. expect(ordinarySawContext).toBe(true)
  257. expect(contextTexts(session)).toHaveLength(1)
  258. })
  259. })
  260. describe('configuration and lifecycle', () => {
  261. it('defaults to the process system zone and retains the zone resolved at plugin load', async () => {
  262. process.env['TZ'] = 'Asia/Shanghai'
  263. const { ctx } = await mount()
  264. process.env['TZ'] = 'America/New_York'
  265. const session = new Session(SessionId('system-zone'))
  266. openMessageTurn(session, 1)
  267. await fire(ctx, sessionAgent(session), 1, 1)
  268. expect(contextTexts(session)[0]).toContain('2026-07-14T08:00:00+08:00[Asia/Shanghai]')
  269. })
  270. it('fails loud for an invalid explicit zone or an unavailable process zone', async () => {
  271. const invalid = new Context()
  272. await invalid.plugin(AgentRegistry)
  273. await expect(invalid.plugin(timeContext, { timeZone: 'Not/A_Real_Zone' })).rejects.toThrow(
  274. /invalid IANA timeZone/,
  275. )
  276. vi.spyOn(Intl, 'DateTimeFormat').mockImplementationOnce(() => {
  277. throw new RangeError('system zone unavailable')
  278. })
  279. const unresolved = new Context()
  280. await unresolved.plugin(AgentRegistry)
  281. await expect(unresolved.plugin(timeContext, {})).rejects.toThrow(/failed to resolve the system time zone/)
  282. })
  283. it('rejects invalid refresh intervals at plugin load with one diagnostic', async () => {
  284. const invalid = [-1, 0.5, Number.MAX_SAFE_INTEGER + 1, Number.POSITIVE_INFINITY, Number.NaN]
  285. for (const refreshIntervalMs of invalid) {
  286. await expect(mount({ refreshIntervalMs })).rejects.toThrow(
  287. 'time-context: refreshIntervalMs must be a non-negative safe integer',
  288. )
  289. }
  290. })
  291. it('removes its listener when the plugin fiber disposes', async () => {
  292. const { ctx, fiber } = await mount()
  293. const session = new Session(SessionId('dispose'))
  294. const agent = sessionAgent(session)
  295. openMessageTurn(session, 1)
  296. await fire(ctx, agent, 1, 1)
  297. await fiber.dispose()
  298. await fire(ctx, agent, 1, 2)
  299. expect(contextTexts(session)).toHaveLength(1)
  300. })
  301. })
  302. describe('real agent-loop request history', () => {
  303. it.each([
  304. ['throws', 'error'],
  305. ['cancels', 'aborted'],
  306. ] as const)('discards the pending preparation reading when a later step listener %s', async (mode, reasonKind) => {
  307. const adapter = new ScriptedAdapter([textResponse('unused')])
  308. const ctx = await loopHarness(adapter)
  309. let laterSawReading = false
  310. ctx.on('agent/step', (subject) => {
  311. laterSawReading = contextTexts(subject.session).length === 1
  312. if (mode === 'throws') throw new Error('later pre-step failure')
  313. subject.cancel({ kind: 'user' })
  314. })
  315. const agent = ctx.agentLoop.create(SessionId(`late-${mode}`), { provider: 'mock', model: 'mock' })
  316. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'start' }], source: { kind: 'user' } }))
  317. await agent.whenIdle()
  318. expect(laterSawReading).toBe(false)
  319. expect(contextTexts(agent.session)).toHaveLength(0)
  320. expect(adapter.requests).toHaveLength(0)
  321. expect(agent.session.events.some(event => event.type === 'step/start')).toBe(false)
  322. const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end')
  323. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe(reasonKind)
  324. await ctx.fiber.dispose()
  325. })
  326. it('persists one ordered context per request, accumulates readings, and leaves system headers unchanged', async () => {
  327. const adapter = new ScriptedAdapter([toolCallResponse(), textResponse('done')])
  328. const ctx = await loopHarness(adapter)
  329. ctx.tools.register(defineContentToolFixture({
  330. name: 'tick',
  331. description: 'advance fake time',
  332. parameters: {},
  333. async execute() {
  334. vi.setSystemTime(BASE + 61_000)
  335. return [{ type: 'text' as const, text: 'advanced' }]
  336. },
  337. }))
  338. const agent = ctx.agentLoop.create(SessionId('loop'), { provider: 'mock', model: 'mock' })
  339. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'start' }], source: { kind: 'user' } }))
  340. await agent.whenIdle()
  341. expect(adapter.requests).toHaveLength(2)
  342. const contexts = agent.session.events.filter(
  343. (event): event is SessionEvent<'user/message'> => event.type === 'user/message' && event.data.source.kind === 'plugin')
  344. const starts = agent.session.events.filter(event => event.type === 'step/start')
  345. expect(contexts).toHaveLength(adapter.requests.length)
  346. expect(starts).toHaveLength(adapter.requests.length)
  347. for (let index = 0; index < contexts.length; index += 1) {
  348. expect(contexts[index]!.seq).toBeLessThan(starts[index]!.seq)
  349. }
  350. expect(contexts.every(event => event.data.source.kind === 'plugin'
  351. && event.data.source.plugin === 'time-context'
  352. && event.surfaceOp === 'append')).toBe(true)
  353. const firstRequestText = requestText(adapter.requests[0]!)
  354. const secondRequestText = requestText(adapter.requests[1]!)
  355. expect(firstRequestText).toContain('Time sampled while preparing turn 1, step 1:')
  356. expect(firstRequestText).toContain('Elapsed since the preceding model-visible message: 0s.')
  357. expect(firstRequestText).not.toContain('Time sampled while preparing turn 1, step 2:')
  358. expect(secondRequestText).toContain('Time sampled while preparing turn 1, step 1:')
  359. expect(secondRequestText).toContain('Time sampled while preparing turn 1, step 2:')
  360. expect(secondRequestText).toContain('Elapsed since the preceding step context: 1m 1s.')
  361. for (const request of adapter.requests) expect(request.system).not.toContain('Time sampled while preparing')
  362. const headers = agent.session.events.filter(event => event.type === 'request/header')
  363. expect(JSON.stringify(headers)).not.toContain('Time sampled while preparing')
  364. await ctx.fiber.dispose()
  365. })
  366. })
  367. describe('real Loader export path', () => {
  368. it('keeps namespace metadata and boots the agent listener through unwrapExports', async () => {
  369. expect('default' in timeContext).toBe(false)
  370. const loader = Object.create(Loader.prototype) as Loader
  371. const unwrapped = loader.unwrapExports(timeContext) as Record<string, unknown>
  372. expect(unwrapped).toBe(timeContext)
  373. expect(unwrapped.name).toBe('time-context')
  374. expect(unwrapped.inject).toEqual(['agents'])
  375. expect(unwrapped.Config).toBeDefined()
  376. expect(typeof unwrapped.apply).toBe('function')
  377. const ctx = new Context()
  378. await ctx.plugin(AgentRegistry)
  379. const plugin = loader.unwrapExports(timeContext) as Parameters<Context['plugin']>[0]
  380. await ctx.plugin(plugin)
  381. const session = new Session(SessionId('loader'))
  382. openMessageTurn(session, 1)
  383. await fire(ctx, sessionAgent(session), 1, 1)
  384. expect(contextTexts(session)[0]).toContain('Time sampled while preparing turn 1, step 1:')
  385. })
  386. })