MalganisWu/red-bean-qing-tuan
About
可嵌入的 TypeScript Agent Runtime —— model→tool 循环、checkpoint、interrupt 屏障,零生产依赖,可嵌进任何宿主。
AI & Machine LearningMeasured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- 0
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.en.md
Originalred-bean-qing-tuan · 青团
An embeddable TypeScript agent runtime. Model→tool loop, pipelines, checkpointing, interrupts, compression, delegation, and a vendor-neutral observability seam — with zero production dependencies.
English · 简体中文
Why this exists
Agent frameworks usually decide too much on your behalf: they assume an HTTP server, a database, a session model, and a UI. This one assumes none of them.
red-bean-qing-tuan is the execution layer and nothing else. It runs the model→tool loop,
persists checkpoints through a store you provide, and emits neutral events. HTTP, SSE,
databases, caches, authentication, and product sessions stay in the host — where they can be
shaped to fit the product instead of the framework.
It has zero production dependencies and ships as ESM JavaScript with type declarations and source maps. Adopting it does not add a dependency tree to your service.
Install
Not yet published to npm. Consume it from Git today:
pnpm add git+https://github.com/MalganisWu/red-bean-qing-tuan.git#<commit>
Or build it locally:
git clone https://github.com/MalganisWu/red-bean-qing-tuan.git
cd red-bean-qing-tuan
pnpm install --frozen-lockfile
make ts-build
Requires Node.js >=24.9.0 <26.
Quick start
import { AgentRuntime, MemoryCheckpointStore } from 'red-bean-qing-tuan'
import { OpenAiAdapter } from 'red-bean-qing-tuan/llm'
const runtime = new AgentRuntime({
model: new OpenAiAdapter({
apiKey: process.env['OPENAI_API_KEY'] ?? '',
modelName: 'gpt-4',
}),
checkpointStore: new MemoryCheckpointStore(),
systemPrompt: 'You are an assistant.',
})
const result = await runtime.run(
{ threadId: 'session-1', userId: 'user-1', input: 'Hello' },
AbortSignal.timeout(60_000)
)
if (result.status === 'suspended' && result.interrupt !== undefined) {
await runtime.resume(
{
threadId: 'session-1',
userId: 'user-1',
requestId: 'resume-1',
interruptId: result.interrupt.toolCallId,
response: '{"approved":true}',
},
AbortSignal.timeout(60_000)
)
}
await runtime.close(AbortSignal.timeout(10_000))
RuntimeResult.status distinguishes completed, suspended, exhausted, cancelled, and
failed. Failures throw RuntimeExecutionError, whose result carries partial output and a
diagnosable checkpoint.
MemoryCheckpointStore is a development and contract-reference implementation — it is not
a cross-instance production store.
What the runtime owns, and what it does not
This boundary is the whole point of the library, so it is worth stating precisely.
The runtime owns:
- The ReAct state machine, model streaming, tool scheduling, cancellation, and timeouts.
- The interrupt execution barrier and persistent checkpoints with idempotent resume.
- Neutral run events and a structured
Result. - Safe-by-default builtin tools, plus explicitly named high-privilege constructors.
The host owns:
- HTTP / SSE / WebSocket protocols, UI sections and cards, and localization.
- User identity, session lists and titles, authentication, and approvals.
- Cache and database keys, scheduled-task metadata, sub-execution records.
- Which network destinations are allowed, which filesystem roots are reachable, and how secrets are supplied.
Concretely: the runtime does not provide leases, TTLs, heartbeats, claim-timeout takeover, or exactly-once external side effects. Fencing protects checkpoint commits only. Those are host policies, and pretending otherwise would be a lie of omission.
Checkpoint and concurrency
- A normal run loads revision
Rand saves the result with a CAS toR+1. resumefirst consumes the interrupt atomically (R→R+1), then saves the terminal state under a claim owner (R+1→R+2).- Replaying a completed
requestIdreturns the stored receipt without calling the model again; conflicting requests fail closed. - Non-zero fencing tokens are generated by the host's lease system. The runtime and store reject stale fences.
Custom stores should run the framework-agnostic contract suite:
import {
runCheckpointStoreContract,
runCheckpointStoreFencingUnsupportedContract,
} from 'red-bean-qing-tuan/testing'
await runCheckpointStoreContract(() => new CustomCheckpointStore(), {
supportsFencing: true,
dispose: async (store) => store.close(),
})
Implementations that do not support fencing should also run
runCheckpointStoreFencingUnsupportedContract, which asserts that non-zero tokens fail closed.
Public API surface
package.json#exports is the only public boundary:
| Entry point | Contents |
|---|---|
red-bean-qing-tuan |
AgentRuntime, checkpoint stores, protocols |
red-bean-qing-tuan/llm |
Neutral LLM adapter interface and the OpenAI-compatible default |
red-bean-qing-tuan/pipeline |
RuntimeContext, PipelineBuilder, AgentNode |
red-bean-qing-tuan/tools |
Tool definitions, dispatcher, builtins, delegation |
red-bean-qing-tuan/observability |
Neutral Tracer and the runtime trace plugin |
red-bean-qing-tuan/testing |
Framework-agnostic contract suites for host implementations |
Do not import from src/**, dist/**, or any other deep path. The full surface is specified in
docs/contracts/typescript-runtime-api.md.
Interrupts
Any tool may return a structured InterruptSignal to suspend the run. An interrupt is an
execution barrier: no other tool in the same batch runs before the answer arrives. Callers
using the high-level API continue with runtime.resume; hosts driving the lower-level pipeline
append a tool message matching interrupt.toolCallId and continue.
Product cards, CLI prompts, and localized copy are the host's responsibility — the runtime never formats user-facing text.
Builtin tool safety
lookupBuiltinTool(id)returns a fresh instance forsys_get_time,sys_http_request, andsys_fetch_urlonly. It registers no global state.- HTTP and fetch refuse private, loopback, link-local, multicast, CGNAT, and unspecified addresses by default, and re-check on connection and on every redirect.
createRootedReadTool(root)blocks path and symlink escapes.UnrestrictedReadToolis only appropriate for hosts that already run inside a process-level filesystem sandbox.- Tools that can touch files, networks, or delegate work must be explicitly injected and authorized by the host.
Plugins and observability
plugins are registered at AgentRuntime construction and closed thereafter. A plugin may
wrap run/resume, model, and tool calls, and may register shutdown functions. Earlier-registered
middleware sits further out, and no plugin can short-circuit ToolPolicy.
red-bean-qing-tuan/observability provides a neutral Tracer and RuntimeTracePlugin. The
default span hierarchy is:
agent.run / agent.resume
├── llm.stream
└── tool.execute
└── agent.delegate
Span.within(operation) propagates the parent span explicitly. The runtime ships no exporter
and no vendor SDK, and never records prompts, tool arguments, or model output. Choose
structured logging, OpenTelemetry, or your own adapter.
Development
make setup # install the toolchain
make ts-build # build ESM and declarations
make ts-test # unit, contract, and conformance tests
make ts-api-check # the six entry points, declaration consumption, and API surface
make typecheck # strict type checking
make ts-lint # type-aware ESLint
make verify # the full local gate
make verify* never modifies tracked files.
Documentation and layout
Start at src/README.md to walk the six entry points from facade through
protocol/port, service/adapter, composition, and host implementations.
src/ Runtime source
test/ Unit, contract, and conformance tests
testdata/ API surface and stable-serialization fixtures
tooling/ TypeScript policy and consumer smoke tests
Conventions live in AGENTS.md; the documentation index is
docs/README.md; the terms most easily mistaken for ones you already know are
in docs/glossary.md (checkpoint revision, fencing token, claim,
interrupt barrier — each with a one-line definition and a "this is not…" boundary);
unreleased changes are in CHANGELOG.md.
Related repository
red-bean-nian-gao is a full agent chat
platform built on this runtime — a worked example of a host that owns sessions, persistence,
HTTP/SSE, scheduled tasks, and a UI. It pins this repository by commit through a runtime.lock
file, which is one way to consume an unreleased SDK.
License
Explore related projects
Loading…