@reinsjs/brain 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # @reinsjs/brain
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - First public release.
8
+
9
+ - **Timeline first.** Append-only event log with `schemaVersion` on every event and fail-closed upcast on read; projection decides what the model sees each turn; replay and fork from the log alone.
10
+ - **A loop you can copy.** `runLoop` as an exported async generator: pause/resume is a return value with a small signed state, bounded retry on transient failures only while nothing has been written, tool pipeline `beforeTool → validate → approval → execute → afterTool`, sub-agent pause bubbling (`Interruption { kind: "subagent" }`).
11
+ - **Brain modules** (`@reinsjs/brain`): perception, compact (with folded-result manifest and `recall`; recommended on after measuring 100% recall at lower token cost on two model families), pins, spill, handoff, memory (`memory_20250818` shape, namespace isolation), approval (deny → ask → allow, fail-closed), budget (five limits, sub-agent usage included), skills (Agent Skills with progressive disclosure: a `SKILL.md` menu in the prompt, `skill_read` to load one on demand; sources are any `MemoryStore`, `inlineSkills`, or `fsSkillSource` from the new `@reinsjs/brain/node` entry).
12
+ - **Lowering** (`@reinsjs/lowering-pi`): Anthropic Messages and OpenAI Responses via pi-ai with a declared loss matrix, trust markers on untrusted content, cache-breakpoint handling.
13
+ - **Serving** (`@reinsjs/server`, `@reinsjs/ui-agui`): Web-standard handler with SSE replay from `lastSeq`, per-session run lock, `authorizeSession` (only `true` allows), AG-UI as the first-class UI protocol.
14
+ - **Stores**: SQLite (`node:sqlite` / `bun:sqlite`) and Postgres (`pg` / PGlite), conformance-tested; configurable memory table for per-role isolation.
15
+ - **Tools**: MCP servers as one socket (`@reinsjs/tools-mcp`, tools bound per run, annotations as defaults not permissions); `asTool(agent)` in `reins`.
16
+ - **TanStack AI** middleware (`@reinsjs/adapter-tanstack-ai`): the brain on TanStack's loop with the log as the single source of truth; idempotent client-message import; runtime check for the approval interrupt.
17
+ - **Eval harness** (`@reinsjs/eval`): fixtures from real recordings, recorded tools, arm-vs-arm runner, metrics, the four-rule gate.
18
+
19
+ ### Patch Changes
20
+
21
+ - Updated dependencies
22
+ - @reinsjs/core@0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NewRate Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # @reinsjs/brain
2
+
3
+ Pre-packaged driving experience for [reins](../../README.md) agents: nine `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, and reading the host's skills when a task calls for them. 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.
4
+
5
+ ```bash
6
+ pnpm add @reinsjs/brain
7
+ ```
8
+
9
+ ```ts
10
+ import { approval, budget, compact, memory, perception, pins, skills, spill } from "@reinsjs/brain"
11
+ import { fsSkillSource } from "@reinsjs/brain/node"
12
+ import { createAgent } from "reins"
13
+
14
+ const agent = createAgent({
15
+ model,
16
+ store,
17
+ tools,
18
+ sockets: [
19
+ perception(), // "you have used 61% of your context" — as a note, not an action
20
+ compact(), // a `compact` tool the model calls when it decides to tidy
21
+ pins({ host: ["Never touch prod without approval"] }),
22
+ spill(), // big tool results go to the BlobStore; the model gets a preview + fetch_blob
23
+ memory({ namespace: () => "/roles/analyst" }),
24
+ // a menu of SKILL.md names in the prompt; the model reads one with skill_read.
25
+ // fsSkillSource resolves relative paths against process.cwd(): pass an absolute path
26
+ skills({ source: fsSkillSource(new URL("./skills", import.meta.url).pathname) }),
27
+ budget({ limits: { turns: 30, totalTokens: 400_000 } }),
28
+ approval({ ask: ["deploy", "delete_*"] }), // keep approval last: it judges the input other sockets may have rewritten
29
+ ],
30
+ })
31
+ ```
32
+
33
+ ## The modules
34
+
35
+ | module | what the model gets | what it costs you |
36
+ | --- | --- | --- |
37
+ | `perception()` | A `system_note` at the end of the timeline with context usage, history length and budget headroom, in coarse tiers so it does not change every turn (cache-friendly). Calibrated against the last real `budget_usage`. | nothing |
38
+ | `compact()` | A `compact` tool: the model summarizes a range of old turns itself; the summary carries a manifest of the folded tool results and a `recall({ seq })` tool fetches any of them back verbatim. A threshold fallback folds the oldest turns when the projection would overflow. **Recommended on** since 2026-09-10: measured on DeepSeek and Claude, recall stayed at 100% while tokens went down. | a `BlobStore` is not required |
39
+ | `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. | nothing |
40
+ | `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` |
41
+ | `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. **Off by default** — turn it on when tasks routinely outlive one context window. | host must rebind the UI to the new session (`onHandoff`) |
42
+ | `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. **Off by default.** | a `MemoryStore` |
43
+ | `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). | nothing |
44
+ | `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"`; resuming starts a fresh run budget. `totalTokens` includes what sub-agents spent through `asTool`. | nothing |
45
+ | `skills()` | [Agent Skills](https://agentskills.io) 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 host tool already named `skill_read` 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` |
46
+
47
+ ### Skills from a database
48
+
49
+ 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`, 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. `skills()` refuses a `root` that overlaps `/memories` — a skill the model could write itself must never be trusted like the system prompt.
50
+
51
+ ## Things that are deliberate
52
+
53
+ - **Sockets run in order, and order matters.** `approval()` belongs last so it judges the arguments after any `rewrite`; `perception()` appends its note at the end of the visible events so the model reads it last.
54
+ - **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.
55
+ - **Defaults come from measurements, not taste.** `compact` is recommended-on and `memory` / `handoff` are off because `examples/eval` says so. If you change a default, rerun the eval.
56
+ - **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/node` touches the file system.
57
+ - **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 pass `allowConfigDrift`. With `rules: false` the menu is not contributed at all, so this protection is gone unless your own system prompt carries the menu.
58
+ - **Skills are trusted because you wrote them.** `skill_read` results carry `trust: "system"` and skip the `<untrusted>` marker, so whatever fills the source (a folder you deploy, a database row, a CLI's `skills read` output) 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 by `recall` or `fetch_blob` is `untrusted` again — deliberate, conservative.
59
+ - **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.
60
+ - **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 `recall` fixed it; removing the manifest requires rewriting the rules text too, or the prompt lies.
61
+
62
+ ## Documentation
63
+
64
+ `docs/技术方案.md` §9 (module specs and measurements), `docs/模块盘点/brain.md` (file map), `docs/踩坑记录.md` (pitfalls) — in Chinese, at the repository root.
65
+
66
+ MIT © 2026 NewRate Limited.
@@ -0,0 +1,11 @@
1
+ // src/skills/constants.ts
2
+ var DEFAULT_SKILLS_ROOT = "/skills";
3
+ var SKILL_FILE_NAME = "SKILL.md";
4
+ var SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
5
+
6
+ export {
7
+ DEFAULT_SKILLS_ROOT,
8
+ SKILL_FILE_NAME,
9
+ SKILL_NAME_RE
10
+ };
11
+ //# sourceMappingURL=chunk-5O2TB7FV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/skills/constants.ts"],"sourcesContent":["/**\n * skills 模块的字面常量,单独成文件、零依赖:`@reinsjs/brain/node` 的 fsSkillSource 也要用同一份 `/skills`,\n * 而它不能把整个 skills 模块拖进 `dist/node.js`(\"同一个值在两处必须同一份\",踩坑记录)。\n */\n\n/** 载体里技能的键前缀缺省值:`${root}/<name>/SKILL.md` */\nexport const DEFAULT_SKILLS_ROOT = \"/skills\"\n\n/** 每个技能目录里的入口文件名(Agent Skills 规范固定,不可配) */\nexport const SKILL_FILE_NAME = \"SKILL.md\"\n\n/** 技能名:小写字母 / 数字 / 连字符,64 字符内,须与目录名一致(Agent Skills 规范) */\nexport const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/\n"],"mappings":";AAMO,IAAM,sBAAsB;AAG5B,IAAM,kBAAkB;AAGxB,IAAM,gBAAgB;","names":[]}