No description
  • TypeScript 100%
Find a file
2026-10-25 18:43:54 +00:00
test Run in RPC mode and publish plain-text status for host UIs 2026-10-25 18:43:54 +00:00
.gitignore Add Pi cache-expiry status extension with provider overrides 2026-10-23 18:11:54 +00:00
cache-expiry.ts Add Pi cache-expiry status extension with provider overrides 2026-10-23 18:11:54 +00:00
index.ts Run in RPC mode and publish plain-text status for host UIs 2026-10-25 18:43:54 +00:00
package.json Add Pi cache-expiry status extension with provider overrides 2026-10-23 18:11:54 +00:00
README.md Run in RPC mode and publish plain-text status for host UIs 2026-10-25 18:43:54 +00:00
tsconfig.json Add Pi cache-expiry status extension with provider overrides 2026-10-23 18:11:54 +00:00

Pi cache expiry

A small, dependency-free runtime extension for Pi coding-agent 1.4.0. Publishes cache-expiry through ctx.ui.setStatus() without replacing the footer. Works with Pi's native footer and compatible status consumers, including ZenTUI.

CE: 05:00
CE: 00:15       # theme error colour at <=5% remaining
CE: expired    # stays in the error colour until another eligible response

Times use MM:SS, or H:MM:SS from one hour. Seconds round up; the 5% threshold uses unrounded remaining time. The theme's semantic error colour is normally red, but custom themes or footer recolouring can change it.

This is a completed-response estimate, not a server cache-expiry guarantee or evidence of a cache hit. It is hidden before the first matching successful response, for unknown/disabled/infinite lifetimes, and for excluded providers unless explicitly enabled.

Install

With Pi already installed:

pi install /absolute/path/to/cache-warning

This registers the local directory without copying it. Restart Pi or run /reload. To try it without saving package settings, run from this directory:

pi -e ./index.ts

There is no runtime npm installation or ZenTUI dependency. Do not load both the package and the entry file separately.

Optional global configuration

The extension reads join(getAgentDir(), "cache-expiry.json") at interactive session_start, including /reload. Normally this is:

~/.pi/agent/cache-expiry.json

PI_CODING_AGENT_DIR changes the directory, for example PI_CODING_AGENT_DIR=/my/pi selects /my/pi/cache-expiry.json. It uses Pi's exported getAgentDir(), not the working directory or a hard-coded home path. An SDK's separate agentDir option is not exposed by that function; use the environment variable to keep the paths aligned.

Example:

{
  "providers": {
    "anthropic": 3600,
    "some-provider": 300,
    "openai": null,
    "openai-codex-2": 300
  }
}
  • Keys are exact, case-sensitive provider IDs, not model IDs. No per-model configuration.
  • Values are positive finite numbers in seconds, including fractions, or null to hide. Zero, negatives, strings and infinity are invalid.
  • A provider override always wins, even over metadata, tier selection and automatic exclusion. Thus the last example explicitly enables a normally hidden Codex variant.
  • The file must be a JSON object containing only a providers object. {"providers":{}} uses automatic inference.
  • Missing file: silently infer defaults. Invalid JSON/schema or an unreadable file: warn once per extension runtime and infer defaults for the entire file. /reload creates a new runtime, so it can warn again.
  • Configuration is never created or modified. Edit it yourself, then /reload.

Inference precedence and boundaries

After an exact provider override:

  1. Hide OpenAI/Codex providers and ordinary -/_ variants (including openai-codex-2), Azure OpenAI providers, Codex/Azure Responses APIs, and official api.openai.com/chatgpt.com hosts.
  2. Hide known local provider names: llama.cpp/llama-cpp/llamacpp, Ollama, LM Studio, vLLM, SGLang, local/LocalAI, Jan, GPT4All, KoboldCpp and text-generation-webui, with ordinary -/_ suffixes. Also hide localhost/.localhost, IPv4 127/8, IPv6 ::1, IPv4-mapped 127/8, and wildcard bind addresses.
  3. Infer long only when PI_CACHE_RETENTION === "long"; otherwise infer short. For the Anthropic Messages API, explicit compat.supportsLongCacheRetention: false forces short.
  4. Use ctx.model.promptCache[the inferred tier] in seconds when present. Non-positive, non-finite or otherwise invalid values hide the status rather than falling back.
  5. With missing tier metadata, the native anthropic provider or an Anthropic Messages model at the exact api.anthropic.com host falls back to 300 seconds short / 3600 seconds long. Other Anthropic-compatible gateways do not get that fallback.
  6. Everything else is unknown and hidden. Metadata for only the other tier is not sufficient for an unknown provider.

An openai-completions API alone is not excluded: hosted providers can declare their own promptCache. Detection is deliberately small and name/host based, not a comprehensive provider registry. It does not identify arbitrary renamed OpenAI/local providers, private-network services, or DNS aliases resolving to loopback. Conversely, a provider deliberately named openai-* is excluded. Use an explicit override when these boundaries do not fit your setup. The native anthropic provider name is trusted even if its URL has been customised; unknown gateway provider names are not.

Estimate limits

Public extension hooks do not expose the effective typed per-request cache-retention options. This extension does not scan or interpret provider payloads. Environment plus model metadata cannot establish whether a request actually used caching, overrode retention to none/another tier, used request-local environment values, or had a cacheable prefix. PI_CACHE_RETENTION=none is not a disabled setting here: like Pi's environment fallback, only the exact value long selects long, all other values select short. Use null to hide a provider.

Successful assistant message_end events (stop, length, toolUse) anchor to Date.now(). Errors, aborts, pending and deferred records do not refresh it. A response must match the selected provider, model ID and API before starting its countdown. A different response model reported by the server does not substitute for the requested model ID.

Startup/resume/reload, session_tree, and model_select restore the latest successful matching assistant on the active branch, not all session entries. Restored completion is message.timestamp + durationMs where available; legacy records use request-start timestamp, expiring conservatively earlier. Switching model never starts a fresh TTL. A bounded in-memory record of 32 recent completions preserves live completion estimates when restoring matching branch records during the same runtime. It is not persisted.

Messages do not record endpoint identity, so changing a URL while retaining the same provider/model/API cannot distinguish old and new caches. Background cache warming, server eviction, prefix changes, other clients, request duration and wall-clock changes can all make real expiry differ. This extension neither warms caches nor makes network requests.

One unreferenced timer starts only in interactive session_start; every second recomputes from the completion timestamp and TTL, so delayed ticks do not accumulate drift. Shutdown clears the timer and status idempotently. RPC mode behaves the same but publishes plain text (no colour codes) for host UIs such as the Pi sidebar. Print and JSON handlers return without configuration reads, history scans, timers or UI work.

ZenTUI

Checked against installed pi-zentui 0.32.0 source, not a private integration:

Open /zentui extensions after an eligible response. Set cache-expiry to a visible placement rather than Off, and colour to Original to retain the red warning. Discovery is best-effort; a hidden status may not appear until published. Native positive placements retain native positioning. Hidden and Starship keep separate colour preferences.

If editing zentui.json manually, merge the relevant leaves, preserving your other settings:

{
  "components": {
    "extensionStatuses": {
      "visibility": { "cache-expiry": "show" },
      "hidden": { "colorModes": { "cache-expiry": "original" } }
    },
    "footer": {
      "styles": {
        "starship": {
          "extensionStatuses": {
            "placements": { "cache-expiry": "right" },
            "colorModes": { "cache-expiry": "original" }
          }
        }
      }
    }
  }
}

Global/per-key visibility and the active footer's layout still control what is shown. Explicit colour customisation, third-party footers, narrow-width truncation, or a custom Pi error colour can prevent a visibly red status. This extension does not override those choices or publish a special ZenTUI protocol.

Development and verification

Node 22.19+ runs the TypeScript tests directly, with no test framework. Pi 1.4.0 is a development dependency solely for real API types/runtime checks; Pi supplies it when loading the extension.

npm install --ignore-scripts
npm run typecheck
npm test
npm pack --dry-run

Tests cover inference/overrides, config validation, model correlation, active-branch restoration, live completion anchors, formatting/thresholds, timer lifecycle and non-TUI inactivity. No credentials or model requests are needed. Visual integration depends on the active terminal/theme/footer; source compatibility and ANSI publication tests are not a guarantee for every user layout.