npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

hffmnnj.cache-protect

v0.3.0

Published

<p align="center"> <img src="https://unpkg.com/[email protected]/assets/banner.png" alt="Cache Protect: a dark vintage kitchen with a lit gas burner, kettle, and brass clock, captioned 'Keep the warm window safe.'" width="100%"> </p>

Readme

opencode-cache-protect

An OpenCode V2 execution guard that keeps a stale subagent wake from unnecessarily forcing a provider to rebuild a warm prompt cache. It blocks native subagent resumes, new session.prompt admissions, and context and compaction model dispatch when a child's last verifiable execution activity is more than 295 seconds old. Exactly 295 seconds remains allowed. DeepSeek models use an extended 12-hour window instead of 295 seconds. Official openai sessions and identified primary sessions are fully exempt.

A rejected native tool call tells the orchestrator to spawn a fresh worker, omit sessionID, provide a concise handoff (goal, relevant findings, remaining work), and avoid interrupting or duplicating work that is still running. The plugin never spawns the replacement itself, interrupts a worker, deletes history, sends keepalives, or makes provider requests.

Built against OpenCode V2's 2.0.25 plugin API. The separate hffmnnj.prompt-cache package provides optional cross-provider context projection without replacing or changing the safety plugin.

Install

The guard is published as hffmnnj.cache-protect; its catalog ID is hffmnnj.cache-protect.

Add the package to the plugins list in your OpenCode V2 configuration, preserving existing entries:

{
  "plugins": [
    { "package": "hffmnnj.cache-protect" }
  ]
}

OpenCode loads the package's ./dist/index.js export. It watches configuration, so the plugin reloads without restarting the service.

If you previously loaded this checkout by directory, replace that entry with the npm package entry. Do not keep both: the old and new entries would register the same safety hooks twice.

The guard's former opencode.cache-protect runtime ID is not retained. It does not use plugin storage, so no persisted state is tied to the old ID and replacing the old entry is safe.

For local development, build the checkout with bun install --frozen-lockfile and bun run build, then use the checkout's absolute directory as a package entry. The directory's index.ts loads the built dist/index.js.

To disable it, remove only this plugin entry from the current configuration. Do not restore an entire old configuration over concurrent changes. If you also added matching orchestrator guidance, update it to match the 295-second cutoff and no-keepalive policy, or remove it separately.

What it guards

  • tool.hook("execute.before") checks native subagent calls that include an existing input.sessionID. A fresh spawn without that field passes through unchanged.
  • session.hook("prompt") checks direct messages to child sessions, including prompts issued internally by the native executor. A fresh child's initial prompt is allowed.
  • session.hook("context") checks model-request context preparation. Native retries of already-admitted prompt IDs skip the prompt hook but still wake execution; this check prevents a stale pending prompt from reaching the provider.
  • session.hook("compaction") checks compaction requests, which can run before primary context. Neither dispatch hook counts its own attempt as activity.
  • Successfully identified primary sessions (no parentID) are not age-restricted. Unreadable or malformed target metadata cannot be classified as primary and fails closed.
  • Official openai provider sessions are exempt from the stale-child cutoff. This exemption does not disable the single-main-server safeguard or broaden diagnostic access.
  • DeepSeek models are exempt from the 295-second cutoff for up to 12 hours of inactivity. Detection matches the session's providerID and model ID case-insensitively (for example deepseek-chat or a routed DeepSeek/deepseek-reasoner); past 12 hours the normal stale rejection applies. This does not disable the single-main-server safeguard or broaden diagnostic access.
  • Every check shares one 2,000 ms lookup deadline across its metadata and context reads, with cancellation. Missing, malformed, future, or unreadable required timestamps/history block admission or dispatch rather than silently admitting a potentially stale resume.
  • The safety hooks do not modify inputs, replace the executor/schema, or alter permissions. Other native and plugin hooks remain in control.

Activity evidence

Activity is derived on demand from native persisted state, with no private activity store or live-only subscription:

| Native evidence | Use | | --- | --- | | Session.Info.time.created | Initial baseline, including a child's first prompt | | Assistant time.created | Native model step dispatch timestamp projected from session.step.started | | Assistant time.streamed / time.completed | Provider-body completion / step settlement | | Assistant tool time.ran / time.completed | Tool call / settlement during a running step; aborted settlement completion is excluded | | Completed compaction time.created, only when tokens.output is positive | Model-backed auto-compaction (a real provider call) |

The latest valid checkpoint wins. time.idle is never activity, regardless of outcome: both a denied execution and a successful delivered-ID empty wake can advance it without a model call. Native wake/reopen can also mark abandoned tools aborted without executing them again, so those completion timestamps are ignored. Recent real model/tool work remains eligible even with an old terminal idle timestamp. time.updated, viewed, titles, reads, user/synthetic messages, compaction controls/summaries without model output, tool-input construction timestamps, and the plugin's own setup/attempt times do not refresh activity. Reloading the plugin or reopening the host reconstructs the decision from native checkpoints, not a new initialization time.

Status snapshot

Discover cache_protect_status in Code Mode, then call its returned path with {} for the caller or { "sessionID": "ses_..." } for a verified descendant. Siblings, ancestors, unrelated targets, malformed metadata, and lookup failures return a sanitized unverifiable result without target details.

The tool returns status (allowed, stale, exempt_openai, exempt_primary, or unverifiable), policy (the fixed durable_meaningful_activity label), and cutoffMs (the effective cutoff: 295 seconds normally, 12 hours for DeepSeek); applicable decisions include activityAgeMs. Stale and unverifiable results include a concise fresh-worker handoff. It shares enforcement's calculation and 2,000 ms lookup deadline, and descendant checks are bounded to 32 ancestry levels. It never refreshes activity, messages a session, or makes provider requests. A status is a snapshot, not an admission reservation or override; inspecting or externally running background work never extends freshness.

Expired-session recall

A blocked stale resume loses the worker's transcript. When that history matters, the orchestrator tells a fresh subagent to call session_history_recall (Code Mode only, so it is never in the default tool list) for the expired session. The fresh worker gets one bounded digest and returns a short distillation; the orchestrator's own context never absorbs the transcript.

The blocked-resume message and cache_protect_status guidance name the tool and the target session, and state that the orchestrator must not call it itself. Guardrails keep it from bloating context:

  • Subagents only. Primary sessions are refused with instructions to delegate.
  • Expired targets only. The target must be stale (past the applicable cutoff: 295 seconds, or 12 hours for DeepSeek) and a sibling or descendant under the caller's orchestrator. Warm sessions (resume them), strangers, and the caller itself are refused.
  • One specific question. question (8–400 characters) is required. The digest is the session's task, latest outcome, any compaction summary, a tool tally, and at most five passages ranked by the question's terms, quoted as data, not instructions.
  • Hard caps. 6,000 characters by default (maxChars 1,000–12,000), at most 3 calls, 2 per target, and 20,000 characters per calling session; parallel calls are refused. Counters live in plugin memory and reset on reload.
  • It reads only session.context (history since the latest compaction, plus its summary), never writes, and reports native failures without their messages. Use the bundled skill below for older history.

Bundled skill

The plugin registers the searching-session-history skill, which searches full session history (including pre-compaction messages and subagent sessions) through the running server's read-only HTTP API with a bounded script. It needs OPENCODE_SERVER_PASSWORD in the shell's environment and is run with the shell tool. If you keep a local copy of the same skill, remove one of them.

Single-main-server safeguard

The default entrypoint verifies that the plugin process owns the managed OpenCode server before any tool execution and before the prompt, context, compaction, generate, and title session hooks.

On Linux, it compares process.pid with the MainPID of the fixed opencode-web-v2.service user unit through /usr/bin/systemctl (5 s timeout, 128-byte output cap).

On Windows, it reads the managed service registration from $XDG_STATE_HOME/opencode/service.json (or ~/.local/state/opencode/service.json). It accepts only loopback HTTP registrations for 127.0.0.1 or [::1] with no URL credentials, path, query, or fragment. When the registration carries a password, it authenticates the /api/info probe with HTTP Basic authentication and rejects redirects; the advertised PID and version must match the registration, and the registered PID must equal the plugin process. The registration probe has a one-second deadline and fails closed on missing, invalid, unreachable, or mismatched registrations. Registration credentials are never logged. Other platforms retain the fixed systemd-user-unit check. Standalone hosts, non-loopback registrations, and otherwise unregistered hosts remain blocked by design.

Both lookups share one in-flight call and cache a successful match for at most five seconds. A failed lookup within five minutes of a successful verification remains allowed, because a busy host can stall the lookup; a definite PID mismatch blocks immediately and clears that grace. Lookup failure outside the grace period or a mismatch denies with a sanitized Tool.Error.

Its shell pre-check rejects commands that would launch an OpenCode CLI (opencode, opencodev2, or opencode2, including .exe) directly or through common wrappers, including an unresolved $CLI; ordinary file and path arguments remain allowed. On Windows, a line-oriented scan additionally recognizes direct PowerShell invocation forms, including the Desktop opencode-cli.exe and .cmd or .bat launchers; it does not interpret arbitrary scripts or dynamically generated commands. Unsupported or ambiguous forms fail closed.

Heredoc boundary: quoted bodies (for example python3 - <<'PY', node <<'JS', cat <<'EOF') are data and stay allowed, including any $(...) or backticks inside them. In unquoted bodies, only $(...) and backtick expansions are checked. Heredocs that feed a shell (bash <<'EOF', cat <<'EOF' | bash) are checked as shell code, while a non-shell consumer under bash -c (for example bash -c "cat") with a quoted body stays allowed. An actual OpenCode command before or after a heredoc still blocks.

It is an accidental-execution safeguard, not an interpreter or hostile-code sandbox, and not isolation from other processes running as the same user. Encoded or interpreted programs and other process-launch paths remain outside the classifier's boundary.

Limits

  • Execution boundary. This is an execution guard at native tool, prompt-admission, and context and compaction request hooks, not an isolation or security boundary against arbitrary plugins, direct storage writes, shell/HTTP injection, or auxiliary APIs such as transient generation that do not invoke those hooks.
  • Admitted retries. An already-admitted prompt ID retry can still return its original admission and cause native wake, inbox promotion, and terminal/idle transitions. The dispatch guard prevents a stale child provider request; it does not undo previously admitted history or turn the retry API into a typed rejection. Repeated retries, including successful empty wakes, do not refresh freshness.
  • Checkpoint granularity. It measures native durable execution checkpoints, not every streaming token. Before the native host publishes a model step (which can be deferred until the first provider output), only earlier persisted activity is available. A long request with no newer durable checkpoint can have additional sends conservatively rejected. The running request itself is never interrupted. Do not automatically duplicate ongoing work.
  • Compaction visibility. Native context omits history before the latest completed compaction. A completed compaction counts at its creation time only when tokens.output is positive; a hook-supplied or control summary without output tokens never counts. Creation time can only under-state recency. A plugin that supplies output tokens can still count, because plugins are trusted in-process code and the guard targets accidental stale resumes. If no checkpoint is visible, the guard falls back to creation time.
  • Rejection surfaces. Rejection text is model-visible in the native tool result. In V2 2.0.25, throwing from the direct prompt admission hook is mapped by the HTTP adapter to a generic ClientError: UnexpectedStatus: 500; the actionable Tool.Error text is not preserved by that adapter. A rejected new admission fails before inbox insertion or a model request. Dispatch-hook failures instead settle the awakened execution as failed, before primary step creation/provider dispatch.
  • No cache guarantee. This does not guarantee any provider's prompt-cache retention, billing behavior, or cache hit rate.
  • Plugin composition. Composition with other plugins uses native hook registration, not executor replacement. Compatibility was reviewed statically for a workstreams-style wrapper; combined delegation against a paid provider was not exercised.

Prompt-cache projection

The separate, optional hffmnnj.prompt-cache package registers the stateful runtime ID opencode.prompt-cache. It does not move, replace, or alter the safety plugin. A local prompt-cache/ checkout remains usable after bun run build:prompt-cache.

Load it as its own plugin entry after all context-producing plugins, including Goals, Memory, Clef, and any other plugin that injects transient context:

{
  "plugins": [
    { "package": "[email protected]" }
  ]
}

Keep exactly one prompt-cache entry; two copies would both project the same snapshots and duplicate the policy part. Its projection uses the 2.0.32 message-constructor submodule, bundled into its output. Do not externalize the entire AI package here: loading its provider graph can pull incompatible runtime internals into the plugin sandbox. Existing safety dependencies remain pinned.

On primary requests for every model provider, it keeps earlier Goals, Memory, and Clef context snapshots in their original positions and appends changed snapshots. Unchanged payloads are not repeated; the latest revision for each source supersedes older ones. All current payloads and refresh behavior remain available. Retention is intentional and can grow context faster, which may cause earlier compaction. Eligible primary requests always carry exactly one copy of the instruction that snapshots are quoted task data, not instructions, even before the first snapshot appears or after all sources are suppressed; a failed storage read leaves the request untouched.

Native plugin storage retains injected snapshot text, canonical-history hashes, and the request's system hash and model identity. It does not retain a duplicate of the authored conversation or tools. Compaction and genuine model/system/history changes reset the projection; inactive sources are removed to preserve suppression and disable behavior. Auxiliary requests are unchanged. OpenAI storage keys remain compatible; every other provider's state is provider-qualified so identical model IDs cannot share snapshots. No wire hooks, explicit cache fields, warming, retries, TTL overrides, or cache keys are introduced.

Projection can be restricted with options.sessions, an array of exact session IDs:

{
  "package": "[email protected]",
  "options": { "sessions": ["ses_..."] }
}

Omitting this option enables all eligible sessions; an invalid option disables projection. Diagnostic logs contain session/model identity, snapshot counts, reset state, or a fixed storage-failure category, never prompt text or credentials. resetReasons distinguishes directly observed model, system, shortened/changed history and producer changes; reset events also report fixed-cardinality resetCounts since plugin setup. Multiple reasons can coexist. See the projection package for the exact labels and limits; these are projection decisions, not provider cache-miss measurements.

Intentional instruction or catalog changes, compaction, account switches, and provider expiry can still invalidate caches; the projection does not promise cache hits. Actual reuse must be established with ordinary real-work usage; local continuation tests are not evidence of server cache reuse. Explicit checkpoints are deliberately not used. Goals usage counters belong in the full Goals tool response, not the injected request tail; otherwise every tool step creates a new snapshot without changing task state. The cross-provider audit and acceptance scope are in docs/SPEC.md.

Validate the watched artifact in the actual V2 plugin catalog and native requests; a plain Bun import is not an equivalent plugin-loading test.

Development

Dependencies are pinned. Run these from the checkout:

bun install --frozen-lockfile
bun run typecheck
bun test tests/unit
bun run build
bun run check       # typecheck, deterministic unit tests, both local builds
bun run test:host   # real isolated SDK 2.0.25 native host
bun test            # full plugin suite, after build

bun run check builds the safety entrypoint (dist/index.js), the local projection artifact (dist/prompt-cache.js), and the separate package's bundle and revisioned watch entrypoint (prompt-cache/dist/index.js and prompt-cache/index.ts).

The host test launches a child process with isolated HOME/XDG/config/database paths under a per-run temporary directory outside the checkout. Its only configured provider is a loopback scripted server with a synthetic key. It disables built-in providers and model fetching/snapshots; it does not borrow credentials or make paid calls. Scripted provider requests exercise the real native schema, executor, prompt/context hooks, history, inbox, permission filtering, and package loader. Regressions include stale pending-ID wake, repeated denied/empty wakes, host reopen, and a delivered-ID no-op wake followed by a rejected new stale prompt. Hosts and loopback servers are closed in finally; isolated evidence directories are retained rather than recursively deleted.

registerCacheProtect exposes an internal injected clock for deterministic tests. This is not a user configuration override; the shipped default always uses Date.now() and the fixed cutoff.