time-context.spec.ts 18 KB

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