index.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 type { Message } 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 'context/message':
  60. case 'steering/message':
  61. return event.time
  62. default:
  63. // Merge-extensible session events: non-surface records are not messages.
  64. break
  65. }
  66. }
  67. return undefined
  68. }
  69. /** Find the preceding time-context event within the open turn. */
  70. function precedingStepContextTime(agent: Agent, turn: number): number | undefined {
  71. for (const event of [...agent.session.events].reverse()) {
  72. if (event.type === 'turn/start' && event.data.turn === turn) return undefined
  73. if (event.type === 'context/message'
  74. && event.data.source.kind === 'plugin'
  75. && event.data.source.plugin === name) {
  76. return event.time
  77. }
  78. }
  79. return undefined
  80. }
  81. /** Find this plugin's latest durable injection, including a shadowed surface event. */
  82. function latestInjectionTime(agent: Agent): number | undefined {
  83. for (const event of [...agent.session.events].reverse()) {
  84. if (event.type === 'context/message'
  85. && event.data.source.kind === 'plugin'
  86. && event.data.source.plugin === name) {
  87. return event.time
  88. }
  89. }
  90. return undefined
  91. }
  92. function renderText(
  93. now: number,
  94. turn: number,
  95. step: number,
  96. previous: number | undefined,
  97. formatter: Intl.DateTimeFormat,
  98. timeZone: string,
  99. ): string {
  100. const elapsed = previous === undefined ? 'unavailable' : formatDuration(now - previous)
  101. const baseline = step === 1 ? 'model-visible message' : 'step context'
  102. return `Time sampled while preparing turn ${turn}, step ${step}: ${formatTimestamp(now, formatter, timeZone)}\n`
  103. + `Elapsed since the preceding ${baseline}: ${elapsed}.`
  104. }
  105. /** Reject refresh intervals that cannot represent an exact elapsed-millisecond threshold. */
  106. function validateRefreshInterval(refreshIntervalMs: number | undefined): void {
  107. if (refreshIntervalMs !== undefined && (
  108. !Number.isSafeInteger(refreshIntervalMs)
  109. || refreshIntervalMs < 0
  110. )) {
  111. throw new TypeError(
  112. `time-context: refreshIntervalMs must be a non-negative safe integer, got ${String(refreshIntervalMs)}`,
  113. )
  114. }
  115. }
  116. /**
  117. * Register a prepended pre-step listener for the lifetime of `ctx`.
  118. * @param ctx - plugin context; the listener is disposed with it.
  119. * @param config - time zone and durable refresh scheduling configuration.
  120. * @throws when the refresh interval is invalid or the configured or process time zone cannot be resolved.
  121. */
  122. export function apply(ctx: Context, config: Config): void {
  123. const timeZone = config.timeZone
  124. const refreshIntervalMs = config.refreshIntervalMs
  125. validateRefreshInterval(refreshIntervalMs)
  126. let formatter: Intl.DateTimeFormat
  127. try {
  128. formatter = new Intl.DateTimeFormat('en-US', {
  129. ...(timeZone === undefined ? {} : { timeZone }),
  130. year: 'numeric',
  131. month: '2-digit',
  132. day: '2-digit',
  133. hour: '2-digit',
  134. minute: '2-digit',
  135. second: '2-digit',
  136. hourCycle: 'h23',
  137. timeZoneName: 'longOffset',
  138. })
  139. } catch (error: unknown) {
  140. const message = timeZone === undefined
  141. ? 'time-context: failed to resolve the system time zone'
  142. : `time-context: invalid IANA timeZone ${JSON.stringify(timeZone)}`
  143. throw new Error(message, { cause: error })
  144. }
  145. const resolvedTimeZone = formatter.resolvedOptions().timeZone
  146. ctx.on('agent/pre-step', (
  147. agent: Agent,
  148. turn: number,
  149. step: number,
  150. _fullSystemPrompt: string,
  151. _sessionPrefix: readonly Message[],
  152. signal: AbortSignal,
  153. ) => {
  154. if (signal.aborted) return
  155. const now = Date.now()
  156. if (refreshIntervalMs !== undefined && refreshIntervalMs > 0) {
  157. const lastInjection = latestInjectionTime(agent)
  158. if (lastInjection !== undefined
  159. && now >= lastInjection
  160. && now - lastInjection < refreshIntervalMs) return
  161. }
  162. const previous = step === 1
  163. ? precedingMessageTime(agent)
  164. : precedingStepContextTime(agent, turn)
  165. agent.inject(
  166. [{ type: 'text', text: renderText(now, turn, step, previous, formatter, resolvedTimeZone) }],
  167. { source: { kind: 'plugin', plugin: name } },
  168. )
  169. }, { prepend: true })
  170. }