index.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /**
  2. * Opt-in request-preparation clock context. Eligible pre-step attempts append
  3. * durable, source-attributed time readings to conversation history.
  4. *
  5. * @module @deepseek-ai/dsh-time-context
  6. */
  7. import type { Context } from 'cordis'
  8. import z from 'schemastery'
  9. import type { Agent } from '@deepseek-ai/dsh-agent'
  10. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  11. /** Cordis plugin name used by loader diagnostics. */
  12. export const name = 'time-context'
  13. /** The agent registry that owns the pre-step lifecycle seam. */
  14. export const inject = ['agents']
  15. /** Request-preparation clock formatting and append scheduling. Invalid values fail plugin load. */
  16. export interface Config {
  17. /** IANA time zone used for the rendered timestamp. Omit to resolve the Node process's system zone at plugin load. */
  18. timeZone?: string
  19. /** Minimum milliseconds between durable injections in one session. Omit or set to 0 to inject on every eligible pre-step attempt. */
  20. refreshIntervalMs?: number
  21. }
  22. /** Schemastery validation for {@link Config}. */
  23. export const Config: z<Config> = z.object({
  24. timeZone: z.string(),
  25. refreshIntervalMs: z.number(),
  26. })
  27. type TimestampPart = 'day' | 'hour' | 'minute' | 'month' | 'second' | 'timeZoneName' | 'year'
  28. /** Format an epoch millisecond value as an ISO-shaped timestamp with offset and IANA zone. */
  29. function formatTimestamp(now: number, formatter: Intl.DateTimeFormat, timeZone: string): string {
  30. const parts = Object.fromEntries(
  31. formatter.formatToParts(now).map(part => [part.type, part.value]),
  32. ) as Record<TimestampPart, string>
  33. const offset = parts.timeZoneName.replace(/^GMT$/, 'GMT+00:00').slice(3)
  34. return `${parts['year']}-${parts['month']}-${parts['day']}T${parts['hour']}:${parts['minute']}:${parts['second']}${offset}[${timeZone}]`
  35. }
  36. /** Format a non-negative elapsed millisecond count as compact whole-second units. */
  37. function formatDuration(elapsedMs: number): string {
  38. let seconds = Math.floor(Math.max(0, elapsedMs) / 1000)
  39. const days = Math.floor(seconds / 86_400)
  40. seconds %= 86_400
  41. const hours = Math.floor(seconds / 3600)
  42. seconds %= 3600
  43. const minutes = Math.floor(seconds / 60)
  44. seconds %= 60
  45. const parts: string[] = []
  46. if (days > 0) parts.push(`${days}d`)
  47. if (hours > 0) parts.push(`${hours}h`)
  48. if (minutes > 0) parts.push(`${minutes}m`)
  49. parts.push(`${seconds}s`)
  50. return parts.join(' ')
  51. }
  52. /** Find the latest model-visible event, excluding this plugin's pending append. */
  53. function precedingMessageTime(agent: Agent): number | undefined {
  54. for (const event of [...agent.session.events].reverse()) {
  55. switch (event.type) {
  56. case 'user/message':
  57. case 'assistant/message':
  58. case 'tool/result':
  59. case 'steering/message':
  60. return event.time
  61. default:
  62. // Merge-extensible session events: non-surface records are not messages.
  63. break
  64. }
  65. }
  66. return undefined
  67. }
  68. /** Find the preceding time-context event within the open turn. */
  69. function precedingStepContextTime(agent: Agent, turn: number): number | undefined {
  70. for (const event of [...agent.session.events].reverse()) {
  71. if (event.type === 'turn/start' && event.data.turn === turn) return undefined
  72. if (event.type === 'user/message'
  73. && event.data.source.kind === 'plugin'
  74. && event.data.source.plugin === name) {
  75. return event.time
  76. }
  77. }
  78. return undefined
  79. }
  80. /** Find this plugin's latest durable injection, including a shadowed surface event. */
  81. function latestInjectionTime(agent: Agent): number | undefined {
  82. for (const event of [...agent.session.events].reverse()) {
  83. if (event.type === 'user/message'
  84. && event.data.source.kind === 'plugin'
  85. && event.data.source.plugin === name) {
  86. return event.time
  87. }
  88. }
  89. return undefined
  90. }
  91. function renderText(
  92. now: number,
  93. turn: number,
  94. step: number,
  95. previous: number | undefined,
  96. formatter: Intl.DateTimeFormat,
  97. timeZone: string,
  98. ): string {
  99. const elapsed = previous === undefined ? 'unavailable' : formatDuration(now - previous)
  100. const baseline = step === 1 ? 'model-visible message' : 'step context'
  101. return `Time sampled while preparing turn ${turn}, step ${step}: ${formatTimestamp(now, formatter, timeZone)}\n`
  102. + `Elapsed since the preceding ${baseline}: ${elapsed}.`
  103. }
  104. /** Reject refresh intervals that cannot represent an exact elapsed-millisecond threshold. */
  105. function validateRefreshInterval(refreshIntervalMs: number | undefined): void {
  106. if (refreshIntervalMs !== undefined && (
  107. !Number.isSafeInteger(refreshIntervalMs)
  108. || refreshIntervalMs < 0
  109. )) {
  110. throw new TypeError(
  111. `time-context: refreshIntervalMs must be a non-negative safe integer, got ${String(refreshIntervalMs)}`,
  112. )
  113. }
  114. }
  115. /**
  116. * Register a prepended pre-step listener for the lifetime of `ctx`.
  117. * @param ctx - plugin context; the listener is disposed with it.
  118. * @param config - time zone and durable refresh scheduling configuration.
  119. * @throws when the refresh interval is invalid or the configured or process time zone cannot be resolved.
  120. */
  121. export function apply(ctx: Context, config: Config): void {
  122. const timeZone = config.timeZone
  123. const refreshIntervalMs = config.refreshIntervalMs
  124. validateRefreshInterval(refreshIntervalMs)
  125. let formatter: Intl.DateTimeFormat
  126. try {
  127. formatter = new Intl.DateTimeFormat('en-US', {
  128. ...(timeZone === undefined ? {} : { timeZone }),
  129. year: 'numeric',
  130. month: '2-digit',
  131. day: '2-digit',
  132. hour: '2-digit',
  133. minute: '2-digit',
  134. second: '2-digit',
  135. hourCycle: 'h23',
  136. timeZoneName: 'longOffset',
  137. })
  138. } catch (error: unknown) {
  139. const message = timeZone === undefined
  140. ? 'time-context: failed to resolve the system time zone'
  141. : `time-context: invalid IANA timeZone ${JSON.stringify(timeZone)}`
  142. throw new Error(message, { cause: error })
  143. }
  144. const resolvedTimeZone = formatter.resolvedOptions().timeZone
  145. ctx.on('agent/step', (
  146. agent: Agent,
  147. turn: number,
  148. step: number,
  149. signal: AbortSignal,
  150. ) => {
  151. if (signal.aborted) return
  152. const now = Date.now()
  153. if (refreshIntervalMs !== undefined && refreshIntervalMs > 0) {
  154. const lastInjection = latestInjectionTime(agent)
  155. if (lastInjection !== undefined
  156. && now >= lastInjection
  157. && now - lastInjection < refreshIntervalMs) return
  158. }
  159. const previous = step === 1
  160. ? precedingMessageTime(agent)
  161. : precedingStepContextTime(agent, turn)
  162. agent.inject(createUserMessage({ content: [{ type: 'text', text: renderText(now, turn, step, previous, formatter, resolvedTimeZone) }], source: { kind: 'plugin', plugin: name } }))
  163. }, { prepend: true })
  164. }