@reinsjs/adapter-tanstack-ai
v0.6.1
Published
reins — the brain as a TanStack AI chat middleware: EventLog stays the source of truth, sockets drive onConfig / onChunk / tool hooks
Readme
@reinsjs/adapter-tanstack-ai
Run the reins brain inside TanStack AI's chat() as a middleware. TanStack drives the loop, executes tools and handles interrupts; reins keeps the event log as the single source of truth, projects it into what the model sees on every turn, and runs its brain modules (compaction, pins, spill, memory, approval, budget, perception) on TanStack's hooks.
pnpm add @reinsjs/adapter-tanstack-ai @tanstack/[email protected]import { reinsApprovalInterrupt, reinsMiddleware } from "@reinsjs/adapter-tanstack-ai"
import { approval, compact, perception, spill } from "@reinsjs/brain"
import { chat, toolDefinition } from "@tanstack/ai"
// approval() asks about every tool whose risk it does not know: declare it on read-only host tools
const lookup = toolDefinition({
name: "lookup",
description: "Look up an order",
inputSchema,
metadata: { reins: { risk: "low" } },
}).server(findOrder)
const stream = chat({
adapter,
messages,
tools: [lookup, deploy],
systemPrompts: ["You are…"],
middleware: [
reinsMiddleware({
sessionId,
log: store.log,
blobs: store.blobs,
sockets: [perception(), compact(), spill(), approval({ ask: ["deploy"] })],
capabilities: { contextWindow: 200_000 }, // TanStack does not tell middleware how big the window is
}),
],
interrupts: [reinsApprovalInterrupt], // required: dynamic approvals are a generic interrupt
})What the middleware does
onConfig(init)reads the log (fail-closed on unknown events), merges the brain's static tools and prompt fragment, and imports the client's new user messages. Import is idempotent: a network retry that re-sends the same request does not write the message twice (key = messageidif present, else its position in the client array, plus exact content).onConfig(beforeModel)replacesproviderMessageswith the projection of the log — TanStack's ownmessagesarray only serves the UI.onChunk/onUsageappend the model's blocks and abudget_usageevent.onInterruptBoundary(beforeTools)runs the socket pipeline for every pending call; adeferbecomes areinsApprovalInterruptso the run pauses and the client resumes it withresume.onInterruptResolutionrecords an answer asapproval_decisiononly when it points at a call of this session that is waiting for approval on a reins card (one answer per call); other answers are dropped with a warning. Arun_resumedcomes first, as in the default loop.onAfterToolCall/onToolPhaseCompleteappend results, including the ones TanStack handled itself (nativeneedsApproval, client-side tools).
Boundaries you should know
- Register the interrupt. If
reinsApprovalInterruptis missing fromchat({ interrupts }), the type layer complains; at run time the middleware also checks the engine's registry, warns once, and treats every call that would need approval as denied (anapproval_decisionwithby: "reins"is left in the log) instead of letting the engine throw mid-run. deferpauses the whole tool batch, not just the call that needs approval — that is where TanStack's boundary sits.- Declare
riskon host tools. The brain reads a TanStack tool's risk frommetadata.reins(ReinsToolMetadata:risk,replayable), the same fields a reinsToolhas. Without it the tool counts as a write tool:approval()'s defaultbyRiskasks a human before every call (soapproval({ ask: ["deploy"] })alone also asks aboutlookup), and each call logs atool_startedfirst. A value outside the allowed ones is treated as undeclared and reported throughwarn. - One approval card per call. Reins tools (brain tools, MCP tools from
@reinsjs/tools-mcp) are asked only throughreinsApprovalInterrupt, whatever form theirneedsApprovaltakes. A host tool with TanStack's staticneedsApproval: trueis asked only through TanStack's native approval, even when a socket such asapproval()also wants to ask; theapproval_requestthen carries the socket's policy and summary. Native answers sent withresumeare logged asapproval_decision(by: "tanstack") at the start of the resumed run, before any tool runs, server or client. Answers carried byUIMessageapproval-respondedparts never reachresume: for a server tool the approval is logged just before it runs (andapproval({ ttlMs })is re-checked then); for a client tool it is logged only when the client's result arrives with the next request, asapproved: trueif that result is not an error andfalseotherwise — a client-side execution error is then indistinguishable from a refusal. If a socket rewrites the arguments of a call that goes to the native card, the call is not executed even when approved (the card shows the arguments the model wrote, so running the rewritten ones would run something nobody approved); for a server tool the human is still asked once, because the engine raises the card before the middleware can step in, while a client tool is normally cancelled before any card (if the same batch also raises a reins interrupt, the engine may still show its native card; approving it does not run the call). Do not rewrite calls of tools with a staticneedsApproval. - Approval answers come from the client. TanStack does not sign generic-interrupt continuations, so the
keyand thebyof areinsApprovalInterruptanswer are whatever the resuming client sends. The middleware only records answers for calls of this session that are waiting for approval (one answer per call); anything else is dropped with a warning. If who approved matters, checkresumebefore callingchat(). - Socket blocks reach client tools through the engine's cancel list. Client tools (no
execute) never pass throughonBeforeToolCall, so when a socket blocks one (including anapproval()deny) the middleware adds the call to the engine'scancelledToolCallIdsat thebeforeToolsboundary and the client is never asked to run it. This relies on TanStack AI 0.53.0 handing everyonConfigits own mutable set; a middleware placed before reins that replaces that set with a copy defeats it. In that case the client's real result is logged as it came back, followed by acore.error(categorytanstack-ai, not shown to the model) saying the block was not enforced. If you must stop a client tool regardless, give it a staticneedsApprovalso the engine raises its own card, or check in the front end before running it. - A client tool that needs a reins approval can reach the front end before the answer. When a socket defers a client tool (no
execute) for approval, the run ends with two interrupts: TanStack's client-execution request for the call and the reins approval. A front end that runs every client-execution request it receives may run the call before the approval is answered; a later denial keeps the result out of the log but cannot undo what already happened in the browser. Until this is fixed in the middleware, have the front end hold a client-execution request while a reins approval interrupt for the sametoolCallIdis open, or give such tools a staticneedsApprovalso only TanStack's native card is raised. - Edited arguments are not executed. If the approver answers TanStack's native approval with
editedArgsthat differ from the call the model made, the call is denied instead (approval_decisionwithby: "reins", whose reason names the edited arguments) and handed to the engine as cancelled, so neither a server tool nor a client tool runs with them: the log keeps the model's call as it was written, so running other arguments would make it lie. The model sees the arguments the approver wanted and can make the call again. As a second line, a server tool is not run when the call text the engine is about to execute (toolCall.function.arguments, parsed the way the engine parses it) differs from the logged call — for instance a client resending edited history. The check compares the call text, not the schema's output, so a schema default that differs on every parse (randomUUID(),Date.now()) does not trip it. - No
systemrole.system_noteevents travel as a framedusermessage and are declared lossy; thinking is replayed only with a same-provider signature. The complete table isTANSTACK_LOSS_MATRIX. - Sub-agent pause bubbling (
asTool) is not available here. A tool returningsubagentPauseis reported to the model as an error; the child session stays paused and can be resumed by the host. - Content parts: data-sourced image, video and audio parts translate both ways; TanStack has no duration field, so
durationSecis not exported and imported clips have none (the estimate falls back to byte size). URL sources, documents and parts whose mime type does not match their kind become a placeholder and are reported indropped. Whether the provider takes video or audio is up to TanStack's provider adapter, not reins. @tanstack/aiis pinned to an exact version because the middleware relies on hook contracts read from its source.
Two more boundaries
capabilities.deferredToolsis alwaysfalseon this path, even if you passtrue: TanStack's adapter decides how tools reach the provider, so there is no place fordefer_loading/tool_reference, andBeforeModelPatch.deferredToolsis not read.lazyTools()therefore always takes its filtering path here; the cache-preserving native path isrunLoop+@reinsjs/lowering-fetchon Anthropic.- TanStack's own lazy tools (
lazy: true) work: when the engine adds a tool it just discovered, or drops its discovery tool, the next model request follows it. Tools only appear this way — a host tool missing from the engine's list is otherwise kept, since a middleware placed after this one may hide tools turn by turn. The change is not logged as a newtools_bound; the next run's snapshot shows it. approval({ ttlMs })works here exactly as in the default loop: TanStack re-enters thebeforeToolsboundary after an interrupt is resolved, so thebeforeToolpipeline runs again and an approval that arrived too late is denied withapproval_decision(by: "approval.expired")before the tool runs (middleware.test.ts, "审批").ctx.batchis filled, but the engine checks a whole batch inbeforeToolsbefore running any of it, sobeforeToolsees no results from the same batch (only those of a resumed batch logged by an earlier run) andheldstays empty — adeferpauses the whole batch anyway.haltOnFailure()therefore never holds back calls of a fresh batch here. A resumed batch also gets noonTurnEnd: after the leftover calls run, the engine asks the model straight away, sostopAfter()cannot end a run on a wrap-up call that waited behind an approval (middleware.test.ts, "TurnContext.batch").
Documentation
docs/系统全景图_模块盘点/adapter-tanstack-ai.md and docs/archive/implementation-plans/2026-09-08-技术方案v1.0.md §2 / §11 — in Chinese, at the repository root.
MIT © 2026 NewRate Limited.
