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, Inbox, 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({ toFake: ['Date'] })
  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. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  39. status: 'running',
  40. ctx: new Context(),
  41. send: () => {},
  42. followup: () => {},
  43. steer: () => {},
  44. inject: () => { throw new Error('time-context must append directly to the open step') },
  45. cancel() {},
  46. runMaintenance: task => task(new AbortController().signal),
  47. whenIdle: () => Promise.resolve(),
  48. }
  49. }
  50. function openMessageTurn(session: Session, turn: number): void {
  51. session.append('turn/start', { turn })
  52. session.append('user/message', createUserMessage({
  53. content: [{ type: 'text', text: `turn ${turn}` }],
  54. source: { kind: 'user' },
  55. }), { surfaceOp: 'append' })
  56. }
  57. function contextTexts(session: Session): string[] {
  58. const texts: string[] = []
  59. for (const event of session.events) {
  60. if (event.type === 'user/message'
  61. && event.data.source.kind === 'plugin'
  62. && event.data.source.plugin === 'time-context') {
  63. texts.push(event.data.content.find(block => block.type === 'text')?.text ?? '')
  64. }
  65. }
  66. return texts
  67. }
  68. async function fire(
  69. ctx: Context,
  70. agent: Agent,
  71. turn: number,
  72. step: number,
  73. signal: AbortSignal = SIGNAL,
  74. ): Promise<void> {
  75. const decision = await agentEvents(ctx, agent).waterfall(
  76. 'agent/pre-step',
  77. [],
  78. { turn, step, signal },
  79. () => Promise.resolve({ kind: 'enter' as const, messages: [] }),
  80. )
  81. if (decision.kind === 'enter') {
  82. for (const message of decision.messages) {
  83. agent.session.append('user/message', message, { surfaceOp: 'append' })
  84. }
  85. }
  86. }
  87. function textResponse(text: string): StreamChunk[] {
  88. return [
  89. { type: 'block-start', index: 0, blockType: 'text' },
  90. { type: 'block-end', index: 0, block: { type: 'text', text } },
  91. { type: 'finish', reason: { kind: 'stop' } },
  92. ]
  93. }
  94. function toolCallResponse(): StreamChunk[] {
  95. return [
  96. { type: 'block-start', index: 0, blockType: 'tool-call' },
  97. {
  98. type: 'block-end',
  99. index: 0,
  100. block: { type: 'tool-call', id: CallId('tick-1'), name: 'tick', arguments: '{}' },
  101. },
  102. { type: 'finish', reason: { kind: 'tool-calls' } },
  103. ]
  104. }
  105. class ScriptedAdapter extends LlmAdapter {
  106. readonly requests: GenerateOptions[] = []
  107. constructor(private readonly script: StreamChunk[][]) {
  108. super()
  109. }
  110. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  111. this.requests.push(options)
  112. const chunks = this.script.shift()
  113. if (chunks === undefined) throw new Error('ScriptedAdapter: script exhausted')
  114. for (const chunk of chunks) yield chunk
  115. }
  116. }
  117. async function loopHarness(adapter: ScriptedAdapter, config: Config = {}): Promise<Context> {
  118. const ctx = new Context()
  119. await mountAgentLoopTestDependencies(ctx)
  120. await ctx.plugin(AgentLoop, { agents: [] })
  121. await ctx.plugin(timeContext, config)
  122. ctx.llm.registerAdapter(['mock'], adapter)
  123. return ctx
  124. }
  125. function requestText(request: GenerateOptions): string {
  126. return request.messages
  127. .flatMap(message => message.content)
  128. .filter(block => block.type === 'text')
  129. .map(block => block.text)
  130. .join('\n')
  131. }
  132. describe('durable step context', () => {
  133. it('records turn, step, zoned time, and the preceding model-visible message baseline', async () => {
  134. const { ctx } = await mount({ timeZone: 'Asia/Shanghai' })
  135. const session = Session.create(SessionId('first'))
  136. openMessageTurn(session, 1)
  137. vi.setSystemTime(BASE + 90_061_000)
  138. await fire(ctx, sessionAgent(session), 1, 1)
  139. expect(contextTexts(session)).toEqual([
  140. 'Time sampled while preparing turn 1, step 1: 2026-07-15T09:01:01+08:00[Asia/Shanghai]\n'
  141. + 'Elapsed since the preceding model-visible message: 1d 1h 1m 1s.',
  142. ])
  143. const event = session.events.at(-1)
  144. expect(event?.type).toBe('user/message')
  145. if (event?.type !== 'user/message') throw new Error('missing time context')
  146. expect(event.data.source).toEqual({ kind: 'plugin', plugin: 'time-context' })
  147. expect(event.surfaceOp).toBe('append')
  148. })
  149. it('reports an unavailable first-step baseline when no model-visible message precedes it', async () => {
  150. const { ctx } = await mount()
  151. const session = Session.create(SessionId('unavailable'))
  152. session.append('turn/start', { turn: 1 })
  153. await fire(ctx, sessionAgent(session), 1, 1)
  154. expect(contextTexts(session)[0]).toContain(
  155. 'Elapsed since the preceding model-visible message: unavailable.',
  156. )
  157. })
  158. it.each([
  159. ['omitted interval', {}],
  160. ['zero interval', { refreshIntervalMs: 0 }],
  161. ] as const)('uses the preceding durable step-context timestamp after step one with %s', async (_label, config) => {
  162. const { ctx } = await mount(config)
  163. const session = Session.create(SessionId('later-step'))
  164. const agent = sessionAgent(session)
  165. openMessageTurn(session, 3)
  166. await fire(ctx, agent, 3, 1)
  167. vi.setSystemTime(BASE + 61_000)
  168. await fire(ctx, agent, 3, 2)
  169. expect(contextTexts(session)[1]).toBe(
  170. 'Time sampled while preparing turn 3, step 2: 2026-07-14T00:01:01+00:00[UTC]\n'
  171. + 'Elapsed since the preceding step context: 1m 1s.',
  172. )
  173. })
  174. it('reports an unavailable later-step baseline at the matching turn boundary', async () => {
  175. const { ctx } = await mount()
  176. const session = Session.create(SessionId('later-step-boundary'))
  177. openMessageTurn(session, 4)
  178. await fire(ctx, sessionAgent(session), 4, 2)
  179. expect(contextTexts(session)[0]).toContain(
  180. 'Elapsed since the preceding step context: unavailable.',
  181. )
  182. })
  183. it('reports an unavailable later-step baseline when event lookup is exhausted', async () => {
  184. const { ctx } = await mount()
  185. const session = Session.create(SessionId('later-step-exhausted'))
  186. await fire(ctx, sessionAgent(session), 1, 2)
  187. expect(contextTexts(session)[0]).toContain(
  188. 'Elapsed since the preceding step context: unavailable.',
  189. )
  190. })
  191. it('injects after backward wall-clock movement and clamps elapsed time to zero', async () => {
  192. const { ctx } = await mount({ refreshIntervalMs: 60_000 })
  193. const session = Session.create(SessionId('backward'))
  194. const agent = sessionAgent(session)
  195. openMessageTurn(session, 1)
  196. await fire(ctx, agent, 1, 1)
  197. vi.setSystemTime(BASE - 5_000)
  198. await fire(ctx, agent, 1, 2)
  199. expect(contextTexts(session)).toHaveLength(2)
  200. expect(contextTexts(session)[1]).toContain('Elapsed since the preceding step context: 0s.')
  201. })
  202. it('uses a shadowed durable injection after resume and injects at the exact threshold', async () => {
  203. const { ctx } = await mount({ refreshIntervalMs: 1_000 })
  204. const original = Session.create(SessionId('seed-source'))
  205. openMessageTurn(original, 1)
  206. await fire(ctx, sessionAgent(original), 1, 1)
  207. const user = original.events.find(event => event.type === 'user/message' && event.data.source.kind === 'user')
  208. const reading = original.events.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  209. if (user === undefined || reading === undefined) throw new Error('missing source surface events')
  210. original.append('user/message', createUserMessage({
  211. content: [{ type: 'text', text: 'compacted history' }],
  212. source: { kind: 'plugin', plugin: 'compact-basic' },
  213. }), {
  214. surfaceOp: { op: 'replace', start: user.seq, end: reading.seq },
  215. sourceEventSeqs: [user.seq, reading.seq],
  216. })
  217. original.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  218. expect(JSON.stringify(original.deriveMessages())).not.toContain('Time sampled while preparing')
  219. const resumed = Session.create(SessionId('resumed'), [...original.events])
  220. const resumedAgent = sessionAgent(resumed)
  221. vi.setSystemTime(BASE + 999)
  222. openMessageTurn(resumed, 2)
  223. const beforeSkip = resumed.events.length
  224. await fire(ctx, resumedAgent, 2, 1)
  225. expect(resumed.events).toHaveLength(beforeSkip)
  226. expect(contextTexts(resumed)).toHaveLength(1)
  227. vi.setSystemTime(BASE + 1_000)
  228. await fire(ctx, resumedAgent, 2, 2)
  229. expect(contextTexts(resumed)).toHaveLength(2)
  230. expect(contextTexts(resumed)[1]).toContain(
  231. 'Elapsed since the preceding step context: unavailable.',
  232. )
  233. })
  234. it('applies a positive interval across turns without sharing state between sessions', async () => {
  235. const { ctx } = await mount({ refreshIntervalMs: 1_000 })
  236. const first = Session.create(SessionId('interval-first'))
  237. const firstAgent = sessionAgent(first, 'first-agent')
  238. openMessageTurn(first, 1)
  239. await fire(ctx, firstAgent, 1, 1)
  240. first.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  241. vi.setSystemTime(BASE + 500)
  242. openMessageTurn(first, 2)
  243. const beforeSkip = first.events.length
  244. await fire(ctx, firstAgent, 2, 1)
  245. const independent = Session.create(SessionId('interval-independent'))
  246. openMessageTurn(independent, 1)
  247. await fire(ctx, sessionAgent(independent, 'independent-agent'), 1, 1)
  248. expect(first.events).toHaveLength(beforeSkip)
  249. expect(contextTexts(first)).toHaveLength(1)
  250. expect(contextTexts(independent)).toHaveLength(1)
  251. })
  252. it('skips an already-aborted prompt submission', async () => {
  253. const { ctx } = await mount()
  254. const session = Session.create(SessionId('ordering'))
  255. const agent = sessionAgent(session)
  256. openMessageTurn(session, 1)
  257. await fire(ctx, agent, 1, 1)
  258. const abort = new AbortController()
  259. abort.abort()
  260. await fire(ctx, agent, 1, 2, abort.signal)
  261. expect(contextTexts(session)).toHaveLength(1)
  262. })
  263. })
  264. describe('configuration and lifecycle', () => {
  265. it('defaults to the process system zone and retains the zone resolved at plugin load', async () => {
  266. process.env['TZ'] = 'Asia/Shanghai'
  267. const { ctx } = await mount()
  268. process.env['TZ'] = 'America/New_York'
  269. const session = Session.create(SessionId('system-zone'))
  270. openMessageTurn(session, 1)
  271. await fire(ctx, sessionAgent(session), 1, 1)
  272. expect(contextTexts(session)[0]).toContain('2026-07-14T08:00:00+08:00[Asia/Shanghai]')
  273. })
  274. it('fails loud for an invalid explicit zone or an unavailable process zone', async () => {
  275. const invalid = new Context()
  276. await invalid.plugin(AgentRegistry)
  277. await expect(invalid.plugin(timeContext, { timeZone: 'Not/A_Real_Zone' })).rejects.toThrow(
  278. /invalid IANA timeZone/,
  279. )
  280. vi.spyOn(Intl, 'DateTimeFormat').mockImplementationOnce(() => {
  281. throw new RangeError('system zone unavailable')
  282. })
  283. const unresolved = new Context()
  284. await unresolved.plugin(AgentRegistry)
  285. await expect(unresolved.plugin(timeContext, {})).rejects.toThrow(/failed to resolve the system time zone/)
  286. })
  287. it('rejects invalid refresh intervals at plugin load with one diagnostic', async () => {
  288. const invalid = [-1, 0.5, Number.MAX_SAFE_INTEGER + 1, Number.POSITIVE_INFINITY, Number.NaN]
  289. for (const refreshIntervalMs of invalid) {
  290. await expect(mount({ refreshIntervalMs })).rejects.toThrow(
  291. 'time-context: refreshIntervalMs must be a non-negative safe integer',
  292. )
  293. }
  294. })
  295. it('removes its listener when the plugin fiber disposes', async () => {
  296. const { ctx, fiber } = await mount()
  297. const session = Session.create(SessionId('dispose'))
  298. const agent = sessionAgent(session)
  299. openMessageTurn(session, 1)
  300. await fire(ctx, agent, 1, 1)
  301. await fiber.dispose()
  302. await fire(ctx, agent, 1, 2)
  303. expect(contextTexts(session)).toHaveLength(1)
  304. })
  305. })
  306. describe('real agent-loop request history', () => {
  307. it.each([
  308. ['throws'],
  309. ['cancels'],
  310. ] as const)('does not commit a preparation reading when a downstream pre-step listener %s', async (mode) => {
  311. const adapter = new ScriptedAdapter([textResponse('unused')])
  312. const ctx = await loopHarness(adapter)
  313. ctx.on('agent/pre-step', (subject, _messages, _context, next) => {
  314. if (mode === 'throws') throw new Error('later pre-step failure')
  315. subject.cancel({ kind: 'user' })
  316. return next()
  317. })
  318. const agent = ctx.agentLoop.create(SessionId(`late-${mode}`), { provider: 'mock', model: 'mock' })
  319. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'start' }], source: { kind: 'user' } }))
  320. await agent.whenIdle()
  321. expect(contextTexts(agent.session)).toHaveLength(0)
  322. expect(adapter.requests).toHaveLength(0)
  323. expect(agent.session.events.some(event => event.type === 'step/start')).toBe(false)
  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).toBeGreaterThan(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: unavailable.')
  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 = Session.create(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. })