(state: SessionState, logger: Logger)
| 291 | } |
| 292 | |
| 293 | export function createEventHandler(state: SessionState, logger: Logger) { |
| 294 | return async (input: { event: any }) => { |
| 295 | const eventTime = |
| 296 | typeof input.event?.time === "number" && Number.isFinite(input.event.time) |
| 297 | ? input.event.time |
| 298 | : typeof input.event?.properties?.time === "number" && |
| 299 | Number.isFinite(input.event.properties.time) |
| 300 | ? input.event.properties.time |
| 301 | : undefined |
| 302 | |
| 303 | if (input.event.type !== "message.part.updated") { |
| 304 | return |
| 305 | } |
| 306 | |
| 307 | const part = input.event.properties?.part |
| 308 | if (part?.type !== "tool" || part.tool !== "compress") { |
| 309 | return |
| 310 | } |
| 311 | |
| 312 | if (part.state.status === "pending") { |
| 313 | if (typeof part.callID !== "string" || typeof part.messageID !== "string") { |
| 314 | return |
| 315 | } |
| 316 | |
| 317 | const startedAt = eventTime ?? Date.now() |
| 318 | const key = buildCompressionTimingKey(part.messageID, part.callID) |
| 319 | if (state.compressionTiming.startsByCallId.has(key)) { |
| 320 | return |
| 321 | } |
| 322 | state.compressionTiming.startsByCallId.set(key, startedAt) |
| 323 | logger.debug("Recorded compression start", { |
| 324 | messageID: part.messageID, |
| 325 | callID: part.callID, |
| 326 | startedAt, |
| 327 | }) |
| 328 | return |
| 329 | } |
| 330 | |
| 331 | if (part.state.status === "completed") { |
| 332 | if (typeof part.callID !== "string" || typeof part.messageID !== "string") { |
| 333 | return |
| 334 | } |
| 335 | |
| 336 | const key = buildCompressionTimingKey(part.messageID, part.callID) |
| 337 | const start = consumeCompressionStart(state, part.messageID, part.callID) |
| 338 | const durationMs = resolveCompressionDuration(start, eventTime, part.state.time) |
| 339 | if (typeof durationMs !== "number") { |
| 340 | return |
| 341 | } |
| 342 | |
| 343 | state.compressionTiming.pendingByCallId.set(key, { |
| 344 | messageId: part.messageID, |
| 345 | callId: part.callID, |
| 346 | durationMs, |
| 347 | }) |
| 348 | |
| 349 | const updates = applyPendingCompressionDurations(state) |
| 350 | if (updates === 0) { |
no test coverage detected