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

@reinsjs/server

v0.12.0

Published

reins — Web-standard (Request) => Response handler: runs the loop, streams the timeline as SSE, replays from lastSeq on reconnect

Readme

@reinsjs/server

A Web-standard (Request) => Promise<Response> handler around the reins loop. POST starts or resumes a run and streams the timeline as SSE (id: = event seq); GET replays from lastSeq and joins a run in progress. No framework, no private runtime dependency — written against Web standards only; verified on Node 22 and Cloudflare workerd (strictest compat, no nodejs_compat), Bun / Deno / Vercel Edge not yet tested.

pnpm add @reinsjs/server
import { createAgentHandler } from "@reinsjs/server"

export const POST = createAgentHandler(agentDefinition, {
  principal: (req) => verifyToken(req.headers.get("authorization")),
  authorizeSession: async ({ sessionId, principal, isNew }) => {
    if (!principal) throw new Response("unauthorized", { status: 401 })
    return isNew ? true : ownsSession(principal.id, sessionId)
  },
})

Node's http module needs a tiny adapter, which is the only place node:* appears:

import { nodeListener } from "@reinsjs/server/node"
createServer(nodeListener(handler)).listen(8787)

The umbrella package @reinsjs/agent wraps this as createAgent(...).handler with the AG-UI encoder as default; used directly, this package streams raw timeline events (rawEncoder).

Protocol

| request | body / query | behaviour | | --- | --- | --- | | POST | { input } | new session, id returned in the start frame and the X-Reins-Session header | | POST | { sessionId, input } | continue a session | | POST | { sessionId, resume, decisions } | resume a paused run with approval decisions (resume is the state from the result frame of the run that paused, or from the end frame of a replay — see below; a decision for a sub-agent's call carries sessionId: childSessionId) | | POST | { sessionId, stop: true } | the user pressed stop. Answers JSON { status: "stopping" | "idle", sessionId } right away (no stream). A run active in this process is aborted with RunStop and its stream still ends with the result frame; an idle session with pending calls gets a short run that only closes them as not executed; otherwise idle. Must not be combined with input / resume / decisions. Only runs of this process can be stopped | | POST | { sessionId, input, deliveryId? } while a run is active, with midRunInput: true | the message is queued into that run and answers JSON 202 { status: "queued", sessionId, deliveryId } (no stream); see "Messages during a run" | | POST / GET | lastSeq | replay (lastSeq, tail] first, then continue live. GET also honours the Last-Event-ID header (so a plain EventSource reconnects correctly); POST reads body.lastSeq only |

Frames: start, one frame per event, delta (optional streaming increments), result (the RunResult, including a signed state when paused), error. One run per session at a time: a second POST while a run is active answers 409 run_in_progress unless midRunInput queues it (see "Multiple instances" for what "active" means across processes).

Security defaults

  • authorizeSession is not optional in multi-tenant deployments. Without it, anyone who knows a sessionId can read that timeline and continue that run. Only an explicit true allows; false or undefined answers 404 (not 403, which would confirm the session exists). method is "GET", "POST" or "STOP" — a hook that allows writes only when method === "POST" therefore refuses stop requests until it names "STOP" too. decisions is the request's approval decisions as sent (empty for GET, STOP and requests without any).

  • Input is whitelisted twice. A POST body's input may be text, content parts, or a draft of type core.user_message or core.tool_result (the latter only for a pending client-side tool). Anything else — a forged approval_decision, a system_note claiming system trust, a compaction hiding history — is refused here with 400, and the loop keeps its own, slightly wider, whitelist as a second line (it is not reachable through this handler). An array input must be a non-empty list of text / image / video / audio parts (an image may be inline or a reference, see below, and its mime must be image/jpeg, image/png, image/gif or image/webp — the same check as isSupportedImageMime in @reinsjs/core: providers reject other types, and one written into a session would fail every later request); every part — and the content of a draft — is rebuilt from its known fields only, so extra fields never reach the loop. Arrays of event drafts (a host briefing plus a task, see @reinsjs/core) are for in-process hosts only and are refused here.

  • A replay hands back the resume state. When a replay-only stream ends (end frame, no run in progress) and the session's last event is the run's pause, the frame carries that pause's signed state — the same object the live result frame had — so a page reloaded, reopened or opened on another device can still approve. It is the state from the moment of the pause, never recomputed on read, so a tool changed afterwards still fails the check. The state is that of the latest pause, whatever its reason: after a resume the frame has none until the run pauses again, and a stop, a budget pause or an abort each end in a pause of their own. So a state alone does not mean "ask for approval" — draw an approval card only for the ids in state.pendingToolCallIds that have a core.approval_request in the replay (after a stop the list is empty). Two clients holding the same state cannot both act on it: while one resume runs the other gets 409 run_in_progress, afterwards 409 pending_mismatch. Every core.run_paused event carries its state, so an onEvent sink or a raw event stream forwarded to a third party carries these signed states too; older ones fail validation, but treat them like any other resume token.

  • Who may approve is your call. The handler checks that a decision points at a call waiting for approval, not who sent it; by is whatever the client wrote. When the approver is not the session's owner, refuse approvals from anyone else in authorizeSession, and keep allowing refusals — a client that sends a new message instead of approving rejects the call in the same request:

    authorizeSession: async ({ sessionId, principal, isNew, decisions }) =>
      (isNew || (await canTouch(principal, sessionId))) &&
      (!decisions.some((d) => d.approved) || isApprover(principal)),

    decisions includes entries addressed to sub-agent sessions (with sessionId), so a check over the whole array covers them too. It is a frozen copy: changing it does not change the run. A request may carry only one decision per call (400 otherwise). A client-side tool that also needs approval cannot have its result filled in while it waits for approval (409 approval_pending): the decision has to come through decisions first. Likewise, a client-side tool result is accepted only after a run has evaluated that call and paused for it: when the last run was aborted by the host (a dropped connection with onDisconnect: "abort", a lost lease) or paused for budget or by a Socket, calls later in the batch may never have been checked, so filling one in answers 409 call_not_evaluated. POST { sessionId } without input first; the run evaluates the pending calls again (asking for approval where needed) without calling the model, and the result can be filled in after that pause.

  • Resume is validated before anything is written. Signature (when secret is set) and the digest of pending tool calls must match the log, and the model and the definitions of the tools behind the pending calls must be unchanged (states from before 0.10 still compare the whole configuration hash); drift answers 409 config_mismatch unless the host passes allowConfigDrift. A request carrying decisions must carry resume as well (400 otherwise); the state is in the result frame of the paused run and in the end frame of a replay.

  • Session ids must be non-empty printable ASCII without spaces (400 otherwise).

  • Request bodies are capped at 16 MiB by default (maxBodyBytes). A larger POST answers 413 with { error: "payload_too_large", message } and is never parsed: a Content-Length over the limit is refused before a byte is read, and a body without one (or with one that understates it) is counted as it streams in and the read is cancelled once it passes the limit. One oversized request would otherwise take the whole process — and every other session on it — down. The check runs before authorizeSession, so it covers unauthenticated callers too; the principal hook runs before it.

  • Failures after the stream has opened arrive as a 200 with an error frame, and the run slot is released so the session does not stay 409 forever.

  • Approval decisions are checked against the right session. A decision without sessionId (or with this session's id) must point at one of this session's calls that is waiting for approval (pending, with an approval request and no decision yet), else 409 unknown_tool_call — the same check runLoop makes, so a pending call that never asked for approval cannot be approved in advance; a decision carrying a sub-agent's childSessionId is passed through untouched and checked by the sub-agent's own run.

Options

| option | default | meaning | | --- | --- | --- | | encode | raw events | StreamEncoderFactory; aguiEncoding() from @reinsjs/ui-agui | | deltas | true | forward streaming text/thinking deltas as delta frames. A stream that attaches to a run already in progress (GET) skips deltas until the next event, so it never receives the second half of a block whose first half it missed; that block arrives complete with its event | | heartbeatMs | 15 000 | SSE comment heartbeat; 0 disables | | maxBodyBytes | 16 MiB (DEFAULT_MAX_BODY_BYTES) | largest POST body in bytes; larger ones answer 413 payload_too_large unread (see "Security defaults"). A positive integer or Infinity (no limit). Images sent by reference keep bodies small; raise it only if you inline many images | | onDisconnect | "continue" | or "abort" the run when the client goes away | | principal(req) | — | who is asking; passed to the loop and tools | | authorizeSession(input) | — | whether they may touch this session (see above) | | onEvent(event, input) | — | side-channel observer: called once per event a run appends (see below) | | warn(message) | console.warn | where an onEvent failure is reported | | midRunInput | false | queue user messages that arrive while a run is active into that run instead of answering 409 (see below) | | runs | new InMemoryRunRegistry() | run registry — one run per session at a time. The default only knows this process; multi-instance deployments pass leasedRunRegistry(store.runLease) (below) | | newSessionId() | uuidv7 | id factory for new sessions |

Messages during a run

With midRunInput: true, a user who types while the agent is working ("only account A", "keep the budget under 100") does not have to wait for the run or stop it. The message goes into a per-run, in-memory mailbox, and the run writes it into the timeline right before its next model call (the pullInput semantics of @reinsjs/core). The draft carries provenance: { source: USER_DELIVERY_SOURCE, ref: deliveryId }; @reinsjs/ui-agui copies that onto the user message's TEXT_MESSAGE_START as metadata.reins.provenance.

Delivered means one thing: the timeline holds a core.user_message whose provenance.ref is your deliveryId. There is no list of undelivered messages in the result frame; whatever is still in the mailbox when the run ends is dropped.

A message is queued only when all of these hold: the body has sessionId and a user-message input (text, content parts or a core.user_message draft) and no resume / decisions; the session's run is active in this process, was started by a plain POST through a handler with midRunInput: true that shares this handler's runs, and has not been aborted; and the sender is the run's starter (same principal?.id, or both anonymous) — a run executes as the principal it started with, so someone else's words must not run under that identity. Otherwise the request takes the normal path, so the answer is one of:

| answer | meaning | what the client does | | --- | --- | --- | | 202 queued | in the current run's mailbox | watch the stream that carries the run; if it ends (result / error) without the message, it was not delivered. If the stream had already ended when the 202 arrived, it was not delivered | | SSE 200 | the run had just ended, so this message started a new run | read it like any POST; the message is the run's input, with the same provenance | | 409 run_in_progress | stopping or aborted, another instance, another principal, a stop clean-up run, a run started by a handler without midRunInput, or the instant between the run being registered and its mailbox opening | resend later, or tell the user | | 429 mailbox_full | 16 messages are waiting to be written | resend later |

  • Generate the deliveryId before sending and always send it with lastSeq (deliveryId: printable ASCII without spaces, at most 128 characters; it may be omitted, then the server makes one and returns it in the 202). A plain POST that starts a run carries it too, so every message is checked the same way. A retry with the same id is idempotent within one run; across runs, look for the ref in the events you already have before resending.
  • deliveryId belongs to user messages only. A core.tool_result filling in a client-side tool must not carry it (400); it is delivered when the timeline holds a result for its toolCallId, and resending it is safe — once written the call is no longer pending, so a duplicate is never written twice and answers 409 (unknown_tool_call, or run_in_progress while the run it resumed is still going).
  • A host that builds a handler per request (for example, tools assembled from per-session credentials) gets mid-run input as long as every handler is created with the same runs instance — the same requirement as for 409 and stop requests to work across them. createAgent from @reinsjs/agent builds a new registry on every call, so create one at process level (leasedRunRegistry(store.runLease) or new InMemoryRunRegistry()) and pass it as handler: { runs }; otherwise each call has its own and a mid-run message answers 409 — or, without a RunLease, starts a second run on the same session (which typically ends in seq_conflict).
  • Handlers sharing one runs form one trust domain: the receiving handler's principal and authorizeSession decide whether a message is accepted, while the run executes it with the starting handler's tools, log and onEvent. Share a registry only between handlers that use the same log, the same namespace of principal ids and the same authorization rules.
  • You need a stream attached to the run to see the message arrive: the POST that started it, or GET ?sessionId&lastSeq to reconnect.
  • If the stream ends with an error frame (for example a seq_conflict or a storage timeout while writing), whether the message was written is unknown: replay with GET and look for the ref before putting the text back in the input box.
  • Typical reasons a queued message is not delivered: it arrived after the run's last model call; the run paused (approval, budget, stop, maxTurns) or failed; it was aborted right after taking the message; it ended with a handoff (send to toSessionId instead); a resumed run's catch-up turn does not take new input. When the run paused for approval, send the undelivered text together with your decisions — only the client knows how to combine them; the handler never starts a run by itself.
  • Mid-run messages make runs longer: maxTurns and budgets are reached sooner, nothing resets them.
  • The mailbox lives in this process only: a crash loses undelivered messages (the client sees them missing and resends). Limit request body size at your gateway; the mailbox caps the count, not the size. authorizeSession sees method: "POST" for a queued message — a host that counts POSTs as runs counts these too — and onEvent keeps reporting the starting request's principal / request.
/** Send one message; the caller keeps the deliveryId (and reuses it when retrying). */
async function send(endpoint: string, sessionId: string, deliveryId: string, text: string, lastSeq: number) {
  const res = await fetch(endpoint, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ sessionId, input: text, deliveryId, lastSeq }),
  })
  if (res.status === 202) return { kind: "queued" } as const // watch the run's stream for it
  if (res.status === 200) return { kind: "started", stream: res } as const // a new run, read as usual
  if (res.status === 409 || res.status === 429) return { kind: "retry-later" } as const
  throw new Error(`send failed with ${res.status}`)
}

/** Delivered ⟺ the timeline holds the user message carrying this deliveryId. */
const delivered = (events: readonly Event[], deliveryId: string) =>
  events.some(
    (e) =>
      e.type === "core.user_message" &&
      e.provenance?.source === USER_DELIVERY_SOURCE &&
      e.provenance.ref === deliveryId,
  )

Images by reference

A user message (or a client-tool result) may carry { type: "image", mime, blobId } instead of inline data: put the raw bytes into the agent's BlobStore under the session's id first, then send the reference. The handler checks every reference before it queues a message during a run or starts a run, with the same function the loop uses (checkImageRefs from @reinsjs/core):

  • not this session's blob (and not already shown as an image in this session's timeline), no such blob, a mime that differs from the blob's, or no BlobStore → 400 with Blob <id> not found in this session — the same sentence for all of them, nothing written;
  • the BlobStore throws while checking → 503 storage_unavailable (try again), nothing written.

This pre-check only needs ownership and mime, so it calls BlobStore.stat(id) when your store has one (the in-memory, SQLite and Postgres stores do) and falls back to get otherwise. The run then reads each new image's bytes once. If your stat reads a separate index, write it together with the object: when the two disagree, the loop's check (which uses get) wins and the request ends in a 200 with an error frame instead of a 400.

The handler does not serve blob bytes. To show the pictures in your UI, add your own route, run your session check first (the same one as authorizeSession), and decide with blobUsableBy — comparing meta.sessionId alone would hide a parent's pictures in a forked session. registry is your event registry (createCoreRegistry()):

/** Raster formats only: an SVG opened from your origin runs its scripts there, with the viewer's credentials. */
const SERVABLE_IMAGES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"])

/** GET /images?sessionId=…&id=… — call it only after your own session check (the same one as `authorizeSession`). */
async function serveImage(log: EventLog, blobs: BlobStore, sessionId: string, id: string): Promise<Response> {
  const notFound = () => new Response("not found", { status: 404 })
  let blob: { bytes: Uint8Array; meta: BlobMeta }
  try {
    blob = await blobs.get(id)
  } catch (err) {
    if (err instanceof StoreError && err.code === "not_found") return notFound()
    throw err
  }
  const timeline = await readTimeline(log, sessionId, { registry })
  if (!blobUsableBy(sessionId, blob.meta, id, timeline)) return notFound()
  if (!SERVABLE_IMAGES.has(blob.meta.mime)) return notFound()
  return new Response(blob.bytes.slice(), {
    headers: {
      "content-type": blob.meta.mime,
      "cache-control": "private, max-age=31536000, immutable",
      "x-content-type-options": "nosniff",
      "content-security-policy": "default-src 'none'; sandbox",
    },
  })
}

Blob ids are never reused and bytes never change after put, so the response can be cached for good.

Keep the format check: blobUsableBy also accepts the session's own non-image blobs, such as spilled tool results, and sessions written before the image type allowlist (jpeg, png, gif, webp) may still reference an image/svg+xml blob. An SVG served from your origin and opened directly (a link, a new tab) runs its scripts with the viewer's credentials — for example an approver's, who could then be made to approve a pending call. Serve only raster formats from your origin, keep nosniff and the sandboxing content-security-policy, and if you must show SVGs, serve them from a separate domain that carries no credentials. With the default AG-UI encoding a client finds the ids in metadata.reins.parts of a user message or tool result (@reinsjs/ui-agui, "Images and other media").

Multiple instances

The run registry is what turns a second POST on a busy session into 409. The default InMemoryRunRegistry is a Map in this process, so two instances behind a load balancer can both start a run on the same session: the second one spends a model call and then fails with seq_conflict when it tries to append (the log stays correct — the seq check in the store is the last gate — but the call was wasted and the client sees an error frame instead of a clean 409).

To make the guard span processes, share a RunLease through the store. @reinsjs/store-pg provides one (pgStores() includes it; the reins_runs table, expiry decided by the database clock, not by each instance's own), and createAgent({ store }) installs it automatically when store.runLease is present. Using this package directly:

import { createAgentHandler, leasedRunRegistry } from "@reinsjs/server"

const runs = leasedRunRegistry(store.runLease, { ttlMs: 30_000 })   // one per process
createAgentHandler(agent, { runs })

How it behaves: POST acquires the lease before the run starts (held elsewhere → 409 run_in_progress); the run renews it every ttlMs / 3; if a renewal comes back negative — this process was frozen for longer than ttlMs and another instance took over — the run is aborted and returns paused(host) so it can be resumed; when the run ends the lease is released (a failed release only warns; the lease expires on its own). A crashed process therefore locks its sessions for at most ttlMs (default 30 s).

What it does not do: GET only joins runs in this process. A reconnect that lands on another instance replays from the log up to the current tail and ends (start.live === false); use sticky sessions if you need the live tail after a reconnect. Any RunLease implementation that passes runLeaseConformance from @reinsjs/core/testing works — the semantics (heartbeat, abort on loss, release) live in leasedRunRegistry, not in the store.

Observability

A run is an async generator. In-process, iterating agent.run() is observing it — every event is yielded the moment it is appended, so there is nothing to hook:

for await (const event of agent.run({ input })) log.info({ seq: event.seq, type: event.type })

Over HTTP the consumer of that generator is the handler itself, so it exposes the same stream as a side channel. onEvent is called once per event the run appends, in seq order, with the session id, the resolved principal and the originating Request — enough to attach a trace id or a user id to your own logs:

createAgentHandler(agent, {
  onEvent: (event, { sessionId, principal, request }) =>
    logger.info({ trace: request.headers.get("x-trace-id"), user: principal?.id, sessionId, seq: event.seq, type: event.type }),
})

It observes, it does not edit: the event is already in the log. Only live events are reported — replays (lastSeq, GET reconnects) are read back from the log and not observed again — and only this session's: a sub-agent started with asTool runs in its own session and does not pass through the handler. The hook never slows or breaks the run: the event is pushed to SSE subscribers first, async return values are chained in event order without blocking the loop, and a throw or rejection is reported once per run through warn. The run's result frame (and ActiveRun.done, hence a Worker's waitUntil) waits for the chain to settle, so the last observation is flushed before the run is declared finished. The flip side: a hook that never settles keeps the run open and the session 409 — wrap slow sinks in your own timeout.

Documentation

docs/archive/implementation-plans/2026-09-08-技术方案v1.0.md §12, docs/系统全景图_模块盘点/server.md, README.md at the repository root ("Security notes") — in Chinese unless noted.

MIT © 2026 NewRate Limited.