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

opencode-middleware

v0.1.2

Published

Composable middleware pipeline for OpenCode subagent tasks

Readme

Middleware

An OpenCode plugin that wraps subagent task execution with composable middleware. Middleware is declared on the agent being executed, not the caller. It shapes input before the task runs and output after it completes.

How It Works

The plugin registers two hooks with OpenCode:

  1. tool.execute.before — fires before a task tool executes

    • Reads the agent name from args.subagent_type
    • Looks up which middleware the agent declares
    • Runs before hooks sequentially (outside-in: A → B → C)
    • Before hooks can mutate args to shape the task's input
  2. tool.execute.after — fires after a task tool completes

    • Looks up the middleware established during the before phase (correlated by callID)
    • Runs after hooks sequentially in reverse order (inside-out: C → B → A)
    • After hooks can mutate title, output, and metadata

For middleware declared [A, B, C] on an agent:

A.before → B.before → C.before
      ← task executes →
C.after → B.after → A.after

Callers never know middleware ran. They see the final output.

Writing Middleware

Each middleware is a .ts file with a default export containing optional before and after hooks:

export default {
  after: async (ctx, result) => {
    const checks = (ctx.config.checks ?? []) as string[]
    const findings = checks.map((check) => ({
      check,
      mentioned: result.output.toLowerCase().includes(check.toLowerCase()),
    }))
    const passed = findings.every((finding) => finding.mentioned)
    const summary = passed ? "All checks passed." : "Some checks missing."
    result.output = summary + "\n\n" + result.output
  },
}

The filename becomes the registry key. auditor.ts registers as "auditor".

Hook Signatures

interface MiddlewareModule {
  before?: (ctx: MiddlewareContext, args: { args: unknown }) => Promise<void>
  after?: (ctx: MiddlewareContext, result: { title: string; output: string; metadata: unknown }) => Promise<void>
}

Both hooks mutate their second argument in place.

ctx carries:

  • client — the OpenCode SDK client
  • session.id — the OpenCode session ID
  • subtask.agent — the agent being executed (e.g., "red")
  • subtask.prompt — what the agent was asked to do
  • config — per-entry config from agent frontmatter

What Middleware Can Do

Before hooks shape input:

  • Inject additional instructions into args
  • Throw to abort execution

After hooks shape output:

  • Append audit results or summaries to output
  • Rewrite the title
  • Attach metadata

Configuring Agents

Middleware is declared in agent frontmatter under options.middleware:

# red.md
---
description: Write one failing test
mode: subagent
options:
  middleware:
    - run: auditor
      config:
        checks:
          - aaa
          - single_test
---
  • run — middleware name, resolved from the registry by filename
  • config — arbitrary config injected as ctx.config
  • Order matters — determines before/after execution order

Directory Layout

Middleware files live on disk. By default, the plugin scans ~/.config/opencode/middleware/.

Directories are scanned recursively — organize middleware into subdirectories as you see fit:

~/.config/opencode/middleware/
  auditing/
    auditor.ts        → registered as "auditor"
    compliance.ts     → registered as "compliance"
  distilling/
    distiller.ts      → registered as "distiller"
  learner.ts          → registered as "learner"

The filename (without .ts) becomes the registry key regardless of subdirectory depth. Duplicate basenames across subdirectories are an error.

To scan additional directories, create ~/.config/opencode/middleware.json:

{
  "directories": [
    "~/.config/opencode/middleware",
    "/path/to/project/middleware"
  ]
}

directories replaces the default entirely. Include the default path if you still want it scanned.

Local Setup

npm install
npm test                    # unit tests
npm run test:integration    # unit + integration tests
npm run build               # compile to dist/

Register with OpenCode

Add the plugin to your project's opencode.json:

{
  "plugin": ["/absolute/path/to/middleware"]
}

OpenCode runs on Bun, which imports TypeScript directly — no build step needed for local use.

Examples

The examples/ directory contains working samples:

  • examples/middleware/auditor.ts — after hook that checks output against configurable criteria and prepends an audit summary
  • examples/middleware/tag.ts — after hook that appends a configurable label to output
  • examples/agents/red.md — agent frontmatter declaring middleware with per-entry config
  • examples/opencode.json — plugin registration
  • examples/middleware.json — config override pointing at the examples directory

Architecture

src/
  index.ts           — entry point (default export, wires production deps)
  chain/
    runner.ts        — BeforeHook, AfterHook, MiddlewareModule, runBefore, runAfter
    builder.ts       — ChainEntry, buildChain (binds config + context to hooks)
  registry/
    registry.ts      — Registry, createRegistry (name → MiddlewareModule lookup)
  loader/
    loader.ts        — FileSystem, ModuleLoader, loadMiddleware (directory scanning)
    config.ts        — ConfigFile, MiddlewareConfig, readConfig
  plugin/
    hook.ts          — createMiddlewareHooks (before + after handlers, callID correlation)
    agent-provider.ts — createAgentProvider (agent name → middleware config)
    plugin.ts        — createPlugin (top-level wiring)
  platform/
    node.ts          — Node.js implementations of FileSystem, ModuleLoader, ConfigFile

PluginDependencies (FileSystem, ModuleLoader, ConfigFile) are injected interfaces. Production implementations in src/platform/node.ts wrap Node's fs.readdir, import(), and fs.readFile. Tests substitute fakes.