time-context.spec.ts 17 KB

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