@reinsjs/brain
v0.12.1
Published
reins — brain: perception, compact, pins, spill, handoff, memory, approval, budget, skills, lazy-tools
Readme
@reinsjs/brain
Pre-packaged driving experience for reins agents: twelve Socket modules that make a model good at long tasks — seeing its own context, tidying it, keeping constraints, spilling large results, handing off, remembering, asking before dangerous actions, stopping at a budget, reading the host's skills when a task calls for them, loading tools from a large table only when it needs them, holding back the rest of a batch when an earlier call failed, and ending a run when the model calls its wrap-up tool. Each module is optional, individually configurable, and only depends on the contracts in @reinsjs/core. None of them decides for the model; they let it see, give it means, set bounds, and leave a record.
pnpm add @reinsjs/brainimport { approval, budget, compact, memory, perception, pins, skills, spill } from "@reinsjs/brain"
import { fsSkillSource } from "@reinsjs/brain/node"
import { createAgent } from "@reinsjs/agent"
const agent = createAgent({
model,
store,
tools,
sockets: [
perception(), // "you have used 61% of your context" — as a note, not an action
compact(), // a `compact` tool the model calls when it decides to tidy
pins({ pins: ["Never touch prod without approval"] }),
spill(), // big tool results go to the BlobStore; the model gets a preview + fetch_blob
memory({ namespace: () => "/roles/analyst" }),
// a menu of SKILL.md names in the prompt; the model reads one with skill_read.
// fsSkillSource resolves relative paths against process.cwd(): pass an absolute path
skills({ source: fsSkillSource(new URL("./skills", import.meta.url).pathname) }),
budget({ limits: { turns: 30, totalTokens: 400_000 } }),
approval({ ask: ["deploy", "delete_*"] }), // keep approval last: it judges the input other sockets may have rewritten
],
})The modules
| module | what the model gets | what it costs you |
| --- | --- | --- |
| perception() | A system_note at the end of the timeline with context usage (and where auto-folding starts), compactions so far, budget headroom and spilled results, in coarse tiers so it does not change every turn (cache-friendly). Calibrated against the last real budget_usage. Unfolded turns and session tokens are measured too but only kept in meta.reading (pass your own render to show them). | nothing |
| compact() | A compact tool: the model summarizes a range of old turns itself; the summary carries a manifest of the folded tool results, plus a second list of folded user messages that carried images, video or audio, and a recall({ seq }) tool fetches any of them back verbatim (a recalled user message comes back as an untrusted tool result, media included). When the window passes 75% and the model has not compacted since the last fold, it appends a note asking the model to compact first, and asks once more, more bluntly, at 80% (decidedBy: "forced"; force: false turns this off, force: { at, render, directive } tunes it — at takes one ratio or an ascending list). The request is marked as a directive, so lowerings deliver it as a tagged user note even where mid-conversation system messages are accepted: some upstreams accept those but do not act on instructions inside them. If the model still does not compact, a threshold fallback at 85% folds the oldest turns down to 60%. Compacting maxConsecutive (default 3) times in a row without a turn of progress pauses the run with reason: "budget" and code: "reins.compact_stalled". Recommended on since 2026-09-10: measured on DeepSeek and Claude, recall stayed at 100% while tokens went down. | a BlobStore is not required |
| pins() | Host-declared constraints (static text or extracted from the conversation) plus a pin tool. Pinned notes survive compaction and are re-injected when they scroll out. A host spec can also be a resident snapshot ({ name, snapshot }, sync or async): taken at the start of each segment — the session's first turn and the first turn after every compaction — and appended only when it differs from the copy in view, so an index of the model's memory stays at hand without being rewritten mid-task (see below). | nothing |
| spill() | Tool results above a size limit are stored whole in the BlobStore; the model sees head + tail + a blob id and pages through with fetch_blob. Without a BlobStore the module warns once and passes results through unchanged (no silent truncation). | a BlobStore |
| handoff() | A handoff tool: the model writes a summary and next steps and moves to a fresh session; visible pins travel along. The mechanics (new session, opening note) are in the core loop. In the new session the summary note is recorded as the model's (actor: "model"), and so is a triggerMessage the model wrote itself; a message that repeats one of the session's user messages word for word keeps that message's author (the user's stays the user's), with provenance.ref pointing at the original. Off by default — turn it on when tasks routinely outlive one context window. | host must rebind the UI to the new session (onHandoff) |
| memory() | A memory tool shaped like Anthropic's memory_20250818 (view / create / str_replace / insert / delete / rename under /memories). Every operation leaves a memory_op event. Isolation is by namespace, invisible to the model: keys are stored as <namespace>/memories/…, and the namespace must be "" or a canonical path (/users/alice: leading /, no trailing /, no empty, ., .. or memories segments) so that no two namespaces nest — anything else makes the memory call fail (fail-closed), with one warning per memory() instance for the first invalid value. If your store routes memory into layers (/memories/personal, /memories/project, …), declare them as directories so an empty layer views as an empty directory instead of "does not exist", and shows up when the model views /memories. Off by default. | a MemoryStore |
| approval() | A deny → ask → allow policy pipeline in beforeTool. deny leaves an approval_decision and blocks; ask pauses the run for a human; allow leaves no event. Default policy byRisk: tools without a declared risk are treated as medium and ask — mark read-only tools risk: "low". Policy evaluation errors deny (fail-closed). ttlMs gives approvals a lifetime: one that arrives later than that (measured between the approval_request and the host's approval_decision on the timeline) is not honoured — the call is denied with by: "approval.expired" and a message telling the model it may re-issue the call for a fresh approval. | nothing |
| budget() | Five limits — contextTokens, totalTokens, turns, toolCalls, wallMs — checked in onTurnEnd. Hitting one while the model wants to continue pauses the run with reason: "budget" and code: "reins.budget" (pass code: (hits) => string to compute your own, and note: (hits) => string to customize the pause note — pause codes are lowercase, so lowercase a dimension name before using it); resuming starts a fresh run budget for totalTokens, turns, toolCalls and wallMs. contextTokens is the size of the latest request, not a per-run total: resuming does not reset it. Each turn is checked against the request that turn made, before any compaction in it takes effect, so a resumed run pauses at least once more; the limit clears only once a later request is smaller (after the model compacts, or the session hands off). totalTokens includes what sub-agents spent through asTool. | nothing |
| skills() | Agent Skills with progressive disclosure: the system prompt carries only a menu (each SKILL.md's name + description); the model reads a skill, or one of its supporting files, with skill_read({ name, path?, range? }), and the text lands in the timeline as a tool_result — so compaction, recall and spill apply to it unchanged. Skills are host-authored, so skill_read results are trusted like the system prompt (no <untrusted> marker). Skills that fail the spec (bad name, missing description) are skipped with one warning; no source, no valid skill, or a tool already named skill_read (from the host or a socket registered before skills(), such as an MCP server; see Tool name clashes) means nothing is registered (one warning). Opt-in: give it a source. | a SkillSource — the read-only half of any MemoryStore (see below), fsSkillSource(dir) from @reinsjs/brain/node for a folder of <name>/SKILL.md, or inlineSkills({ "code-review": "---\nname: code-review\ndescription: How we review PRs.\n---\n\n1. …" }) for bundled strings (Workers) — the object key must equal the frontmatter name |
| lazyTools() | Tool discovery for large tool tables — the consumer of Tool.lazy. Tools marked lazy: true appear in the system prompt only as a menu (name: one-line summary, first line of the description by default); the model loads the ones a task needs with tool_find({ names }), which returns each tool's full description and input schema, and from the next turn on those tools are in the request's tool list. Which tools are loaded is rebuilt from the timeline (the tool_find calls and their non-error results), so pause / resume, later runs on the same session and process restarts agree. Calling a listed-but-unloaded tool is blocked with a pointer to tool_find. The menu is built from the tools bound before this socket — the host's and those of sockets registered earlier, e.g. mcpTools({ override: (t, info) => info.annotations?.readOnlyHint ? { ...t, lazy: true } : false }) — so register lazyTools() after every socket whose tools it should hide, and before approval() (which stays last): sockets are asked in order and the first to block or defer decides, so behind approval() an unloaded tool would go to a human, or be reported unknown, instead of being pointed at tool_find. lazy tools from later sockets are never hidden, one warning names them. No lazy tool bound before it, or a tool already named tool_find: nothing registered, one warning. Opt-in: install it. | summarize(tool) to replace the default summary, summaryChars (160), maxPerCall (20), rules, warn; groups / groupOf / collapsed to fold groups of tools into one menu line each (see Folding tool groups) |
| haltOnFailure() | Models put several calls in one reply to save round trips, and the order is often a dependency: update the item, then tell the team it is ready. The model cannot make the second call conditional on the first — it does not see results inside one reply. With this module, once a call in the batch has failed (or is still waiting for approval or a client result), the calls after it are not run: each gets an error result naming the earlier call and asking the model to handle it first. Tool call ids stay one-to-one, nothing is executed, nothing counts toward the toolCalls budget. counts(result) picks which failures matter, applies(call, tool) which later calls to hold back (e.g. let risk: "low" reads run). Register it first. Opt-in. | nothing |
| stopAfter({ tools }) | Ends the run (done) at the end of a turn in which the model successfully called one of tools — a wrap-up tool such as end_run({ note }) placed in the same reply as the last actions, which saves the extra request for a closing message. It does not stop if anything in that batch failed or is still pending (the model sees the failure next turn), and a call left over from a paused run does not end a resumed run that brought new user input. Register it after handoff() and before compact() / budget(): the first socket with an opinion decides the turn. Opt-in. | nothing |
Tool name clashes
compact() (compact, recall), spill() (fetch_blob), pins() (pin), handoff(), memory(), skills() (skill_read) and lazyTools() (tool_find) bring their own tools, and their rules and hooks refer to them by name. When a tool of the same name is already bound before the module — a host tool, or a tool from a socket registered earlier, such as an MCP server — the loop keeps the first one, so the module's rules would send the model to someone else's tool (a spilled result fetched from an MCP server, a successful MCP handoff call ending the session). Instead the module registers nothing for that run, its hooks stay idle, and it warns once (each of these modules takes a warn option): spill() then stops spilling, as without a BlobStore; pins() keeps the host's pins and drops only the pin tool, as with tool: false. Passing the module's own tool object in the host's tools is not a clash, and neither is a beforeModel patch that copies the tool table (ctx.tools.map((t) => ({ ...t }))): a copy that keeps the same execute function still counts as the module's tool. A same-name tool with a different or wrapped execute does not, and the module's hooks stay idle for it. To keep both tools, rename the other one — mcpTools({ prefix }) does that for an MCP server — or register the MCP socket after these modules (its clashing tool is then the one dropped, and @reinsjs/tools-mcp warns).
Act, then announce
haltOnFailure and stopAfter read ctx.batch — the calls of the current batch, the results logged so far, the calls left waiting, and whether this is a resumed batch — and work together:
const sockets = [
haltOnFailure({ applies: (_call, tool) => tool?.risk !== "low" }), // first: a held-back call never reaches the others
handoff(),
stopAfter({ tools: ["end_run"] }), // after handoff, before compact / budget
compact(),
budget({ limits: { turns: 30 } }),
approval({ ask: ["deploy"], allow: ["board_update", "chat_send", "end_run"] }), // last, as always
]If board_update fails in [board_update, chat_send, end_run], chat_send and end_run are held back, so the run does not stop and the model sees the failure on the next turn. With TanStack AI (@reinsjs/adapter-tanstack-ai) the engine checks a whole batch before running any of it, so haltOnFailure only sees failures from earlier runs of a resumed batch; and a resumed batch gets no onTurnEnd there, so a wrap-up tool left waiting behind an approval costs one more model request.
Skills from a database
Any MemoryStore (in-memory, @reinsjs/store-sqlite, @reinsjs/store-pg) is also a SkillSource: write /skills/<name>/SKILL.md (frontmatter with name equal to <name> and a description) and, optionally, /skills/<name>/<file> for supporting files, then pass the same store as source. The model's memory tool only reaches /memories (stored as <namespace>/memories/…), so one table holds writable private notes and read-only shared skills at once; memory({ namespace }) prefixes apply to memories only, skills are shared by every principal. A skill the model could write itself must never be trusted like the system prompt, so a memories path segment is reserved: skills() refuses a root containing one, and a skill folder or supporting file whose key contains one is skipped from the menu and reads as nonexistent — whatever your namespace returns.
Folding tool groups
A large tool table often splits into lines of business that rarely meet — say, manual ad campaigns and GMV Max — and most users only work with one. Give lazyTools() the groups, say which group each menu tool belongs to, and decide per run which groups to fold. A folded group takes one menu line (- gmv_max (352 tools): summary); the model lists its tools with tool_find({ groups: ["gmv_max"] }) (names and summaries only) and then loads the ones it needs with tool_find({ names }). Folding is only about what the menu shows: the bound tools, tools_bound, how loaded tools are tracked and hidden, and the block for unloaded calls are the same as without groups, and a tool in a folded group can be loaded by name without listing the group first. Which groups were listed is rebuilt from the timeline (expandedLazyGroups); listing never changes the system prompt or the next run's folding — that is up to you:
import { expandedLazyGroups, lazyTools } from "@reinsjs/brain"
import type { Event, EventLog, Tool } from "@reinsjs/core"
const LINES = {
ads: "Manual and Smart+ campaigns: create, edit, pause, report.",
gmv_max: "GMV Max campaigns for e-commerce: stores, products, ROI targets.",
}
/** Which business line a tool belongs to, by name prefix; anything else stays on the menu line by line */
const lineOf = (tool: Tool) =>
tool.name.startsWith("gmv_max_") ? "gmv_max" : tool.name.startsWith("ads_") ? "ads" : undefined
/** principal id → lines the user has opened (keep this in your own database) */
const usedLines = new Map<string, Set<string>>()
const lazyByLine = lazyTools({
groups: LINES,
groupOf: lineOf,
// Fold the lines this user has not worked with yet
collapsed: (setup) => {
const used = usedLines.get(setup.principal?.id ?? "") ?? new Set()
return Object.keys(LINES).filter((line) => !used.has(line))
},
})
/** After a run: remember the lines the model opened, so the next run lists them in full */
async function rememberLines(log: EventLog, sessionId: string, principalId: string) {
const events: Event[] = []
for await (const e of log.read(sessionId)) events.push(e)
const used = usedLines.get(principalId) ?? new Set()
for (const line of expandedLazyGroups(events, new Set(Object.keys(LINES)))) used.add(line)
usedLines.set(principalId, used)
}SocketSetup has no session id, so per-user folding goes by setup.principal. collapsed may be async and may be called twice for one request (the server's resume pre-check and the loop each resolve the sockets); it must give the same answer both times — read your state there, don't change it — or the pre-check and the loop can disagree about whether a paused run may resume. expandedLazyGroups counts a group when the model asked to list it in a tool_find call that succeeded, which is the signal you want ("this user started on that line"). Notes:
- Group names match
LAZY_GROUP_RE(lowercase letters, digits,_,-, up to 64 characters); a tool belongs to at most one group — leave tools both lines need ungrouped.groupOfis only called for menu tools;undefinedornullmeans ungrouped. groupOfreturning an undeclared name lists that tool line by line, andcollapsedreturning one is ignored — each warns once, so a new kind of tool on an MCP server never stops sessions from starting.collapsedreturning something other than an array of strings makes the run fail before anything is logged.- With no folded group in a run (no
groups,collapsedempty, or the folded groups have no tools this run) the system prompt andtool_find's description, schema and messages are exactly what they are without groups, so the prompt cache andconfigHashdo not change. Changing the folded set changes the system prompt once; a paused run still resumes, unlesstool_finditself is one of the pending calls and the run switches between having folded groups and not (its schema differs, so the resume is refused as configuration drift). - A listing stays in the conversation, as every tool result does, until
compact()folds it away; the menu line is still there and the model can list the group again orrecallthe listing. The saving is in sessions that never touch the folded line. - On Anthropic's native path (
capabilities.deferredTools), atool_findthat both loads tools and lists a group puts the listing right after the tool results in the same user message instead of inside the result (recorded as lossy); the expected use, list first and load next, is unaffected.
Resident context that survives compaction
Compaction folds the conversation, not the system prompt or the tool list, so the model keeps who it is and what it can do. What it loses is context you attached to the conversation — an index of its memory, the item it is working on. Declare that as a resident snapshot instead:
/** One line per memory file: the index, not the content. The model opens a file with its `memory` tool. */
function memoryIndex(store: MemoryStore) {
return async (): Promise<string | undefined> => {
const paths = await store.list("/memories/")
if (paths.length === 0) return undefined
return ["Your memory files (open one with the memory tool):", ...paths.map((p) => `- ${p}`)].join("\n")
}
}
const residentContext = (store: MemoryStore) =>
pins({ pins: [{ name: "memory-index", snapshot: memoryIndex(store) }], tool: false })The snapshot is taken when a segment starts: the first turn of the session, and the first turn after each compaction (the model's own, a requested one, or the threshold fallback). Within a segment it is not refreshed — whatever the model wrote to memory is already in its context; after a compaction folds that away, the index is taken again and the old copy disappears in the same turn. If nothing changed, nothing is appended. Changes made by someone else mid-segment show up after the next compaction; use extract if you need them live. A snapshot is a pin and occupies context permanently: keep it to an index and short status, and let the model open the details. It is not carried through handoff — the new session takes its own. If snapshot throws, the run fails; catch inside it and return undefined to keep the previous copy instead.
Things that are deliberate
- Sockets run in order, and order matters.
approval()belongs last so it judges the arguments after anyrewrite;lazyTools()goes right before it, after the sockets whose tools it hides (mcpTools()→lazyTools()→approval());perception()appends its note at the end of the visible events so the model reads it last;haltOnFailure()goes first; inonTurnEndthe first socket with an opinion decides, sohandoff()→stopAfter()→compact()/budget(). - Nothing is hidden from the log. A note the model sees, a summary it wrote, a memory it changed — each is an event you can replay.
- Defaults come from measurements, not taste.
compactis recommended-on andmemory/handoffare off becauseexamples/evalsays so. If you change a default, rerun the eval. - Skills are read, not executed. A skill's
scripts/are not run by the library — a child process would break the zero-Node-builtins rule of@reinsjs/brain— expose what a skill needs as ordinary tools. Only@reinsjs/brain/nodetouches the file system. - The skill menu is part of the run's config hash. The menu is read once when a run starts and stays fixed for that run. Adding, removing or renaming a skill (or editing its
description) while a run is paused makes the resume fail as config drift — editing a skill's body does not. Deploy skill changes between runs, or passallowConfigDrift. Withrules: falsethe menu is not contributed at all, so this protection is gone unless your own system prompt carries the menu. - Skills are trusted because you wrote them.
skill_readresults carrytrust: "system"and skip the<untrusted>marker, so whatever fills the source (a folder you deploy, a database row, a CLI'sskills readoutput) is trusted like your system prompt. Do not give the model a tool that can write into the skill source. A skill body brought back later byrecallorfetch_blobisuntrustedagain — deliberate, conservative. - Loading a tool keeps the prompt cache on the native path (Anthropic, DeepSeek's Anthropic-compatible endpoint), re-warms it once elsewhere. When the lowering layer reports
capabilities.deferredTools(@reinsjs/lowering-fetchon official Anthropic models, Haiku 4.5 and later, and on DeepSeek's own Anthropic-compatible endpoint),lazyTools()sends the whole tool table on every request with the menu tools markeddefer_loading: true; thetool_findresult carriestool_referenceparts that the provider expands in place, so the tool list never changes and the cache prefix survives (measured: the request after atool_findreads 8.5k cached tokens on Haiku 4.5 instead of rewriting them;spikes/l1-deferred-tools/). Without that capability the request's tool list changes on the turn after atool_find, which invalidates the tools / system / messages prefix once — the rules text asks the model to load everything a task needs in one call; numbers inspikes/d1-lazy-tools-cache/.tool_findresults are trusted like the system prompt (trust: "system"): tool descriptions and schemas are host configuration, and only system-trusted results are translated into nativetool_referenceblocks. - Exports beyond this table (
loadSkillMenu,parseSkillMarkdown,parseMemoryCommand,previewOf, …) exist for hosts that replace a module's prompt or tool. They follow semver but are documented only in the type declarations. - Compaction never makes information unreachable. Early runs showed models refusing to answer once they saw "this was summarized", even when the detail was still visible. Attaching the manifest and giving them
recallfixed it; removing the manifest requires rewriting the rules text too, or the prompt lies.recall: false(you give the model another way to read the log) swaps the default rules, thecompacttool description and the manifest headings for versions that do not mentionrecall; customrulesare yours to keep consistent.
Documentation
docs/archive/implementation-plans/2026-09-08-技术方案v1.0.md §9 (module specs and measurements), docs/系统全景图_模块盘点/brain.md (file map), docs/踩坑记录.md (pitfalls) — in Chinese, at the repository root.
MIT © 2026 NewRate Limited.
