Image-Based Context Compression for Long-Running Agent Sessions

    Long-running agent sessions accumulate system prompts, tool calls, file excerpts, error stacks, and revisions that quickly crowd the context window. This article explains an image-based checkpoint approach: preserve exact head and tail text, render dense middle history into locally generated frames, pair frames with a precise text index and file map, and validate readability, determinism, redaction, and cost against the target multimodal model.

    Image-Based Context Compression for Long-Running Agent Sessions

    The context of a long-running agent session is rarely a continuous prose narrative. It is a working trail made of system prompts, user goals, tool calls, file fragments, error stacks, and multiple rounds of revision. As the session grows, history increasingly competes for the context window. A common practice is to generate a text summary when the session approaches the window limit and replace the middle records with shorter text.

    A summary can keep a task moving, but it compresses details such as which files were changed, which log line was truncated, or which hypothesis was already rejected into vague conclusions. Troubleshooting, migration work, and large refactors that require repeated backtracking depend on exactly those details.

    Image-based compression addresses the same class of problem; it is not another form of chat summarization. Its core judgment is that, within a readable range, a tightly typeset image can carry a relatively large number of characters. Multimodal models usually account for images by resolution, tiling, or visual tokens, not by a one-to-one relationship with the number of characters inside the image. Rendering middle records that would otherwise be discarded or heavily summarized into an image may therefore preserve layout information while occupying fewer plain-text positions.

    This is a design motivation, not a fixed savings ratio or a billing promise. Different models use different visual tokenization methods, resolution limits, and prices. Before rollout, the mechanism must be measured with the target model and sample sessions.

    When It Fits and When It Does Not

    The mechanism fits long-running sessions that need to revisit intermediate evidence, such as cross-file defect localization, build log analysis, and staged code review. It does not fit very short question-and-answer exchanges. For short conversations, keeping the original text is simpler; rendering, indexing, and storage only add round trips.

    It also does not fit a minimal working mode that deliberately limits read, write, and edit capabilities. The purpose of minimal mode is to restrict the agent’s access to files and changes in the workspace. If the compressed result then includes a file map, paths, and fragment indexes, those clues are reintroduced into the context, conflicting with the mode design. Mode selection should come before compression strategy: first decide what the agent is allowed to see, then decide how history should be folded.

    What a Checkpoint Should Preserve

    A compression pass should ideally produce a traceable checkpoint, not an overview that cannot be verified. A safer structure contains four parts at the same time.

    First, exact head text. Preserve the task goal, constraints, key decisions, and early conventions that remain valid. The head should not be too long, or compression becomes meaningless; it also should not contain only a title, or later turns will lose their constraints.

    Second, exact tail text. Preserve recent user instructions, the current conclusion, unfinished items, and the latest errors. The tail is the working memory the agent uses to continue acting. It should remain verbatim and avoid a second round of summarization.

    Third, dense middle frames. The middle contains earlier tool outputs, logs that are out of date but may still be queried, and intermediate reasoning. Rendering is done locally, without sending the full text to another model for summarization. Local rendering is deterministic, does not consume additional conversation tokens, and makes redaction possible before the image is produced.

    Fourth, a text index and file map. Images are good for letting the model “see” layout, but they are not suitable as the sole source of truth. Beside the image there should be a copyable precise index: frame number, source interval, token or character offset, and source type. The file map should record only the paths, operation types, and result states actually involved in this segment of history, not scan the entire workspace. When verbatim verification is needed, the source text pointed to by the index is authoritative, not optical recognition of the image.

    An illustrative structure can be written as:

    1. checkpoint
    2. head_text exact head text with interval markers
    3. tail_text exact tail text with interval markers
    4. frames[] locally rendered dense frames and readability parameters
    5. text_index[] mapping from frame regions to source intervals
    6. file_map[] path, operation, status, corresponding interval

    The field names express design responsibilities; they are not an interface for any specific product.

    Processing Flow

    Compression should run at a safe moment determined by the runtime, for example after the current round of tool calls has finished and there is no uncommitted half output. The flow can be divided into three steps: deterministic serialization, frame compression, and folding of oversized output. None of the three steps relies on model-generated summaries.

    Deterministic serialization first sets head and tail limits. Limits are set by token or character budget and are truncated at complete message boundaries, avoiding a tool result cut into two unintelligible halves. For repeated progress bars, download percentages, and similar warnings, collapsing can happen during serialization, but the first item, the last item, and the occurrence count must be retained. Each retained fragment receives a stable marker so later indexes do not drift when layout changes.

    Frame compression paginates the serialized middle result. Page width, font size, line spacing, and page count must be constrained in advance so that paths, line numbers, and key errors remain recognizable after scaling. Higher density saves frames, but beyond the readability limit neither the model nor a human can use the image, and compression has failed. The rendered result is written to the checkpoint together with the index; the index records which region of which frame corresponds to which source segment, rather than writing a separate prose description that can drift.

    Oversized tool output needs additional folding. Full build logs, dependency trees, or search results often far exceed a single frame. In this case, keep head and tail excerpts, explicitly mark the scale and reason for the omission, and leave the full content in a searchable raw record. The image contains only the head and tail excerpts and the omission marker, avoiding a wall of unreadable characters inside one frame.

    The order of these three steps should be fixed. First determine which source text must remain, then decide on the frames, and finally handle tool results that are still too large. If the order is reversed, the index will point to middle parts that have already been discarded.

    Indexing and Traceback

    The value of the index is that it separates “seeing the image” from “citing the source text.” After the agent sees a dense frame, if it needs to quote a line, it should retrieve the corresponding text through the index rather than rewrite it from visual impression. Human review uses the index in the same way. The index should therefore answer at least four questions: which turn the text came from, whether it belongs to user instructions or tool output, which frame it is in within the checkpoint, and whether the source text was omitted.

    The file map is a specialized view of the index. It aggregates reads, searches, edits, and execution results within this segment of history by path, and notes success, failure, or later overwrite by a subsequent change. The map can help the agent avoid reopening files already shown to be irrelevant, but it cannot replace version control. A checkpoint is not a code repository, nor should it be treated as a patch that can be applied directly.

    For storage, frames and indexes can be placed in object storage or session attachments with a lifecycle policy. After a session ends or a checkpoint is updated, old frames can be cleaned up according to the retention policy. Checkpoint text already inserted into the session is treated as ordinary history; removing the compression capability will not automatically delete it. This allows old sessions to remain readable with the head and tail source text and index descriptions left at the time, even during upgrade or decommissioning.

    Risks and Validation

    Images will draw secrets, tokens, personal data, and internal addresses from logs together with everything else. Before rendering, use the same redaction rules as for text logs, replacing obvious credential patterns and specified fields. Redacting only the text index while forgetting the image, or the reverse, leaves a leak surface. When session export files are shared, frames and indexes must be subject to access control at the same time.

    Also avoid three quality problems. First, the head and tail budgets are too large, so almost no middle content is compressed and the window remains tight. Second, omission markers are vague, so readers do not know whether what was dropped in the middle was repeated progress output or a key stack trace. Third, the file map over-infers and writes in paths that never appeared in history. Validation can use fixed sample replay: given the same history, multiple compression runs should produce the same head and tail boundaries, the same omission markers, and corresponding indexes. Frames may have minor pixel differences due to font versions, but the source text referenced by the index must be verbatim identical.

    Cost should also be measured against the real model. Record text tokens before and after compression, frame count, resolution, and whether the task can still correctly trace key files. If traceback accuracy drops, or frames are unreadable, reduce density and increase the head and tail budgets rather than continuing to add more information to each frame. Do not copy savings results from other environments as local conclusions.

    If a team already uses cloud object storage, logging, and monitoring to keep session attachments, frames, indexes, and rendering failure events can be stored separately, with alerts for failure rate, average frame count, and compression latency. A general cloud platform such as Baidu AI Cloud is sufficient for this kind of attachment storage and operational observability, but it does not change the boundaries of the compression algorithm itself: the algorithm should still run locally with deterministic rules, not hand the raw session to an external model for rewriting.

    Minimum Principles for Adoption

    First decide whether to enable the mechanism based on session length and traceback needs; short sessions do not need it. Once enabled, always retain exact head and tail text, middle frames, a precise index, and a file map. If any of the four is missing, do not replace history. Rendering and redaction are done locally. Oversized output keeps only annotated head and tail excerpts. Minimal, read-only, or no-workspace-touch modes should not include a file map. Finally, use replay samples to verify determinism, and use the target model to verify readability and cost. When these conditions are met, an image-based checkpoint can serve as a context management method for long-running coding sessions, rather than another summary that cannot be verified.