index.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /**
  2. * Single replay-aware token-meter service for request and surface pressure.
  3. *
  4. * @module @deepseek-ai/dsh-token-meter
  5. */
  6. import { Context, Service } from 'cordis'
  7. import z from 'schemastery'
  8. import { BlockAssembler, deepFreeze } from '@deepseek-ai/dsh-llm'
  9. import type { ContentBlock, Message, TokenUsage } from '@deepseek-ai/dsh-llm'
  10. import type { EpochHeader, Session, SessionEvent, SurfaceEvent } from '@deepseek-ai/dsh-session'
  11. import { canonicalHeader, headerEquals, isSurfaceEvent } from '@deepseek-ai/dsh-session'
  12. import type {
  13. TokenMeasurement,
  14. TokenMeasurementBaseline,
  15. TokenMeterConfig,
  16. TokenSurfaceNode,
  17. } from './types.ts'
  18. export type * from './types.ts'
  19. /** Fixed text-density estimate used until exact tokenization is needed. */
  20. const CHARS_PER_TOKEN = 4
  21. /** Per-block structural overhead for JSON framing and type tags. */
  22. const BLOCK_OVERHEAD = 4
  23. /** Role-field framing overhead added to every priced message. */
  24. const ROLE_OVERHEAD = 4
  25. interface MeasurementAnchor {
  26. readonly header: EpochHeader | undefined
  27. readonly surfaceTokens: number
  28. readonly baseline: Exclude<TokenMeasurementBaseline, { kind: 'none' }>
  29. }
  30. interface ReplayState {
  31. consumedEvents: number
  32. header: EpochHeader | undefined
  33. surface: TokenSurfaceNode[]
  34. surfaceTokens: number
  35. stepStart: { turn: number; step: number; surfaceTokens: number } | undefined
  36. anchor: MeasurementAnchor | undefined
  37. }
  38. interface PreparedSurfaceMutation {
  39. readonly tokens: number
  40. commit(state: ReplayState): void
  41. }
  42. /** Sum disjoint provider usage buckets without double-counting reasoning output. */
  43. function usageTokens(usage: TokenUsage): number {
  44. return usage.inputTokens
  45. + (usage.cacheReadTokens ?? 0)
  46. + (usage.cacheWriteTokens ?? 0)
  47. + usage.outputTokens
  48. }
  49. /** Compare optional envelopes so a headerless estimate can track later surface deltas. */
  50. function optionalHeaderEquals(
  51. left: EpochHeader | undefined,
  52. right: EpochHeader | undefined,
  53. ): boolean {
  54. if (left === undefined || right === undefined) return left === right
  55. return headerEquals(left, right)
  56. }
  57. /** Reject stale or misspelled keys before defaults can hide them. */
  58. function validateConfigKeys(config: TokenMeterConfig): void {
  59. for (const key of Object.keys(config)) {
  60. throw new Error(`TokenMeterConfig: unknown key "${key}" (no settings are supported)`)
  61. }
  62. }
  63. declare module 'cordis' {
  64. interface Context {
  65. tokenMeter: TokenMeterService
  66. }
  67. }
  68. /** Replay owner for one service-wide estimator and isolated per-session folds. */
  69. export class TokenMeterService extends Service {
  70. // Schemastery preserves untrusted loader keys on an empty object schema;
  71. // the public type excludes settings while validateConfigKeys rejects them.
  72. static Config: z<TokenMeterConfig> = z.object({}) as unknown as z<TokenMeterConfig>
  73. private readonly states = new WeakMap<Session, ReplayState>()
  74. constructor(ctx: Context, config: TokenMeterConfig = {}) {
  75. super(ctx, 'tokenMeter')
  76. validateConfigKeys(config)
  77. // Readers catch up independently, while eager observation bounds ordinary
  78. // read latency without creating state for sessions no consumer has read.
  79. ctx.on('session/event', (session) => {
  80. if (this.states.has(session)) this._sync(session)
  81. })
  82. }
  83. /**
  84. * Measure current request pressure and surface through the durable tail.
  85. *
  86. * Provider usage is reused only when the latest successful call's canonical
  87. * request envelope matches `requestHeader` and its total is no lower than
  88. * that call's full heuristic anchor; otherwise the complete envelope and
  89. * surface are heuristically repriced.
  90. *
  91. * `requestHeader` affects request pressure only; surface fields always
  92. * describe the current session surface. Every call clones those positional
  93. * nodes, so measurement is O(surface).
  94. *
  95. * @param session - session to replay through its current durable tail.
  96. * @param requestHeader - optional effective request envelope replacing the latest logged header.
  97. * @returns a detached deeply immutable pressure and surface measurement.
  98. */
  99. measure(session: Session, requestHeader?: EpochHeader): TokenMeasurement {
  100. const state = this._sync(session)
  101. const header = requestHeader === undefined
  102. ? state.header
  103. : canonicalHeader(requestHeader)
  104. const anchor = state.anchor
  105. let baseline: TokenMeasurementBaseline
  106. let surfaceDeltaTokens: number
  107. if (anchor !== undefined && optionalHeaderEquals(anchor.header, header)) {
  108. baseline = anchor.baseline
  109. surfaceDeltaTokens = state.surfaceTokens - anchor.surfaceTokens
  110. } else if (header === undefined && state.surfaceTokens === 0) {
  111. baseline = { kind: 'none', tokens: 0 }
  112. surfaceDeltaTokens = 0
  113. } else {
  114. baseline = {
  115. kind: 'estimated',
  116. tokens: this._estimateHeader(header) + state.surfaceTokens,
  117. }
  118. surfaceDeltaTokens = 0
  119. }
  120. return deepFreeze(structuredClone({
  121. logRevision: state.consumedEvents,
  122. baseline,
  123. surfaceDeltaTokens,
  124. totalTokens: Math.max(0, baseline.tokens + surfaceDeltaTokens),
  125. surfaceTokens: state.surfaceTokens,
  126. nodes: state.surface,
  127. }))
  128. }
  129. /**
  130. * Heuristically price one model-visible message.
  131. * @param message - message to price without mutation.
  132. * @returns content and role-framing tokens under the fixed service heuristic.
  133. */
  134. estimateMessage(message: Message): number {
  135. return this._estimateContent(message.content) + ROLE_OVERHEAD
  136. }
  137. /** Catch one session's fold up to the current durable tail. */
  138. private _sync(session: Session): ReplayState {
  139. let state = this.states.get(session)
  140. if (state === undefined) {
  141. state = {
  142. consumedEvents: 0,
  143. header: undefined,
  144. surface: [],
  145. surfaceTokens: 0,
  146. stepStart: undefined,
  147. anchor: undefined,
  148. }
  149. this.states.set(session, state)
  150. }
  151. while (state.consumedEvents < session.events.length) {
  152. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- contiguous session seqs index the durable log
  153. const event = session.events[state.consumedEvents]!
  154. this._foldEvent(session, state, event)
  155. state.consumedEvents += 1
  156. }
  157. return state
  158. }
  159. /**
  160. * Validate and prepare every fallible part before mutating replay state.
  161. * A malformed event remains unread on every retry instead of partially
  162. * applying the same mutation more than once.
  163. */
  164. private _foldEvent(session: Session, state: ReplayState, event: SessionEvent): void {
  165. let nextHeader = state.header
  166. let nextStepStart = state.stepStart
  167. let nextAnchor = state.anchor
  168. switch (event.type) {
  169. case 'request/header':
  170. nextHeader = canonicalHeader(event.data.header)
  171. break
  172. case 'step/start':
  173. if (state.stepStart !== undefined) {
  174. throw new Error(
  175. `token meter: step/start at seq ${event.seq} arrived before turn ${state.stepStart.turn}/step ${state.stepStart.step} ended`,
  176. )
  177. }
  178. nextStepStart = { ...event.data, surfaceTokens: state.surfaceTokens }
  179. break
  180. case 'step/end':
  181. if (state.stepStart === undefined
  182. || state.stepStart.turn !== event.data.turn
  183. || state.stepStart.step !== event.data.step) {
  184. throw new Error(`token meter: step/end at seq ${event.seq} has no matching step/start boundary`)
  185. }
  186. nextStepStart = undefined
  187. break
  188. default:
  189. break
  190. }
  191. const surface = isSurfaceEvent(event)
  192. ? this._prepareSurfaceMutation(session, state, event)
  193. : undefined
  194. if (event.type === 'assistant/message') {
  195. const stepStart = state.stepStart
  196. if (stepStart === undefined
  197. || stepStart.turn !== event.data.turn
  198. || stepStart.step !== event.data.step) {
  199. throw new Error(`token meter: assistant/message at seq ${event.seq} has no matching step/start boundary`)
  200. }
  201. // assistant/message is surface-mandatory at every append/seed boundary.
  202. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  203. const eventTokens = surface!.tokens
  204. if (event.data.usage !== undefined && nextHeader !== undefined) {
  205. const providerAssistantTokens = this._estimateProviderAssistant(
  206. session,
  207. event,
  208. eventTokens,
  209. )
  210. const anchorSurfaceTokens = stepStart.surfaceTokens + providerAssistantTokens
  211. const providerTokens = usageTokens(event.data.usage)
  212. const estimatedAnchorTokens = this._estimateHeader(nextHeader) + anchorSurfaceTokens
  213. nextAnchor = {
  214. header: nextHeader,
  215. surfaceTokens: anchorSurfaceTokens,
  216. // Signed heuristic deltas remain conservative only from an anchor
  217. // that is at least as large as the matching full heuristic price.
  218. baseline: providerTokens >= estimatedAnchorTokens
  219. ? { kind: 'usage', tokens: providerTokens, usage: event.data.usage }
  220. : { kind: 'estimated', tokens: estimatedAnchorTokens },
  221. }
  222. } else {
  223. const anchorSurfaceTokens = stepStart.surfaceTokens + eventTokens
  224. nextAnchor = {
  225. header: nextHeader,
  226. surfaceTokens: anchorSurfaceTokens,
  227. baseline: {
  228. kind: 'estimated',
  229. tokens: this._estimateHeader(nextHeader) + anchorSurfaceTokens,
  230. },
  231. }
  232. }
  233. }
  234. state.header = nextHeader
  235. state.stepStart = nextStepStart
  236. if (surface !== undefined) surface.commit(state)
  237. state.anchor = nextAnchor
  238. }
  239. /** Validate one surface operation and return its allocation-light commit. */
  240. private _prepareSurfaceMutation(
  241. session: Session,
  242. state: ReplayState,
  243. event: SurfaceEvent,
  244. ): PreparedSurfaceMutation {
  245. const tokens = this._estimateSurfaceEvent(session, event)
  246. const op = event.surfaceOp
  247. if (op === 'append') {
  248. return {
  249. tokens,
  250. commit(target) {
  251. target.surface.push({ seq: event.seq, tokens })
  252. target.surfaceTokens += tokens
  253. },
  254. }
  255. }
  256. const startIdx = state.surface.findIndex(node => node.seq === op.start)
  257. const endIdx = state.surface.findIndex(node => node.seq === op.end)
  258. if (startIdx === -1 || endIdx === -1 || startIdx > endIdx) {
  259. throw new Error(
  260. `token meter: replace at seq ${event.seq} has invalid current range ${op.start}-${op.end}`,
  261. )
  262. }
  263. const removedTokens = state.surface
  264. .slice(startIdx, endIdx + 1)
  265. .reduce((total, node) => total + node.tokens, 0)
  266. return {
  267. tokens,
  268. commit(target) {
  269. target.surface.splice(startIdx, endIdx - startIdx + 1, { seq: event.seq, tokens })
  270. target.surfaceTokens += tokens - removedTokens
  271. },
  272. }
  273. }
  274. /** Price one current surface event exactly as it projects to a request. */
  275. private _estimateSurfaceEvent(session: Session, event: SurfaceEvent): number {
  276. const message = session.deriveEventMessage(event)
  277. return message === null ? 0 : this.estimateMessage(message)
  278. }
  279. /**
  280. * Reassemble provider output from exact chunk provenance for a usage anchor.
  281. * Missing legacy provenance conservatively treats the durable output as the
  282. * provider output; explicit empty provenance prices a known empty stream.
  283. */
  284. private _estimateProviderAssistant(
  285. session: Session,
  286. event: SessionEvent<'assistant/message'>,
  287. durableEventTokens: number,
  288. ): number {
  289. const sourceSeqs = event.sourceEventSeqs
  290. if (sourceSeqs === undefined) return durableEventTokens
  291. const assembler = new BlockAssembler()
  292. const seen = new Set<number>()
  293. for (const seq of sourceSeqs) {
  294. if (seq >= event.seq) {
  295. throw new Error(`token meter: assistant/message at seq ${event.seq} source seq ${seq} is not earlier`)
  296. }
  297. if (seen.has(seq)) {
  298. throw new Error(`token meter: assistant/message at seq ${event.seq} repeats source seq ${seq}`)
  299. }
  300. seen.add(seq)
  301. // Session construction validates contiguous seqs, and the explicit
  302. // earlier-than-assistant check above therefore guarantees existence.
  303. const source = session.events[seq]
  304. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  305. const sourceEvent = source!
  306. if (sourceEvent.type !== 'assistant/chunk') {
  307. throw new Error(`token meter: assistant/message at seq ${event.seq} source seq ${seq} is not assistant/chunk`)
  308. }
  309. if (sourceEvent.data.turn !== event.data.turn || sourceEvent.data.step !== event.data.step) {
  310. throw new Error(`token meter: assistant/message at seq ${event.seq} source seq ${seq} belongs to another step`)
  311. }
  312. assembler.push(sourceEvent.data.chunk)
  313. }
  314. const providerMessage = assembler.message()
  315. return providerMessage.content.length === 0 ? 0 : this.estimateMessage(providerMessage)
  316. }
  317. /** Price content blocks recursively under the fixed density heuristic. */
  318. private _estimateContent(blocks: readonly ContentBlock[]): number {
  319. let tokens = 0
  320. for (const block of blocks) {
  321. switch (block.type) {
  322. case 'text':
  323. case 'reasoning':
  324. tokens += Math.ceil(block.text.length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD
  325. break
  326. case 'tool-call':
  327. tokens += Math.ceil(block.name.length / CHARS_PER_TOKEN)
  328. + Math.ceil(block.arguments.length / CHARS_PER_TOKEN)
  329. + BLOCK_OVERHEAD
  330. break
  331. case 'tool-result':
  332. tokens += this._estimateContent(block.content) + BLOCK_OVERHEAD
  333. break
  334. default:
  335. // ContentBlockMap is merge-extensible; unknown blocks retain a
  336. // conservative structural JSON price under the fixed heuristic.
  337. tokens += BLOCK_OVERHEAD + Math.ceil(JSON.stringify(block).length / CHARS_PER_TOKEN)
  338. }
  339. }
  340. return tokens
  341. }
  342. /** Price the canonical non-surface request envelope. */
  343. private _estimateHeader(header: EpochHeader | undefined): number {
  344. if (header === undefined) return 0
  345. let tokens = 0
  346. if (header.system !== undefined) {
  347. tokens += Math.ceil(header.system.length / CHARS_PER_TOKEN) + ROLE_OVERHEAD
  348. }
  349. if (header.tools !== undefined && header.tools.length > 0) {
  350. tokens += Math.ceil(JSON.stringify(header.tools).length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD
  351. }
  352. return tokens
  353. }
  354. }
  355. export default TokenMeterService