# 策展 · X (Twitter) 🔥

> 📖 本站完整內容索引（documentation index）：[llms.txt](/llms.txt)

> 作者：琥珀青葉@KohakuLab (@KBlueleaf) · 平台：X (Twitter) · 日期：2026-04-20

> 原始來源：https://x.com/kblueleaf/status/2045838664920707315

## 中文摘要

KohakuTerrarium 1.0.0 發布通用 Agent 框架。

@KBlueleaf (琥珀青葉@KohakuLab) 發布 [KohakuTerrarium 1.0.0](https://github.com/Kohaku-Lab/KohakuTerrarium)，這是 Python 3.10+ 的通用 Agent 框架，解決 LLM/Agent 領域從零重寫 substrate 的痛點，讓使用者透過 config files 和 system prompts 快速建置或重現如 openclaw、hermes agent 等架構，甚至設計全新 Agent，無需修改核心框架。

**核心抽象與定位**
KohakuTerrarium 將 Agent 抽象為 **creature**（獨立 Agent，含 controller、tools、sub-agents、triggers、memory、I/O），多 creature 水平組成 **terrarium**（純 wiring layer，管理 lifecycle、channels、通訊，無 LLM 決策）。這填補市場空白：過去兩年產品如 Claude Code、Codex、OpenClaw、Gemini CLI、Hermes Agent、OpenCode 皆重複實作 substrate（controller loop、tool dispatch、trigger system、sub-agent mechanism、sessions、persistence、多 Agent wiring），框架將其集中，讓新 Agent 形狀只需 config + custom modules，而非新 repo。

定位表顯示其獨特性：
|  | Product | Framework | Utility / Wrapper |
|--|---------|-----------|-------------------|
| **LLM App** | ChatGPT, Claude.ai | LangChain, LangGraph, Dify | DSPy |
| **Agent** | ***kt-biome***, Claude Code, Codex, OpenCode, OpenClaw, Hermes Agent… | ***KohakuTerrarium***, smolagents | — |
| **Multi-Agent** | ***kt-biome*** | ***KohakuTerrarium*** | CrewAI, AutoGen |

框架強調 Agent-level abstraction，非多 Agent orchestration 的薄 Agent 概念。

**Creature 組件**
Creature 分六大模組，五個 user-extensible（config/Python 替換），Controller（reasoning loop）罕見替換：
| Module | What it does | Example custom use |
|--------|---------------|--------------------|
| **Input** | Receives external events | Discord listener, webhook, voice input |
| **Output** | Delivers agent output | Discord sender, TTS, file writer |
| **Tool** | Executes actions | API calls, database access, RAG retrieval |
| **Trigger** | Generates automatic events | Timer, scheduler, channel watcher |
| **Sub-agent** | Delegated task execution | Planning, code review, research |

**Terrarium 架構**
Terrarium 為 proposed horizontal multi-agent architecture，含 channels（Queue：one consumer per message；Broadcast：all subscribers receive）與 output wiring（deterministic pipeline edges），支援 hot-plug、observation；仍在演進，見 `ROADMAP.md`。Root agent 位於 team 外，操作 team；偏好 sub-agents（vertical）於單 creature decompose task，提供 context isolation。Environment 為 shared terrarium state（shared channels），Session 為 private creature state（scratchpad、private channels、sub-agent state），private by default。

**關鍵特徵**
- Agent-level abstraction：六模組 creature 為一級概念，新形狀只需 config + custom modules。
- 內建 session persistence/resume：存 operational state（非僅 chat history），`kt resume` 數小時後續跑；sessions 存 `~/.kohakuterrarium/sessions/`。
- Searchable session history：事件索引，`kt search` 與 `search_memory` tool 查過去工作；支援 FTS + vector memory search（model2vec/sentence-transformer/API embedding）。
- Non-blocking context compaction：長運行 Agent 背景壓縮 context 持續工作。
- 綜合內建 tools/sub-agents：file、shell、web、JSON、search、editing、planning、review、research、terrarium management（含 single-edit/multi-edit file mutation）；background tool execution、非 blocking agent flow。
- MCP (Model Context Protocol) support：per-agent 或 global stdio/HTTP MCP servers，tools 自動 prompt 表面。
- Package system：從 Git/local 安裝 creatures/terrariums/plugins/LLM presets，inheritance 組成；`kt install`、`kt update`。
- Python-native：async Python objects，可嵌入 tools/triggers/plugins/outputs。
- Composition algebra：`>>` (sequence)、`&` (parallel)、`|` (fallback)、`*` (retry)、`.iterate` (async loop)。
- 多 runtime surfaces：CLI、TUI、web dashboard、desktop app。
- Plugins 修改 modules 間 connections（prompt plugins、lifecycle hooks），無需 fork。

**60 秒快速示範**
```bash
pip install kohakuterrarium                                         # install
kt login codex                                                      # authenticate
kt install https://github.com/Kohaku-Lab/kt-biome.git            # get OOTB creatures
kt run @kt-biome/creatures/swe --mode cli                        # run one
```
獲得互動 shell 含完整 coding Agent（file tools、shell access、web search、sub-agents、resumable sessions）；`Ctrl+D` 退出，`kt resume --last` 續跑。[kt-biome](https://github.com/Kohaku-Lab/kt-biome) 為官方展示包，含有用 OOTB creatures/plugins。

**安裝步驟**
1. From PyPI：
   ```bash
   pip install kohakuterrarium
   # Optional extras: pip install "kohakuterrarium[full]"
   ```
2. Or from source（uv convention）：
   ```bash
   git clone https://github.com/Kohaku-Lab/KohakuTerrarium.git
   cd KohakuTerrarium
   uv pip install -e ".[dev]"
   # Build web frontend (for `kt web` / `kt app`)
   npm install --prefix src/kohakuterrarium-frontend
   npm run build --prefix src/kohakuterrarium-frontend
   ```
3. 安裝 OOTB creatures/plugins：
   ```bash
   kt install https://github.com/Kohaku-Lab/kt-biome.git
   kt install <git-url>  # Any third-party
   kt install ./my-creatures -e  # editable install
   ```
4. 認證 model provider（支援 OpenRouter、OpenAI、Anthropic、Google Gemini、OpenAI-compatible）：
   ```bash
   kt login codex  # Codex OAuth (ChatGPT subscription)
   kt model default gpt-5.4
   # Or kt config provider add
   ```

**運行範例**
- Single creature：
  ```bash
  kt run @kt-biome/creatures/swe --mode cli
  kt run @kt-biome/creatures/researcher
  ```
- Multi-agent terrarium：
  ```bash
  kt terrarium run @kt-biome/terrariums/swe_team
  ```
- Web dashboard：
  ```bash
  kt serve start  # long-running daemon
  kt web          # one-shot foreground
  ```
- Native desktop：
  ```bash
  kt app  # requires pywebview
  ```

**程式化 Python 使用**
單 Agent：
```python
import asyncio
from kohakuterrarium.core.agent import Agent

async def main():
    agent = Agent.from_path("@kt-biome/creatures/swe")
    agent.set_output_handler(lambda text: print(text, end=""), replace_default=True)
    await agent.start()
    await agent.inject_input("Explain what this codebase does.")
    await agent.stop()

asyncio.run(main())
```

多 Agent terrarium：
```python
import asyncio
from kohakuterrarium.core.agent import Agent
from kohakuterrarium.core.channel import ChannelMessage
from kohakuterrarium.terrarium.config import load_terrarium_config
from kohakuterrarium.terrarium.runtime import TerrariumRuntime

async def main():
    runtime = TerrariumRuntime(load_terrarium_config("@kt-biome/terrariums/swe_team"))
    await runtime.start()
    tasks = runtime.environment.shared_channels.get("tasks")
    await tasks.send(ChannelMessage(sender="user", content="Fix the auth bug."))
    await runtime.run()
    await runtime.stop()

asyncio.run(main())
```

Composition algebra 範例：
```python
import asyncio
from kohakuterrarium.compose import agent, factory
from kohakuterrarium.core.config import load_agent_config

def make_agent(name, prompt):
    config = load_agent_config("@kt-biome/creatures/general")
    config.name, config.system_prompt, config.tools, config.subagents = name, prompt, [], []
    return config

async def main():
    # Persistent agents
    async with await agent(make_agent("writer", "You are a writer.")) as writer, \
               await agent(make_agent("reviewer", "You are a strict reviewer. Say APPROVED if good.")) as reviewer:
        pipeline = writer >> (lambda text: f"Review this:\n{text}") >> reviewer
        async for feedback in pipeline.iterate("Write a haiku about coding"):
            print(f"Reviewer: {feedback[:100]}")
            if "APPROVED" in feedback:
                break

    # Parallel with retry + fallback
    fast = factory(make_agent("fast", "Answer concisely."))
    deep = factory(make_agent("deep", "Answer thoroughly."))
    safe = (fast & deep) >> (lambda results: max(results, key=len))
    safe_with_retry = (safe * 2) | fast
    print(await safe_with_retry("What is recursion?"))

asyncio.run(main())
```

**Session 管理與搜尋**
```bash
kt resume                    # interactive pick
kt resume --last             # most recent
kt resume swe_team           # name prefix
kt embedding <session>       # build FTS + vector indices
kt search <session> "auth bug fix"  # hybrid/semantic/FTS
```
`.kohakutr` files 存 conversation/tool calls/events/scratchpad/sub-agent state/channel messages/jobs/resumable triggers/config metadata。

**Packages 管理**
```bash
kt install https://github.com/someone/cool-creatures.git
kt install ./my-creatures -e
kt list
kt update --all
```
執行：`kt run @cool-creatures/creatures/my-agent`、`kt terrarium run @cool-creatures/terrariums/my-team`。

**適合與不適合對象**
適合：需新 Agent 形狀但不欲重建 substrate；自訂 OOTB creatures；嵌入 Agent 至既有 Python；需求仍在演進。不適合：既有產品（如 Claude Code、Codex）已滿足穩定需求；心智模型不符 controller/tools/triggers/sub-agents/channels；需 sub-50 ms per-operation latency。詳見 `docs/en/concepts/boundaries.md`。

**程式碼庫地圖**
```
src/kohakuterrarium/
  core/              # Agent runtime, controller, executor, events, environment
  bootstrap/         # Agent initialisation factories (LLM, tools, I/O, triggers, plugins)
  cli/               # `kt` command dispatcher
  terrarium/         # Multi-agent runtime, topology wiring, hot-plug, persistence
  builtins/          # Built-in tools, sub-agents, I/O modules, TUI, user commands, CLI UI
  builtin_skills/    # Markdown skill manifests for on-demand docs
  session/           # Session persistence, memory search, embeddings
  serving/           # Transport-agnostic service manager and event streaming
  api/               # FastAPI HTTP + WebSocket server
  compose/           # Composition algebra primitives
  mcp/               # MCP client manager
  modules/           # Base protocols for tools, inputs, outputs, triggers, sub-agents, user commands
  llm/               # LLM providers, profiles, API key management
  parsing/           # Tool-call parsing and stream handling
  prompt/            # Prompt aggregation, plugins, skill loading
  testing/           # Test infrastructure (ScriptedLLM, TestAgentBuilder, recorders)

src/kohakuterrarium-frontend/   # Vue web frontend
kt-biome/                    # (separate repo) Official OOTB pack
examples/                       # Example creatures, terrariums, code samples, plugins
docs/                           # Tutorials, guides, concepts, reference, dev
```

**文件資源**
全 docs 在 `docs/en/README.md`。Tutorials：First Creature (`docs/en/tutorials/first-creature.md`)、First Terrarium (`docs/en/tutorials/first-terrarium.md`)、First Python Embedding (`docs/en/tutorials/first-python-embedding.md`)、First Custom Tool (`docs/en/tutorials/first-custom-tool.md`)、First Plugin (`docs/en/tutorials/first-plugin.md`)。Guides：Getting Started (`docs/en/guides/getting-started.md`)、Creatures (`docs/en/guides/creatures.md`)、Terrariums (`docs/en/guides/terrariums.md`)、Sessions (`docs/en/guides/sessions.md`)、Memory (`docs/en/guides/memory.md`)、Configuration (`docs/en/guides/configuration.md`)、Programmatic Usage (`docs/en/guides/programmatic-usage.md`)、Composition (`docs/en/guides/composition.md`)、Custom Modules (`docs/en/guides/custom-modules.md`)、Plugins (`docs/en/guides/plugins.md`)、MCP (`docs/en/guides/mcp.md`)、Packages (`docs/en/guides/packages.md`)、Serving (`docs/en/guides/serving.md`)、Examples (`docs/en/guides/examples.md`)。Concepts：Glossary (`docs/en/concepts/glossary.md`)、Why KohakuTerrarium (`docs/en/concepts/foundations/why-kohakuterrarium.md`)、What is an agent (`docs/en/concepts/foundations/what-is-an-agent.md`)、Composing an agent (`docs/en/concepts/foundations/composing-an-agent.md`)、Modules (`docs/en/concepts/modules/README.md`)、Agent as a Python object (`docs/en/concepts/python-native/agent-as-python-object.md`)、Composition algebra (`docs/en/concepts/python-native/composition-algebra.md`)、Multi-agent (`docs/en/concepts/multi-agent/README.md`)、Patterns (`docs/en/concepts/patterns.md`)、Boundaries (`docs/en/concepts/boundaries.md`)。Reference：CLI (`docs/en/reference/cli.md`)、HTTP (`docs/en/reference/http.md`)、Python API (`docs/en/reference/python.md`)、Configuration (`docs/en/reference/configuration.md`)、Builtins (`docs/en/reference/builtins.md`)、Plugin hooks (`docs/en/reference/plugin-hooks.md`)。Resources：`examples/README.md (`examples/README.md`)。

**Roadmap 與貢獻**
近期待辦：更可靠 terrarium flow、更豐富 UI output/interaction modules（跨 CLI/TUI/web）、更多 built-in creatures/plugins/integrations、daemon-backed workflows 支援 long-running/remote。詳見 `ROADMAP.md`。貢獻：Contributing docs (`docs/en/dev/README.md`)、Testing (`docs/en/dev/testing.md`)、Internals (`docs/en/dev/internals.md`)、Frontend architecture (`docs/en/dev/frontend.md`)。

**授權資訊**
KohakuTerrarium License 1.0 (`LICENSE`)，基於 Apache-2.0，附加 naming/attribution：衍生作品須含 `Kohaku` 或 `Terrarium` 名稱，並提供 visible attribution 連結此專案。Copyright 2024-2026 Shih-Ying Yeh (KohakuBlueLeaf) 和 contributors。

## 標籤

Agent, 新產品, 開源專案, KohakuTerrarium
