Introduction

When calculating session history, DeepSeek Harness (DSH) accumulates Token usage across four core buckets. Among them, cacheReadTokens and cacheWriteTokens have default null-coalescing protection (?? 0), but inputTokens and outputTokens are treated as raw numbers without type validation.

When an upstream provider, local inference service, or custom gateway returns non-standard data payloads (such as missing fields or NaN), the JavaScript arithmetic operation total += NaN causes the cumulative total to become NaN immediately. DSH’s Schema validation then rejects the session summary, making the entire conversation history unreadable.

dsh-usage-guard is a runtime interceptor. It modifies DSH’s projection calculation logic by Monkey-Patching, cleaning, mapping, and validating data before it enters the accumulator, thereby recovering corrupted sessions and preventing future data corruption.

Plugin Positioning

  • Name: dsh-usage-guard (maintained by goodandready)
  • Positioning: Session Token usage cleaner, history crash protection, and arithmetic safety tool
  • Core function: Prevents history corruption caused by malformed Provider metrics and supports instant recovery.

Core Features

1. Instant Replay Recovery

The plugin does not modify log files on disk. Instead, it hooks into the runtime projection folding point. Because session replay passes through this interception point, after installing the plugin, all previously corrupted or locked sessions are immediately recovered and become readable.

2. Comprehensive Alias Borrowing Dictionary

Before defaulting to 0, the plugin checks a broad set of industry-standard field aliases and maps them to DSH’s predefined fields. Common mappings include:
* inputTokens: input_tokens, input, promptTokens, prompt_tokens, promptTokenCount, prompt_eval_count
* outputTokens: output_tokens, output, completionTokens, completion_tokens, candidatesTokenCount, eval_count
* cacheReadTokens: cache_read_tokens, cachedTokens, cached_tokens, cache_read_input_tokens, cachedContentTokenCount, prompt_tokens_details.cached_tokens
* cacheWriteTokens: cache_write_tokens, cacheCreationTokens, cache_creation_input_tokens

3. Bounded Non-Negative Integer Sanity Check

Strictly validates typeof value === 'number' && Number.isFinite(value) && value >= 0 && Number.isInteger(value), filtering out NaN, Infinity, null, undefined, negative error codes (such as -1), non-integer floating-point numbers, and malformed strings.

4. Safe Zero Fallback and Floating-Point Rounding

If alias resolution fails, counters are safely initialized to 0. Math.round() is used to safely round fractional Token counts or decimal strings, satisfying the DSH core contract z.number().int().nonnegative().

5. In-Memory Registry Monkey-Patching

  • Existing projections: Wraps the existing .apply method in sessionProjections.registrations, preserving the this context.
  • Lazy binding: Wraps map.set to intercept future projection registrations, ensuring 100% coverage.
  • General protection: Protects Token counters, context pressure calculators, and busy-state analyzers.
  • Performance: Uses shallow copies and WeakMap caching, maintaining zero performance overhead across 10–15 parallel DSH projections.

6. Deduplicated Diagnostic Reports

Records detailed diagnostic warnings, including session ID, turn, step, raw payload, and recovery actions (such as “borrowed from alias” or “zeroed out”). Logs are deduplicated in memory to prevent log flooding during replay, with a cached cap of 1,000 FIFO entries.

7. Native Web UI Settings Card

Mounted to the settings tab Settings → Plugins → Plugin Settings, displaying real-time status badges, auto-dismissing save feedback, and bilingual localization in English and Chinese.

8. Token Peak Clamping

Caps abnormally large per-step usage counters before projection calculation (for example > 1,000,000), preventing integer overflow and session summary corruption. This can be configured in settings or set to 0 to disable.

9. In-Memory Telemetry and Diagnostic Endpoint

Provides the /api/dsh-usage-guard/telemetry endpoint for real-time tracking of repaired malformed samples, total repaired Tokens, clamped peaks, and a recent-event FIFO circular buffer with precise timestamps and coordinates.

10. Local One-Click Update

Provides the /api/dsh-usage-guard/update endpoint to enable host-side one-click updates.

Usage Examples

The plugin automatically handles the following scenarios at runtime:
* Alias mapping: Maps upstream prompt_tokens to inputTokens.
* Data cleansing: Replaces NaN or missing fields with 0.
* Format correction: Converts fractional Tokens or decimal strings to integers.
* Anomaly clamping: Clamps abnormal counters exceeding 1,000,000.

Environment Requirements and Dependencies

  • Node.js version: >= 20
  • Dependencies:
    • @deepseek-ai/cordis (^4.0.1)
    • @deepseek-ai/schemastery (^3.18.1)
  • Log handling: The plugin does not modify or rewrite log files on disk.

Summary

dsh-usage-guard inserts guard logic into DSH’s core projection layer, addressing the issue of permanent session history corruption caused by malformed upstream data. Through strict type validation, alias compatibility, and in-memory interception, it ensures the integrity of Token statistics and supports instant recovery of corrupted sessions.

GitHub repository