omp packages

pi-image-context-trimmer0.7.0

Reduce repeated image uploads in stateless Pi conversations.

terencel Published 2 days ago MIT ~1.2K downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

pi-image-context-trimmer

English | 简体中文

Reduce repeated Base64 image uploads in Pi without discarding active visual evidence. Historical images become recoverable references when trimming is worthwhile.

Installation

Package version: 0.7.0.

pi install npm:pi-image-context-trimmer

Try the latest source without changing global settings:

git clone https://github.com/yoonshilee/pi-image-context-trimmer.git
cd pi-image-context-trimmer
npm ci --ignore-scripts
pi -e ./src/index.ts

Requires Pi with context_with_system (tested with 1.6.0). Supports vision-capable stateless openai-completions, openai-responses, and anthropic-messages APIs. SDK hosts explicitly using openai-codex-responses over SSE can load pi => imageContext(pi, { codexTransport: "sse" }) through extensionFactories. Native incremental/WebSocket transports and sessions without the recall tool are bypassed. Core-only hosts must integrate the context transformation and image lookup from src/image-context.ts themselves.

What it does

  • Preserve evidence: keep distinct active-task images by default; deduplicate exact copies and replace eligible completed-task images with SHA-256 references. recall_context_image can restore the original from the current session branch.
  • Automatic preview grouping: provide a session-specific preview workspace for native read and accept explicit disposable image groups from custom tools, without path or tool lists. Only a newer batch in the same group can make an earlier processed preview eligible for trimming; separate groups, user attachments, independent images, and explicit recalls remain visible.
  • Protect cache: compare ordered content-block prefixes and estimated cache-rebuild costs with future read savings. Trim economical historical suffixes rather than rewriting every image at once, including when projected pricing tiers differ. Inspired by SoL-Pi.
  • Bound traffic: enforce per-request and cumulative deferred-Base64 budgets; context-window pressure overrides deferral. Optional request image targets offload older processed tool images in batches while preserving protected evidence.
  • Optional artifact manifest: register managed image and non-image files, then publish a per-session JSON manifest with archive, delete, or upload intents after each settled run. Any integrating program can read it; the extension never performs file disposition. See the artifact manifest integration reference.
  • Coordinate compaction: defer automatic threshold compaction when the trimmed context safely fits, without intercepting manual compaction or overflow recovery.

No external image storage, persistent history edits, or extra summarization requests are introduced. Single-image resizing remains Pi's responsibility (inputLimits.images.resize).

Configuration & statistics

Defaults in ~/.pi/agent/image-context-trimmer.json (or the configured Pi agent directory):

{
  "enabled": true,
  "display": "summary",
  "cacheAware": true,
  "cacheHorizonRequests": 4,
  "maxDeferredBase64Bytes": 1048576,
  "maxCumulativeDeferredBase64Bytes": 4194304,
  "compactionGuard": true,
  "maxRequestImages": 0,
  "maxRequestImageBytes": 0,
  "imageOffloadCountQuantum": 5,
  "imageOffloadByteQuantum": 2621440,
  "artifactManifest": false
}

cacheAware: false or a zero byte budget gives bandwidth-first trimming. The assumed horizon is not a forecast. The cumulative budget resets after eligible history is fully trimmed or the cache/session context changes; the statistics remain cumulative. SDK hosts may override configPath.

For native tools, Trimmer creates ~/.pi/agent/image-context-trimmer/sessions/<session-id>/previews/ when an eligible run starts with read enabled, and gives the agent the actual path in the system prompt. Each first-level subdirectory is a separate replaceable preview group (for example desktop/ and mobile/); the agent can choose names and freely create multiple files within a group. Use each group only for disposable iterations of the same view. Keep references, independent pages, comparisons, and deliverables elsewhere. Root-level images, failed or nested reads, unavailable files, escaped or aliased group paths, and unsupported path aliases are not grouped. The extension creates directories, never moves, overwrites, or deletes files. If the workspace is unavailable, conservative image handling continues. SDK hosts may supply previewBaseDir (the parent of the session-ID directories) when tools use an isolated accessible filesystem. With a custom configPath, the default workspace is relative to the configuration directory.

Direct-image tools can explicitly opt into disposable preview grouping by including details: { imageContextTrimmerReplaceablePreviewGroup: "desktop" } with the returned image. Only use this field when a subsequent iteration can replace the earlier image; choose a stable nonempty group identifier. Groups are isolated per tool, independently of native read groups. Without the declaration, an image retains its ordinary lifecycle. Pending, failed, and parallel batches remain protected, and cache and bandwidth policies still apply.

Upgrade: remove replaceableReadPaths, replaceableReadDirs, and replaceableImageTools from existing configuration files. These keys are no longer used; other settings remain effective. The old imageContextTrimmerPreviewGroup metadata field is not a standalone authorization to replace images and is no longer used. Custom tools should adopt the new field only for disposable previews. No image grouping declaration grants permission to dispose of a physical file.

maxRequestImages and maxRequestImageBytes are optional per-request targets (0 disables each). After ordinary lifecycle and cache decisions, the oldest eligible retained images are replaced with recallable references when the request exceeds a target. This can offload older processed tool images even outside declared preview groups, so comparisons may require explicit recall. Current-task user attachments, explicit recalls, failed or pending tool results, the latest batch in each recognized group, and the newest retained image take priority. Unidentifiable or unrecoverable images are never replaced. If protected evidence prevents meeting a target, the request can exceed it and the statistics card reports that outcome.

imageOffloadCountQuantum and imageOffloadByteQuantum batch additional replacements to reduce frequent prompt-prefix changes. Issued references remain stable across successful requests in the same loaded context unless an image becomes protected; branch, model or session changes reset the policy. For example, set maxRequestImages to 20 and maxRequestImageBytes to 10485760 (10 MiB of Base64 content). The budget can override cache deferral, so smaller requests do not necessarily cost less. Both targets are off by default.

Enable artifactManifest with dedicated absolute root and manifest directory paths, and explicitly register the managed files through a shared Pi event bus or allowlisted tool result metadata. See the integration reference for the versioned JSON contract, registration examples, session isolation, readiness checks and consumer responsibilities. A budget-only image omission does not establish automatic file deletion eligibility.

Command Effect
/trimmer status Show cumulative statistics since load.
/trimmer on / off Enable/disable trimming.
/trimmer display summary / display off Enable/disable automatic task cards.

Expand the native conversation card with Ctrl+O to inspect omitted bytes, image recalls, reported token usage/cache-read ratio, estimated break-even, deferred bytes, and compactions. Cards never enter the model context. Commands apply to the loaded session; they do not edit the config file.

Validation

npm run check passes type checking and 86 unit and Pi 1.6.0 SDK integration tests, including native-only zero-path-configuration grouping, session isolation, prompt override compatibility, image recall, request budgets, and artifact authorization.

Default-configuration preview comparison (0.7.0)

2026-12-02 · Pi 1.6.0 · stateless OpenAI-compatible HTTP/SSE with a deterministic local mock model. Each arm runs the same 15-request Bash/read and custom preview workflow using 11 distinct frozen Chromium-rendered PNGs. Neither plugin version has user-configured preview paths or tool lists; both use default cache economics and the new request image targets remain off. The new version creates its workspace automatically and recognizes the custom tool's explicit disposable groups. All six trials retain all 11 original session images and pass 71/71 required-image presence checks in actual serialized requests.

Default-configuration preview benchmark: no extension, 0.6.0, and 0.7.0

Cache condition Metric No extension 0.6.0 0.7.0
Cold Cumulative Base64 bytes 6,473,364 6,473,364 5,384,916
Cold Serialized request bytes 6,615,307 6,623,617 5,544,616
Cold Image blocks 85 85 71
Simulated warm Cumulative Base64 bytes 6,473,364 6,473,364 6,473,364
Simulated warm Serialized request bytes 6,615,307 6,623,617 6,633,532
Simulated warm Image blocks 85 85 85

Cold-cache Base64 is 16.81% lower than the preceding version at default configuration; this does not establish a benefit over manually configured 0.6.0. In the simulated warm-cache workflow the default policy defers the newly eligible replacements, so Base64 is unchanged and workspace guidance adds JSON overhead. The optional request budget is verified separately: in an eight-request SDK workflow with simulated warm cache, enabling the image-count target reduced Base64 from 230,040 to 172,256 bytes while preserving the tested attachments and recall. The target is not a hard limit on protected evidence. Artifact tests verify that no files are physically modified or deleted, and unauthorized tool metadata cannot register file intents. These results are serialized-request and local correctness measurements, not real-model adherence, visual accuracy, actual network traffic, provider cache behavior, billing, or sandbox storage reclamation.

Contributing

See the contribution guide for local development, testing, and submitting pull requests.

MIT.