The current DeepSeek API pricing table lists separate input prices for cache hits, cache misses, and output tokens. That distinction is useful, but it does not make a growing prompt small.
Symptom: Cache hit rate stays high while the session gets slower and Token consumption keeps climbing.
Fastest fix: Measure every usage field, then apply Compaction, trim oversized tool results, or start a new session based on whether the task state is still recoverable.
Last updated: August 18, 2026. Data checked against the official DeepSeek Harness repository, the official token usage documentation, the context caching guide, and the current pricing page.
This guide is for:
- Individual developers whose long DeepSeek Harness sessions keep adding tokens.
- Engineering teams operating persistent Agents and trying to control response time and API spend.
- Technical leads comparing model calls, local resources, storage growth, and recovery effort.
SECTION 01DeepSeek Harness Compaction Cost Reduction Starts With Usage Fields
A long Agent session does not have one single “conversation token” number. Each request can contain several different sources of input:
- New user instructions added in the current turn.
- The accumulated session history.
- System instructions and harness metadata.
- Tool definitions and tool-call arguments.
- Tool results returned from shell commands, searches, builds, tests, or file reads.
- The model’s new output, including reasoning content when the selected mode returns it.
The official usage documentation explains that tokens are the billing unit and that actual processing should be read from the API response rather than inferred from character counts. For a persistent Agent, that means you should inspect request-level usage records instead of estimating from the visible transcript.
A simple diagnostic model is:
prompt_tokens
≈ new_input
+ retained_history
+ system_context
+ tool_definitions
+ tool_results
total_session_tokens
= sum(prompt_tokens + completion_tokens) across requests
This is not a pricing formula. It is a tracing model. It helps you identify which part is expanding.
A session can become expensive even when the latest user message is short. If each new request carries the previous conversation, the same repository instructions, earlier tool calls, and large command output, the prompt sent on every turn becomes larger. The model may also need to reread stale assumptions before it reaches the new instruction.
The first operational rule is therefore simple:
Do not optimize the cache before you understand the prompt shape.
Record these fields for every API request:
prompt_tokenscompletion_tokensprompt_cache_hit_tokensprompt_cache_miss_tokens- model name
- session identifier
- tool count
- compaction or session-reset event
- response time
- process memory and storage size
The cache fields are especially important because a high hit ratio can hide a large absolute input. For example, a request with a large prompt can have most of its prefix served from cache while still carrying a growing uncached suffix. The ratio may look healthy while the total prompt keeps increasing.
SECTION 02Tool Output Is Often the Fastest Source of Context Growth
Tool results are usually more dangerous than user messages because they arrive in bursts. A single build, test, search, or file-read operation can add a large block of text to the next request.
Typical high-volume sources include:
- Full compiler output when only the first error matters.
- Test logs containing repeated stack traces.
- Search results with many near-duplicate matches.
- Generated files or lockfiles read in full.
- Directory listings from large workspaces.
- Shell output that includes progress lines and environment details.
- Tool results repeated after a retry.
The correct response is not “delete all tool output.” The Agent still needs evidence. Separate the result into three classes.
Keep exactly:
- Exit status.
- Command or tool name.
- Relevant file paths.
- Exact error messages.
- Line numbers and short surrounding excerpts.
- Test names and failure reasons.
- Values needed for the next decision.
Summarize when repeated:
- Successful command output.
- Progress indicators.
- Duplicate search matches.
- Long lists of unchanged files.
- Repeated environment banners.
- Verbose dependency or build details already recorded elsewhere.
Store as an external artifact when auditability matters:
- Complete build logs.
- Security scan output.
- Reproducibility evidence.
- Large data samples.
- Generated reports.
- Before-and-after files required for review.
This is where official tool-result trimming and summary-based compression have different jobs. A trimming component reduces what enters the next context window. Compaction creates a smaller representation of the session state. Trimming is local and immediate. Compaction is a state transition that can affect future decisions.
Warning: Never replace exact failure evidence with a vague sentence such as “the tests failed” when the Agent still needs to repair the failure. Preserve the error class, file, line, and failing test before compression.
A useful tool wrapper returns structured fields rather than one unbounded text blob:
{
"status": "failed",
"command": "test command",
"duration": "recorded separately",
"errors": ["exact error lines"],
"files": ["relevant paths"],
"artifact": "path to full log",
"summary": "short next-action summary"
}
The exact schema can vary, but the principle should not: the context should contain the facts required for the next action, while the full result remains available outside the prompt.
SECTION 03Cache Hits Do Not Cancel Input Growth
The context caching guide describes prefix-based caching. A later request can reuse a matching prefix, but cache matching is not the same as deleting or skipping the rest of the request. The guide also exposes prompt_cache_hit_tokens and prompt_cache_miss_tokens, which should be read from the usage object.
This distinction explains a common DeepSeek Harness diagnosis:
- The system prompt and stable repository instructions remain unchanged.
- Those prefixes continue to produce cache hits.
- New tool output and session history are appended after the stable prefix.
- The input grows even though the cache hit percentage remains attractive.
- Response time, memory pressure, or miss-token cost rises.
Cache behavior is also sensitive to prefix mutation. Adding volatile timestamps, changing instruction order, injecting dynamic status text, or placing frequently changing data near the beginning can reduce reuse. Keep stable instructions at the front and volatile state later, but do not preserve an oversized history merely to protect cache alignment.
Use this variable-based cost model rather than a universal average:
input_cost =
(cache_hit_tokens / 1,000,000 × hit_price)
+ (cache_miss_tokens / 1,000,000 × miss_price)
output_cost =
completion_tokens / 1,000,000 × output_price
estimated_api_cost =
input_cost + output_cost
The current official pricing table lists separate prices for cache-hit input, cache-miss input, and output. Pricing can change, so load the values from the page on the day you build your budget model. Do not copy prices from an old screenshot, a third-party parser, or a community dashboard.
Do not confuse three different numbers:
- Official API usage fields returned for a request.
- The totals displayed by the DeepSeek Harness interface.
- Values reconstructed by a wrapper or external parser.
They may use different aggregation windows or omit events. For an audit, retain the raw API usage object and the session event log.
SECTION 04Compaction Needs a State Recovery Test
Compaction is useful when the task is still one continuous job but the session contains too much redundant history. It is risky when the summary becomes the only representation of a subtle code state.
Before compressing a coding session, verify that the session can answer these questions:
- What is the current objective?
- Which files were changed?
- Which changes are intentional?
- Which tests passed?
- Which tests failed?
- What action is next?
- Which user constraints are still active?
- Which assumptions remain unverified?
- Where is the complete log or artifact stored?
The official repository is in developer preview and warns that compatibility-breaking changes can occur. Treat Compaction behavior, event names, default triggers, and component combinations as version-sensitive. Check the current repository state before automating against internal events or undocumented defaults.
Use a repeatable validation loop:
- Save the full session log and workspace state.
- Ask the Agent for the current goal, changed files, test status, next action, and constraints.
- Run Compaction.
- Ask the same recovery questions again.
- Continue the original task for one controlled action.
- Compare the result with the pre-compaction path.
- Revert or start a new controlled session if a critical fact is missing.
A successful summary does not need to preserve every sentence. It must preserve the state needed to make the next correct decision.
A failed validation is not always a model failure. It can expose an application design problem: the session relied on hidden state that was never written to a file, artifact, task record, or structured event.
SECTION 05Session Splitting Rules
Compaction and session splitting solve different problems.
Use Compaction when:
- The objective is unchanged.
- The same workspace remains active.
- The Agent has accumulated repetitive history.
- The important state can be represented and verified.
- You need continuity across the next implementation step.
Start a new session when:
- The product or coding objective has changed.
- You switched repositories or workspace boundaries.
- The earlier Agent made incorrect assumptions that now dominate the context.
- The task moved from exploration to an independent implementation.
- You need a clean audit boundary.
- Different permissions or secrets should apply.
Pause the task instead of either option when:
- The next action depends on a human decision.
- A required external artifact is not ready.
- The workspace is unstable.
- The current task has no safe next action.
- Continuing would generate more logs without resolving the blocker.
For a new session, create a handoff artifact containing the verified objective, changed files, test evidence, unresolved risks, and explicit constraints. Do not copy the entire old transcript into the new prompt. That recreates the problem you were trying to solve.
SECTION 06FAQ: Long-Session Cost and Context Recovery
Why can a high cache hit rate still produce heavy Token consumption?
A cache hit makes part of the input cheaper or faster, depending on the current API behavior. It does not remove the full request from the session history or from local processing. If each turn appends new tool output, assistant messages, and instructions, the uncached portion can grow. Inspect absolute hit and miss tokens, not only the percentage shown in a dashboard.
Can Compaction lose important code-task context?
It can. The risk is highest when the task depends on exact error text, a file-level change, a failed test, or a user constraint that was only stated once. Preserve those facts in structured state or external artifacts, then compare the same recovery questions before and after compression. If the Agent cannot reconstruct the next action, do not continue from that summary.
When is a new session safer than compression?
A new session is safer when the goal or workspace boundary changes, or when the old context contains unresolved wrong assumptions. Compression is better for one stable task with repetitive history. The handoff should be shorter than the original transcript and should contain only verified state. Keep the complete log separately for audit or recovery.
How should you reduce context when tool results are too long?
Return a structured result with status, relevant paths, exact errors, and an artifact reference. Keep a short excerpt for immediate reasoning and store the full output outside the prompt. For search, return the strongest matches rather than every match. For builds and tests, preserve failure evidence and discard routine success noise after recording it.
Which metrics belong in a long-session cost estimate?
Use API prompt_tokens, completion_tokens, prompt_cache_hit_tokens, and prompt_cache_miss_tokens, then add response time, memory, storage growth, retries, and human recovery effort. Apply the official prices to the measured hit and miss tokens. Compare the same task before and after the policy change; one unusually cheap request is not a stable optimization result.
SECTION 07Recovery Checklist
Run this checklist before you change a production Agent policy:
- [ ] Capture raw API usage fields for every request.
- [ ] Separate new input, retained history, system context, tool definitions, and tool results.
- [ ] Identify the largest tool outputs by bytes and token count.
- [ ] Preserve complete logs as external artifacts when audit evidence is required.
- [ ] Keep exact errors, changed files, test status, and user constraints in the active state.
- [ ] Check whether volatile content is mutating the cache prefix.
- [ ] Run the same recovery questions before and after Compaction.
- [ ] Continue one controlled task action after compression.
- [ ] Start a new session when the objective or workspace boundary changes.
- [ ] Compare API cost, latency, memory, storage, retries, and recovery effort on the same benchmark task.
- [ ] Recheck current Compaction behavior and pricing before deploying an automated policy.
SECTION 08Decision Matrix Before the Next Run
| Situation | Preferred action | What to preserve | Main risk |
|---|---|---|---|
| Same task, repetitive history, verified state | Compact the session | Goal, files, tests, next action, constraints | Summary omits a dependency |
| Same task, oversized routine logs | Trim tool results first | Errors, paths, status, artifact reference | Removing evidence needed for repair |
| New objective or new workspace | Start a new session | Short verified handoff | Repeating stale assumptions |
| Audit or compliance workload | Separate active context from full logs | Complete event and artifact history | Losing traceability |
| Blocked by a human or external dependency | Pause the task | Blocker, owner, required input | Generating more irrelevant output |
| Local runtime is crowded by multiple persistent Agents | Move workloads into separate environments | Session identity and recovery files | Resource contention and interference |
A practical budget decision should combine API usage with environment cost. Track process memory, storage growth, response time, retries, and the minutes required to reconstruct a damaged session. A lower API bill is not a win if the Agent loses state and forces an engineer to repeat the investigation.
Keep the session continuous only while state recovery remains cheaper than rebuilding the task.
When long-running DeepSeek Harness work also keeps a local machine occupied, the problem is no longer only Token consumption. A single workstation can suffer from competing builds, background processes, storage growth, permission conflicts, and multiple sessions fighting for the same workspace. In that situation, a Mac environment can be easier to isolate than continuing to stack unrelated workloads on one local setup. You can review Mac configuration choices for development workloads and compare current MACNOX plans before deciding whether a separate runtime is justified.
MACNOX is most useful when you need temporary capacity, a clean test environment, or an isolated window for parallel Agent work. It is not automatically the best choice for a permanent, heavy workload that needs dedicated hardware, physical peripherals, or fixed local storage. If your issue is specifically that persistent sessions interfere with your main machine, renting a separate Mac can remove that environment pressure while you apply the same Compaction and session-splitting rules to control the API side.
SECTION 09FAQ
Why can DeepSeek Harness show strong cache hits while token usage keeps rising?
A cache hit changes the billing path for part of the input, but it does not remove that input from the request. If the session keeps appending messages, tool results, logs, and generated reasoning, the total prompt still grows. Track prompt_cache_hit_tokens, prompt_cache_miss_tokens, prompt_tokens, and completion_tokens together instead of treating the hit rate as a total-cost metric.
Can Compaction lose important context from a coding task?
Yes, if the summary omits the active objective, changed files, failed tests, pending actions, or explicit user constraints. Compaction should be treated as a lossy state transformation until you verify it. Preserve the original session log, run the same follow-up task before and after compression, and start a controlled session when the compressed state cannot reproduce the required facts.
When should you compress a session instead of starting a new one?
Compress when the objective, repository boundary, and task ownership remain stable, but the conversation contains repetitive history or oversized tool output. Start a new session when the goal changes, the workspace changes, or earlier mistakes dominate the context. Carry forward a short verified handoff containing the goal, files, tests, constraints, and unresolved risks.
How can you reduce context usage when tool results are too long?
Trim by information value, not by character count alone. Keep error lines, file paths, command status, test names, and exact evidence needed for the next decision. Replace routine logs, repeated search results, and large unchanged file dumps with a digest or external artifact reference. Never discard evidence that must later support an audit or reproduce a failure.
Which data should you use to estimate the cost of a long session?
Use request-level prompt_tokens, completion_tokens, prompt_cache_hit_tokens, and prompt_cache_miss_tokens from the API usage object. Add response time, process memory, storage growth, retries, and human recovery time. A useful estimate applies the current input hit and miss rates to the official model prices, then compares the result with the same benchmark task after each context policy change.