diff --git a/website/ec.config.mjs b/website/ec.config.mjs new file mode 100644 index 00000000..c0bfc300 --- /dev/null +++ b/website/ec.config.mjs @@ -0,0 +1,21 @@ +// @ts-check +import { defineEcConfig } from '@astrojs/starlight/expressive-code'; +import { + pluginCollapsibleSections, + pluginCollapsibleSectionsTexts, +} from '@expressive-code/plugin-collapsible-sections'; +import { pluginLineNumbers } from '@expressive-code/plugin-line-numbers'; + +pluginCollapsibleSectionsTexts.addLocale('zh-CN', { + collapsedLines: '已折叠 {lineCount} 行代码', +}); + +export default defineEcConfig({ + themes: ['night-owl', 'night-owl-light'], + useStarlightUiThemeColors: true, + plugins: [pluginCollapsibleSections(), pluginLineNumbers()], + defaultProps: { + collapseStyle: 'collapsible-auto', + showLineNumbers: false, + }, +}); diff --git a/website/package.json b/website/package.json index 69edd40b..f2cc88a9 100644 --- a/website/package.json +++ b/website/package.json @@ -19,6 +19,8 @@ "@astrojs/markdown-satteri": "^0.4.3", "@astrojs/starlight": "^0.42.6", "@astrojs/starlight-tailwind": "^5.0.0", + "@expressive-code/plugin-collapsible-sections": "^0.44.4", + "@expressive-code/plugin-line-numbers": "^0.44.4", "@fontsource-variable/jetbrains-mono": "^5.3.0", "@fontsource-variable/outfit": "^5.3.0", "@fontsource/noto-sans-sc": "^5.3.1", diff --git a/website/pnpm-lock.yaml b/website/pnpm-lock.yaml index 1946c153..39cf56cf 100644 --- a/website/pnpm-lock.yaml +++ b/website/pnpm-lock.yaml @@ -208,6 +208,12 @@ importers: '@astrojs/starlight-tailwind': specifier: ^5.0.0 version: 5.0.0(@astrojs/starlight@0.42.6(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(astro@7.4.11(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(@types/node@24.19.0)(@vercel/functions@3.4.3)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(supports-color@10.2.2))(tailwindcss@4.3.3) + '@expressive-code/plugin-collapsible-sections': + specifier: ^0.44.4 + version: 0.44.4 + '@expressive-code/plugin-line-numbers': + specifier: ^0.44.4 + version: 0.44.4 '@fontsource-variable/jetbrains-mono': specifier: ^5.3.0 version: 5.3.0 @@ -886,17 +892,23 @@ packages: cpu: [x64] os: [win32] - '@expressive-code/core@0.44.2': - resolution: {integrity: sha512-Yw5KonQCD1HoOO2P89y4wifqS9qrJcGVY0LkVMUsVZjhi++bhz4WwQ37inenKFNOEVo50P7cjoVsCdaVnUbq8w==} + '@expressive-code/core@0.44.4': + resolution: {integrity: sha512-dkn3fyIZeHaqQCnpX5ESSR7eI9FMeLFiKDCzFliFy2SPog6sf9NFmiO9wzvEMfgmL8GMWK6P25l6JYLP2wRoLA==} - '@expressive-code/plugin-frames@0.44.2': - resolution: {integrity: sha512-gVLm6TQMNIRWIaM7o+mCtxkGNjLZY5/2faSTLoXeo9wv/Pkj/0QAtZyXPVPrRsPARqiipATNFmfvQFLJudxPHQ==} + '@expressive-code/plugin-collapsible-sections@0.44.4': + resolution: {integrity: sha512-j13t8fd+qmV5QjhWvYpO7AlrfHQSoLZBcOwLPAU8lkOGZRQPTSN3bBXjS9FSqecAskl1hjZJgMQ3x119oQLSQA==} - '@expressive-code/plugin-shiki@0.44.2': - resolution: {integrity: sha512-ebWIvCDzXvjyD8rH6T6DfytYJw1GoArLR4nusIAE4VxXrCQf3d+owytiv010KU/dUg+SRLZskDn0N+HaFXeuSg==} + '@expressive-code/plugin-frames@0.44.4': + resolution: {integrity: sha512-wlfwIl62MlPiE6qj1HuqMfpDF96RyAn2YxaD9qct5d+CjmH8G3j819wPJ23NgWtEqSVIJKdZVeN8OcRHafUiyw==} - '@expressive-code/plugin-text-markers@0.44.2': - resolution: {integrity: sha512-SNI7EgUSiADqbqUzzMbj1ZeC/r2pa5eg3KyFOGAd3a7EsIA4qzjXQLp+ODWQtHVDKFCdGs4J3ovSJUqvKIK96g==} + '@expressive-code/plugin-line-numbers@0.44.4': + resolution: {integrity: sha512-/lNaPhXbHbyecrstWtLua4x4xIaLdY3QGaZQQAM+0d0tXoUsxrLjTBmI0W/6PpsI8UnK/9eK2Png/QrcNsvaUA==} + + '@expressive-code/plugin-shiki@0.44.4': + resolution: {integrity: sha512-390h3iPn6eTYzQvdv/b5YD7K96/86PLPHzaEBNLm44dmSufcTqcOC8zR8R0T5DBE+KTlT/ValIhwjUNy/9DreA==} + + '@expressive-code/plugin-text-markers@0.44.4': + resolution: {integrity: sha512-cfjqsNh4oYikxFeylXKhZ0BxvrwIIztu+g5JFFObYMO3YTmHwv66DrHCh91wTgTGz0q4+Tj/iTIYkngqCpX0Cg==} '@fontsource-variable/jetbrains-mono@5.3.0': resolution: {integrity: sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==} @@ -1538,8 +1550,8 @@ packages: resolution: {integrity: sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg==} hasBin: true - astro-expressive-code@0.44.2: - resolution: {integrity: sha512-avop7nZcRwC7quvIxVguhwEZ9Tp6IoTzKUCLwP30Fb7+er+pWQgcysP01dcuzRIJo81kLGg30q/YAI2Yb1Sdzg==} + astro-expressive-code@0.44.4: + resolution: {integrity: sha512-TxdQ/E1xP7P6gq9Z5XHuLNpWzgOP2xz7aKyW3w2FDkIOkXbcyXh/C7of7E+NYIX3Ws2Oq+Aaliuwy/ewavH+UQ==} peerDependencies: astro: ^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0 @@ -1798,8 +1810,8 @@ packages: estree-walker@3.0.3: resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} - expressive-code@0.44.2: - resolution: {integrity: sha512-MLNghkvhyFgVW4oCD5DxBuYnnTXIf0PygzGmfT6OZeOOYWh/D4sH1j931biElkA5RG/J9wY/iuSMGAPF5vzHOg==} + expressive-code@0.44.4: + resolution: {integrity: sha512-xaHx7AG7MCmxBkw9d84IQ7OGZLxzYhLYE8/eurS5JSRfY8P6/1XA6I7FueYwqOGKJH/1HPk3/Pmf+9HgVAsTcg==} extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} @@ -2388,11 +2400,6 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - nanoid@3.3.19: - resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==} - engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} - hasBin: true - nanoid@3.3.20: resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -2485,23 +2492,19 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} - postcss-nested@6.2.0: - resolution: {integrity: sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==} - engines: {node: '>=12.0'} + postcss-nested@7.0.2: + resolution: {integrity: sha512-5osppouFc0VR9/VYzYxO03VaDa3e8F23Kfd6/9qcZTUI8P58GIYlArOET2Wq0ywSl2o2PjELhYOFI4W7l5QHKw==} + engines: {node: '>=18.0'} peerDependencies: postcss: ^8.2.14 - postcss-selector-parser@6.1.6: - resolution: {integrity: sha512-BK87/Qgti3DIcgS2PaCVoteFIkjIFvCJBizZDIVSjdlFNg4Jv+SRqbN2JONb/qQUH4ZFqfXYF+izg15W2HVRvA==} + postcss-selector-parser@7.2.1: + resolution: {integrity: sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ==} engines: {node: '>=4'} postcss-value-parser@4.2.0: resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} - postcss@8.5.28: - resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} - engines: {node: ^10 || ^12 || >=14} - postcss@8.5.32: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} @@ -2551,8 +2554,8 @@ packages: regex@6.1.0: resolution: {integrity: sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==} - rehype-expressive-code@0.44.2: - resolution: {integrity: sha512-jvjQpsfWKBquDrEl5YQA3CJybRRIuDOYsui1BJTs5oKDUK8pPkJSSxY8FjxNlIFIdtgrTjC1zuahuY4Cc1j9SQ==} + rehype-expressive-code@0.44.4: + resolution: {integrity: sha512-TciCyvRGs1bAXsTr7ZtUksNBxj6gqvgD9yqJDOW/c/V3mkYglgwcjnY281nbYblGDUn+IhBT+HwQP6rT/OFwsw==} rehype-raw@7.0.0: resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==} @@ -3229,7 +3232,7 @@ snapshots: '@types/js-yaml': 4.0.9 '@types/mdast': 4.0.4 astro: 7.4.11(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(@types/node@24.19.0)(@vercel/functions@3.4.3)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) - astro-expressive-code: 0.44.2(astro@7.4.11(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(@types/node@24.19.0)(@vercel/functions@3.4.3)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) + astro-expressive-code: 0.44.4(astro@7.4.11(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(@types/node@24.19.0)(@vercel/functions@3.4.3)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) bcp-47: 2.1.1 hast-util-format: 1.1.0 hast-util-select: 6.0.4 @@ -3565,30 +3568,38 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true - '@expressive-code/core@0.44.2': + '@expressive-code/core@0.44.4': dependencies: '@ctrl/tinycolor': 4.2.1 hast-util-select: 6.0.4 - hast-util-to-html: 9.0.5 + hast-util-to-html: 9.0.6 hast-util-to-text: 4.0.2 hastscript: 9.0.1 - postcss: 8.5.28 - postcss-nested: 6.2.0(postcss@8.5.28) + postcss: 8.5.32 + postcss-nested: 7.0.2(postcss@8.5.32) unist-util-visit: 5.1.0 unist-util-visit-parents: 6.0.2 - '@expressive-code/plugin-frames@0.44.2': + '@expressive-code/plugin-collapsible-sections@0.44.4': dependencies: - '@expressive-code/core': 0.44.2 + '@expressive-code/core': 0.44.4 - '@expressive-code/plugin-shiki@0.44.2': + '@expressive-code/plugin-frames@0.44.4': dependencies: - '@expressive-code/core': 0.44.2 - shiki: 4.4.3 + '@expressive-code/core': 0.44.4 - '@expressive-code/plugin-text-markers@0.44.2': + '@expressive-code/plugin-line-numbers@0.44.4': dependencies: - '@expressive-code/core': 0.44.2 + '@expressive-code/core': 0.44.4 + + '@expressive-code/plugin-shiki@0.44.4': + dependencies: + '@expressive-code/core': 0.44.4 + shiki: 4.6.0 + + '@expressive-code/plugin-text-markers@0.44.4': + dependencies: + '@expressive-code/core': 0.44.4 '@fontsource-variable/jetbrains-mono@5.3.0': {} @@ -4133,10 +4144,10 @@ snapshots: astring@1.9.0: optional: true - astro-expressive-code@0.44.2(astro@7.4.11(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(@types/node@24.19.0)(@vercel/functions@3.4.3)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)): + astro-expressive-code@0.44.4(astro@7.4.11(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(@types/node@24.19.0)(@vercel/functions@3.4.3)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)): dependencies: astro: 7.4.11(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(@types/node@24.19.0)(@vercel/functions@3.4.3)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) - rehype-expressive-code: 0.44.2 + rehype-expressive-code: 0.44.4 url-extras: 0.1.0 astro@7.4.11(@astrojs/markdown-remark@7.3.1(supports-color@10.2.2))(@types/node@24.19.0)(@vercel/functions@3.4.3)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1): @@ -4484,12 +4495,12 @@ snapshots: '@types/estree': 1.0.9 optional: true - expressive-code@0.44.2: + expressive-code@0.44.4: dependencies: - '@expressive-code/core': 0.44.2 - '@expressive-code/plugin-frames': 0.44.2 - '@expressive-code/plugin-shiki': 0.44.2 - '@expressive-code/plugin-text-markers': 0.44.2 + '@expressive-code/core': 0.44.4 + '@expressive-code/plugin-frames': 0.44.4 + '@expressive-code/plugin-shiki': 0.44.4 + '@expressive-code/plugin-text-markers': 0.44.4 extend@3.0.2: {} @@ -5478,8 +5489,6 @@ snapshots: ms@2.1.3: {} - nanoid@3.3.19: {} - nanoid@3.3.20: {} neotraverse@1.0.1: {} @@ -5578,23 +5587,17 @@ snapshots: picomatch@4.0.7: {} - postcss-nested@6.2.0(postcss@8.5.28): + postcss-nested@7.0.2(postcss@8.5.32): dependencies: - postcss: 8.5.28 - postcss-selector-parser: 6.1.6 + postcss: 8.5.32 + postcss-selector-parser: 7.2.1 - postcss-selector-parser@6.1.6: + postcss-selector-parser@7.2.1: dependencies: util-deprecate: 1.0.2 postcss-value-parser@4.2.0: {} - postcss@8.5.28: - dependencies: - nanoid: 3.3.19 - picocolors: 1.1.1 - source-map-js: 1.2.2 - postcss@8.5.32: dependencies: nanoid: 3.3.20 @@ -5657,9 +5660,9 @@ snapshots: dependencies: regex-utilities: 2.3.0 - rehype-expressive-code@0.44.2: + rehype-expressive-code@0.44.4: dependencies: - expressive-code: 0.44.2 + expressive-code: 0.44.4 rehype-raw@7.0.0: dependencies: diff --git a/website/src/content/docs/docs/app/configure.mdx b/website/src/content/docs/docs/app/configure.mdx index 10e17828..84da5836 100644 --- a/website/src/content/docs/docs/app/configure.mdx +++ b/website/src/content/docs/docs/app/configure.mdx @@ -1,34 +1,32 @@ --- title: Configuration -description: How to configure the Bub application. +description: Configure the Bub app with the setup wizard, YAML config, BUB_* environment variables, fallback models, and optional Telegram channel. --- -Bub reads configuration in this order, highest priority first: +Bub resolves configuration in this order (highest priority first): -1. Environment variables (the `BUB_` prefix); -2. `.env`, loaded from the current workspace at CLI startup, or read by settings classes that declare `env_file=".env"`; -3. `~/.bub/config.yml`, created by `bub onboard`. +1. Environment variables (`BUB_` prefix); +2. `.env` in the current workspace; +3. `~/.bub/config.yml` (created by `bub onboard`). -Fields not declared in the configuration use the settings class defaults. See the [full example](/docs/reference/settings/#example) for every writable field. - -:::note[Before you begin] - -- Make sure the Bub CLI is [installed](/docs/getting-started/install/). -- You have an API key from a model provider, or you have completed OAuth with `bub login codex` (OpenAI only). +Unset fields use their defaults. See the [Settings reference](/docs/reference/settings/) for all options. +:::note[Before you start] +- [Install the Bub CLI](/docs/getting-started/install/#app-install). +- Prepare an API key from a model provider, or sign in with `bub login codex` (OpenAI only). ::: -## 1. Finish the initial setup {#initial-setup} +## 1. Run the setup wizard {#initial-setup} -Run the following command in your terminal to start the interactive setup. When it finishes, it writes the result to `~/.bub/config.yml`. +Run the following command in your terminal to start the interactive setup wizard and generate `~/.bub/config.yml`: ```bash bub onboard ``` -## 2. Check the config file {#check-the-config} +## 2. Inspect the config file {#check-the-config} -Now check whether `~/.bub/config.yml` contains the content described in the [full example](/docs/reference/settings/#example). Here is an example: +Now inspect `~/.bub/config.yml`. Here is an example of what it looks like: ```yaml title="~/.bub/config.yml" model: openrouter:openrouter/free @@ -39,56 +37,56 @@ telegram: ``` :::danger -**By default, your keys are written directly to the config file in plain text.** If you need stronger security and want to avoid storing model provider API keys locally in plain text, pass environment variables when running Bub to set or override them instead. +`bub onboard` writes API keys to `~/.bub/config.yml` in plain text by default. To avoid storing keys in the config file, leave the key blank during onboarding and pass it via environment variables instead. ::: -## 3. Override with environment variables {#environment-variables} +## 3. Use environment variables {#environment-variables} -Commonly used environment variables include: +Common environment variables: | Variable | Description | |---|---| -| `BUB_MODEL` | Model identifier, such as `openrouter:openrouter/free` or `codex:`. | -| `BUB_API_KEY` | API key for the current provider; not needed with `bub login codex`. | -| `BUB_API_BASE` | Provider service URL; leave it blank for the default endpoint. | -| `BUB_HOME` | Runtime data directory, default `~/.bub`. | -| `BUB__API_KEY` | Key for a specific provider, such as `BUB_OPENROUTER_API_KEY`. | -| `BUB__API_BASE` | Service URL for a specific provider. | +| `BUB_MODEL` | Model identifier in `provider:model` format (e.g. `openrouter:openrouter/free`, `codex:`) | +| `BUB_API_KEY` | API key for the current provider (not needed with `bub login`) | +| `BUB_API_BASE` | Provider API base URL; leave blank for the default endpoint | +| `BUB_HOME` | Runtime data directory (default `~/.bub`) | +| `BUB__API_KEY` | Provider-specific API key, e.g. `BUB_OPENROUTER_API_KEY` | +| `BUB__API_BASE` | Provider-specific API base URL | -See the [settings reference](/docs/reference/settings/) for the full table. +See the [Settings reference](/docs/reference/settings/) for the full table. -## 4. Configure the model and fallback models {#configure-models} +## 4. Configure fallback models {#configure-models} -The `model` setting uses the `provider:model` format. To try fallback models in order when the primary model is unavailable, configure them in `~/.bub/config.yml`: +Set `fallback_models` to try backup models in order when the primary model is unavailable: -```yaml +```yaml title="~/.bub/config.yml" ins={2-3} model: openai:gpt-5-mini fallback_models: - openrouter:openrouter/free ``` -Each candidate provider needs its own valid credentials. Fallbacks only cover failures while creating a client and opening a request; errors after the message stream has started are not retried with another model, to avoid duplicate side effects. See [Models and fallback](/docs/reference/settings/#model-routing) for the full rules. +Each candidate provider requires valid credentials. Fallbacks apply only when creating a client or opening the request stream fails; errors after streaming has started do not retry on another model to avoid duplicate tool side effects. See [Models and fallback](/docs/reference/settings/#model-routing). -## 5. Configure the Telegram channel (optional) {#telegram-channel} +## 5. Configure Telegram (optional) {#telegram-channel} -If you want to use Bub as a Telegram bot, use the built-in Telegram channel. Example configuration: +If you want to use Bub as a Telegram bot, configure the built-in Telegram channel in `.env`: -```bash +```bash title=".env" BUB_TELEGRAM_TOKEN=123456789:your-telegram-bot-token BUB_TELEGRAM_ALLOW_USERS=123456789,your_username BUB_TELEGRAM_ALLOW_CHATS=-1001234567890 BUB_TELEGRAM_PROXY=http://127.0.0.1:7890 # optional ``` -See [Telegram channel](/docs/app/gateway/#telegram) for more configuration options. +See [Telegram gateway](/docs/app/gateway/#telegram) for details. ## 6. Verify {#verify} -Now try talking to Bub: +Now try talking to Bub with a one-off prompt to verify your setup: ```bash wrap $ bub run "Can you introduce yourself?" [cli:local] -I'm a virtual assistant designed to support a wide range of tasks including coding, design, research, and automation. I can integrate with code repositories, access web resources, leverage specialized skills, and streamline workflows. If you have specific tasks or questions about my capabilities, feel free to ask! +I'm a virtual assistant designed to support a wide range of tasks... ``` diff --git a/website/src/content/docs/docs/app/deploy.mdx b/website/src/content/docs/docs/app/deploy.mdx index e0e66108..bc3d9b2d 100644 --- a/website/src/content/docs/docs/app/deploy.mdx +++ b/website/src/content/docs/docs/app/deploy.mdx @@ -1,45 +1,39 @@ --- title: Deployment -description: Run the Bub gateway and cloud sandbox, covering Docker Compose and Daemon service modes. +description: Deploy the Bub gateway and isolated execution sandbox in production using Docker Compose or a system daemon, with a security checklist. --- import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; -Bub can be used interactively in a local terminal (see [Terminal interaction](/docs/app/terminal/)), or deployed to a server to run as a long-lived process: +Bub works interactively in your local terminal (see [Terminal interaction](/docs/app/terminal/)), and you can also deploy it to a server as a long-running service: -- **Persistent gateway (Gateway)**: listen on channels such as Telegram and Feishu around the clock and respond to messages. -- **Cloud isolated sandbox (Remote Workspace)**: provide a complete development toolchain inside an isolated container, accessed through the terminal with `bub chat`, keeping the host machine safe. +- **Persistent message gateway**: listen on Telegram, Feishu, or Discord 24/7 and reply to messages. +- **Containerized sandbox**: run development toolchains inside an isolated container and attach via `bub chat` without exposing the host filesystem. -There are two main deployment approaches: +Comparison of the two deployment modes: -| Approach | Scenario | Advantages | +| Mode | Best for | Key benefits | | --- | --- | --- | -| **Docker Compose** (recommended) | Cloud servers, VPS, NAS, local containers | Works out of the box with Node/pnpm/Python/Git and other toolchains included; isolated environment, easy to back up and upgrade | -| **Daemon mode** | Linux / Windows hosts that already have a Python environment | Low resource usage; register as a system background service in one step with `bub gateway --install` | - ---- +| **Docker Compose** (recommended) | Cloud VMs, VPS, NAS, local containers | Bundles Python, `uv`, Git, Node.js, and pnpm; isolates the host; easy to back up and upgrade | +| **System daemon** | Linux / Windows hosts with an existing Python environment | Low overhead; registers as a user service in one command via `bub gateway --install` | ## Before you start {#before-you-start} -Complete the following preparation before deploying: - -1. **Model configuration**: specify `BUB_MODEL` and `BUB_API_KEY` in `.env`. See [Configuration](/docs/app/configure/) for details. -2. **Channel credentials and allowlist**: when connecting channels such as Telegram, **always configure an allowlist** (for example `BUB_TELEGRAM_ALLOW_USERS`) to prevent unauthorized access from consuming tokens. -3. **Data persistence**: session state (Tape), history, and plugins are stored in the data directory (host `~/.bub`, container `/data`). Make sure persistent storage is in place when deploying. +1. **Model credentials**: set `BUB_MODEL` and `BUB_API_KEY` in `.env` (see [Configuration](/docs/app/configure/)). +2. **Channel allowlists**: **always configure an allowlist** (such as `BUB_TELEGRAM_ALLOW_USERS`) so unauthorized users cannot invoke your agent. +3. **Persistent data volume**: mount the data directory (host `~/.bub`, container `/data`) to preserve session Tapes and managed plugins across restarts. :::caution[Security warning] -Never leave the allowlist empty in a production deployment! If the allowlist is empty, anyone who can find the bot can send it commands and invoke Agent tools. +Never deploy to production with an empty allowlist. Without an allowlist, anyone who finds your bot can send prompts and run Agent tools. ::: ---- +## Docker Compose deployment {#docker-compose} -## Docker Compose {#docker-compose} +The official image (`ghcr.io/bubbuild/bub`) comes preinstalled with Python 3.12, `uv`, Git, Node.js, and pnpm. -The official image (`ghcr.io/bubbuild/bub`) bundles Python 3.12, `uv`, Git, Node.js, pnpm, and common command-line tools. The host only needs to provide configuration files and storage volumes. +### 1. Prepare configuration {#configure} -### 1. Configure the environment {#configure} - -Fetch [`docker-compose.yml`](https://github.com/bubbuild/bub/blob/main/docker-compose.yml) and [`env.example`](https://github.com/bubbuild/bub/blob/main/env.example) into the deployment directory: +Download [`docker-compose.yml`](https://github.com/bubbuild/bub/blob/main/docker-compose.yml) and [`env.example`](https://github.com/bubbuild/bub/blob/main/env.example): ```bash mkdir -p bub-deploy && cd bub-deploy @@ -48,71 +42,61 @@ curl -O https://raw.githubusercontent.com/bubbuild/bub/main/env.example cp env.example .env ``` -Fill in the core parameters in `.env`: +Edit `.env`: -```bash +```bash title=".env" # Model BUB_MODEL=openrouter:openrouter/free BUB_API_KEY=sk-or-... -# Channel (Telegram as an example) +# Channel (Telegram example) BUB_TELEGRAM_TOKEN=123456789:your-telegram-bot-token BUB_TELEGRAM_ALLOW_USERS=123456789,your_telegram_username -# Host data directory and workspace (optional) +# Optional host paths # BUB_HOME_HOST=~/.bub # BUB_WORKSPACE_PATH=. ``` -`docker compose` reads `.env` from the current directory automatically. Never commit an `.env` containing tokens to a public repository. - -### 2. Mount directories {#volumes} +### 2. Review volume mounts {#volumes} -By default, `docker-compose.yml` contains three volume mounts: +`docker-compose.yml` mounts three directories by default: -```yaml +```yaml title="docker-compose.yml" volumes: - ${BUB_WORKSPACE_PATH:-.}:/workspace - ${BUB_HOME_HOST:-${HOME}/.bub}:/data - ${BUB_AGENT_HOME:-${HOME}/.agents}:/root/.agents ``` -| Container path | Corresponding host path | Description | +| Container path | Host path | Purpose | | --- | --- | --- | -| `/workspace` | `BUB_WORKSPACE_PATH` (default current directory) | **Workspace**: the directory where the Agent executes commands and reads/writes files | -| `/data` | `BUB_HOME_HOST` (default `~/.bub`) | **Data directory**: stores Tape, history, and managed plugins (`/data/bub-project`) | -| `/root/.agents` | `BUB_AGENT_HOME` (default `~/.agents`) | **Global skills**: Agent skills directory reused across projects | +| `/workspace` | `BUB_WORKSPACE_PATH` (default `.`) | **Workspace**: directory where the Agent reads/writes files and runs commands | +| `/data` | `BUB_HOME_HOST` (default `~/.bub`) | **Data directory** (`BUB_HOME=/data`): stores session Tapes and managed plugins | +| `/root/.agents` | `BUB_AGENT_HOME` (default `~/.agents`) | **Global skills**: shared skills across workspaces | -`BUB_HOME=/data` is set inside the container, so session data and plugins survive container destruction and recreation. - -:::danger[Isolation precautions] -The workspace determines the file scope the Agent can reach. **Never** mount the host root `/` or any directory containing sensitive keys into `/workspace`. +:::danger[Do not mount sensitive host directories] +The workspace defines which files the Agent can access. **Never** mount the host root `/` or directories containing secrets into `/workspace`. ::: -### 3. Start {#start} +### 3. Start the container {#start} - - Pull the image and start it in the background: - + ```bash docker compose pull docker compose up -d docker compose logs -f app ``` - In production, pin a specific tag in `.env` (for example `BUB_IMAGE=ghcr.io/bubbuild/bub:0.6.0`). + In production, pin a specific version tag in `.env` (e.g. `BUB_IMAGE=ghcr.io/bubbuild/bub:0.6.0`). - Build from source and start: - ```bash docker compose up -d --build ``` - - The equivalent command when you do not use Compose: - + ```bash docker run -d --name bub --restart unless-stopped \ --env-file .env \ @@ -127,147 +111,118 @@ The workspace determines the file scope the Agent can reach. **Never** mount the -### 4. Verify {#verify} - -Check the container status and gateway logs: +### 4. Verify startup {#verify} ```bash docker compose ps docker compose logs -f app ``` -When the Telegram gateway starts normally, it outputs: +When the Telegram gateway is ready, it logs: ```text telegram.start allow_users_count=1 allow_chats_count=0 proxy_enabled=False telegram.start polling ``` -Check that an environment variable was injected (without printing its value): +### 5. Attach an interactive chat {#chat} -```bash -docker compose exec app sh -c 'test -n "$BUB_TELEGRAM_TOKEN" && echo token-present' -``` - -### 5. Interactive chat {#chat} - -Compose enables `stdin_open` and `tty` by default. Even if the container runs the gateway in the background, you can enter the container at any time and start an interactive conversation: +Compose enables `stdin_open` and `tty` by default. Even while the container runs the gateway in the background, you can attach at any time for an interactive `bub chat` session: ```bash docker compose exec -it app bub chat ``` -This lets you pair-program directly with the Agent using the preinstalled toolchain in a fully isolated cloud sandbox. +This lets you pair-program directly with the Agent inside an isolated cloud sandbox with the preinstalled toolchain. ### 6. Customize startup and dependencies {#entrypoint} -On container startup, `entrypoint.sh` runs the following in order: +At container startup, `entrypoint.sh` runs three steps: -1. **Install Python dependencies**: if `/workspace/bub-reqs.txt` exists, install them automatically with `uv pip install`. - -2. **Sync plugins**: activate the virtual environment and run `bub install` to sync the managed plugins in `/data/bub-project`. - -3. **Run the entrypoint**: if `/workspace/startup.sh` exists, run it with `bash`; otherwise run `bub gateway`. +1. If `/workspace/bub-reqs.txt` exists, installs extra Python packages via `uv pip install`. +2. Activates the virtual environment and runs `bub install` to sync managed plugins in `/data/bub-project`. +3. Executes `/workspace/startup.sh` if present; otherwise runs `bub gateway`. -#### Override the startup command example {#override-command} - -Create `startup.sh` in the workspace and make it executable: +To customize the startup command, create an executable `/workspace/startup.sh` (use `exec` so shutdown signals reach the gateway): ```bash #!/bin/bash # /workspace/startup.sh set -euo pipefail - -# You must use exec to replace the process so that system signals are delivered to the gateway correctly exec /app/.venv/bin/bub gateway --enable-channel telegram ``` -### 7. Plugin management {#plugins} +### 7. Manage plugins inside the container {#plugins} -Managed plugins live in the persistent volume `/data/bub-project`. Install them directly inside the container without rebuilding the image: +Managed plugins live on the `/data/bub-project` volume and can be installed or updated without rebuilding the image: ```bash -# Install a plugin docker compose exec app bub install https://github.com/owner/repo.git@v1.2.0 - -# Update plugins docker compose exec app bub update - -# Restart to activate the new plugins docker compose restart app ``` -### 8. Backup and upgrade {#upgrade} +### 8. Back up and upgrade {#upgrade} -Tape is an append-only JSONL file. Before upgrading, pause writes and make a backup: +Stop the container and back up the data directory before upgrading: ```bash -# 1. Stop writes and back up docker compose stop app tar -czf "bub-data-$(date +%Y%m%d-%H%M%S).tar.gz" "$HOME/.bub" cp .env ".env.bak-$(date +%Y%m%d-%H%M%S)" -# 2. Pull the new image and start docker compose pull docker compose up -d ``` -To roll back, simply switch back to the old tag in `.env` (for example `BUB_IMAGE=ghcr.io/bubbuild/bub:0.6.0`) and restart. +To roll back, switch `BUB_IMAGE` back to the previous tag in `.env` (for example `BUB_IMAGE=ghcr.io/bubbuild/bub:0.6.0`) and restart. --- -## Daemon mode {#daemon} +## System daemon mode {#daemon} -On a host that already has a Python environment, you can use the built-in `--install` command of `bub gateway` to register it directly as a system background service: +On a Linux or Windows host with Python installed, you can register the gateway as a background user service with `bub gateway --install`: - **Linux**: registers as a systemd user service at `~/.config/systemd/user/bub-gateway.service`. -- **Windows**: registers as a scheduled task for the current user (auto-start at login, automatic restart on failure). -- **macOS**: `--install` is not supported yet; use launchd, tmux, or the Docker approach above. +- **Windows**: registers as a scheduled task for the current user (starts at login and restarts on failure). +- **macOS**: `--install` is not supported yet; use `launchd`, `tmux`, or the Docker approach above. ### 1. Install the service {#daemon-install} -Run the following in the workspace directory that contains `.env`: +Run in the workspace directory containing `.env`: ```bash -# Create the environment and install the app uv venv && source .venv/bin/activate uv pip install 'bub[app]' - -# Install and start the background service in one step bub gateway --install ``` The installer automatically records the current Python interpreter path, workspace directory, and environment variables. -### 2. Keep alive and manage {#daemon-manage} +### 2. Manage the service (Linux) {#daemon-manage} -After a Linux user logs out of SSH, user-level services are suspended by default. To keep running around the clock, enable linger: +After you log out of SSH on Linux, user-level services stop by default. Enable linger to keep the gateway running 24/7: ```bash loginctl enable-linger $USER ``` -Common management commands: +Common `systemctl` commands: ```bash -# Check status systemctl --user status bub-gateway - -# Follow logs in real time journalctl --user -u bub-gateway -f - -# Restart and stop systemctl --user restart bub-gateway systemctl --user stop bub-gateway ``` ### 3. Uninstall the service {#daemon-uninstall} -To remove the background service: +To remove the background service, run: ```bash bub gateway --uninstall @@ -275,10 +230,10 @@ bub gateway --uninstall --- -## Security recommendations {#security-checklist} +## Security checklist {#security-checklist} -- **Strict allowlist**: configure `BUB_TELEGRAM_ALLOW_USERS` or `BUB_TELEGRAM_ALLOW_CHATS`; messages that fail validation are rejected or silently dropped. -- **Minimize the workspace**: mount only the project directories you need into the workspace, and do not let the Agent access directories containing host keys or critical system paths. -- **Step limit**: cap the steps per task with `BUB_MAX_STEPS` to guard against infinite loops and API quota consumption. It is unlimited by default (`sys.maxsize`), so production deployments should set it explicitly, for example to 50. -- **Credential security**: inject secrets through `.env` or environment variables, and never commit tokens to version control. -- **Regular backups**: periodically archive and back up the Tape files in `~/.bub` (or the container's `/data`). +- **Configure allowlists**: set `BUB_TELEGRAM_ALLOW_USERS` or `BUB_TELEGRAM_ALLOW_CHATS`. +- **Scope the workspace**: mount only the target project directory, never host credentials or system paths. +- **Set a step limit**: configure `BUB_MAX_STEPS` (unlimited by default; set to e.g. `50` in production) to prevent runaway loops. +- **Protect secrets**: pass API keys via `.env` or environment variables and keep them out of version control. +- **Back up Tapes regularly**: archive `~/.bub` (or container `/data`) periodically. diff --git a/website/src/content/docs/docs/app/distribution.mdx b/website/src/content/docs/docs/app/distribution.mdx index 1fc79bd3..aa28acba 100644 --- a/website/src/content/docs/docs/app/distribution.mdx +++ b/website/src/content/docs/docs/app/distribution.mdx @@ -1,69 +1,66 @@ --- title: Packaging and distribution -description: Package Bub apps, your own commands, plugins, and skills into standard Python distributions, and verify them before release. +description: Package custom Bub CLI commands, plugins, and skills into a standard Python wheel, install locally, and verify before publishing. --- import { FileTree, Steps } from '@astrojs/starlight/components'; -When you build custom tools, channel plugins, or workflow-specific skills on top of Bub, or even want to ship a branded CLI of your own, you can package them as standard Python distributions (wheels) and publish them to PyPI or a private index for your team and users to install. +When you build custom tools, channel plugins, or workflow-specific skills on top of Bub—or want to ship a branded CLI of your own—you can package them as a standard Python wheel and publish them to PyPI or a private index for your team and users to install. -In Bub, packaging and distribution usually falls into one of three shapes: +Common distribution patterns: -| Shape | Deliverable | When to use it | +| Pattern | Contents | Use case | | --- | --- | --- | -| **Capability extension** | Plugin entry point + skill namespace | Contribute custom tools, long-running services, or specialized skills to the existing Bub ecosystem | -| **Dedicated business CLI** | Your own command script (for example `my-bub`) | Wrap Bub as an agent for one business scenario, pinning the workspace or baking in default settings | -| **All-in-one suite** | Own commands + plugins + skills | Deliver a complete vertical-domain agent that works as soon as users install it | +| **Extension package** | Plugin entry point + skills directory | Add tools, channels, or skills to an existing Bub install | +| **Custom CLI** | Custom script entry point (e.g. `my-bub`) | Ship a branded command name or pin a default workspace | +| **All-in-one package** | Custom CLI + plugins + skills | Deliver a ready-to-run domain-specific agent in one package | :::note -This page focuses on **building and distributing a standalone installable package**. If you are integrating Bub as code into an existing web framework or backend service, see [Reuse the Bub app](/docs/integrations/reuse-app/). +This page covers building **standalone installable Python packages**. To embed Bub inside an existing web service or backend, see [Reuse Bub in a service](/docs/integrations/reuse-app/). ::: -## Publish your own command {#publish-a-command} +## Publish a custom CLI command {#publish-a-command} -A distribution can provide its own command name and call Bub's CLI entry point internally. This lets you give the agent its own brand or fix its default behavior: +A package can expose its own command name and delegate to Bub's CLI entrypoint, letting you brand the agent or pin default behavior: ```python title="src/my_bub/cli.py" -from pathlib import Path import os +from pathlib import Path from bub.__main__ import main as bub_main def main() -> None: - # Optional: pin a default workspace. Bub's workspace defaults to the current - # directory and has no BUB_* environment variable, so change directory before - # calling bub_main(); a user-supplied --workspace still overrides it. + # Optional: set a default workspace (overridable via --workspace) if workspace := os.getenv("MY_BUB_WORKSPACE"): os.chdir(Path(workspace).expanduser()) - # Call Bub's CLI dispatcher; chat, run, gateway, and the other subcommands work unchanged bub_main() ``` -Register the command in `pyproject.toml` with `[project.scripts]`: +Declare the script in `pyproject.toml`: -```toml +```toml title="pyproject.toml" [project.scripts] my-bub = "my_bub.cli:main" ``` -After installation, users can run `my-bub chat`, `my-bub gateway`, or `my-bub run` directly. Bub's Typer CLI mounts every native subcommand, and standard arguments such as `--workspace` keep working. +Once installed, users can run `my-bub chat`, `my-bub run`, and `my-bub gateway` directly, with all native subcommands and flags like `--workspace` intact. -## Distribute plugins and skills {#bundle-plugins-and-skills} +## Bundle plugins and skills together {#bundle-plugins-and-skills} -A single wheel can provide plugin entry points, a standard skill namespace package, and custom CLI commands together: +A single wheel can bundle a custom CLI command, plugin entry points, and a `skills` namespace package: - my-bub/ - - pyproject.toml + - **pyproject.toml** - src/ - my_bub/ - \_\_init\_\_.py - - cli.py # Your CLI entry point - - plugin.py # Plugin and hook implementations + - **cli.py** # Custom CLI entrypoint + - **plugin.py** # Plugin and hook implementations - tools.py # Custom tools - - skills/ # Skill namespace package (never add \_\_init\_\_.py) + - **skills/** # Skill namespace package (do NOT add \_\_init\_\_.py) - repo-reviewer/ - SKILL.md - references/ @@ -71,13 +68,11 @@ A single wheel can provide plugin entry points, a standard skill namespace packa -:::caution[Namespace package rules] -Ship `src/skills/` as a **PEP 420 implicit namespace package**, and **never** create `__init__.py` inside `src/skills/`. Only the namespace layout lets the package's skills merge with Bub's bundled skills and the skills of other extension packages in `skills.__path__` once users install it. For how to write skills, see [Skills](/docs/app/skills/). +:::caution[Do not add `__init__.py` to `src/skills/`] +`src/skills/` must be packaged as a **PEP 420 implicit namespace package**. **Never** place an `__init__.py` inside `src/skills/`; otherwise its skills cannot merge with Bub's bundled skills and other installed skill packages under `skills.__path__`. ::: -### Configure pyproject.toml {#configure-packaging} - -Set up the entry points and Hatch build includes in `pyproject.toml`: +### Configure `pyproject.toml` {#configure-packaging} ```toml title="pyproject.toml" mark={14-15,17-18,20-21} [build-system] @@ -90,7 +85,7 @@ version = "0.1.0" description = "My Custom Bub Agent Distribution" requires-python = ">=3.12" dependencies = [ - "bub[app]>=0.6.0", # Required for the CLI, plugin loading, and the skill runtime + "bub[app]>=0.6.0", ] [project.scripts] @@ -103,60 +98,54 @@ my_plugin = "my_bub.plugin:plugin" packages = ["src/my_bub", "src/skills"] ``` -#### Key settings {#key-settings} +Key settings: -1. **Dependencies**: Always declare `bub[app]`. Since 0.6.0 the core `bub` package holds only the lightweight kernel; the CLI, plugin loading, and the skill runtime all come from the `app` extra, following the package restructuring described in the [0.6 migration notes](/docs/migration/v0-6/). Declare third-party libraries your plugins depend on (such as `httpx` or `pydantic`) in the distribution's `dependencies` as well. -2. **Entry point format**: The entry point group must be `"bub"`. See the [plugin registration rules](/docs/app/plugins/#entry-point-forms) for the exact syntax. -3. **Packaging scope**: Explicitly include `"src/skills"` in `packages` under `[tool.hatch.build.targets.wheel]` so skill assets ship in the wheel and install into `site-packages/skills/`. +1. **Depend on `bub[app]`**: the base `bub` package installs only the core kernel; the CLI, plugins, and skill loader require `bub[app]` (see the [0.6.0 upgrade guide](/docs/migration/v0-6/)). +2. **Use the `"bub"` entry-point group**: register plugins under `[project.entry-points."bub"]` (see [entry-point forms](/docs/app/plugins/#entry-point-forms)). +3. **Include `"src/skills"`**: list `"src/skills"` in `packages` under `[tool.hatch.build.targets.wheel]`. -## Build and distribute {#build-and-distribute} +## Build and install {#build-and-distribute} -[`uv`](/docs/getting-started/install/) builds a standard wheel and source distribution quickly: +Build the wheel and sdist with `uv`: ```bash uv build ``` -The artifacts land in `dist/` (for example `my_bub-0.1.0-py3-none-any.whl`). Publish them to PyPI, or distribute them inside your organization through a private index. +Artifacts are written to `dist/`. Users can install your package in two ways: -For downstream users: - -- **Install as a global CLI**: `uv tool install my-bub`. -- **Install as a managed plugin**: to install the package into the separate project or container environment that Bub manages, use [`bub install`](/docs/reference/cli/#bub-install). +- **As a standalone CLI tool**: `uv tool install my-bub` +- **As a managed Bub plugin**: [`bub install `](/docs/reference/cli/#bub-install) ## Verify before release {#verify-a-release} -Before publishing publicly or releasing to production, always verify the package in a fresh virtual environment. +Before publishing publicly or rolling out to production, test the built `.whl` file in a clean virtual environment: -1. **Create an isolated environment and install the wheel**: +1. **Create a clean virtual environment and install the wheel**: ```bash uv venv .test-env && source .test-env/bin/activate uv pip install dist/*.whl ``` - Always install from the built wheel rather than running from the development source directory. -2. **Verify plugin and hook loading**: +2. **Verify plugin registration**: ```bash my-bub hooks ``` - Check that the output lists your plugin identifier, confirming the entry point loaded with no deprecation warnings or import errors. + Confirm your plugin identifier appears without import errors. 3. **Verify skill discovery**: ```bash my-bub run ",skill" + my-bub run ",skill name=repo-reviewer" ``` - Confirm that the distributed skill (such as `repo-reviewer`) appears in the discovered list, then run `my-bub run ",skill name=repo-reviewer"` to check that variable interpolation and body expansion work. + Confirm bundled skills are listed and expand properly. -4. **Verify your command and the interaction path**: +4. **Verify chat and tools**: ```bash my-bub run "Test model and custom tool calls" my-bub chat ``` - Confirm model interaction, custom tool execution, internal command dispatch, and session history persistence. - -5. **Verify the gateway and host integration (if applicable)**: - If the distribution provides channel extensions or is embedded in a host system, follow [Deploy](/docs/app/deploy/) and [Reuse the Bub app](/docs/integrations/reuse-app/) to wire it into the host service, and verify concurrency, stream closure, and shutdown cleanup. diff --git a/website/src/content/docs/docs/app/gateway.mdx b/website/src/content/docs/docs/app/gateway.mdx index 6f02f51a..cbe38df4 100644 --- a/website/src/content/docs/docs/app/gateway.mdx +++ b/website/src/content/docs/docs/app/gateway.mdx @@ -1,119 +1,117 @@ --- title: Gateway -description: Configure and run the Bub gateway, connect chat platforms, and manage messages and sessions. +description: Configure and run the Bub gateway to connect Telegram or custom chat channels, manage sessions, and run Bub as a background service. --- import { Steps } from '@astrojs/starlight/components'; -Bub was originally inspired by always-on agents such as OpenClaw and nanobot. In addition to terminal interaction, Bub provides a gateway. +Bub was originally inspired by always-on agents such as OpenClaw and nanobot. Beyond terminal sessions, Bub can run as a long-lived gateway that listens for messages from chat platforms. -Running the `bub gateway` subcommand starts Bub as a gateway and runs all enabled channels. - -Bub currently ships with only the Telegram channel. Other platforms require community [plugins](https://hub.bub.build/), so this document focuses on configuring and using the Telegram channel. +Run `bub gateway` to start all enabled message channels. Bub includes a built-in Telegram channel; other platforms can be added via community [plugins](https://hub.bub.build/). ## Start the Telegram gateway {#telegram} :::note -First make sure the Bub application is installed and configured correctly, and get a bot token from [@BotFather](https://t.me/BotFather). +Make sure Bub is installed and configured, and obtain a bot token from [@BotFather](https://t.me/BotFather). ::: 1. **Configure `.env`** - Set these in `.env` at the workspace root: + Add your bot token and allowed user ID (look up your numeric ID via [@userinfobot](https://t.me/userinfobot)) to `.env` in your workspace root: ```bash title=".env" BUB_TELEGRAM_TOKEN=123456789:your-telegram-bot-token BUB_TELEGRAM_ALLOW_USERS=123456789 ``` - Set `BUB_TELEGRAM_ALLOW_USERS` to your numeric ID; you can look it up with [@userinfobot](https://t.me/userinfobot). - 2. **Start the gateway** - Run it in the workspace that contains the `.env` file: - ```bash bub gateway ``` - Example log from a successful startup: + Startup log output: ```text telegram.start allow_users_count=1 allow_chats_count=0 proxy_enabled=False telegram.start polling ``` -3. **Verify a private chat** +3. **Test a private message** - Send the bot a private message and wait a moment to see whether it replies. If there is no reply, see [Configure replies](#telegram-outbound) and [Troubleshooting](#troubleshooting). + Try sending your bot a direct message on Telegram and wait a moment for a reply. If it does not respond, check [How replies are sent](#telegram-outbound) and [Troubleshooting](#troubleshooting). -Bub requires at least one enabled channel to run as a gateway. The Telegram channel is enabled whenever `BUB_TELEGRAM_TOKEN` is non-empty. +The gateway requires at least one enabled channel. The Telegram channel is enabled automatically whenever `BUB_TELEGRAM_TOKEN` is non-empty. ## Configure Telegram {#configure-telegram} -### Restrict access {#restrict-access} - -Set `BUB_TELEGRAM_ALLOW_USERS` to restrict which users can access the bot, and `BUB_TELEGRAM_ALLOW_CHATS` to restrict which chats can access it. +### Access allowlists {#restrict-access} -Separate multiple values with commas; usernames are case-sensitive: +Use `BUB_TELEGRAM_ALLOW_USERS` to restrict which users can message the bot, and `BUB_TELEGRAM_ALLOW_CHATS` to restrict which chats or groups are allowed (comma-separated; usernames are case-sensitive): ```bash BUB_TELEGRAM_ALLOW_USERS=123456789,your_username BUB_TELEGRAM_ALLOW_CHATS=-1001234567890,-1009876543210 ``` -| Allowlist configuration | Pass condition | When it fails | +| Allowlist variable | Pass condition | On failure | | --- | --- | --- | -| `BUB_TELEGRAM_ALLOW_USERS` | Numeric ID or username matches | The user receives `Access denied.` | -| `BUB_TELEGRAM_ALLOW_CHATS` | Chat ID matches | The message is dropped silently | +| `BUB_TELEGRAM_ALLOW_USERS` | Numeric user ID or username matches | Replies `Access denied.` | +| `BUB_TELEGRAM_ALLOW_CHATS` | Chat ID matches | Silently drops the message | -When both are set, both must pass. When both allowlists are **empty**, anyone can use the bot; set at least one before deploying it publicly. +When both are set, both must match. **When both allowlists are empty, anyone on Telegram can use your bot** — always configure at least one before deploying publicly. -### Configure group chats {#telegram-inbound} +### Group chat triggers {#telegram-inbound} -Turn off **Privacy Mode** in BotFather. Otherwise the bot only sees commands and cannot read ordinary group messages. +Before adding the bot to a group, disable **Privacy Mode** in [@BotFather](https://t.me/BotFather); otherwise Telegram only delivers `/` slash commands to the bot. -| Message source or type | Received when | +To keep the bot from jumping into every casual conversation, Bub accepts group messages under these rules: + +| Message type | Trigger condition | | --- | --- | -| Non-command messages in a private chat | Always | -| Text messages in a group chat | Mentions `@`, contains `bub`, or replies to the bot | -| Images and files with text captions in a group chat | Same as text messages | -| Non-text messages without captions in a group chat | Only when replying to the bot | -| `/bub ` | The `/bub ` prefix is removed and the rest becomes the prompt | +| Non-command messages in private chats | Always accepted | +| Group text messages | Mentions `@`, contains `bub` (case-insensitive substring match, so `bubble` also matches), or replies to a bot message | +| Group images/files with captions | Same as group text messages | +| Group images/stickers/files without captions | Only when replying directly to a bot message | +| `/bub ` | Strips `/bub ` and passes the remaining text as the prompt | + +Other group messages are ignored unless the group was triggered recently and is still within `BUB_ACTIVE_TIME_WINDOW` (see [Merge consecutive messages](#merge-consecutive-messages)). -Group messages that do not meet these conditions are ignored. If the session is still within `BUB_ACTIVE_TIME_WINDOW`, those messages may also join the current batch. `bub` uses substring matching, so `bubble` also matches. +### How replies are sent {#telegram-outbound} -### Configure replies {#telegram-outbound} +In the Telegram channel, **ordinary messages** and **comma commands** use different outbound paths: -| Input | `output_channel` | How it is sent | +| Input type | `output_channel` | How replies are sent | | --- | --- | --- | -| Ordinary message | `"null"` | The built-in `telegram` skill sends replies, progress, and edits | -| Comma command | `"telegram"` | Tool output goes to the originating `chat_id` | +| Ordinary message | `"null"` (disables automatic direct reply) | The model calls the built-in `telegram` skill to send replies, quote messages, or edit status | +| Comma command (e.g. `,help`) | `"telegram"` | Skips the model and sends tool output directly back to `chat_id` | -The model output for an ordinary message is not sent to Telegram automatically; the model must call the `telegram` skill, or the user receives no reply. Typing is renewed every 4 seconds and only means the Turn has not finished. +Why the split? In group chats and multi-step tasks, an Agent often needs to post a status update, edit it in place, or stay quiet when a message needs no reply. Routing ordinary messages through the built-in `telegram` skill gives the model full control over when and how to respond. + +:::note +For ordinary messages, **the model must call the `telegram` skill for the user to receive a reply in Telegram**. While a Turn is running, the `typing...` indicator renews every 4 seconds to show that the background Turn is still active. +::: -When a comma command's output is JSON with a `message` field, only that field is sent; other non-empty output is sent as-is, and empty output is dropped. +Comma commands (such as `,tape.info`) skip the model and send their output directly: if the result is JSON with a `message` field, only `message` is sent; other non-empty text is sent as-is; empty output is ignored. ### Merge consecutive messages {#merge-consecutive-messages} -Telegram merges consecutive messages sent within a short period into one Turn. You can adjust the merging strategy with the following environment variables: +In chat apps, people often split one thought across several short messages (for example, sending "check this error" followed right away by a stack trace). To avoid wasting tokens and fragmenting context, the Telegram channel automatically merges consecutive messages arriving within a short window into a single Turn (joined by newlines): -| Variable | Default | Description | +| Environment variable | Default | Description | | --- | --- | --- | -| `BUB_DEBOUNCE_SECONDS` | `1.0` | Short wait that is reset by each active message | -| `BUB_MAX_WAIT_SECONDS` | `10.0` | Upper bound on waiting for inactive follow-up messages | -| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | Time window in which inactive messages can join the batch | +| `BUB_DEBOUNCE_SECONDS` | `1.0` | **Active message debounce**: wait timer reset by each active message (private chat or group message mentioning the bot) | +| `BUB_MAX_WAIT_SECONDS` | `10.0` | **Follow-up max wait**: maximum wait time when buffering unmentioned follow-up messages in a group | +| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | **Active group window**: seconds after an active trigger during which unmentioned group messages join the current batch | -Messages explicitly addressed to the bot in private and group chats are active; subsequent unmentioned group messages in the same session are inactive. Both are staged per session and merged with newlines once the timer ends. Input that starts with the command prefix (`,` by default) does not participate in merging and is dispatched immediately. +Direct commands starting with the command prefix (`,` by default) skip debouncing and run immediately. ### Proxy {#telegram-reference} -You can configure a proxy for the Telegram channel: - ```bash BUB_TELEGRAM_PROXY=http://127.0.0.1:7890 # socks5://:@host:port is also supported @@ -121,9 +119,7 @@ BUB_TELEGRAM_PROXY=http://127.0.0.1:7890 ## Connect other platforms {#other-platforms} -Although Bub ships with only the Telegram channel, the community provides a variety of [plugins](https://hub.bub.build/) for connecting other platforms. - -After installing a plugin for another platform, restart the gateway and use `bub hooks` to confirm the corresponding name appears under `provide_channels`. At startup, channels without configured credentials are skipped. +Install community channel [plugins](https://hub.bub.build/), restart the gateway, and run `bub hooks` to verify the channel name appears under `provide_channels` (channels without configured credentials are skipped at startup): | Platform | Channel name | Plugin | | --- | --- | --- | @@ -135,13 +131,11 @@ After installing a plugin for another platform, restart the gateway and use `bub | DingTalk | `dingtalk` | [`bub-dingtalk`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-dingtalk) | | QQ | `qq` | [`bub-qq`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-qq) | -See each plugin's documentation for channel-specific configuration. - -## Custom channels {#custom-channels} +## Build a custom channel {#custom-channels} -If no existing plugin is available, you can implement your own channel in Python: subclass `Channel`, set the `name` attribute, and implement the `start`, `stop`, and `send` methods. Here is a minimal example: +If no community plugin exists for your platform, you can write your own by subclassing `Channel` and implementing `start`, `stop`, and `send`: -```python +```python showLineNumbers collapse={1-6} {8, 30-37} import asyncio from bub.channels.base import Channel @@ -149,7 +143,7 @@ from bub.channels.message import ChannelMessage class MyChannel(Channel): - name = "myapp" # Channel name + name = "myapp" def __init__(self, on_receive, token: str) -> None: self._on_receive = on_receive @@ -161,7 +155,7 @@ class MyChannel(Channel): return bool(self._token) async def start(self, stop_event: asyncio.Event) -> None: - # start must not block the main loop, or the gateway cannot receive subsequent messages. + # start must not block the event loop; spawn a background task self._listener = asyncio.create_task(self._listen(stop_event)) async def stop(self) -> None: @@ -170,7 +164,7 @@ class MyChannel(Channel): async def _listen(self, stop_event: asyncio.Event) -> None: while not stop_event.is_set(): - chat_id, text = await self._next_message() # Platform message + chat_id, text = await self._next_message() await self._on_receive( ChannelMessage( session_id=f"myapp:{chat_id}", @@ -184,35 +178,30 @@ class MyChannel(Channel): await self._post(message.chat_id, message.content) ``` -Note: +Implementation notes: -- Call the framework-provided `on_receive` event handler for every inbound message. -- Use the `:` format for `session_id` so sessions from different platforms do not collide. -- Return `False` from `enabled` by default when the configuration is incomplete; the gateway skips that channel. -- Return `True` from `needs_debounce` when consecutive short messages need to be merged. +- Call the `on_receive` callback passed by the framework for each inbound message. +- Format `session_id` as `:` to avoid cross-platform collisions. +- Return `False` from `enabled` when credentials are missing so the gateway skips the channel. +- Return `True` from `needs_debounce` if consecutive short messages should be batched. -When finished, expose the channel through the plugin's entry-point module with `provide_channels`: +Register the channel via the `provide_channels` hook: ```python import os - from bub import hookimpl -# From the previous snippet -# class MyChannel(Channel): -# ... - @hookimpl def provide_channels(message_handler): return [MyChannel(on_receive=message_handler, token=os.environ.get("MYAPP_TOKEN", ""))] ``` -After installing the plugin, run the corresponding channel with `bub gateway --enable-channel myapp`. +Start the gateway with `bub gateway --enable-channel myapp`. -## Run as a daemon {#daemon} +## Run as a background service {#daemon} -To keep Bub running as a system service, configure it with the following commands: +If you want Bub to stay running in the background as a system service, install it with: ```bash bub gateway --install @@ -221,25 +210,23 @@ bub gateway --install # bub gateway --uninstall ``` -Behavior varies slightly by system: - -| System | Behavior | +| OS | Behavior | | --- | --- | -| Linux | systemd user unit `bub-gateway.service`; to keep it running after logout, run `loginctl enable-linger $USER` | +| Linux | systemd user unit `bub-gateway.service`; run `loginctl enable-linger $USER` to keep it running after SSH logout | | Windows | Scheduled task for the current user; starts at login and restarts on failure | -| macOS | `--install` is not supported; use launchd, tmux, or [container deployment](/docs/app/deploy/) | +| macOS | `--install` is not supported; use `launchd`, `tmux`, or [Docker deployment](/docs/app/deploy/) | -Installation records the current Python interpreter, workspace, and explicit `--enable-channel` values. Reinstall after changing the environment or workspace. +`--install` records the current Python interpreter, workspace directory, and `--enable-channel` flags. Re-run `bub gateway --install` if you move the workspace or change virtual environments. ## Troubleshooting {#troubleshooting} | Symptom | Possible cause | Fix | | --- | --- | --- | -| `No channels are enabled` | No usable channel | Check the token and the `.env` location; inspect plugins with `bub hooks` | -| No `telegram.start` in the log | Telegram token is empty | Set the token and confirm it reaches the `bub` process | -| Private chat receives `Access denied.` | The user allowlist rejected the user | Add the numeric ID or username to `BUB_TELEGRAM_ALLOW_USERS` | -| No response in a private chat | The chat allowlist rejected the chat | Add the chat ID to `BUB_TELEGRAM_ALLOW_CHATS` | -| No response in a group chat | Privacy Mode is on, or receive conditions are not met | Turn off Privacy Mode; for testing, @-mention the bot directly | -| Typing forever with no reply | The model did not call the `telegram` skill | See [reply rules](#telegram-outbound) | -| `409 Conflict` | Multiple long-polling processes use the same token | Stop the duplicate instances | -| No offline messages after a restart | Backlog updates are discarded at startup | Expected behavior | +| `No channels are enabled` | No channel is enabled | Check your token and `.env` path; run `bub hooks` to verify channel plugins | +| No `telegram.start` in logs | `BUB_TELEGRAM_TOKEN` is empty | Confirm the token is set in the environment running `bub` | +| Private chat replies `Access denied.` | User is not in the allowlist | Add your numeric ID or username to `BUB_TELEGRAM_ALLOW_USERS` | +| No response in private chat | Chat ID is not in the allowlist | Add the chat ID to `BUB_TELEGRAM_ALLOW_CHATS` | +| No response in group chat | Privacy Mode is enabled or trigger rules were not met | Disable Privacy Mode in BotFather; @-mention the bot directly to test | +| `typing...` forever with no reply | Model did not call the `telegram` skill | See [How replies are sent](#telegram-outbound) | +| `409 Conflict` | Multiple gateway instances use the same bot token | Stop duplicate processes | +| Offline messages are skipped on restart | Backlog updates are discarded at startup | Expected behavior | diff --git a/website/src/content/docs/docs/app/plugins.mdx b/website/src/content/docs/docs/app/plugins.mdx index 561b4995..749cddd2 100644 --- a/website/src/content/docs/docs/app/plugins.mdx +++ b/website/src/content/docs/docs/app/plugins.mdx @@ -1,32 +1,31 @@ --- title: Plugins and Hooks -description: Write, install, and debug Bub plugins, and master entry point declarations, common Hook recipes, and system extension capabilities. +description: Write, install, and debug Bub plugins using Python entry points and hooks to extend tools, services, prompts, and CLI commands. --- import { FileTree } from '@astrojs/starlight/components'; -Plugins are one of the core capabilities of the Bub app. Bub discovers plugins automatically through the standard [Python Entry Points](https://packaging.python.org/en/latest/specifications/entry-points/) mechanism, and injects custom logic into every runtime stage of the app through Hook contracts. +Bub discovers plugins automatically via standard [Python Entry Points](https://packaging.python.org/en/latest/specifications/entry-points/) and uses hooks to inject custom logic into each stage of the runtime. -Through plugins, you can extend three core capabilities for Bub: +Plugins can extend Bub in three ways: +- **Custom tools**: register tool functions via `provide_tools`; +- **Background services**: mount long-running services (such as MCP clients or message channels) via `Lifecycle`; +- **Pipeline hooks**: rewrite prompts, approve or block tool calls, and persist state across Turns. -- **Custom tools**: provide dedicated tool functions to the Agent via `provide_tools`; -- **Long-running background services**: mount resident daemons that run with the app (such as MCP clients, external channels, or event schedulers) via `Lifecycle`; -- **Rewriting flow logic**: intercept messages, rewrite prompts, approve tool calls, or persist session state through Hooks. +## Create a minimal plugin {#create-a-plugin} -## Basics: Create a plugin {#create-a-plugin} +Before diving into advanced hooks, let's build a minimal offline echo plugin that needs no model API key so you can walk through the full workflow end to end. -Before diving into the more complex capabilities, let's build an understanding of Bub plugins with an example plugin that requires no external model credentials. +### 1. Initialize the project {#initialize-project} -### Initialize the plugin project {#initialize-project} - -Use [uv](https://docs.astral.sh/uv/) to quickly scaffold a Python library project, then enter the project directory: +Scaffold a Python library with `uv`: ```bash uv init --lib bub-echo-plugin cd bub-echo-plugin ``` -Create `plugin.py` inside the `src/bub_echo_plugin/` source directory to hold the plugin and Hook logic. The initialized directory structure looks like this: +Create `src/bub_echo_plugin/plugin.py`: @@ -35,13 +34,13 @@ Create `plugin.py` inside the `src/bub_echo_plugin/` source directory to hold th - src/ - bub_echo_plugin/ - \_\_init\_\_.py - - plugin.py # New: holds the plugin and Hook logic + - **plugin.py** # Plugin and hook implementations -### Declare the entry point {#declare-entry-point} +### 2. Declare the entry point {#declare-entry-point} -In `pyproject.toml`, expose the plugin object to Bub through `[project.entry-points."bub"]`: +Expose the plugin under `[project.entry-points."bub"]` in `pyproject.toml`: ```toml title="pyproject.toml" mark={11-12} [build-system] @@ -58,16 +57,14 @@ dependencies = ["bub[app]"] echo = "bub_echo_plugin.plugin:echo_plugin" ``` -Note: - -- **`entry-points` name**: must be `"bub"`; Bub automatically scans all plugins under this namespace at startup; -- **Plugin identifier and target**: the `echo` key is the plugin's globally unique identifier; the value points to the module, instance, or factory class to be loaded. +- The entry-point group name must be `"bub"`. +- The key (`echo`) is the plugin identifier; the value points to the module, instance, or class to load. -### Implement the Hook logic {#implement-hooks} +### 3. Implement a hook {#implement-hooks} -When writing plugin logic in the module, mark hook implementations with the `@hookimpl` decorator: +Mark hook methods with `@hookimpl`: -```python title="src/bub_echo_plugin/plugin.py" +```python title="src/bub_echo_plugin/plugin.py" "@hookimpl" from bub import hookimpl @@ -80,19 +77,19 @@ class EchoPlugin: echo_plugin = EchoPlugin() ``` -This example implements `run_model` to replace the built-in model invocation stage, directly concatenating the input text with the session ID and returning it as the result, which makes it easy to verify the entire plugin pipeline offline. +Implementing `run_model` replaces the default model call and returns the echoed prompt with the session ID. -### Entry point declaration forms {#entry-point-forms} +### Entry-point target forms {#entry-point-forms} -Depending on whether a plugin needs to maintain internal state or access host context, an entry point supports three target forms: +An entry point can reference a module, an instance, or a class/factory: -| Entry point target syntax | Registered object | When to use | +| Target syntax | Registered object | When to use | | --- | --- | --- | -| `bub_myplugin.plugin` | Module | Hooks are pure functions with no shared state | -| `bub_myplugin.plugin:plugin` | Existing instance | Hooks need to share state through `self` | -| `bub_myplugin.plugin:MyPlugin` | Class or factory function | The plugin needs access to the global `BubFramework` instance | +| `bub_myplugin.plugin` | Module | Hooks are stateless functions | +| `bub_myplugin.plugin:plugin` | Instance | Hooks share state via `self` | +| `bub_myplugin.plugin:MyPlugin` | Class or factory function | Plugin needs access to the `BubFramework` instance | -When the entry point targets a class or factory function, Bub automatically passes the current `BubFramework` instance as the first argument when instantiating the object: +When targeting a class or factory function, Bub passes the `BubFramework` instance as the first argument: ```python from bub import BubFramework, hookimpl @@ -104,61 +101,54 @@ class MyPlugin: @hookimpl def build_prompt(self, message, session_id, state): - # Access global runtime information such as the workspace path through the framework - return f"Current workspace path: {self.framework.workspace}\n{message}" + return f"Workspace: {self.framework.workspace}\n{message}" ``` ## Install and verify {#install-and-run} -After writing the plugin, you need to install it into the runtime environment where Bub runs, and verify how Hooks are loaded and in what order they execute. - -### Install for local development {#local-install} +Once your plugin is written, install it into the environment where Bub runs and verify that its hooks are discovered and executed. -From the plugin project root, run sync to install it into the current virtual environment in editable mode: +### Install in editable mode {#local-install} ```bash uv sync ``` -### Check hook registration {#check-hook-registration} - -Use the `bub hooks` command to check whether the plugin has been recognized correctly: +### Verify hook registration {#check-hook-registration} ```bash uv run bub hooks ``` -In the hook list printed in the terminal, the registered `echo` plugin should appear correctly under `run_model`. +Confirm `echo` appears under `run_model`. ### Run a test {#run-tests} -Send a test command to the app to verify that the plugin actually takes effect: +Now send a test prompt to verify that your plugin is active: ```bash uv run bub run "hello from my plugin" ``` -The console prints the echoed text intercepted by the plugin: +You should see the echoed output intercepted by your plugin: ```text [echo:cli:local] hello from my plugin ``` -### Troubleshooting and dispatch {#troubleshooting-and-dispatch} - -If the plugin is not loaded or executed as expected, troubleshoot using the following principles: +### Troubleshooting and execution order {#troubleshooting-and-dispatch} -1. **Check the runtime environment**: confirm that the Python environment running the `bub` CLI is exactly the same as the one where the plugin is installed; -2. **Re-sync metadata**: if you changed the entry point configuration in `pyproject.toml`, you must run `uv sync` (or `pip install -e .`) again to refresh the package's Entry Points metadata; -3. **Check hook execution order and priority**: Bub follows the Pluggy specification, registering built-in implementations first and then loading entry point plugins. At equal priority, **plugins registered later run first** (LIFO). To explicitly adjust the order, specify `@hookimpl(tryfirst=True)` (run as early as possible) or `@hookimpl(trylast=True)` (run as late as possible) in the decorator. See [Hook priority and dispatch](/docs/reference/hooks/#priority-and-dispatch). +1. **Matching Python environment**: ensure `bub` runs in the same virtual environment where the plugin was installed. +2. **Refresh entry-point metadata**: re-run `uv sync` (or `pip install -e .`) after editing `entry-points` in `pyproject.toml`. +3. **Hook priority**: Bub registers `builtin` hooks first, then entry-point plugins. At equal priority, **plugins registered later run first** (LIFO). Use `@hookimpl(tryfirst=True)` or `@hookimpl(trylast=True)` to adjust ordering explicitly (see [Hooks reference: Priority and dispatch](/docs/reference/hooks/#priority-and-dispatch)). -## Advanced: Customize behavior with Hooks {#advanced-hooks} +## Common hook patterns {#advanced-hooks} -Bub provides a full set of extension points covering inbound parsing, model invocation, tool interception, state, and lifecycle (see the [Hooks reference](/docs/reference/hooks/) for complete signatures and lifecycle contracts). In real-world scenarios, the most common customization needs fall into the following four categories: +Bub provides extension points across the entire runtime lifecycle (see the [Hooks reference](/docs/reference/hooks/) for all 27 signatures). Most real-world customizations fall into four common patterns: ### 1. Provide tools {#provide-tools} -Plugins can register Python functions declared with `@tool` to the Agent through the `provide_tools` hook: +Register `@tool` functions with `provide_tools`: ```python from bub import hookimpl, tool @@ -177,27 +167,24 @@ class OrdersPlugin: return [get_order] ``` -#### Deferred loading {#deferred-loading} +#### Deferred tool schemas {#deferred-loading} -When a plugin provides a large number of tools, injecting the full schema of every tool into the system prompt at once consumes a significant amount of the context window. You can enable deferred loading in the decorator: +When a plugin registers many tools, injecting every full schema into the system prompt consumes context tokens. Set `deferred=True` to load schemas on demand: -```python +```python "deferred=True" @tool(name="orders.export", deferred=True) def export_orders(format: str) -> str: - """Export a report of all historical orders.""" + """Export a report of historical orders.""" ... ``` -Note: - -- **Deferred mechanism**: tools with `deferred=True` only expose their name and a brief description to the system prompt by default; -- **Dynamic expansion**: when the model decides it needs to call the tool, it automatically loads the full definition temporarily through the built-in `tool.describe`, and starts executing the call from the next step. +Deferred tools initially expose only their name and short description; the model calls `tool.describe` to load the full schema when needed. -### 2. Rewrite and intercept flows {#rewrite-and-intercept} +### 2. Rewrite prompts, intercept calls, and persist state {#rewrite-and-intercept} -#### Rewrite the prompt {#change-the-prompt} +#### Rewrite prompts {#change-the-prompt} -- **Rewrite model input**: `build_prompt` receives the inbound message, session ID, and the current turn's state, and returns the final input provided to the model: +- **Rewrite user input** (`build_prompt`): ```python from bub import hookimpl from bub.envelope import content_of @@ -206,21 +193,21 @@ Note: @hookimpl def build_prompt(message, session_id, state): text = content_of(message) - return [f"Please answer using the project's professional terminology:\n\n{text}"] + return [f"Answer using project terminology:\n\n{text}"] ``` -- **Append system instructions**: if you only want to append global constraints to the model without changing the inbound content, use `system_prompt` (content appended by multiple plugins is concatenated with line breaks according to priority): +- **Append system instructions** (`system_prompt`, joined with blank lines by priority): ```python @hookimpl def system_prompt(prompt, state): - return "Please include the paths of the referenced code files at the end of your reply." + return "Include referenced file paths at the end of your reply." ``` -#### Intercept calls {#control-a-model-or-tool-call} +#### Intercept model or tool calls {#control-a-model-or-tool-call} -Interception hooks run before the actual call is triggered. Exceptions raised are recorded by the framework and skipped; to actively intervene, modify, or block execution, you must return the corresponding decision object (Decision): +Interception hooks run before a call executes. Note: raising an exception in an interception hook is logged and skipped — **it does not block execution**. Return a decision object to modify or block a call: -- **Limit LLM sampling parameters**: +- **Cap model parameters** (`before_llm_call`): ```python from dataclasses import replace from bub import hookimpl @@ -233,7 +220,7 @@ Interception hooks run before the actual call is triggered. Exceptions raised ar return replace(request, max_tokens=max_tokens) ``` -- **Approve or deny high-risk tool calls**: +- **Approve or deny tool calls** (`before_tool_call`): ```python from bub import hookimpl from bub.hooks.interception import ToolCall, ToolCallDecision @@ -242,15 +229,15 @@ Interception hooks run before the actual call is triggered. Exceptions raised ar @hookimpl def before_tool_call(call: ToolCall, state): if call.tool == "orders.cancel" and not state.get("can_cancel_orders", False): - return ToolCallDecision.deny("This session is not allowed to cancel orders.") + return ToolCallDecision.deny("This session is not permitted to cancel orders.") return None ``` -For the semantics of proceeding, rewriting, denying, and replacing, see [Decisions come before side effects](/docs/concepts/events/#call-control); for the complete return types, see the [Hooks reference](/docs/reference/hooks/#toolcalldecision). +See [Pre-call interception and decisions](/docs/concepts/events/#call-control) and [`ToolCallDecision`](/docs/reference/hooks/#toolcalldecision). -#### Call auditing {#observe-completed-calls} +#### Audit completed calls {#observe-completed-calls} -Completion hooks fire after a call finishes, making them suitable for measuring latency, reporting monitoring metrics, or recording audit logs: +Completion hooks run after a call finishes, making them handy for measuring latency, reporting metrics, or writing audit logs: ```python from bub import hookimpl @@ -266,9 +253,9 @@ def after_tool_call(call, result, state): print(f"tool={call.tool} error={result.error!r} elapsed={result.duration_ms}ms") ``` -#### Persist state across turns {#keep-application-state-across-turns} +#### Persist state across Turns {#keep-application-state-across-turns} -The example below uses `load_state` and `save_state` to keep a count across Turns. For the lifetime of `TurnState` and where data belongs, see [Turn](/docs/concepts/turn/#state) and [where data belongs](/docs/concepts/tape/#state). +Use `load_state` and `save_state` to persist application state across Turns (see [TurnState](/docs/concepts/turn/#state)): ```python import asyncio @@ -294,11 +281,11 @@ class TurnCounter: turn_counter = TurnCounter() ``` -### 3. Mount services and resources {#services-and-resources} +### 3. Mount services and storage {#services-and-resources} -#### Long-running services {#lifecycle} +#### Background services (`Lifecycle`) {#lifecycle} -Components that must run alongside the app, such as MCP clients, channel listeners, or scheduled dispatchers, should inherit from the `Lifecycle` base class and be exposed through `provide_channels`: +Components that stay running alongside `bub chat` or `bub gateway` (such as MCP clients or schedulers) subclass `Lifecycle` and register via `provide_channels`: ```python from bub.channels.base import Lifecycle @@ -314,14 +301,12 @@ class MyRuntime(Lifecycle): await self._close() ``` -Note: +- `Lifecycle` services start automatically in `bub chat` and `bub gateway`, and are skipped in one-off `bub run` calls. +- Exclude a service at startup with `--enable-channel '!myapp.lifecycle'`. -- **Lifecycle contract**: long-running services are initialized automatically when `bub gateway` starts or the channel runtime starts, and are cleaned up on exit; note that a single `bub run` execution does not activate long-running services. -- **CLI filtering**: at startup, you can enable one individually with `--enable-channel`, or explicitly exclude it with `--enable-channel '!myapp.lifecycle'`. +#### Process-wide lifespan resources {#runtime-resources} -#### Lifecycle resources {#runtime-resources} - -When you need to hold resources such as a global database connection pool or HTTP client for the entire process lifetime, implement `provide_lifespan` with an async generator: +Use `provide_lifespan` with an async generator to manage database pools or HTTP clients across `framework.running()`: ```python from bub import hookimpl @@ -336,9 +321,9 @@ async def provide_lifespan(): await client.close() ``` -#### Session storage {#provide-a-tape-store} +#### Custom Tape store {#provide-a-tape-store} -`provide_tape_store` lets you replace the default local-file session store (for example, to use PostgreSQL or cloud storage; see [SQLAlchemy integration](/docs/integrations/storage/)): +Replace the default file store via `provide_tape_store` (see [Store conversation history in a database](/docs/integrations/storage/)): ```python from pathlib import Path @@ -351,9 +336,9 @@ def provide_tape_store(): return FileTapeStore(Path("./application-tapes")) ``` -### 4. Extend CLI commands {#add-an-application-command} +### 4. Add CLI subcommands {#add-an-application-command} -Plugins can register subcommands directly with the Bub root CLI (built on Typer) through `register_cli_commands`: +Register custom Typer subcommands on the root `bub` CLI via `register_cli_commands`: ```python import typer @@ -364,32 +349,30 @@ from bub import hookimpl def register_cli_commands(app: typer.Typer): @app.command() def my_cmd(name: str = "world") -> None: - typer.echo(f"Executed successfully: {name}") + typer.echo(f"Executed: {name}") ``` -#### Interactive input {#prompt-for-input} +#### Interactive terminal prompts {#prompt-for-input} -If a plugin subcommand needs to interactively confirm with the user or obtain input in the terminal, use the interactive input utilities provided by `bub.inquirer`: +Use `bub.inquirer` to prompt for input or confirmation inside custom CLI commands: ```python from bub.inquirer import ask_confirm, ask_text -token = ask_text("Enter the verification token") +token = ask_text("Enter verification token") if ask_confirm("Continue execution?", kind="permission"): pass ``` -## Distribution and extensions {#share-a-plugin} +## Distribution and WASM extensions {#share-a-plugin} -### Package and distribute {#package-and-distribute} +### Package as a Python wheel {#package-and-distribute} -A finished plugin can be packaged as a standard Python Wheel for distribution. A single distribution can contain plugin entry points, skill namespace packages, and custom CLI commands at the same time. For packaging configuration and pre-release verification, see [Packaging and distribution](/docs/app/distribution/). For cross-language ecosystem package specifications, see [Load Agent Plugins](/docs/integrations/agent-plugins/). +Package plugins, skills, and custom CLI commands into a standard Python wheel. See [Packaging and distribution](/docs/app/distribution/) for build configuration, or [Load portable Agent Plugins](/docs/integrations/agent-plugins/) for declarative cross-platform packages. ### WASM plugins (experimental) {#wasm-plugins} -With the [`bub-extism`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-extism) extension, binary modules compiled from other languages such as Go and Rust can be mounted directly as Bub Hook handlers via WebAssembly. - -`extism.json` specifies the module files and hook mapping: +With [`bub-extism`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-extism), WebAssembly modules compiled from Go, Rust, or other languages can run as Bub hooks: ```json title="extism.json" { diff --git a/website/src/content/docs/docs/app/skills.mdx b/website/src/content/docs/docs/app/skills.mdx index 884e4eff..013df8f0 100644 --- a/website/src/content/docs/docs/app/skills.mdx +++ b/website/src/content/docs/docs/app/skills.mdx @@ -1,86 +1,86 @@ --- title: Skills -description: Write, verify, and use Bub skills, and understand how skills are discovered and how same-name skills are overridden. +description: Create, verify, and distribute reusable Bub skills (SKILL.md) with discovery priority rules, bundled skills, and variable interpolation. --- -A [skill](https://agentskills.io/) is the format published as a standard by Anthropic for extending AI agent capabilities with specialized knowledge and workflows. A skill is a folder containing a `SKILL.md` file that explains how to do one kind of task; the model loads it on demand. +A [skill](https://agentskills.io/) is an open standard format initiated by Anthropic for extending AI agents with domain knowledge and step-by-step workflows. Each skill is a folder containing a `SKILL.md` file that explains how to handle a task; the model loads it on demand. -## Discovery and priority {#discovery} +## Discovery priority {#discovery} -Bub discovers and loads skills automatically in the following priority order. **When names collide, the first match wins**: +Bub discovers skills in the following order. **When names collide, the first match wins**: -1. **Workspace directory**: `/.agents/skills/` (the legacy `.agent/skills/` still works) +1. **Workspace directory**: `/.agents/skills/` (legacy `.agent/skills/` is also supported) 2. **User global directory**: `~/.agents/skills/` -3. **Installed packages**: every installed `skills` namespace package in the environment, including Bub's [bundled skills](#builtin-skills) +3. **Installed Python packages**: any `skills` namespace package in the environment, including Bub's [bundled skills](#builtin-skills) ## Bundled skills {#builtin-skills} -The Bub app ships three skills: +The Bub app includes three bundled skills: | Skill | Purpose | External dependency | | --- | --- | --- | | `telegram` | Send, reply to, and edit Telegram messages | Telegram Bot token | -| `gh` | Manage repositories, issues, PRs, and Actions through the GitHub CLI | `gh` installed and authenticated | -| `skill-creator` | Guide the creation or update of skills | None | +| `gh` | Manage repositories, issues, PRs, and Actions via the GitHub CLI | `gh` installed and authenticated | +| `skill-creator` | Scaffold or update skills | None | ## Write a skill {#write-a-skill} -Try creating a skill in the current workspace or the global user directory, for example `.agents/skills/repo-map/SKILL.md`: +Try creating a skill (`/SKILL.md`) in your workspace or global skills directory, for example `.agents/skills/repo-map/SKILL.md`: -```markdown +```markdown title=".agents/skills/repo-map/SKILL.md" --- name: repo-map description: Read the local repository structure before changing code. --- -1. Run `rg --files` to see the repository structure. -2. Read the files that explain this change. -3. Describe the affected modules before editing code. +1. Run `rg --files` to inspect the repository layout. +2. Read the files relevant to the requested change. +3. State which modules will be affected before editing code. ``` -### Fields and variables {#skill-fields} +### Frontmatter fields and variables {#skill-fields} -The `SKILL.md` YAML frontmatter follows this spec: +YAML frontmatter fields in `SKILL.md`: | Field | Requirement | | --- | --- | -| `name` | Required; must exactly match the skill directory name; lowercase letters, digits, and hyphens only; at most 64 characters | -| `description` | Required; state the task and the trigger conditions clearly so the model can decide when to use the skill; at most 1,024 characters | -| `metadata` | Optional; key-value mapping, both keys and values must be strings | +| `name` | **Required**. Must match the skill directory name; lowercase letters, digits, and hyphens only; max 64 characters | +| `description` | **Required**. Explains when to use the skill (used by the model to select skills); max 1,024 characters | +| `metadata` | Optional. String-to-string key-value mapping | -Supporting scripts or reference files can live in `scripts/`, `references/`, or `assets/` inside the skill directory. The skill body supports the following variable interpolation: +Helper scripts and reference files can be placed in `scripts/`, `references/`, or `assets/` inside the skill folder. The skill body supports variable interpolation: -| Variable | Expansion | +| Variable | Expands to | | --- | --- | -| `$SKILL_DIR` | Absolute path of the current skill directory | +| `$SKILL_DIR` | Absolute path of the skill directory | | `$PYTHON` | Path of the Python interpreter running Bub | -| `${config.path.to.value}` | Value of the corresponding field in the Bub config file | +| `${config.path.to.value}` | Value of the dotted path in the Bub config file | -Scripts in a skill do not run automatically. The body should tell the model which tool to call to run them, and ensure the environment has the required external dependencies installed (this example needs `rg`). +Scripts inside a skill do not execute automatically; instruct the model in the skill body to run them with `bash` (and ensure required CLI tools such as `rg` are installed). -If you would rather not create a skill by hand, delegate it to your agent tool or the Bub app, for example: +Of course, if you would rather not create a skill by hand, you can ask Bub to generate one with the bundled `$skill-creator` skill: ```bash -bub run 'Use the $skill-creator skill to create a skill named `repo-map` with this flow: -1. Run `rg --files` to see the repository structure. -2. Read the files that explain this change. -3. Describe the affected modules before editing code.' +bub run 'Use the $skill-creator skill to create a skill named `repo-map` with these steps: +1. Run `rg --files` to inspect the repository layout. +2. Read the files relevant to the requested change. +3. State which modules will be affected before editing code.' ``` ## Verify and use {#verify-a-skill} -In the Bub app you can invoke skills in these ways: +Once your skill is ready, verify and invoke it in these ways: | Command | Description | | --- | --- | -| `bub run ",skill"` | List the skills actually discovered in the current workspace | -| `bub run ",skill name=repo-map"` | Print the body with variables expanded, without calling the model; if it returns `(no such skill)`, check that the directory name matches `name` | -| `bub run 'Use the $repo-map skill, then list the top-level modules you found.'` | Expand the body into this turn's system prompt; the model then calls tools to complete the steps | +| `bub run ",skill"` | List all skills discovered in the current workspace | +| `bub run ",skill name=repo-map"` | Print the expanded skill body without calling the model (returns `(no such skill)` if the directory name and `name` do not match) | +| `bub run 'Use the $repo-map skill and list the top-level modules.'` | Explicitly expand the skill body into this turn's system prompt | :::note -Without an explicit `$skill-name`, the model still decides whether to use a skill based on its `description`. +Even without an explicit `$skill-name` in the prompt, the model can load a skill on demand based on its `description`. ::: -## Distribute with a Python package {#include-skills-in-a-wheel} +## Distribute in a Python package {#include-skills-in-a-wheel} -Skills can be distributed through plugin packages. For how to organize a plugin package's directory structure, configure packaging, and verify the release in an isolated environment, see [Packaging and distribution](/docs/app/distribution/#bundle-plugins-and-skills). +Skills can be bundled into a Python wheel alongside plugins. See [Packaging and distribution](/docs/app/distribution/#bundle-plugins-and-skills) for directory layout and build configuration. diff --git a/website/src/content/docs/docs/app/subagents.mdx b/website/src/content/docs/docs/app/subagents.mdx index 571f1f9e..3072f5e8 100644 --- a/website/src/content/docs/docs/app/subagents.mdx +++ b/website/src/content/docs/docs/app/subagents.mdx @@ -1,15 +1,15 @@ --- title: Subagents -description: Delegate tasks to background subagents with the built-in subagent tool, define reusable subagent profiles, and narrow what a subagent can use. +description: Delegate tasks to background subagents with the built-in subagent tool, define reusable subagent profiles, and limit subagent tools and skills. --- -The Bub app includes a built-in `subagent` tool that lets the current agent delegate a specific subtask to a child run of the same agent. +The Bub app includes a built-in `subagent` tool that delegates a subtask to a background child run. -Subagents are a good fit for tasks that generate a huge amount of intermediate context — **large-scale retrieval, long document reading, independent code review** — so that only the final conclusions return to the main session and intermediate details don't consume its context window. +Subagents are ideal for tasks that produce large amounts of intermediate output — **broad codebase searches, reading long documents, or independent code reviews**. Intermediate tool calls stay isolated inside the subagent's session, and only the final conclusion from its last step returns to the parent session. ## Delegate a task {#delegate} -In `bub chat`, you can ask the model to call a subagent directly: +In `bub chat`, you can ask the model to delegate directly to a subagent: ```text Use the subagent tool to review the authentication flow: @@ -18,34 +18,34 @@ Use the subagent tool to review the authentication flow: 3. Return the review findings with the relevant file paths. ``` -The parent agent then calls the `subagent` tool, which starts the child in the background and returns a task ID at once. The child calls tools inside its own loop, finishes the analysis, and its final answer reaches the parent as a message. Only that answer, the text of the child's last step, comes back; the child's intermediate narration and tool calls stay out of the parent's context. +When the parent calls `subagent`, the child starts in the background and immediately returns a `task_id`. The child runs its own tool loop and delivers only its final answer back to the parent. -The child sees only its `prompt` (and, with `session="fork"`, the conversation so far), so the prompt should be self-contained: say what to do, what to return, and any limits. +Because a subagent sees only its `prompt` by default (plus prior conversation history when `session="fork"`), the delegated `prompt` should be self-contained: state the goal, expected return format, and constraints. -Beyond asking by hand, you can also set a rule in the workspace `AGENTS.md` or in a skill (for example, "complex retrieval or code review should be delegated to a read-only subagent first, and the main agent only applies changes based on the review") to get **automatic delegation**. +You can also add delegation rules to `AGENTS.md` or a skill (e.g., "delegate broad searches or code reviews to a read-only subagent first") so the parent delegates automatically. -## Choose a session strategy {#sessions} +## Session modes {#sessions} -The `session` parameter decides what the child starts from and what is kept: +The `session` parameter controls the subagent's initial context and whether its history is kept afterwards: -| Session mode | Behavior | Use it for | +| `session` value | Behavior | Best for | | --- | --- | --- | -| `temp` (default) | A new, empty `temp/` session, discarded afterwards | **Most common.** One-off analysis or research that returns conclusions only | -| `fork` | Starts from a copy of the current conversation, including the current turn so far; discarded afterwards | Subtasks that need what the user and the parent already said, without the parent re-explaining it | -| A custom string | Uses that fixed session ID, which is kept | Longer work you want to continue later with `subagent.send`, or inspect afterwards | +| `temp` (default) | Starts a blank `temp/` session; discarded when finished | **Most common.** One-off research, retrieval, or reviews where only the final answer matters | +| `fork` (alias `inherit`) | Copies the current conversation snapshot at the moment of the call; discarded when finished | Subtasks that depend on recent context without the parent re-explaining it | +| Custom session ID string | Uses that fixed session ID and keeps its history | Multi-round tasks you want to continue later via `subagent.send` or inspect afterwards | -`inherit` is accepted as an alias of `fork`. A fork copies the conversation at the moment of the call, so the child does not see what the parent does next, and nothing the child does is written back to the parent's history. +`fork` copies the conversation snapshot at the time of the call: the child does not see later parent actions, and the child's entries are not merged back into the parent's Tape. -## Receive results {#background} +## Receive results and manage tasks {#background} -Subagents always run in the background: the parent keeps working while they run, so several subagents can work in parallel while the parent does something else: +Subagents always run asynchronously in the background. The parent can start multiple subagents in parallel while continuing its own work: ```text Start three subagents, one per service, to check the logs for errors. Keep working on the migration; summarize their findings when they are done. ``` -When a task ends, its result reaches the parent as a message: +When a subagent finishes, its result arrives as a notification message before the parent's next Step: ```text @@ -53,23 +53,25 @@ No errors in the payments service logs since the last deploy. ``` -The parent reads it before its next step. A turn does not end while subagents it started are still running: when the parent has nothing else to do, it waits for the next result and continues with it, so it can summarize every finding before replying. A task that outlives its turn, because the turn failed, was cancelled or reached its step limit, reports with the session's next turn. The parent can also manage tasks directly: +A Turn does not finish while subagents it started are still running: when the parent has no other tool calls to make, it automatically waits for the next subagent to finish and continues reasoning with the result. If the parent Turn ends early due to an error, cancellation, or `max_steps`, remaining subagents deliver their results on the session's next Turn. -| Tool | What it does | +The parent can also manage background tasks explicitly: + +| Tool | Purpose | | --- | --- | -| `subagent.wait` | Return results, waiting up to `timeout_seconds` (default 60; `0` only checks). Without `task_ids`, covers the session's unread tasks. A result read here sends no notification. | -| `subagent.send` | Message a running task, which reads it before its next step; or continue a finished task that used a named session. | -| `subagent.cancel` | Stop a running task. | +| `subagent.wait` | Wait for and return subagent results up to `timeout_seconds` (default 60; `0` checks status without blocking). Defaults to all unread tasks in the session. Tasks read via `subagent.wait` do not send a duplicate notification | +| `subagent.send` | Send a follow-up instruction to a running task (read before its next Step), or resume a finished task that used a custom named session | +| `subagent.cancel` | Cancel a running subagent task | -At most `BUB_SUBAGENT_MAX_CONCURRENCY` subagents (default 4) run at once; later ones wait in a queue. `timeout_seconds` on the call, or `BUB_SUBAGENT_TIMEOUT_SECONDS` globally, stops a child that runs too long. Ending Bub, or the `,quit` command for a session, cancels its running subagents. +At most `BUB_SUBAGENT_MAX_CONCURRENCY` subagents (default 4) run concurrently in one process; extra tasks queue. Limit runtime per call with `timeout_seconds` or globally with `BUB_SUBAGENT_TIMEOUT_SECONDS`. Exiting Bub or running `,quit` cancels all active subagents. ## Define subagent profiles {#profiles} -A profile is a reusable subagent: a markdown file in `.agents/agents/` in the workspace, or in `~/.agents/agents/` for every workspace. The front matter sets its configuration, and the body is added to the child's system prompt: +If you regularly delegate to recurring roles (such as a code reviewer or log analyzer), save their model, allowed tools, and system prompt as a reusable **profile**. Just create a Markdown file in `.agents/agents/` in your workspace (or `~/.agents/agents/` globally) — YAML frontmatter sets default parameters, and the Markdown body is appended to the subagent's system prompt: ```markdown title=".agents/agents/reviewer.md" --- -description: Reviews a change for bugs and reports findings without editing files +description: Reviews code changes for bugs and reports findings without editing files model: openai:gpt-5-mini tools: [fs.read, bash, tape.search] skills: [] @@ -82,32 +84,32 @@ paths and line numbers, and never modify files. | Field | Meaning | | --- | --- | -| `description` | Required. Tells the parent when to use the profile | -| `name` | Optional; defaults to the file name without `.md` | -| `model`, `reasoning_effort` | The child's model and reasoning effort | -| `tools`, `skills` | The child's allowed tools and skills (a list, or a comma-separated string) | -| `timeout_seconds` | The child's time limit | +| `description` | **Required**. Tells the parent when to select this profile | +| `name` | Optional; defaults to the filename without `.md` (e.g. `reviewer`) | +| `model`, `reasoning_effort` | Default model and reasoning effort for the subagent | +| `tools`, `skills` | Allowed tools and skills (YAML list or comma-separated string) | +| `timeout_seconds` | Timeout in seconds | -When the `subagent` tool is available, the parent's system prompt lists the profiles, and the model uses one by passing its name as `agent`. Arguments given in the call take precedence over the profile. A workspace profile overrides a home profile with the same name. +Discovered profiles are listed in the parent's system prompt automatically. The parent activates one by passing `agent="reviewer"` to `subagent`; explicit call arguments override profile defaults. Workspace profiles override global profiles of the same name. -## State sharing and capability boundaries {#boundaries} +## State sharing and boundaries {#boundaries} -A subagent is a child run of the same agent instance as its parent. What it inherits and what stays isolated: +A subagent runs on the same `BubAgent` instance as its parent with the following boundaries: -| Resource | Boundary | Notes and controls | +| Resource | Boundary | Notes | | --- | --- | --- | -| **Base instance** | Fully shared | Shares plugin hooks, model credentials, and `BubAgent` configuration | -| **Execution environment** | Fully shared | Shares the workspace directory, local filesystem, Shell processes, and network access | -| **Model selection** | Set separately | Defaults to the profile's model or the parent's; use `model` to pick a lighter one | -| **Tools and skills** | At most the parent's | Defaults to the parent run's tools and skills; `allowed_tools` and `allowed_skills` narrow them further. Children cannot start subagents | -| **Turn state** | Copied | The child gets a copy of the parent's turn state with its own steering key, so messages sent to the parent stay with the parent | -| **Conversation records** | Per session strategy | `temp` and `fork` are discarded; a named session is kept | +| **Agent instance** | Shared | Shares plugin hooks, model credentials, and `BubAgent` settings | +| **Execution environment** | Shared | Shares workspace directory, local filesystem, Shell processes, and network | +| **Model** | Configurable | Defaults to profile or parent model; override via `model` | +| **Tools and skills** | Subset of parent | Defaults to the parent run's allowed tools and skills; limit further with `allowed_tools` and `allowed_skills`. Subagents cannot call `subagent` | +| **TurnState** | Shallow copy | Copies the parent's `TurnState` with an isolated steering inbox key so parent steering messages stay with the parent | +| **Session history** | Per `session` mode | `temp` and `fork` are discarded on exit; custom named sessions are kept | -Parameter types and defaults are listed in the [subagent reference](/docs/reference/tools/#subagent). Channels can observe subagents through [events](/docs/reference/tools/#subagent-events). +See the [`subagent` tool reference](/docs/reference/tools/#subagent) for parameter details and [subagent events](/docs/reference/tools/#subagent-events) for lifecycle events. ### Security limits {#security-limits} -Like the parent, a subagent also runs in the local environment under the current user's privileges, and can affect the current system: +Like the parent, a subagent runs in your local environment with your user permissions. Keep these boundaries in mind: -1. A session strategy isolates only **conversation records and model context**, not files, network requests, or system processes. File changes and network requests made by the child have real system side effects and are not rolled back on exit. -2. In chat, the model writes the `subagent` arguments, so `allowed_tools` restricts model behavior but **is not an enforced security boundary**. To hard-block dangerous commands or out-of-scope tools, use [tool interception hooks](/docs/reference/hooks/#interception-through-pluginagenthooks); for physical isolation, configure a separate [execution environment](/docs/app/tools/#environment). +1. **No filesystem isolation**: `session` isolates only **conversation history and model context**. File edits, shell commands, and network requests made by a subagent affect the local system directly and are not rolled back on exit. +2. **`allowed_tools` is not a security boundary**: in chat, the model generates `subagent` arguments, so `allowed_tools` only guides model behavior. To enforce hard blocks on dangerous commands, use [tool interception hooks](/docs/app/plugins/#control-a-model-or-tool-call); for OS-level isolation, configure a separate [execution environment](/docs/app/tools/#environment). diff --git a/website/src/content/docs/docs/app/terminal.mdx b/website/src/content/docs/docs/app/terminal.mdx index cdaf8fe2..73cca502 100644 --- a/website/src/content/docs/docs/app/terminal.mdx +++ b/website/src/content/docs/docs/app/terminal.mdx @@ -1,120 +1,117 @@ --- title: Terminal -description: Interactive sessions, steering a running agent, commands, and background processes in Bub. +description: Use the Bub terminal CLI for interactive sessions, steering a running agent, adjusting reasoning, direct commands, and background processes. --- -The Bub application provides two ways to interact in the terminal: `bub run` and `bub chat`. Both use the same model, tools, and Tape capabilities: +Bub provides two terminal commands that share the same model, tools, and Tape storage: -- `bub run` handles a single message and is suitable for one-off tasks; -- `bub chat` keeps the session open for continuous conversation. +- `bub run`: processes a single message and exits; suited for one-off tasks and scripts. +- `bub chat`: starts an interactive REPL for multi-turn conversations. ## Start an interactive session {#start-session} -Run the following command in your terminal to start an interactive session. You can then type a message and press Enter to send it: +Run the following command in your terminal to open an interactive session, then type a message and press Enter to send it: ```bash bub chat ``` -Use `,help` to list the internal commands currently available. To exit, press Ctrl+D or enter `,quit` or `,exit`. - -The toolbar shows the speed of the latest model call, measured from the first streamed chunk to the end of the response. It counts every output token, reasoning included, and excludes both the time before the first chunk and tool execution. The `ttft` next to it is that excluded time to first chunk. When the provider does not report usage, it shows `speed:- tok/s`. - -You can also submit the first message directly at startup: +You can also pass an initial prompt at startup: ```bash bub chat "Inspect this repository and suggest a first task." ``` -## Steer a running agent {#steering} +Type `,help` to list internal commands. Press Ctrl+D or enter `,quit` or `,exit` to leave. -If the model's output diverges from your expectations while you are waiting for a response, or you want to add constraints, you can enter a new instruction directly in the interface to guide the agent's behavior. +The bottom status bar shows metrics for the latest model call: -**Steering** adds an instruction while the current turn is still running so the agent can adjust the task in progress. You don't have to wait for the current generation to finish; just type the correction and press Enter: +- `ttft` (time to first token): elapsed time before the first streamed chunk arrives. +- `speed`: average output tokens per second from the first chunk to the end of the response (includes reasoning tokens; excludes `ttft` and tool execution time; shows `speed:- tok/s` if the provider omits usage). + +## Steer a running agent {#steering} + +If the agent starts going off track while you are waiting for a response or tool call—or if you want to add a quick constraint—you do not have to wait for the current turn to finish. Just type your new instruction and press Enter: ```text Do not modify files yet. List the problems and suggestions first. ``` -The Bub app places the message in the steering inbox. The agent reads it when building a later model request; a model or tool call already in progress is not forcibly interrupted. +Adding instructions while a Turn is still running is called **Steering**. Bub places the message in the steering inbox; in-flight model or tool calls are not interrupted, and the agent reads the new instruction on the very next Step. -Bub's admission actions are `steer` and `follow_up`; they differ in when the message takes effect: +When a session is busy, Bub supports two admission actions: -| Approach | Handling | Use it for | +| Action | When it takes effect | Use it for | | --- | --- | --- | -| Steering | Injects into later model requests in the current turn; messages that cannot be consumed in time become pending messages | Correcting direction, adding constraints, and providing new information relevant to the current task | -| Follow up | Processed as a follow-up task after the current turn ends | Adding another task or running several requests in order | - -By default, the Bub app steers ordinary input while a run is in progress; there is no separate follow-up shortcut. Steering messages that the current turn does not consume automatically enter the pending queue instead of being dropped. +| `steer` | Injected into the next Step of the current Turn (or queued for the next Turn if the current Turn finishes first) | Correcting direction, adding constraints, or supplying info for the current task | +| `follow_up` | Queued and run as a new Turn in order after the current Turn finishes | Queuing an independent next task | -To stop the task in the current session, use `,quit`; it clears pending messages and cancels running tasks. +In `bub chat`, ordinary input entered during a run uses `steer` by default. To abort the running task immediately, enter `,quit` (clears the pending queue and cancels active tasks). -## View the reasoning process {#reasoning} +## View and adjust reasoning {#reasoning} -Enter `,thinking` to expand or collapse the model's reasoning process: +Expand or collapse the model's reasoning output in the terminal (display-only): ```text ,thinking ``` -It only controls whether the terminal displays the `reasoning` deltas returned by the model; it does not change the model or the reasoning effort. To adjust reasoning effort, use: +Change the model's reasoning effort (takes effect on the next Turn and persists in the session Tape): ```text ,reasoning_effort high ``` -The available values depend on the model provider. The setting takes effect from the next Turn and is saved in the current session's Tape. +## Choose a session ID {#choose-session} -## Choose a session {#choose-session} - -`bub run` uses `cli:local` as its default session ID, while `bub chat` uses `cli_session`. Specify the same session ID explicitly to continue history between the two entry points: +`bub run` defaults to session ID `cli:local`, while `bub chat` defaults to `cli_session`. Pass `--session-id` to share history between them: ```bash bub chat --session-id cli:echo bub run --session-id cli:echo "Summarize what we discussed." ``` -## Use commands {#commands} +## Run direct commands {#commands} -The command prefix defaults to `,` and is used to skip the model call and execute a tool directly: +Input starting with `,` (the default command prefix) skips the model and calls the matching tool directly: ```bash bub run ",help" bub run ",fs.read path=README.md" ``` -You can enter commands directly in an interactive session too. Press Ctrl-X to switch between Agent and Shell input modes; Shell mode automatically adds the command prefix to your input. Common commands include: +You can enter commands directly inside `bub chat` as well. Press Ctrl+X to toggle between Agent mode and Shell mode (Shell mode prepends `,` automatically). Common commands include: | Command | Purpose | | --- | --- | | `,model openai:gpt-5-mini` | Switch the model for the current session | -| `,reasoning_effort high` | Set the reasoning effort for the current session | +| `,reasoning_effort high` | Set reasoning effort for the current session | | `,code_mode enable=true` | Enable code mode | -| `,tape.info` | View entries, anchors, and token usage | -| `,tape.search query=error` | Search the current session record | -| `,tape.anchors` | List context boundaries | -| `,tape.handoff name=reviewed summary='...'` | Move the default context start point and save a summary | -| `,tape.reset archive=true` | Archive the current Tape and start over | +| `,tape.info` | Show entry count, anchors, and token usage | +| `,tape.search query=error` | Search current session history | +| `,tape.anchors` | List context anchors | +| `,tape.handoff name=reviewed summary='...'` | Advance the default context start and save a summary | +| `,tape.reset archive=true` | Back up and clear the current Tape | | `,thinking` | Expand or collapse reasoning output | -Note: +Notes: -- `,tape.reset archive=true` backs up the main Tape and its sidecar to `/tapes/`, with a UTC timestamp and a `.bak` suffix in the file names. Using `archive=false` or plain `,tape.reset` skips the backup. After a reset, a new `session/start` anchor is created, and the old files are not restored automatically. -- `handoff` does not generate or inject a summary automatically. `summary` is stored in the anchor's `state`; whether it is read later depends on the prompt or context policy. See [Tape](/docs/concepts/tape/#anchors) for details. +- `,tape.reset archive=true` backs up the main Tape and sidecar to `/tapes/` with a UTC timestamp and `.bak` suffix, then resets the Tape with a new `session/start` anchor. Omitting `archive=true` clears without backing up. +- `,tape.handoff` advances the context start and stores `summary` in the anchor's `state`, without automatically generating a summary. See [Tape](/docs/concepts/tape/#anchors). :::caution -Unregistered commands are handed to `bash` for execution. Before entering an unknown command, make sure it is a shell command you are willing to run. +Unregistered comma commands are passed to `bash`. Before running an unfamiliar command, make sure it is a shell command you intend to execute. ::: ## Run background processes {#background-shell} -In `bub chat`, use `background=true` to run a command in a separate background process: +In `bub chat`, pass `background=true` to start a long-running command in the background: ```text ,bash command='npm run dev' background=true ``` -The result includes a `shell_id`. Use it to read output incrementally or terminate the process: +Use the returned `shell_id` to read output incrementally or stop the process: ```text ,bash.output shell_id=bsh-12345678 @@ -122,7 +119,5 @@ The result includes a `shell_id`. Use it to read output incrementally or termina ,bash.kill shell_id=bsh-12345678 ``` -Note: - -- `offset` is the character position in the buffered output, not a line number; use `next_offset` from the returned value for the next read. `limit` caps the number of characters returned in this call. -- A foreground `bash` call **waits 30 seconds** by default. On timeout, the process is not treated as failed; it moves to the background and returns a `shell_id`. Adjust this with `timeout_seconds`. Background tasks should be managed within the same `bub chat` or gateway process, and they are cleaned up when the application exits. +- `offset` and `limit` are **character offsets** (not line numbers); pass the returned `next_offset` to the next read. +- Foreground `bash` calls wait **30 seconds** by default (configurable via `timeout_seconds`). On timeout, the process moves to the background and returns a `shell_id` instead of failing. Background processes are cleaned up when the app exits. diff --git a/website/src/content/docs/docs/app/tools.mdx b/website/src/content/docs/docs/app/tools.mdx index 93be2eaf..f9a28ca4 100644 --- a/website/src/content/docs/docs/app/tools.mdx +++ b/website/src/content/docs/docs/app/tools.mdx @@ -1,70 +1,68 @@ --- title: Tools -description: Learn about the Bub app's built-in tools, how tools are called, and how to configure code mode and extensions. +description: Use Bub app built-in tools for files, shell commands, web fetch, and code mode, with execution security boundaries and custom extensions. --- -Tools carry out concrete external actions for the Bub app, such as reading and writing files, running commands, and managing sessions. +Tools allow Bub to read and write files, run commands, fetch web pages, and manage sessions. ## Built-in tools {#builtin-tools} -The Bub app ships with the following core tools: +The Bub app ships with these built-in tools: | Category | Tool | Purpose | | --- | --- | --- | -| **Process management** | `bash` | Run Shell commands; supports a working directory, timeouts, and background runs | -| | `bash.output`, `bash.kill` | Read background output incrementally, or terminate a running process | -| **File operations** | `fs.read`, `fs.write`, `fs.edit` | Paged reads, whole-file writes, and precise text replacement | -| **Web fetch** | `web.fetch` | Issue GET requests to fetch pages (Markdown preferred) | -| **Capability discovery** | `skill` | List skills discovered in the workspace, or read a specified skill's body | -| | `tool.describe` | Load the full definition of a deferred tool | -| **Session management** | `tape.info`, `tape.search` | Check token usage and search conversation records | -| | `tape.handoff`, `tape.reset` | Move the context start point to compact the session, or archive and reset the context | -| | `spill.read` | Read large tool results that exceed the context limit in chunks | -| **Multi-task coordination** | [`subagent`](/docs/app/subagents/) | Delegate a task to a subagent that runs in the background | -| | `subagent.wait`, `subagent.send`, `subagent.cancel` | Wait for results, message a subagent, or stop it | -| **Code mode** | `run_code` | Compose multiple tools in Python when code mode is on | - -Built-in tool parameters and defaults are listed in the [tools reference](/docs/reference/tools/). - -## Use tools {#instructions} - -In the Bub app, tools can be called in two ways: - -1. **The model picks them**: ask a question as usual, and the model selects and calls tools based on the task intent and tool descriptions. -2. **Call from the command line**: use the comma prefix in a terminal to call a tool directly (no model call, no token usage): +| **Processes** | `bash` | Run Shell commands with working directory, timeout, and background options | +| | `bash.output`, `bash.kill` | Read background process output incrementally or terminate a process | +| **Files** | `fs.read`, `fs.write`, `fs.edit` | Read files by line range (or images), write whole files, and replace exact text | +| **Web** | `web.fetch` | Send HTTP GET requests to fetch web pages (prefers Markdown) | +| **Discovery** | `skill` | List discovered skills or load a skill's `SKILL.md` body | +| | `tool.describe` | Load the full schema of deferred tools (`deferred=True`) on demand | +| **Session & Tape** | `tape.info`, `tape.search` | Inspect session metrics and token usage, or search session history | +| | `tape.handoff`, `tape.reset` | Advance the context start point, or archive and reset session history | +| | `spill.read` | Read large tool outputs in chunks | +| **Subagents** | [`subagent`](/docs/app/subagents/) | Delegate a task to a background subagent | +| | `subagent.wait`, `subagent.send`, `subagent.cancel` | Wait for subagent results, send follow-up instructions, or cancel a subagent | +| **Code mode** | `run_code` | Compose multiple tools in Python when code mode is enabled | + +For full parameter tables and defaults, see the [Built-in tools reference](/docs/reference/tools/). + +## How tools are called {#instructions} + +In the Bub app, tools can be invoked in two ways: + +1. **Called by the model**: ask a question normally, and the model selects and calls tools based on their descriptions. +2. **Called directly from the terminal**: prepend the command prefix (`,` by default) to execute a tool without calling the model or spending tokens: ```bash bub run ",fs.read path=README.md" ``` -To constrain or standardize how the model uses tools: -- **Workspace conventions**: write general rules in `AGENTS.md` at the project root; -- **Task procedures**: package multi-step operations as [skills](/docs/app/skills/) that walk the model through the right tools in order. +To guide how the model uses tools: +- **Workspace rules**: add project-wide rules to `AGENTS.md` in the workspace root. +- **Step-by-step workflows**: package multi-step procedures as [skills](/docs/app/skills/). -## Enable code mode {#code-mode} +## Code mode {#code-mode} -For complex logic or batch data processing, repeated tool round-trips consume a lot of context. With code mode on, the model writes Python directly (executed through the `run_code` tool) and composes several tools in a single pass: +For tasks involving loops, conditionals, or batch data processing, repeated tool round-trips consume extra context. With code mode enabled, the model writes Python code (executed via `run_code`) to compose multiple tool calls in a single step: ```text ,code_mode enable=true ``` -Note: - -- The setting takes effect from the next turn and is persisted in the current session record. -- Use `,code_mode enable=false` to turn it off and return to the default mode. -- For the Python syntax for calling tools in code mode, see the [`run_code` reference](/docs/reference/tools/#run-code). +- Takes effect on the next Turn and persists in the current session Tape. +- Run `,code_mode enable=false` to disable code mode. +- See the [`run_code` reference](/docs/reference/tools/#run-code) for Python call syntax. ## Execution environment and security {#environment} -Built-in tools such as Shell commands (`bash`), file access (`fs.*`), and code execution (`run_code`) run directly with the current local user's permissions and can have irreversible effects on your system or data. Keep the following in mind: +Built-in tools (`bash`, `fs.*`, and `run_code`) run directly on the local host with the current user's permissions: -- **Not securely isolated**: the default environment is not an isolated sandbox; commands the model runs have **real read/write and process side effects on the local system**. -- **Permissions and interception**: use [tool interception hooks](/docs/reference/hooks/#interception-through-pluginagenthooks) when you need human approval or extra conditions before high-risk commands run. -- **Containers and isolated environments**: provide a separate [execution environment](/docs/reference/hooks/#provide_environment) through a plugin when you need isolated execution. +- **No default sandbox**: commands executed by the model have real filesystem and process side effects on the host. +- **Approval and interception**: use [tool interception hooks](/docs/app/plugins/#control-a-model-or-tool-call) to require human approval or block dangerous arguments before execution. +- **Isolated environments**: provide a containerized or remote [execution environment](/docs/reference/hooks/#provide_environment) via a plugin when isolation is required. -## Integrate and extend tools {#provide-tools} +## Extend tools {#provide-tools} -If the built-in tools are not enough, extend them in these ways: +When the built-in tools are not enough, you can extend Bub in two ways: -- **Install community plugins**: browse [community plugins](https://hub.bub.build/) to find plugins or third-party MCP services (see [MCP integration](/docs/integrations/mcp/)); -- **Write your own plugin**: write Python functions and register them as Bub tools, then ship them with a plugin; see [Provide tools](/docs/app/plugins/#provide-tools). +- **Install community plugins or MCP servers**: browse [community plugins](https://hub.bub.build/) or [connect MCP servers](/docs/integrations/mcp/). +- **Write custom tool plugins**: register Python functions with `provide_tools` (see [Plugins and Hooks: Provide tools](/docs/app/plugins/#provide-tools)). diff --git a/website/src/content/docs/docs/app/workspace.mdx b/website/src/content/docs/docs/app/workspace.mdx index adc58353..992afb64 100644 --- a/website/src/content/docs/docs/app/workspace.mdx +++ b/website/src/content/docs/docs/app/workspace.mdx @@ -1,11 +1,11 @@ --- title: Workspace -description: How to use Bub within a workspace. +description: Run the Bub CLI in a project workspace, define repo-specific agent rules with AGENTS.md, and inspect available slash commands. --- -By default, Bub runs in a workspace, which is simply a directory. It reads information and instructions about the current workspace from there. +By default, Bub runs in a workspace—which is simply your current directory—and reads files and instructions from there. -## Prepare a workspace (optional) {#prepare-workspace} +## Configure AGENTS.md (optional) {#prepare-workspace} If you don't have a project yet and are just getting started with Bub, create a directory first: @@ -14,26 +14,26 @@ mkdir hello-bub cd hello-bub ``` -Then create an `AGENTS.md` file in that directory and write the following content into it: +Then create an `AGENTS.md` file in the workspace root with rules for the project: -``` +```markdown title="AGENTS.md" You are the Bub agent for this workspace. Read the relevant content before editing files. Keep replies short and specific. ``` -From then on, each time Bub runs, it reads these rules from the instructions so the model can follow them in its output. After trying the example, keep editing this file and see how the model's output changes under different rules. +From then on, whenever Bub starts a session, it automatically reads `AGENTS.md` and injects it into the system prompt. After trying the example, feel free to keep tweaking this file and see how the model's replies change under different rules. :::tip -`AGENTS.md` is a simple open format introduced by OpenAI for guiding coding agents, much like the `README.md` file that many projects have. Learn more about [AGENTS.md](https://agents.md/). +`AGENTS.md` is a simple open format introduced by OpenAI for guiding coding agents—much like a `README.md` for AI agents. Learn more at [agents.md](https://agents.md/). ::: -## Check commands {#check-commands} +## Check available commands {#check-commands} -Now try listing the commands available in Bub from the terminal in a workspace: +Now try listing the built-in commands available in your workspace from the terminal: ```bash bub run ",help" ``` -From then on, any input that starts with a `,` comma calls the related command. You can change it to any character you like in the [settings](/docs/reference/settings/#agent-settings). +From then on, any input starting with `,` (comma) skips the model and runs the command or tool directly. Of course, you can change it to any character you like via [`BUB_COMMAND_PREFIX`](/docs/reference/settings/#command-prefix). diff --git a/website/src/content/docs/docs/concepts/agent.mdx b/website/src/content/docs/docs/concepts/agent.mdx index 4740b506..76b86703 100644 --- a/website/src/content/docs/docs/concepts/agent.mdx +++ b/website/src/content/docs/docs/concepts/agent.mdx @@ -1,35 +1,51 @@ --- title: The Agent loop -description: What an Agent assembles, and how a Run advances through Steps of alternating model and tool calls. +description: "Learn how the Bub Agent loop works: core components, how a Run alternates between LLM inference and tool execution, and core vs. app layers." sidebar: label: Agent loop --- -An Agent assembles a model, tools, the Tape, and a loop: the model decides the next move, the tools perform the actions, the Tape supplies the history, and the loop carries those steps through to a final answer. +A model on its own can only take text in and produce text out. To let it inspect files, call APIs, and work through multi-step tasks, an Agent connects a **model**, **tools**, and **conversation history** (the Tape) inside a loop: the model decides the next move from the current context, tools carry out the actions, the Tape records what happened, and the loop keeps advancing until the model has a final answer. -## The Agent loop {#loop} +## How the loop runs {#loop} -Each iteration advances like this: +In Bub, each pass through the Agent loop follows three steps: -1. Read history through `TapeContext`, append the new user message, and call the model; -2. If the model requests tools, execute them and hand the results back to the model; -3. If the model answers directly, the Run ends. +```mermaid +flowchart LR + A["1. Read context from Tape\nand add new message"] --> B["2. Call the model"] + B --> C{"Did the model request tools?"} + C -->|"Yes"| D["Execute local tools and record results"] + D --> B + C -->|"No"| E["3. Return final answer and finish"] +``` -The loop works at two granularities: +1. **Read context and call the model**: select relevant history via `TapeContext`, append the new user message, and send the request to the model. +2. **Execute tools on demand**: if the model requests tool calls, Bub validates arguments, runs the corresponding Python functions, and feeds the results back into the next model call. +3. **Answer and finish**: once the model has enough information and replies directly without requesting tools, the run finishes. -| Concept | Definition | Ends when | +To make this loop easy to observe and control in code, Bub distinguishes two execution units: + +| Concept | Meaning | Ends when | | --- | --- | --- | -| **Run** | One complete Agent execution, which hands the caller a `StreamEvent` stream | The model requests no more tools, or the caller closes the stream | -| **Step** | One model inference plus every tool call that response requested | Every tool call from this inference has been handled | +| **Run** | One complete Agent execution (one `agent.run()` call), yielding a stream of `StreamEvent` items | The model answers directly without calling tools, or the caller closes the stream | +| **Step** | One pass inside a Run: a single model call plus all tool calls requested by that response | All tool calls requested in that step finish | + +In short, **one Run is made up of one or more Steps**. If the model can answer right away, the Run takes 1 Step; if it calls tools twice before answering, the Run takes 3 Steps. + +Keep three key boundaries in mind when working with the loop: + +- **Consuming the stream drives the Run**: calling `agent.run()` only sets up the execution context. Model and tool calls advance only as you iterate the returned stream with `async for`. Breaking out of the loop and closing the stream cleanly stops the Run. +- **Context is built from the Tape on each Step, not kept in a private list**: a Run does not maintain its own `messages` array in memory. Before each Step, it builds the model messages from the Tape via `TapeContext` (see [Tape and model context](/docs/concepts/tape/)). +- **A Run is not a Turn**: a Run is the core model-and-tool loop; a Turn is the app layer's 7-stage pipeline for handling an inbound message. Direct commands such as `,help` can finish inside a Turn without starting a model Run at all (see [Turn](/docs/concepts/turn/)). -Three boundaries are easy to miss: +## Core layer vs. app layer {#layers} -- **A Run is driven by its event stream.** The model and tool loop advances only while the stream is iterated; iterating is how a Run executes, not a second event mechanism. -- **Model context comes from the Tape, not from the Run.** A Run keeps no separate message list: every model call projects the history through `TapeContext`. See [Tape](/docs/concepts/tape/). -- **A Run is not a Turn.** A Run is one execution of an Agent; a Turn is the application layer handling one message, and a direct command can finish without a Run at all. See [Turn](/docs/concepts/turn/). +`bub.core.Agent` is Bub's microkernel. It focuses strictly on the model–tool–event–Tape loop: **it does not read YAML config files or `BUB_*` environment variables, and it knows nothing about channels or plugin discovery**. -## Core layer and application layer {#layers} +The app layer (`BubFramework` and `BubAgent`) wraps that same core loop with configuration, plugins, hooks, skills, channels, and session routing. -`core.Agent` is Bub's microkernel: it owns the model and tool loop, events, and the Tape, and it takes no responsibility for session routing, configuration, plugin discovery, or message channels. The application layer adds those capabilities around the same loop instead of implementing a second Agent. +That separation lets you choose how much of Bub to adopt: -When embedding Bub in an existing service, the host therefore supplies resources such as the model, tools, and storage explicitly; use the application layer when you need the complete message lifecycle. See the [SDK](/docs/sdk/) and [Reuse Bub in a service](/docs/integrations/reuse-app/) for the entry points. +- **Embed in a Python service**: use the core [SDK](/docs/sdk/) and pass the model, tools, and store explicitly. +- **Use the message pipeline, config, or plugins**: run the Bub CLI directly, or [reuse the Bub app layer in your service](/docs/integrations/reuse-app/). diff --git a/website/src/content/docs/docs/concepts/events.mdx b/website/src/content/docs/docs/concepts/events.mdx index 941f290d..7fd88793 100644 --- a/website/src/content/docs/docs/concepts/events.mdx +++ b/website/src/content/docs/docs/concepts/events.mdx @@ -1,44 +1,61 @@ --- title: Agent events -description: Tell AgentEvent, StreamEvent, and TapeEntry apart, and see how synchronous delivery lets handlers intercept execution before side effects occur. +description: "Understand Bub's synchronous event bus: distinguish AgentEvent, StreamEvent, and TapeEntry, and observe or intercept calls before side effects." sidebar: label: Events --- -Agent events answer more than "what happened": before a side effect occurs, they can also decide whether it should happen at all. Every Agent's `EventBus` supports both observation and synchronous intervention. +In real applications, you often need cross-cutting logic around model inference and tool execution: logging audit trails, tracking token usage, sanitizing tool arguments, or pausing a high-risk tool call (such as deleting data or running a shell command) for a permission check or human approval. -## Three kinds of data {#three-kinds} +Hardcoding those rules inside every tool function quickly tangles business logic with policy. Instead, every `Agent` comes with a synchronous event bus (`agent.events`) that lets you both **observe** what just happened and **intervene** before a model or tool call produces side effects—without touching your tool code. -| Kind | Purpose | How to get it | Can it intervene? | +## Three kinds of data to keep straight {#three-kinds} + +Bub uses three distinct types for runtime control, streaming output, and persisted history: + +| Type | Purpose | How to access | Can it intervene in the run? | | --- | --- | --- | --- | -| `AgentEvent` | Coordinate and intercept the current execution | `agent.events.on(...)` | Yes: modify fields or set `decision` | -| `StreamEvent` | Deliver output to the caller | Iterate the stream from `agent.run()` | Yes: closing the stream ends the Run | -| `TapeEntry` | Keep the history | Query the [Tape](/docs/concepts/tape/#history-and-context) | No: normal recording only appends | +| `AgentEvent` | Observe loop stages or modify/intercept calls | Register handlers with `agent.events.on(...)` | **Yes**: mutate event fields or set `decision` | +| `StreamEvent` | Stream incremental output (reasoning deltas, text deltas, tool progress) to the caller | Iterate `agent.run()` with `async for` | **Yes**: closing the stream cancels the Run | +| `TapeEntry` | Persist conversation history, tool round-trips, and business events | Query the [Tape](/docs/concepts/tape/#history-and-context) | **No**: normal runs only append records | + +These three stay strictly separate: stream chunks do not write themselves to disk, and stored Tape entries do not flow back into a currently running Step. Only entries selected by `TapeContext` become input to subsequent model calls. + +## Why event delivery is synchronous {#handlers} -The three never convert into each other automatically: stream output is not written to disk on its own, and Tape entries do not flow back into the Step that is running. Only the entries `TapeContext` selects become input to later model calls. +When the Agent emits an event, `EventBus.emit()` calls matching handlers one by one in registration order. If a handler is an `async def` coroutine, `emit()` **awaits it before moving on**. -## Synchronous delivery {#handlers} +Delivery is synchronous rather than fire-and-forget for a simple reason: **the Agent must wait for handlers to finish so their argument changes or interception decisions take effect before the model or tool actually runs** (for example, awaiting a user's confirmation in a web UI inside a `ToolCallStarted` handler). -`emit()` calls each matching handler in registration order, and waits for an async handler to finish before it continues. Four rules are worth remembering: +Keep four rules in mind when writing handlers: -1. A handler registered for a base class also receives its subclasses. -2. Return values are ignored; to steer execution, change event fields or set `decision`. -3. Exceptions propagate to the publisher and may fail the whole Run. -4. `event.stopped` is checked before every handler, and `True` ends delivery for that emit. +1. **Base-class subscriptions**: registering on a base class receives all its subclasses (`AgentEvent` receives all events; `TapeEvent` receives all events carrying `event.tape`). +2. **Mutate the event in place**: handler return values are ignored. Update fields on the event (such as `event.call`) or set `event.decision`. +3. **Exceptions propagate**: an unhandled exception raised by a handler bubbles up to the `emit()` caller and can abort the Run. +4. **Early stop on decision**: before calling each handler, the bus checks `event.stopped`. Once a handler sets a deny or replace decision (`event.stopped == True`), remaining handlers for that event are skipped. -## Decisions come before side effects {#call-control} +## Making decisions before side effects {#call-control} -Before-call events expose a replaceable request and a `decision`. One tool call has four possible outcomes: +Before-call events (`ToolCallStarted` and `LLMCallStarted`) expose the upcoming request along with a `decision` attribute. For a tool call, a handler can produce four outcomes: -| Action | Does the original tool run? | What the model receives | +| Handler action | Does the tool function run? | What the model receives | | --- | --- | --- | -| No `decision` | Yes | The real result | -| Replace `event.call` | Yes, with the new call | The real result | -| `deny(message)` | No | A tool error | -| `replace(result)` | No | The given result | +| Leave `decision` unset (proceed) | **Yes** | The tool function's return value | +| Replace `event.call` with new arguments | **Yes** (with new arguments) | The tool function's return value | +| Set `ToolCallDecision.deny(message)` | **No** | A tool error with the denial message | +| Set `ToolCallDecision.replace(result)` | **No** | Your replacement result (for caching or mocking) | + +Whether a tool call runs normally, is denied, or is replaced, `ToolCallFinished` still fires afterwards—so your logging, metrics, and audit handlers never miss a call. + +Model calls follow the same pattern: in an `LLMCallStarted` handler, you can replace `event.request` (for example, to cap `max_tokens`) or set `LLMCallDecision.finish(text)` to return a reply directly without calling the model provider. + +## Agent events vs. App hooks {#app-hooks} + +If you have read both the SDK guides and the application plugin guides, you might wonder how `agent.events` relates to `@hookimpl` hooks: -A denied or replaced call still emits `ToolCallFinished`, so logic that observes completed calls never misses it. Model calls follow the same before-call intervention model: for example, `LLMCallDecision.finish(text)` can produce text without calling the provider. +- **Agent events** (`agent.events`): live in the core layer and cover model calls, tool calls, Steps, and Runs. +- **App hooks** (`@hookimpl`): live in the app layer and cover the 7 Turn stages, tool and channel registration, storage, and CLI extensions, with Python entry-point discovery. -## Division of labor with App hooks {#app-hooks} +Under the hood, the app layer's interception hooks (`before_tool_call`, `after_tool_call`, `before_llm_call`, and `after_llm_call`) are bridged onto the same Agent events via `PluginAgentHooks`, but they differ in how they modify arguments and handle exceptions (for instance, an exception in an app hook is logged and skipped rather than aborting the Run). See the [Hooks reference](/docs/reference/hooks/#event-mapping) for a side-by-side comparison. -Agent events intervene in the model calls, tool calls, Steps, and Runs of the core loop; application hooks cover the application lifecycle — Turn stages, tool supply, storage, and channels — and carry plugin distribution. Application interception hooks can join the same set of Agent events through an adapter, but the two differ in how they return arguments and in their exception policy, as the [Hooks reference](/docs/reference/hooks/#event-mapping) details. For how to write each, see [SDK: events](/docs/sdk/events/) and [Plugins and Hooks: intercept a model or tool call](/docs/app/plugins/#control-a-model-or-tool-call). +For hands-on examples with `agent.events`, see [SDK: Events](/docs/sdk/events/); for writing plugin interception hooks, see [Plugins and Hooks: Intercept calls](/docs/app/plugins/#control-a-model-or-tool-call). diff --git a/website/src/content/docs/docs/concepts/tape.mdx b/website/src/content/docs/docs/concepts/tape.mdx index ed05c3d8..92c9927c 100644 --- a/website/src/content/docs/docs/concepts/tape.mdx +++ b/website/src/content/docs/docs/concepts/tape.mdx @@ -1,16 +1,25 @@ --- title: Tape and model context -description: The Tape keeps what happened; TapeContext decides what the next request can see. +description: Learn how Bub's Tape stores full AI agent session history while TapeContext, anchors, and handoffs select what each model call sees. sidebar: label: Tape --- -An application needs a complete, trustworthy history; a model needs only a bounded, relevant input. Bub keeps the two apart: **the Tape is the durable record, and the model context is one projection of that record**. +Long-running, multi-step Agents face two competing needs for history: + +- **Your application and team** need a complete, append-only record of what happened—every user message, tool call, argument, and result—so you can debug issues, audit decisions, and resume conversations. +- **The model** has a finite context window and works best with a concise, focused slice of relevant messages rather than every intermediate step from the beginning. + +Storing both in a single mutable `messages` array forces a bad trade-off: either let requests grow until the context overflows, or truncate the array and destroy your only historical record. + +Bub separates recording from reading: **the Tape stores the complete append-only history, and `TapeContext` selects and builds the model context before each model call**. ## One record, two views {#history-and-context} -- **The Tape (write)**: appends `TapeEntry` records in order — conversation messages, tool calls, tool results, anchors, and business events recorded explicitly. `tape.query()` returns the raw entries. -- **`TapeContext` (read)**: selects the entries this request needs and converts them into model messages. `tape.read_messages()` returns the projection, not the raw record. +Think of the Tape as the write side of conversation history and `TapeContext` as the read side: + +- **Tape** (write): appends `TapeEntry` records in chronological order, including messages (`message`), tool calls (`tool_call`), tool results (`tool_result`), phase markers (`anchor`), and custom events (`event`). Call `tape.query()` to inspect raw entries. +- **`TapeContext`** (read): selects entries before each model request and converts them into model messages. Call `tape.read_messages()` to get the resulting model context. ```mermaid flowchart LR @@ -18,26 +27,33 @@ flowchart LR E5 ==>|"default context start"| B["Model context
conversation + tool round-trips"] ``` -The default projection, `default_tape_context()`, reads the entries after the most recent anchor and rebuilds the conversation and tool round-trips. Entries marked `context=False` are excluded before selection and never enter the model context. +By default, an Agent uses `default_tape_context()`, which locates the **latest `anchor`** and reads only entries after it. Any entry written with `context=False` is excluded automatically and never enters model context. -:::note[Append-only, but not an immutable audit log] -Normal recording only appends; `tape.reset()` clears the record and writes a new `session/start` anchor. +:::note[Append-only, resettable on demand] +During normal runs, the Tape only appends new entries and never mutates existing ones. Calling `tape.reset()` clears the record and writes a new `session/start` anchor. ::: -## Anchors and handoffs {#anchors} +## Switching phases with anchors and handoffs {#anchors} -An **anchor** marks a cognitive transition, such as finishing information gathering or starting a new task. A **handoff** appends a new anchor, moving the start of the default context forward while keeping every earlier record. +As a conversation grows—or shifts from gathering information to executing changes—you often want the model to move on with a clean slate without deleting the earlier history from storage. -A handoff changes only the default read boundary: it generates no summary, deletes no history, and does not automatically inject the anchor's `state` into the next request. When you need a summary, generate one explicitly and write it into later model input. For usage, see [SDK: anchors and handoffs](/docs/sdk/tape/#anchors-and-handoff) and the app's built-in [`tape.handoff` command](/docs/reference/tools/#tape-handoff). +Bub handles this with **anchors** and **handoffs**: + +- An **anchor** is a milestone marker on the Tape that signals a transition to a new phase (such as `session/start` when a session opens, or `reviewed` after a code review finishes). +- A **handoff** appends a new anchor to the Tape. Because the default `TapeContext` reads only from the latest anchor forward, a handoff **immediately moves the start of the model context to that new marker**, while every earlier entry remains safely stored on the Tape and queryable via `tape.query()`. + +Keep in mind that a handoff only **advances the default read start**: it does not automatically summarize past turns, delete old history, or inject the anchor's `state` into the next prompt. When you want a summary carried forward, generate or supply one explicitly. For code usage, see [SDK: anchors and handoffs](/docs/sdk/tape/#anchors-and-handoff) and the built-in [`tape.handoff` tool](/docs/reference/tools/#tape-handoff). ## Where data belongs {#state} -| Home | Lifetime | Good for | +Different kinds of data in Bub have different lifetimes and belong in different places: + +| Location | Lifetime | Purpose | | --- | --- | --- | -| `state` / `TurnState` | One Run or one Turn | Scratch values shared within a request | -| `metadata` | One Run | Observability data such as a request ID; never enters model input | -| Tape entries | Decided by storage; may span processes | Conversation, tool round-trips, and business facts written explicitly | -| Anchor `state` | Kept with the history | Phase snapshots | -| Application storage | Decided by the app | Session settings restored by `load_state` | +| `state` / `TurnState` | Single Run or Turn | Request-scoped scratch values (request ID, permission flags, callbacks) | +| `metadata` | Single Run | Observability metadata for logs and event handlers; never sent to the model | +| `TapeEntry` | Decided by store backend; persists across processes | Conversation messages, tool round-trips, and explicit business events | +| Anchor `state` | Persisted on the Tape | Structured snapshot or summary saved at a handoff point | +| External app storage | Decided by your application | Business state loaded via `load_state` and saved via `save_state` | -`core.Agent` uses an in-memory store by default. See [SDK: Tape and memory](/docs/sdk/tape/) for persistence, forks, and concurrency, and the [Storage integration](/docs/integrations/storage/) for plugging in a store backend. +`core.Agent` uses an in-memory store (`InMemoryTapeStore`) by default. To persist Tapes to disk, customize context selectors, or work with Tape forks, see [SDK: Tape & Memory](/docs/sdk/tape/); to back the Tape with SQLite or PostgreSQL, see [Store conversation history in a database](/docs/integrations/storage/). diff --git a/website/src/content/docs/docs/concepts/turn.mdx b/website/src/content/docs/docs/concepts/turn.mdx index 878bf1da..7da30d6c 100644 --- a/website/src/content/docs/docs/concepts/turn.mdx +++ b/website/src/content/docs/docs/concepts/turn.mdx @@ -1,39 +1,61 @@ --- title: Turn -description: How the application layer turns one inbound message into replies, including the lifecycle stages, TurnState, and failure boundaries. +description: "Understand the Bub Turn lifecycle: the seven stages of processing an inbound message, shared per-Turn TurnState, and exception boundaries." sidebar: label: Turn --- -A **Turn** is the complete lifecycle the application layer gives one inbound message, owned by `BubFramework`. It fixes the order and error boundaries of session resolution, input preparation, model execution, state saving, and reply delivery; an Agent Run is only the model execution stage inside it. +When you talk to Bub through a terminal or a chat platform such as Telegram, the app layer receives more than a prompt for the model. It needs to figure out which session the message belongs to, restore that session's state, check whether the input is a direct command or a normal question, run the Agent, save updated state, and deliver the reply back to the right channel. -## Lifecycle {#stages} +In the Bub app layer, this end-to-end lifecycle for handling one inbound message is called a **Turn**, orchestrated by `BubFramework`. A core Agent Run is just the model-execution stage inside it. -`process_inbound()` sends every ordinary inbound message through the same set of stages: +## The seven lifecycle stages {#stages} + +Every call to `BubFramework.process_inbound()` moves an inbound message through seven stages in order: + +```mermaid +flowchart LR + A["resolve_session\nIdentify session"] --> B["load_state\nRestore state"] + B --> C["build_prompt\nBuild input"] + C --> D["run_model\nRun Agent"] + D --> E["save_state\nPersist state"] + E --> F["render_outbound\nBuild replies"] + F --> G["dispatch_outbound\nSend to channel"] +``` | Stage | Responsibility | | --- | --- | -| `resolve_session` | Establish which session the message belongs to | -| `load_state` | Restore session state and make the Agent available | -| `build_prompt` | Recognize commands and construct model input | -| `run_model` | Execute the Agent Run and produce model output | -| `save_state` | Persist application state that must outlive the Turn | -| `render_outbound` | Render model output into channel messages | -| `dispatch_outbound` | Deliver replies through the matching channel | +| `resolve_session` | Determine the message's `session_id` (defaults to `:`) | +| `load_state` | Restore session state for this Turn and bind the runtime Agent | +| `build_prompt` | Handle internal commands or build the model input | +| `run_model` | Execute the Agent Run (or streaming `run_model_stream`) | +| `save_state` | Persist application state across Turns after the model stage ends | +| `render_outbound` | Package model output into one or more outbound channel messages | +| `dispatch_outbound` | Deliver outbound messages to the channel | + +Every stage has a hook of the same name, letting plugins extend or replace any stage without touching core code. For exact signatures and dispatch rules, see the [Hooks reference](/docs/reference/hooks/#turn-hooks). + +It helps to distinguish three closely related terms: + +- **Session**: the identity boundary across multiple messages. Ten messages in the same chat belong to 1 Session, but trigger 10 separate Turns. A `session_id` is an identifier, not a lock; same-session concurrency is controlled by channel admission policy or the host application. +- **Turn**: the 7-stage app pipeline for one inbound message. +- **Run**: one execution of `core.Agent`'s model-and-tool loop. A normal message starts a Run during `run_model`; a comma command (such as `,help`) finishes inside the Turn without calling the model; calling `agent.run()` via the SDK starts a Run outside any Turn. -Each stage has a hook of the same name that can extend or replace the default behavior under its contract; signatures are in the [Hooks reference](/docs/reference/hooks/#turn-hooks). +## TurnState: per-Turn shared dictionary {#state} -A Turn is not the same granularity as a Run: a direct command can finish inside a Turn without starting a model Run, and a Run created directly with `core.Agent` belongs to no Turn. A **Session** is the identity and recovery boundary that spans several messages, so one Session can contain many Turns; a session ID itself provides no lock, and whether concurrent Turns are allowed is decided by an admission policy or the host. +As a Turn progresses, hooks, tools, and event handlers often need to pass request-scoped data to one another—such as a request ID, permission flags, or channel metadata. Bub provides `TurnState` for this purpose. -## TurnState {#state} +`TurnState` is a plain Python dictionary (`dict[str, Any]`) that **lives only for the current Turn or Run and is never persisted automatically**. -`TurnState` is a temporary dictionary shared by hooks, tools, and event handlers during the current execution. It lives only for this Turn or Run and is never persisted automatically. +- Save state that must persist across Turns explicitly in `save_state`, and restore it in `load_state`. +- Conversation history and tool records belong on the Tape, not in `TurnState` (see [Where data belongs](/docs/concepts/tape/#state)). +- Keys starting with `_runtime_` are managed internally by Bub; plugins should not modify or overwrite them. -Data that must survive into the next Turn should be saved in `save_state` and restored in `load_state`. Conversation and tool round-trips belong to the Tape, not to `TurnState`; see [where data belongs](/docs/concepts/tape/#state). Keys starting with `_runtime_` are written by the runtime, and plugins should not depend on them. +## Exceptions and failure boundaries {#failures} -## Failure boundaries {#failures} +Network hiccups, model timeouts, or tool failures can interrupt a Turn at any point. The Turn pipeline defines clear failure boundaries so you know what is guaranteed to run: -- Once execution enters the model stage, `save_state` always runs in a `finally`, so a model error or timeout cannot skip it. -- A failure in `resolve_session`, `load_state`, or `build_prompt` happens before that guarantee begins, so `save_state` does not run. -- An unhandled exception goes to `on_error` to be observed and reported, and is then re-raised; `on_error` does not restore the Turn. -- A Turn is not a transaction: files a tool already changed, requests it already sent, and other external side effects are not rolled back. +- **`save_state` always runs once the model stage starts**: as soon as execution enters `run_model`, `save_state` is guaranteed to run in a `finally` block, even if the model call fails or times out. +- **Pre-model failures skip `save_state`**: if an error occurs in `resolve_session`, `load_state`, or `build_prompt`, the model stage has not started and `save_state` is not called. +- **`on_error` observes without recovering**: unhandled exceptions are passed to `on_error` hooks for logging or alerting, then re-raised to the caller. +- **A Turn does not roll back external side effects**: if a tool has already modified files, sent HTTP requests, or written to a database, a later failure in the Turn does not undo those actions. diff --git a/website/src/content/docs/docs/getting-started/index.mdx b/website/src/content/docs/docs/getting-started/index.mdx index 9e451011..6882b8cb 100644 --- a/website/src/content/docs/docs/getting-started/index.mdx +++ b/website/src/content/docs/docs/getting-started/index.mdx @@ -1,54 +1,54 @@ --- title: What is Bub? -description: A lightweight agent runtime written in Python. Run it as-is, or embed it in your own program. +description: Discover Bub, a lightweight Python AI agent runtime with a ready-to-use CLI app, composable SDK, Tape memory, tools, skills, and plugins. --- import { Card, CardGrid } from '@astrojs/starlight/components'; -Bub is a lightweight agent runtime written in Python. It ships with a ready-to-use CLI app and a composable SDK, so you can run it directly or embed agent capabilities in your own programs. +Bub is a lightweight agent runtime written in Python. It ships with a ready-to-use CLI app and a composable SDK, so you can run it out of the box or embed agent capabilities in your own programs. An agent is at heart a loop: the model reads the context and decides which tool to call, the tool result goes back into the context, and the model reads it again. The loop ends when the model stops asking for tools and answers directly. -So an agent rests on four things: a **model**, **tools**, a **context**, and the **loop** that drives them. Working from that shared understanding, Bub keeps a small core and builds a ready-to-run application around it: +So an agent rests on four core parts: a **model**, **tools**, a **context**, and the **loop** that drives them. Working from that idea, Bub keeps a small core and builds a ready-to-run application around it: - - Composable agent capabilities, including the loop, tools, context, the event bus, and the model client. + + Composable agent kernel providing the loop, tools, context (Tape), event bus, and model client. - - A harness on top of the core that provides configuration, plugins, hooks, skills, message channels, and a gateway. + + Application harness on top of the core, providing configuration, plugins, hooks, skills, channels, and a gateway. Which one should you use? -- If you want to **combine Bub with your existing codebase or service**, use the core layer [SDK](/docs/sdk/) directly; -- If you want **Bub to work out of the box**, use the app layer [App](/docs/app/workspace/). +- If you want to **embed Bub in an existing codebase or service**, start with the core [SDK](/docs/sdk/). +- If you want **Bub ready to run out of the box**, use the [CLI app](/docs/app/workspace/). :::tip -The two are not exclusive. When you need to, you can even [reuse the Bub app inside the SDK](/docs/integrations/reuse-app/#model-stage). +The two are not mutually exclusive. When you need to, you can even [reuse Bub app capabilities](/docs/integrations/reuse-app/#model-stage) inside an SDK service. ::: ## Features {#features} -Bub is built around simplicity, composability, and extensibility. You can combine its capabilities as needed or build your own agent on top of it. Its key features include: +Bub is built around simplicity, composability, and extensibility—you can combine its parts as needed or build your own agent on top of it: - Conversation history is appended to the [tape](/docs/concepts/tape/) without modifying existing entries. + Conversation history is appended to the [Tape](/docs/concepts/tape/) without mutating existing entries. - Every model and tool call emits events when it starts, finishes, and returns a result, so you can observe, modify, or intervene in the run. + Every model and tool call emits events so you can observe, modify arguments, or intercept execution. - Write tools as ordinary Python functions and take advantage of the existing Python ecosystem. + Define tools as standard Python functions and use any library in the Python ecosystem. - Capabilities can be extended through plugins. A plugin can provide a tool, an event listener, a message channel, or a complete set of skills. + Extend tools, event listeners, message channels, and skills through plugins. :::tip -Explore the [Agent loop](/docs/concepts/agent/) to understand Bub's core execution model. +Explore [The Agent loop](/docs/concepts/agent/) to see how Bub's core execution model works. ::: -Now you can explore the Bub docs freely, or follow the next page and start your own journey with Bub. +Now you can explore the docs freely, or head to the next page to start your journey with Bub. diff --git a/website/src/content/docs/docs/getting-started/install.mdx b/website/src/content/docs/docs/getting-started/install.mdx index b13b05e4..04e8f5e0 100644 --- a/website/src/content/docs/docs/getting-started/install.mdx +++ b/website/src/content/docs/docs/getting-started/install.mdx @@ -1,10 +1,12 @@ --- title: Install Bub -description: Install Bub step by step, with several install paths to choose from. +description: Install Bub in Python with uv or pip. Choose the full CLI app (bub[app]), the lightweight Python Agent SDK (bub), or run from source. --- import { Tabs, TabItem } from '@astrojs/starlight/components'; +Bub can be used as a CLI app or as a Python SDK, so pick the install path that fits your workflow. + ## Install the CLI app {#app-install} @@ -32,17 +34,17 @@ uv tool update-shell -The install script installs uv and Python 3.12, and puts `bub[app]` into your current environment. `app` is an optional dependency group that bundles the application-layer capabilities such as the CLI, channels, and plugins; you do not need it if you only use the SDK. +The install script sets up `uv`, Python 3.12, and `bub[app]` for you. The `app` extra bundles application-layer capabilities such as the CLI, channels, and plugins; you do not need it if you only use the core SDK. -When it finishes, run `bub --help`, then run `bub onboard` to start configuring. +When it finishes, run `bub --help` to verify the install, then run `bub onboard` to configure your model. :::tip -If the command is not found, check whether the environment variables include the directory that holds the executable, or add `~/.local/bin` to PATH yourself. +If `bub` is not found, check that the install directory is on your `PATH`, or add `~/.local/bin` to `PATH` yourself. ::: ## Install the SDK {#agent-install} -From 0.6.0 on, Bub ships the core only. Use your package manager to add Bub to your project as a dependency. Here is uv: +From 0.6.0 on, the base `bub` package ships the core kernel only. Add it to your project with your package manager—here is `uv`: ```bash uv add bub diff --git a/website/src/content/docs/docs/getting-started/quickstart.mdx b/website/src/content/docs/docs/getting-started/quickstart.mdx index 62361b05..06693db7 100644 --- a/website/src/content/docs/docs/getting-started/quickstart.mdx +++ b/website/src/content/docs/docs/getting-started/quickstart.mdx @@ -1,34 +1,38 @@ --- title: Quick start -description: Get up and running with Bub in your terminal or in your own Python project. +description: "Get started with Bub in minutes: configure an LLM and chat in the terminal CLI, or embed bub.core.Agent into your Python project with the SDK." --- import { CardGrid, LinkCard, Steps } from '@astrojs/starlight/components'; -Since 0.6.0, Bub itself is split in two, so you can pick whichever part fits how you want to use it. +Since 0.6.0, Bub is split into two layers—core and app—so you can pick whichever path fits how you want to use it. -This page assumes [Bub is installed](/docs/getting-started/install/). +This page assumes you have already [installed Bub](/docs/getting-started/install/). ## Start from the CLI {#cli} -Open your terminal and work through the following steps on the command line: +Open your terminal and walk through these steps on the command line: -1. (Optional) If you have never configured Bub, run this command first to finish the initial setup: +1. (Optional) If you have never configured Bub before, run the setup wizard first: ```bash bub onboard ``` -2. Create a workspace (a directory) anywhere and switch into it, then launch an interactive session with `bub chat`: +2. Create a workspace directory anywhere, switch into it, and launch an interactive session with `bub chat`: ```bash mkdir hello-bub && cd hello-bub bub chat ``` -3. Now try copying and pasting the text below to have a conversation with Bub: + :::tip + Run `bub --help` or see the [CLI reference](/docs/reference/cli/) for all options. + ::: + +3. Now try copying and pasting the prompt below to start a conversation with Bub: ```shell Summarize the files in this directory @@ -36,15 +40,15 @@ Open your terminal and work through the following steps on the command line: -Press Ctrl+D or type `,quit` to leave the interactive session. Run `bub --help` to see the commands and options, or see the [CLI reference](/docs/reference/cli/). +Press Ctrl+D or type `,quit` whenever you want to leave the interactive session. -## Run it with the SDK {#sdk} +## Run with the SDK {#sdk} -If you want to embed the agent in your own Python project, start with the base SDK. +If you want to embed an Agent in your own Python project, start with the core SDK: -1. Create a new project and install Bub: +1. Create a new project and install `bub`: ```bash uv init --python 3.12 my-agent && cd my-agent @@ -53,7 +57,7 @@ If you want to embed the agent in your own Python project, start with the base S 2. Save the following code as `main.py`: - ```python title="main.py" + ```python title="main.py" {9-11} import asyncio import republic @@ -73,6 +77,10 @@ If you want to embed the agent in your own Python project, start with the base S asyncio.run(main()) ``` + :::tip + See the [Python API reference](/docs/reference/python-api/) for full signatures. + ::: + 3. Run it with your API key: ```bash @@ -82,23 +90,21 @@ If you want to embed the agent in your own Python project, start with the base S -When you need to look up other APIs, see the [Python API reference](/docs/reference/python-api/). - ## Next steps {#next-steps} -Congrats — you know the basics of Bub. From here you can explore either path more deeply to unlock more use cases. +Congrats — you now know the basics of Bub! Pick a path below to explore further: -And of course, if you like, you can keep reading about the design ideas behind Bub. +And of course, if you are curious, keep reading to see the design ideas behind Bub. diff --git a/website/src/content/docs/docs/integrations/acp.mdx b/website/src/content/docs/docs/integrations/acp.mdx index 7e46ffab..6a93d053 100644 --- a/website/src/content/docs/docs/integrations/acp.mdx +++ b/website/src/content/docs/docs/integrations/acp.mdx @@ -1,31 +1,31 @@ --- title: Connect an IDE over ACP -description: Install bub-acp-server to run and interact with the Bub Agent in Zed or any ACP-compatible code editor. +description: Install bub-acp-server to run the Bub Agent inside Zed or any ACP-compatible IDE, with session sync and remote HTTP/WebSocket mode. sidebar: badge: { text: 'App', variant: 'note' } --- -The [Agent Client Protocol](https://agentclientprotocol.com/) (ACP) is an open standard protocol that lets code editors (such as Zed) start an Agent as a subprocess and exchange sessions, prompts, tool call status, and code editing operations bidirectionally over JSON-RPC streaming. +The [Agent Client Protocol](https://agentclientprotocol.com/) (ACP) is an open standard that lets code editors (such as Zed) run an Agent subprocess and stream sessions, prompts, tool calls, and file edits over JSON-RPC. -The `bub-acp-server` plugin connects the Bub application to the ACP protocol, so you can summon Bub directly in your everyday IDE for coding, refactoring, and troubleshooting. +Install `bub-acp-server` to connect Bub to ACP, so you can summon Bub directly in your everyday IDE for coding, refactoring, and troubleshooting. ```mermaid flowchart LR - IDE["Code editor\n (ACP-compatible)"] + IDE["Code editor\n(ACP-compatible)"] Server["bub-acp-server"] Bub["Bub Agent"] IDE <-->|"JSON-RPC"| Server - Server <-->|"Turn events and tool execution"| Bub + Server <-->|"Turn events and tool calls"| Bub ``` ## Before you start {#before-you-start} -- You have [installed the Bub application](/docs/getting-started/install/#app-install) and configured a working model. -- You have installed the [Zed](https://zed.dev/) editor (or another ACP-compatible client). +- [Install the Bub app](/docs/getting-started/install/#app-install) and configure a model. +- Install [Zed](https://zed.dev/) (or another ACP client). -:::note[Environment variables and paths] -Applications such as Zed inherit a `PATH` and environment variables at launch that usually differ from those of a terminal (such as `~/.zshrc` or `~/.bashrc`). First confirm the absolute path of `bub` in your current environment from the terminal: +:::note[Find the absolute path to `bub`] +GUI applications often launch with a default system `PATH` that omits shell additions from `~/.zshrc` or `~/.bashrc`. Check the absolute path of `bub` in your terminal first: ```bash command -v bub @@ -41,23 +41,17 @@ bub install bub-acp-server@main bub acp --help ``` -If the installation succeeds, the terminal output shows: - -```text -Usage: bub acp [OPTIONS] -``` - -`bub-acp-server` communicates with the host editor over standard input/output (`stdio`) by default. +Seeing `Usage: bub acp [OPTIONS]` confirms installation. By default, `bub acp` communicates over `stdio`. ## 2. Configure Zed {#zed} -In Zed, press `Cmd+Shift+P` (macOS) or `Ctrl+Shift+P` (Linux/Windows) to open the command palette, type and run `zed: open settings`, and add the `agent_servers` configuration to the opened `settings.json`. +In Zed, press `Cmd+Shift+P` (macOS) or `Ctrl+Shift+P` (Linux/Windows), run `zed: open settings`, and add `agent_servers` to `settings.json`. -### Option A: Global installation {#global-install} +### Option A: Direct command {#global-install} -If `bub` is on the system global `PATH` and you do not need to load a project-specific `.env` file, configure it directly: +If you do not need to load a project `.env` file, point directly to `bub` (replace `"bub"` with the absolute path from `command -v bub` if Zed cannot find it): -```json +```json title="~/.config/zed/settings.json" { "agent_servers": { "Bub": { @@ -70,37 +64,35 @@ If `bub` is on the system global `PATH` and you do not need to load a project-sp } ``` -*If Zed reports that it cannot find `bub`, replace `"command"` with the absolute path you obtained earlier from `command -v bub`.* - -### Option B: Use a wrapper script {#wrapper-script} +### Option B: Wrapper script {#wrapper-script} -If your project relies on a specific Python virtual environment, or the model API key is stored in `.env` at the workspace root, we strongly recommend writing a launcher wrapper script (for example `~/.bub/bub-acp-wrapper`): +If your API keys live in a workspace `.env` file or you use a project virtual environment, create a wrapper script at `~/.bub/bub-acp-wrapper`: -```bash +```bash title="~/.bub/bub-acp-wrapper" #!/usr/bin/env bash set -euo pipefail -# 1. Activate the virtual environment (if any) +# 1. Optional: activate virtual environment # source /path/to/venv/bin/activate -# 2. Load workspace or user environment variables +# 2. Load workspace .env if present if [ -f "$PWD/.env" ]; then set -a source "$PWD/.env" set +a fi -# 3. Start Bub ACP using an absolute path +# 3. Launch Bub ACP via absolute path exec /path/to/your/bub acp ``` -After granting execute permission, point Zed settings at the script: +Make it executable and reference it in Zed's `settings.json`: ```bash chmod +x ~/.bub/bub-acp-wrapper ``` -```json +```json title="~/.config/zed/settings.json" { "agent_servers": { "Bub": { @@ -113,50 +105,44 @@ chmod +x ~/.bub/bub-acp-wrapper } ``` -## 3. Start a session {#start} +## 3. Start a session in Zed {#start} After saving the settings, restart Zed or reload the configuration: -1. Press `Cmd+?` (macOS) or `Ctrl+?` (Linux/Windows) to open Zed's Agent side panel. -2. Switch to **Bub** in the model/backend selector menu. -3. Enter a message in the input box to test: +1. Press `Cmd+?` (macOS) or `Ctrl+?` (Linux/Windows) to open Zed's Agent panel. +2. Select **Bub** from the agent menu. +3. Send a test prompt: ```text Hello! Please introduce yourself. ``` -4. Bub streams the response, thinking process, and tool call steps into the panel one by one. +4. Bub streams the response, thinking process, and tool call steps into the panel. -:::tip[Native tool capabilities] -Zed supports letting the Agent operate through the editor's file system and terminal. When Zed has the relevant permissions, Bub's `bash`, `fs.read`, and `fs.write` are automatically executed by the editor in preference; if the client does not declare this capability, they fall back to running locally. +:::tip[Editor-delegated tools] +When Zed advertises filesystem and terminal capabilities, Bub delegates `bash`, `fs.read`, and `fs.write` to the editor automatically, falling back to local execution when unsupported. ::: -## 4. Sessions and restore {#sessions} - -`bub-acp-server` provides full session lifecycle management: +## 4. Sessions and parameter sync {#sessions} -- **New session**: creating a new Thread in the Zed panel corresponds to opening a brand-new session Tape at the underlying layer. -- **History restore**: when you switch back to an old Thread, Bub extracts and replays that session's history messages and tool context from the persistent Tape store. -- **Persistent binding**: the session metadata index is stored in `$BUB_HOME/acp-sessions.json`. As long as your `BUB_HOME` and workspace path stay stable, the history session list remains intact after restarting the editor. -- **Model and reasoning parameters**: the reasoning effort adjusted in the Zed UI, or the specific model alias selected, is automatically appended to subsequent requests in this ACP session. +- **New and restored threads**: starting a new thread in Zed creates a new Tape; switching back to an earlier thread replays history from the Tape store. The session index is saved in `$BUB_HOME/acp-sessions.json`—as long as `BUB_HOME` and your workspace path stay the same, your session list remains intact across editor restarts. +- **Model and reasoning effort**: changing the model or reasoning effort in the Zed UI updates subsequent requests in the active ACP session. -## 5. Remote service mode {#http} +## 5. Remote mode (HTTP / WebSocket) {#http} -In most local development scenarios, the default `stdio` is the lightest, lowest-overhead choice. If you deploy Bub on a cloud development machine (Remote Server) or inside a Docker container and need the editor on your local development machine to call it remotely, you can use HTTP/WebSocket service mode. +For most local setups, `stdio` is the lightest, lowest-overhead choice. When Bub runs on a remote dev server or inside a Docker container, expose ACP over HTTP or WebSocket instead. -### Option 1: Run the service standalone {#standalone-service} +### Run standalone {#standalone-service} ```bash -# Start the HTTP service bub acp --transport http - -# Or start the WebSocket service +# or bub acp --transport websocket ``` -The default listen address is `127.0.0.1:28200` (the HTTP endpoint is `http://127.0.0.1:28200/acp`, and the WebSocket endpoint is `ws://127.0.0.1:28200/acp`). +Listens on `127.0.0.1:28200` by default (`http://127.0.0.1:28200/acp` or `ws://127.0.0.1:28200/acp`). -### Option 2: Run long-lived as a Bub Gateway channel {#gateway-channel} +### Run as a gateway channel {#gateway-channel} -Gateway mode can maintain the session pool and the background connection at the same time: +Gateway mode maintains the session pool and background connection together: ```bash bub gateway --enable-channel acp-server @@ -164,21 +150,20 @@ bub gateway --enable-channel acp-server | Environment variable | Default | Description | | --- | --- | --- | -| `BUB_ACP_SERVER_HOST` | `127.0.0.1` | Host IP to listen on (set to `0.0.0.0` to expose it externally; mind network security) | -| `BUB_ACP_SERVER_PORT` | `28200` | Service port | -| `BUB_ACP_SERVER_CERTFILE` | empty | TLS certificate path (required to enable HTTPS/WSS) | +| `BUB_ACP_SERVER_HOST` | `127.0.0.1` | Listen host IP (use `0.0.0.0` for external access) | +| `BUB_ACP_SERVER_PORT` | `28200` | Listen port | +| `BUB_ACP_SERVER_CERTFILE` | empty | TLS certificate path (required for HTTPS/WSS) | | `BUB_ACP_SERVER_KEYFILE` | empty | TLS private key path | -:::caution[Security boundary] -HTTP/WebSocket endpoints do not provide complex user authentication by default. If you need to expose them over the public internet, be sure to put Nginx or Cloudflare Tunnel in front to add authentication, and enable TLS encryption. +:::caution[Network security] +HTTP/WebSocket endpoints do not include built-in user authentication. Use SSH port forwarding, or place Nginx / Cloudflare Tunnel in front with authentication and TLS. ::: ## Troubleshooting {#troubleshooting} -| Common problem | Starting point | Suggested fix | -| --- | --- | --- | -| Zed reports that it cannot find the Agent Server | Check the `"command"` path | Run `command -v bub` in a terminal and change `command` in the configuration to the system absolute path. | -| The panel shows a startup failure or fallback | Environment variables are not taking effect (for example, a missing API key) | Use [Option B](#zed) to write a wrapper script and force `source` the required `.env` in it. | -| Unclear where the protocol handshake is stuck | Check Zed's ACP communication logs | Open the command palette in Zed and run `dev: open acp logs` to observe JSON-RPC interaction events in real time. | -| Tool calls do not trigger properly | Check client capability negotiation (Capabilities) | Confirm that the workspace has read/write permissions; first test whether tools work with `bub run` in the same terminal. | -| Session history cannot be saved | Check the `BUB_HOME` directory permissions | Make sure the user running Zed has read/write access to the `~/.bub` directory. | +| Symptom | Fix | +| --- | --- | +| Zed cannot find the Agent server | Set `command` in `settings.json` to the absolute path from `command -v bub` | +| Startup fails or API key is missing | Use [Option B](#wrapper-script) to `source` your `.env` file | +| Inspect JSON-RPC traffic | Run `dev: open acp logs` from Zed's command palette | +| Session history does not persist | Verify the user running Zed has read/write permissions on `$BUB_HOME` (`~/.bub`) | diff --git a/website/src/content/docs/docs/integrations/ag-ui.mdx b/website/src/content/docs/docs/integrations/ag-ui.mdx index e3cd00cf..1e6c69fa 100644 --- a/website/src/content/docs/docs/integrations/ag-ui.mdx +++ b/website/src/content/docs/docs/integrations/ag-ui.mdx @@ -1,6 +1,6 @@ --- title: Connect an AI chat frontend to Bub with AG-UI -description: Try Bub's experimental AG-UI support. Connect an AI chat frontend with examples for streaming replies, browser tools, and UI history. +description: Install the bub-ag-ui plugin to connect Bub to an AI web chat frontend over AG-UI, supporting streaming replies, browser tools, and UI history. sidebar: label: Web frontends with AG-UI badge: { text: 'App', variant: 'note' } @@ -147,10 +147,7 @@ async rewrites() { Create `app/BubRuntimeProvider.tsx` to connect the runtime, restore displayed messages, and register the weather tool: -
-app/BubRuntimeProvider.tsx - -```tsx title="app/BubRuntimeProvider.tsx" +```tsx title="app/BubRuntimeProvider.tsx" showLineNumbers collapse={1-14, 19-39, 60-67} "use client"; import { useEffect, useState, type ReactNode } from "react"; @@ -230,8 +227,6 @@ export function BubRuntimeProvider({ children }: { children: ReactNode }) { } ``` -
- Replace `app/assistant.tsx` with the following and keep the existing `app/page.tsx` entry: ```tsx title="app/assistant.tsx" @@ -273,10 +268,7 @@ npm install @copilotkit/react-core@1.85.0 @ag-ui/client@1.0.2 @ag-ui/core@1.0.2 Save the shared files as `src/demo-session.ts` and `src/scenario.json`, then add the shared Vite proxy. Create `src/BubHttpAgent.ts` to restore displayed messages from browser storage without requesting them from Bub: -
-src/BubHttpAgent.ts - -```typescript title="src/BubHttpAgent.ts" +```typescript title="src/BubHttpAgent.ts" showLineNumbers collapse={1-6} import { HttpAgent } from "@ag-ui/client"; import { EventType, type BaseEvent, type RunAgentInput } from "@ag-ui/core"; import { Observable } from "rxjs"; @@ -307,11 +299,9 @@ export class BubHttpAgent extends HttpAgent { } ``` -
- Replace `src/main.tsx`. `useFrontendTool` registers the weather tool and returns its result to Bub: -```tsx title="src/main.tsx" +```tsx title="src/main.tsx" showLineNumbers collapse={1-10, 49-52} "useFrontendTool" import { createRoot } from "react-dom/client"; import { BubHttpAgent, storageKey } from "./BubHttpAgent"; import { readDemoSession, persistDemoSession } from "./demo-session"; @@ -392,10 +382,7 @@ npm install @openuidev/react-ui@0.18.5 @openuidev/react-headless@0.18.5 @openuid Save the shared files as `src/demo-session.ts` and `src/scenario.json`, then add the shared Vite proxy. Replace `src/main.tsx`: -
-src/main.tsx - -```tsx title="src/main.tsx" +```tsx title="src/main.tsx" showLineNumbers collapse={1-28, 41-106} import { createRoot } from "react-dom/client"; import { AgentInterface } from "@openuidev/react-ui"; import { @@ -519,8 +506,6 @@ createRoot(document.getElementById("root")!).render( ); ``` -
- This example keeps one thread in the sidebar and disables deletion. Its default renderer displays Markdown tables as plain text. To customize the UI, see the [OpenUI agent example](https://github.com/thesysdev/openui/tree/main/examples/agent-frameworks/mastra). ### Start the frontend {#openui-start} @@ -592,10 +577,7 @@ npx ai-elements@latest add conversation message prompt-input tool suggestion Save the shared files as `src/demo-session.ts` and `src/scenario.json`, then replace `src/main.tsx`. For component usage, see the [AI Elements guide](https://docs.langchain.com/oss/python/langchain/frontend/integrations/ai-elements). -
-src/main.tsx - -```tsx title="src/main.tsx" +```tsx title="src/main.tsx" showLineNumbers collapse={1-32, 49-180} import { useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import { HttpAgent, type Message as AgMessage } from "@ag-ui/client"; @@ -798,8 +780,6 @@ start().catch((error) => { }); ``` -
- ### Start the frontend {#ai-elements-start} ```bash diff --git a/website/src/content/docs/docs/integrations/agent-plugins.mdx b/website/src/content/docs/docs/integrations/agent-plugins.mdx index 8c479d01..ed2ca364 100644 --- a/website/src/content/docs/docs/integrations/agent-plugins.mdx +++ b/website/src/content/docs/docs/integrations/agent-plugins.mdx @@ -1,21 +1,21 @@ --- title: Load portable Agent Plugins -description: Load a portable Agent Plugin containing skills and MCP servers alongside existing Bub extensions. +description: Load portable, declarative Agent Plugin packages in Bub to reuse bundled skills and MCP servers alongside native Bub extensions. sidebar: badge: { text: 'App', variant: 'note' } --- import { FileTree, Steps } from '@astrojs/starlight/components'; -[Agent Plugins](https://agent-plugins.org/specification) is a cross-platform specification for Agent extension packages. It uses a purely declarative directory structure to package prompt skills and external tools (MCP servers) together, enabling plug-and-play use and reuse across projects without writing or modifying any Python code. +[Agent Plugins](https://agent-plugins.org/specification) is a cross-platform specification for declarative Agent extension packages. Each package bundles prompt skills (`skills/`) and MCP servers (`mcp.json`) in a single folder, enabling plug-and-play reuse across projects with no Python code required. -The [bub-agent-plugins](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-agent-plugins) plugin gives Bub native support for this specification, automatically discovering and loading the skills and tools in each plugin package. +The [`bub-agent-plugins`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-agent-plugins) plugin lets Bub discover and load these packages automatically. -## Get started {#get-started} +## Quick start {#get-started} Below you will create a plugin package containing a summary skill and a time server. The verification commands call the skill and tool directly and do not require a model API key. -Before you start, [install the Bub application](/docs/getting-started/install/#app-install) and make sure `uvx` is on `PATH`. +Before starting, [install the Bub app](/docs/getting-started/install/#app-install) and ensure `uvx` is on your `PATH`. @@ -26,28 +26,28 @@ Before you start, [install the Bub application](/docs/getting-started/install/#a bub hooks ``` - `bub-agent-plugins` depends on `bub-mcp`; install the latest version, and install it explicitly even when you only use skills. The `load_state` and `provide_channels` lines from `bub hooks` should include `agent-plugins`. + `bub-agent-plugins` depends on `bub-mcp` for MCP connection management (install both even if you only use skills). Verify `agent-plugins` appears under `load_state` and `provide_channels` in `bub hooks`. -2. **Create the plugin package** +2. **Create a plugin package** - Create the following structure in your workspace: + Create `.agents/plugins/portable-notes/` in your workspace: - .agents/ - plugins/ - portable-notes/ - - plugin.json + - **plugin.json** - skills/ - plugin-summary/ - - SKILL.md - - mcp.json + - **SKILL.md** + - **mcp.json** - `plugin.json`: + Create `plugin.json` (`$schema` and `name` are required, and `name` must match the directory name): - ```json + ```json title=".agents/plugins/portable-notes/plugin.json" { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "portable-notes", @@ -56,38 +56,22 @@ Before you start, [install the Bub application](/docs/getting-started/install/#a } ``` - `$schema` and `name` are required fields; `skills/` and `mcp.json` are both optional. + Create `skills/plugin-summary/SKILL.md`: - `skills/plugin-summary/SKILL.md`: - - ```markdown + ```markdown title=".agents/plugins/portable-notes/skills/plugin-summary/SKILL.md" --- name: plugin-summary description: Summarize notes into decisions and next actions. --- - Read the supplied notes. List the decisions made, then the remaining actions and their owners. - If an owner is missing, say that it is unassigned. - ``` - - The skill's `name` must match its directory name. Skills with the same name in the workspace or user directories take precedence over skills inside a plugin. - -3. **Verify the skill** - - Run this in the workspace: - - ```bash - bub --workspace . run ',skill' - bub --workspace . run ',skill name=plugin-summary' + Read the supplied notes: + 1. List the key decisions made; + 2. List remaining actions and their owners (mark unassigned items explicitly). ``` - The first command should list `plugin-summary`; the second should print its location and body. Skills do not need a background channel, so `bub run` works. - -4. **Add and call the MCP server** - - `mcp.json`: + Create `mcp.json` (`$schema` is required, and every server must declare `type`: `stdio`, `streamable-http`, or `sse`): - ```json + ```json title=".agents/plugins/portable-notes/mcp.json" { "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", "mcpServers": { @@ -100,44 +84,57 @@ Before you start, [install the Bub application](/docs/getting-started/install/#a } ``` - The portable format requires `$schema`, and every server must declare a `type`: `stdio`, `streamable-http`, or `sse`. Remote servers use `url` and optional `headers`; URLs must use HTTPS except for loopback addresses. +3. **Verify the skill** + + Run these commands in the workspace: + + ```bash + bub --workspace . run ',skill' + bub --workspace . run ',skill name=plugin-summary' + ``` + + The first command lists `plugin-summary`; the second prints its path and body (skills do not need a background channel, so `bub run` works directly). + +4. **Verify the MCP tool** - Start the chat interface: + Start `bub chat` (which starts the `agent-plugins.mcp` background channel): ```bash bub --workspace . chat ``` - Wait for the server to connect, then call the time tool directly: + Once connected, call the plugin's time tool directly (prefixed with `mcp..`): ```text ,mcp.portable-notes.time_get_current_time timezone=UTC ``` - On first launch, `uvx` may need to download the server. If you see `command not found`, check the startup logs and retry after the tool has registered. + On first launch, `uvx` may take a moment to download the server. If you see `command not found`, check the startup logs and retry once the tool registers. -Once you have [configured a model](/docs/app/configure/), you can also let the model call the time tool, or use `$plugin-summary` to summarize notes. +Once you have [configured a model](/docs/app/configure/), you can also let the model call the time tool directly or use `$plugin-summary` to summarize notes. -## Use it alongside existing MCP servers {#with-mcp} +## Coexistence with global MCP servers {#with-mcp} -The two kinds of configuration are managed separately and do not affect each other: +MCP servers inside Agent Plugins are isolated from global `~/.bub/mcp.json` servers: -| Configuration source | Lifecycle channel | Tool name format | -| --- | --- | --- | -| `~/.bub/mcp.json` | `mcp.lifecycle` | `mcp._` | -| `/mcp.json` | `agent-plugins.mcp` | `mcp.._` | +| Source | Config file | Lifecycle channel | Tool name format | +| --- | --- | --- | --- | +| Global config | `~/.bub/mcp.json` | `mcp.lifecycle` | `mcp._` | +| Agent Plugin | `/mcp.json` | `agent-plugins.mcp` | `mcp.._` | -Both can therefore have a server named `time`. `bub mcp add`, `remove`, and `list` only manage `~/.bub/mcp.json`; servers in a plugin package are verified through the startup logs and the tool name that includes the plugin. +Both can define a `time` server without name collisions. Note that `bub mcp list` / `add` / `remove` manage only `~/.bub/mcp.json`. -`bub chat` and `bub gateway` start the enabled lifecycle channels; `bub run` does not. When using `BUB_ENABLED_CHANNELS`, check whether `agent-plugins.mcp` or `mcp.lifecycle` is excluded. +## Configure discovery paths and toggles {#discovery-paths} -## Configure discovery paths and components {#discovery-paths} +By default, Bub scans immediate subdirectories of: +1. **Workspace directory**: `/.agents/plugins/` +2. **User global directory**: `~/.agents/plugins/` -By default, Bub scans the immediate child directories of `/.agents/plugins/` and `~/.agents/plugins/`. To use other locations, configure them in `~/.bub/config.yml`: +Customize discovery paths or toggle components in `~/.bub/config.yml`: -```yaml +```yaml title="~/.bub/config.yml" agent-plugins: paths: - /opt/agent-plugins/reporting @@ -147,23 +144,23 @@ agent-plugins: data_root: ~/.bub/agent-plugins ``` -| Field | Purpose | -| --- | --- | -| `paths` | Explicit plugin root directories, each containing `plugin.json` directly; relative paths resolve against the current workspace | -| `auto_discover` | When set to `false`, only explicit paths are used | -| `skills_enabled` / `mcp_enabled` | Enable the skill and MCP components independently | -| `data_root` | Root directory for persistent plugin data; defaults to `$BUB_HOME/agent-plugins` or `~/.bub/agent-plugins` | +| Field | Default | Purpose | +| --- | --- | --- | +| `paths` | `[]` | Explicit plugin root directories (each containing `plugin.json`; relative paths resolve against the workspace) | +| `auto_discover` | `true` | Scan default `.agents/plugins` directories; set `false` to load only `paths` | +| `skills_enabled` / `mcp_enabled` | `true` | Enable or disable plugin skills and MCP servers independently | +| `data_root` | `~/.bub/agent-plugins` | Root directory for persistent plugin data | -Explicit paths take precedence, followed by the workspace directory and then the user directory. When multiple plugin packages have the same manifest name, the first valid package is used. +**Priority**: explicit `paths` > workspace directory > user global directory (first valid package wins on name collisions; workspace `.agents/skills/` always overrides plugin skills of the same name). -Environment variables use the `BUB_AGENT_PLUGINS_` prefix, with JSON for list values: +Override via `BUB_AGENT_PLUGINS_` environment variables (use JSON for lists): ```bash export BUB_AGENT_PLUGINS_PATHS='["/opt/agent-plugins/reporting"]' export BUB_AGENT_PLUGINS_AUTO_DISCOVER=false ``` -Stdio servers receive `PLUGIN_ROOT` and `PLUGIN_DATA` as absolute paths, and their default working directory is the plugin root. `${PLUGIN_ROOT}` and `${PLUGIN_DATA}` expand only in `args`, `env` values, and `cwd`: +For `stdio` MCP servers, Bub sets the working directory to the plugin root and injects `PLUGIN_ROOT` and `PLUGIN_DATA` environment variables. You can also interpolate `${PLUGIN_ROOT}` and `${PLUGIN_DATA}` in `args`, `env` values, and `cwd`: ```json { @@ -172,14 +169,13 @@ Stdio servers receive `PLUGIN_ROOT` and `PLUGIN_DATA` as absolute paths, and the } ``` -`PLUGIN_DATA` points to a persistent directory named after the plugin under `data_root`. After downloading or updating a plugin package, restart Bub to load the new content. +After downloading or updating a plugin package, restart Bub to load the new content. ## Troubleshooting {#troubleshooting} | Symptom | What to check | | --- | --- | -| `agent-plugins` is absent from `bub hooks` | Confirm that both integration plugins are installed in the current environment and that the `bub-mcp` version is compatible. | -| A package is rejected | Check the `$schema` and `name` in `plugin.json`, and inspect the `bub-agent-plugins:` startup logs. | -| A skill does not appear | Check that `name` matches the directory, whether `skills_enabled` is on, and whether a higher-priority skill has the same name. | -| An MCP tool does not appear | Check `mcp.json`, `mcp_enabled`, the enabled channels, and the connection logs. | -| Skills work but MCP does not | The two components load independently; invalid servers are skipped and do not affect skills. | +| `agent-plugins` missing from `bub hooks` | Confirm both `bub-mcp` and `bub-agent-plugins` are installed in the active environment | +| Skill not discovered | Verify `name` in `plugin.json` matches the plugin folder name, and the skill's `name` matches its subfolder name | +| `mcp....` tool not found | Use `bub chat` or `bub gateway` (`bub run` does not start background MCP channels) | +| Same-named skill ignored | Workspace `.agents/skills/` takes precedence over plugin skills; rename the conflicting skill | diff --git a/website/src/content/docs/docs/integrations/local-models.mdx b/website/src/content/docs/docs/integrations/local-models.mdx index 64520510..41e58657 100644 --- a/website/src/content/docs/docs/integrations/local-models.mdx +++ b/website/src/content/docs/docs/integrations/local-models.mdx @@ -1,60 +1,51 @@ --- title: Connect a local llama.cpp model -description: Start a local llama.cpp server and drive a Bub Agent with a local GGUF model through the standard OpenAI-compatible endpoint. +description: "Run Bub with local LLMs using llama.cpp and Docker: start llama-server, connect via the OpenAI-compatible API, and tune performance." --- -In offline, private deployment, or data-privacy scenarios, you can run an open-source model locally to drive Bub. +For offline, private-deployment, or privacy-sensitive workloads, you can run an open-source model locally to drive Bub. -Bub ships with a standard OpenAI-compatible Provider. This means that as long as the local inference engine exposes a `/v1/chat/completions` endpoint (for example `llama.cpp`, `vLLM`, or `Ollama`), Bub can call local models as seamlessly as it calls cloud models. +Bub ships with a built-in OpenAI-compatible provider, so any local inference server exposing `/v1/chat/completions` (such as `llama.cpp`, `vLLM`, or `Ollama`) works just as seamlessly as a cloud model. ```mermaid flowchart LR Bub["Bub Agent"] - OpenAI["OpenAI-compatible layer"] - LocalServer["Local inference service (e.g. llama.cpp)"] - Model["GGUF model\n(CPU / GPU inference)"] + OpenAI["OpenAI-compatible client"] + LocalServer["Local inference server (e.g. llama.cpp)"] + Model["GGUF model\n(CPU / GPU)"] Bub --> OpenAI OpenAI -->|"HTTP"| LocalServer LocalServer --> Model ``` -This guide demonstrates the setup with `llama.cpp` and the excellent open-source model [`ggml-org/gemma-4-E2B-it-GGUF`](https://huggingface.co/ggml-org/gemma-4-E2B-it-GGUF) (Q8 quantized version). +This guide uses `llama.cpp` with [`ggml-org/gemma-4-E2B-it-GGUF`](https://huggingface.co/ggml-org/gemma-4-E2B-it-GGUF) (Q8 quantized). :::tip[Choosing a local model] - -Agents rely on multi-turn tool calling and long-context reasoning: - -- For lightweight testing, a model around 4B can verify basic conversational connectivity. -- If you need reliable tool calling and code generation, choose a model above 7B/8B that has been fine-tuned on instructions and tools (for example `Qwen2.5-Coder-7B-Instruct` or `Llama-3.1-8B-Instruct`). +- **Connectivity tests**: a ~4B model is enough to verify basic chat responses. +- **Multi-step tool calling and coding**: use a 7B/8B+ instruction-tuned model with strong tool-calling support (such as `Qwen2.5-Coder-7B-Instruct` or `Llama-3.1-8B-Instruct`). ::: -## Before you begin {#before-you-start} +## Before you start {#before-you-start} -- You have [installed the Bub application](/docs/getting-started/install/#app-install). -- Docker is installed and the Docker daemon is running properly. -- It is recommended to reserve at least 8 GB of available memory on the machine (the Q8 quantized model file takes about 5 GB, and you also need room for the context KV cache). -- Download the GGUF model files to the local directory `~/.cache/llama.cpp/`: +- [Install the Bub app](/docs/getting-started/install/#app-install) and Docker. +- Ensure at least 8 GB of free RAM (~5 GB for the Q8 model weights plus KV cache headroom). +- Download the GGUF files into `~/.cache/llama.cpp/`: ```text ~/.cache/llama.cpp/ggml-org_gemma-4-E2B-it-GGUF_gemma-4-E2B-it-Q8_0.gguf ~/.cache/llama.cpp/ggml-org_gemma-4-E2B-it-GGUF_mmproj-gemma-4-E2B-it-Q8_0.gguf ``` -*(Here `mmproj` is the multimodal vision projection model; if you only handle plain-text interaction, you can skip downloading this file.)* +*(`mmproj` is the multimodal vision projector; omit it and the `--mmproj` flag if you only need text chat.)* -## 1. Start llama-server {#start-server} +## 1. Start `llama-server` {#start-server} -To secure the local service endpoint, generate a random API key: +Generate a local API key and start the `llama.cpp` server container: ```bash export LLAMA_API_KEY="local-$(openssl rand -hex 8)" -echo "Generated local key: $LLAMA_API_KEY" -``` -Start the `llama.cpp` server container with Docker: - -```bash docker run --rm -it \ -p 127.0.0.1:8080:8080 \ -v "$HOME/.cache/llama.cpp:/models:ro" \ @@ -67,24 +58,18 @@ docker run --rm -it \ --mmproj /models/ggml-org_gemma-4-E2B-it-GGUF_mmproj-gemma-4-E2B-it-Q8_0.gguf ``` -**Key parameters**: -- `-p 127.0.0.1:8080:8080`: binds only to the host loopback address, so other machines on the LAN cannot reach it. -- `--alias`: defines the model alias requested in `/v1/chat/completions`. -- When the terminal prints `server is listening on http://0.0.0.0:8080`, the model has been loaded into memory successfully. +- `-p 127.0.0.1:8080:8080`: binds only to localhost. +- `--alias`: sets the model name expected by `/v1/chat/completions`. +- The server is ready when it prints `server is listening on http://0.0.0.0:8080`. -## 2. Verify the service endpoint {#verify-endpoint} +## 2. Verify the local endpoint {#verify-endpoint} In another terminal window, use `curl` to verify that the local service is ready: ```bash -# Verify the model list curl -sS http://127.0.0.1:8080/v1/models \ -H "Authorization: Bearer $LLAMA_API_KEY" -``` - -Send a minimal chat completion request: -```bash curl -sS http://127.0.0.1:8080/v1/chat/completions \ -H "Authorization: Bearer $LLAMA_API_KEY" \ -H "Content-Type: application/json" \ @@ -95,11 +80,11 @@ curl -sS http://127.0.0.1:8080/v1/chat/completions \ }' ``` -If the response is JSON containing `choices[0].message.content`, the local OpenAI-compatible service is running correctly. +A JSON response containing `choices[0].message.content` confirms the server is working. -## 3. Configure Bub {#configure-bub} +## 3. Configure and run Bub {#configure-bub} -Set Bub's environment variables so that requests for the OpenAI provider are redirected to the local endpoint: +Point Bub's OpenAI provider settings at the local server: ```bash export BUB_OPENAI_API_BASE="http://127.0.0.1:8080/v1" @@ -107,9 +92,8 @@ export BUB_OPENAI_API_KEY="$LLAMA_API_KEY" export BUB_MODEL="openai:gemma-4-E2B-it" ``` -:::note[Using another inference framework (such as Ollama)] - -If you prefer [Ollama](https://ollama.com/), simply start Ollama and point the environment variables at its compatible endpoint (no custom API key needed): +:::note[Using Ollama] +If you prefer [Ollama](https://ollama.com/), simply start Ollama and point Bub at its default port `11434` (no custom API key needed): ```bash export BUB_OPENAI_API_BASE="http://127.0.0.1:11434/v1" export BUB_OPENAI_API_KEY="ollama" @@ -117,46 +101,46 @@ export BUB_MODEL="openai:qwen2.5-coder:7b" ``` ::: -Run a Bub task once for end-to-end verification: +Run a prompt for end-to-end verification: ```bash -bub run "Introduce yourself in one sentence and mention that you are a local model." +bub run "Introduce yourself in one sentence and mention that you are running locally." ``` -Watch the terminal output. If it starts with `[cli:local]` and prints the model's reply, the whole chain is working. +Watch the terminal output: if it starts with `[cli:local]` and prints the model's reply, Bub is connected to your local model. -## 4. Tune performance {#tune} +## 4. Performance tuning {#tune} -Agent workflows have specific requirements for context window and memory. Depending on your hardware, you can tune the following parameters in the startup command: +Agent workflows place specific demands on context window and memory. Tune these flags based on your hardware: -| Tuning goal | Specific measure | Reason and effect | +| Goal | Flag / adjustment | Effect | | --- | --- | --- | -| **Expand the context window** | Add `--ctx-size 8192` or larger | The Agent's system prompt, tool definitions, and Tape history are long, so the default 2048 is easily exceeded. | -| **Reduce memory usage** | Switch to a `Q4_K_M` quantized GGUF | VRAM/memory usage halves, inference is significantly faster, and accuracy loss is minimal. | -| **GPU hardware acceleration** | Mount the GPU and add `--n-gpu-layers 33` | Offload computation layers to VRAM, improving inference speed by several times to tens of times. | -| **Text-only acceleration** | Remove the `--mmproj` parameter and the corresponding image mapping | Skip image modality initialization overhead and reduce system memory usage. | +| **Larger context window** | Add `--ctx-size 8192` (or higher) | System prompts, tool schemas, and Tape history easily exceed a 2048 default | +| **Lower memory usage** | Use a `Q4_K_M` quantized GGUF | Roughly halves RAM/VRAM usage and speeds up inference | +| **GPU offload** | Pass GPU devices and `--n-gpu-layers 33` | Offloads model layers to GPU VRAM | +| **Text-only mode** | Remove `--mmproj` | Skips vision projector memory overhead | :::caution -Do not blindly increase `--ctx-size` without limit. The memory consumed by the KV cache is proportional to context length, so make sure to leave enough physical memory to prevent the system from triggering OOM. +Do not increase `--ctx-size` without checking available RAM. KV cache memory scales with context length, so leave enough physical memory to avoid OOM crashes. ::: ## Troubleshooting {#troubleshooting} -| Symptom | Possible cause | Solution | +| Symptom | Possible cause | Fix | | --- | --- | --- | -| `curl` returns `401 Unauthorized` | The API key in the request header does not match the one used at container startup | Confirm the `LLAMA_API_KEY` value, or check `--api-key` in `docker run`. | -| The model is reported as not found or returns 404 | The model alias in the request does not match the service | Check that the name after `BUB_MODEL` exactly matches the `--alias` used when starting the container. | -| Cannot call tools or outputs garbled text | The model is too small or was not fine-tuned for Function Calling | Switch to a model above 7B/8B that is fine-tuned for tool calling (such as Qwen2.5-Coder or Llama-3.1). | -| The service crashes or exits when starting the container or during inference | Insufficient physical memory or VRAM causes OOM | Lower `--ctx-size`, or switch to a model file with a smaller quantization level (such as `Q4_K_M`). | +| `401 Unauthorized` | API key mismatch | Ensure `LLAMA_API_KEY` matches the container's `--api-key` | +| `404` or model not found | Alias mismatch | Ensure `BUB_MODEL=openai:` matches `--alias` | +| Tool calls fail or output is malformed | Model is too small or lacks tool-calling tuning | Switch to a 7B/8B+ model tuned for tool calling | +| Container crashes during startup or inference | Out of memory (OOM) | Lower `--ctx-size` or use a `Q4_K_M` quantization | ## Cleanup {#cleanup} -After testing, press `Ctrl+C` in the terminal running the Docker container to stop it, and clear the environment variable overrides in the current terminal: +When you finish testing, press `Ctrl+C` in the container terminal to stop the server and unset the environment overrides: ```bash unset BUB_API_BASE BUB_API_KEY BUB_OPENAI_API_BASE BUB_OPENAI_API_KEY BUB_MODEL LLAMA_API_KEY ``` :::note -After clearing the environment variables, Bub reverts to the default cloud model configuration. Tape session history generated during testing remains in Bub's data directory. +After clearing these environment variables, Bub reverts to your default cloud model configuration. Any Tape session history created during testing remains in Bub's data directory. ::: diff --git a/website/src/content/docs/docs/integrations/mcp.mdx b/website/src/content/docs/docs/integrations/mcp.mdx index 9c75a0b8..511c2b12 100644 --- a/website/src/content/docs/docs/integrations/mcp.mdx +++ b/website/src/content/docs/docs/integrations/mcp.mdx @@ -1,38 +1,38 @@ --- title: Connect MCP servers -description: Install the bub-mcp plugin, configure stdio or HTTP/SSE MCP servers, and call external tools from a Bub conversation. +description: Install the bub-mcp plugin, configure stdio or HTTP/SSE MCP servers, and call external tools from Bub. sidebar: badge: { text: 'App', variant: 'note' } --- import { Steps } from '@astrojs/starlight/components'; -[Model Context Protocol](https://modelcontextprotocol.io/), or **MCP**, is an open protocol that lets Agents securely and consistently call external tools and data sources, whether local or remote. +[Model Context Protocol](https://modelcontextprotocol.io/) (MCP) is an open protocol that lets Agents securely and consistently call local or remote tools and data sources. -By installing the [bub-mcp](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp) plugin, you can seamlessly bring tools from across the MCP ecosystem into the Bub application. +By installing the [`bub-mcp`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp) plugin, you can seamlessly bring tools from across the MCP ecosystem into the Bub app. ```mermaid flowchart LR User["User / client"] --> Bub["Bub Agent runtime"] Bub --> Plugin["bub-mcp plugin"] - Plugin -->|"stdio (child process)"| LocalServer["Local MCP server\n(e.g. filesystem / time)"] - Plugin -->|"HTTP / SSE (remote)"| RemoteServer["Remote MCP server\n(e.g. enterprise API / database)"] + Plugin -->|"stdio (subprocess)"| LocalServer["Local MCP server\n(e.g. filesystem / time)"] + Plugin -->|"HTTP / SSE (remote)"| RemoteServer["Remote MCP server\n(e.g. internal API / database)"] ``` -## Get started {#get-started} +## Quick start {#get-started} -Before you start, make sure you have [installed the Bub application](/docs/getting-started/install/#app-install) and that [`uvx`](https://docs.astral.sh/uv/) is installed on your system (it launches the example tool without installation). +Before starting, [install the Bub app](/docs/getting-started/install/#app-install) and ensure [`uvx`](https://docs.astral.sh/uv/) is available on your `PATH` (it launches the example server without installing it). -1. **Install the plugin and verify the environment** +1. **Install the plugin and verify** ```bash bub install bub-mcp@main bub hooks ``` - `bub install` resolves and installs `bub-mcp` from [`bub-contrib`](https://github.com/bubbuild/bub-contrib). Run `bub hooks` to check whether the plugin is mounted correctly: + `bub install` resolves and installs `bub-mcp` from [`bub-contrib`](https://github.com/bubbuild/bub-contrib). Confirm `mcp` appears in the `bub hooks` output: ```text load_state: builtin, mcp @@ -41,12 +41,12 @@ Before you start, make sure you have [installed the Bub application](/docs/getti ``` :::note - If `mcp` does not appear in the list, the plugin was installed into a different Python environment. Confirm that the path of the `bub` you are running (visible via `command -v bub`) matches the environment where it was installed. + If `mcp` is missing, run `command -v bub` to verify that `bub` runs in the same Python environment where the plugin was installed. ::: 2. **Configure an MCP server** - `bub-mcp` reads `~/.bub/mcp.json` by default (or `$BUB_HOME/mcp.json` when `BUB_HOME` is defined). This example uses the official time tool [`mcp-server-time`](https://pypi.org/project/mcp-server-time/): + `bub-mcp` reads `~/.bub/mcp.json` by default (or `$BUB_HOME/mcp.json` when `BUB_HOME` is set). Configure the official [`mcp-server-time`](https://pypi.org/project/mcp-server-time/) server: ```bash mkdir -p ~/.bub @@ -62,20 +62,17 @@ Before you start, make sure you have [installed the Bub application](/docs/getti EOF ``` - Configuration notes: + Entries with `command` use the local `stdio` transport automatically. - - For local command-line servers (stdio), provide `command` and, optionally, `args` / `env`. - - A configuration containing `command` automatically uses the stdio transport, so no explicit `transport` is needed. +3. **Check connection and discovered tools** -3. **Test the connection and tool discovery** - - Run `bub mcp list` to check whether the configuration takes effect: + Run `bub mcp list` to verify that the configuration takes effect: ```bash bub mcp list ``` - Normally, the output shows the connection is ready and lists the discovered tools: + Output when connected: ```text 🔌 MCP Tools @@ -84,29 +81,27 @@ Before you start, make sure you have [installed the Bub application](/docs/getti Tools: mcp.time_get_current_time, mcp.time_convert_time ``` - Notes: - - - Each MCP tool is named `mcp._` and injected into Bub. - - To save prompt tokens, Bub uses a **deferred loading** strategy by default (the model fetches the detailed schema via `tool.describe` when needed). If you want full schemas to go directly into the system prompt, set the environment variable `BUB_MCP_DEFERRED_TOOLS=false`. + - MCP tools are registered as `mcp._`. + - To save prompt tokens, MCP tools use **deferred loading** by default (the model calls `tool.describe` on demand); set `BUB_MCP_DEFERRED_TOOLS=false` to inject full schemas into the initial system prompt. -4. **Call a tool in a conversation** +4. **Call the tool in a chat session** - MCP tools are kept connected by the background lifecycle channel `mcp.lifecycle`. Therefore, run in long-connection mode: + MCP connections are maintained by the `mcp.lifecycle` background service, so use `bub chat` or `bub gateway`: ```bash bub chat ``` - Ask directly in the interactive interface: + Ask a question: ```text What time is it in UTC right now? ``` - The model automatically infers and calls the `mcp.time_get_current_time` tool to answer. + The model automatically calls `mcp.time_get_current_time` to answer. - :::tip[Direct testing without a model] - If you want to test tool connectivity directly, you can skip model inference and execute a tool command in `bub chat` using a leading comma: + :::tip[Test a tool directly without the model] + If you want to test tool connectivity directly without model inference, use a leading comma in `bub chat`: ```text ,mcp.time_get_current_time timezone=UTC ``` @@ -114,13 +109,13 @@ Before you start, make sure you have [installed the Bub application](/docs/getti -## Add other servers {#add-servers} +## Add more servers {#add-servers} -You can add multiple servers to the `mcpServers` dictionary in `~/.bub/mcp.json`. +You can register multiple servers under `mcpServers` in `~/.bub/mcp.json`. -### Remote servers (HTTP/SSE) {#remote-http-sse} +### Remote servers (HTTP / SSE) {#remote-http-sse} -If the tool runs as a microservice on a remote server or in a local container, configure it with `url` and `transport`: +When a tool runs as a remote service or in a container, configure it with `url`, `transport`, and optional `headers`: ```json title="~/.bub/mcp.json" { @@ -140,9 +135,9 @@ If the tool runs as a microservice on a remote server or in a local container, c } ``` -### Local servers (filesystem) {#local-filesystem} +### Local filesystem server {#local-filesystem} -For local tools with permission restrictions, you can limit their operating directory through `args`: +For local tools that need directory restrictions, pass allowed paths through `args`: ```json title="~/.bub/mcp.json" { @@ -155,16 +150,16 @@ For local tools with permission restrictions, you can limit their operating dire } ``` -### Manage with the CLI {#manage-cli} +### Manage servers from the CLI {#manage-cli} -Besides editing the JSON file directly, you can also use the `bub mcp` CLI to register or remove servers quickly: +Besides editing the JSON file directly, you can use `bub mcp` commands to add or remove servers: ```bash -# Register a local stdio tool +# Add local stdio servers bub mcp add --transport stdio time -- uvx mcp-server-time bub mcp add --transport stdio --env API_KEY=secret custom -- node ./my-server.js -# Register a remote HTTP or SSE server (with an auth header) +# Add remote HTTP or SSE servers bub mcp add --transport http weather https://weather.example.com/mcp bub mcp add --transport sse --header "Authorization: Bearer token" events https://events.example.com/mcp @@ -172,21 +167,21 @@ bub mcp add --transport sse --header "Authorization: Bearer token" events https: bub mcp remove time ``` -## Use with Agent Plugins {#with-agent-plugins} +## Use alongside Agent Plugins {#with-agent-plugins} -Bub also supports standard [Agent Plugins](/docs/integrations/agent-plugins/). MCP servers from the two sources have separate lifecycle channels and tool namespaces, so they can run seamlessly at the same time: +Global MCP servers and [Agent Plugins](/docs/integrations/agent-plugins/) use separate lifecycle channels and tool prefixes, so they can run side by side: -| Source | Configuration file | Runtime channel | Tool name prefix | +| Source | Config file | Lifecycle channel | Tool name format | |---|---|---|---| | Global MCP | `~/.bub/mcp.json` | `mcp.lifecycle` | `mcp._` | | Agent Plugin | `/mcp.json` | `agent-plugins.mcp` | `mcp.._` | ## Troubleshooting {#troubleshooting} -| Symptom | Possible cause | Solution | +| Symptom | Possible cause | Fix | | --- | --- | --- | -| `mcp` is missing from `bub hooks` | The plugin was not installed into the Python environment currently in use | Run `command -v bub`, confirm the current execution environment, then run `bub install bub-mcp@main` again. | -| `bub mcp list` shows `Status: Disconnected` | The external service is not running or the command cannot execute | Run `uvx mcp-server-time` separately in a terminal, or access the `url` with `curl`, to confirm it responds correctly. | -| MCP tools cannot be called in `bub run "..."` | `bub run` is a one-shot task and does not start the background lifecycle channel | For long-running use, use `bub chat` or `bub gateway`; for a one-off call, use `,mcp.` in the interactive session. | -| `bub mcp add` prints `CancelledError` when saving | The process exits early, but the configuration is usually already persisted | Run `bub mcp list` to confirm whether the entry was written to `mcp.json`. | -| `Permission denied` when writing the configuration | The owner permissions of the `~/.bub/` directory do not match | Check the permissions of the `~/.bub` directory, or set `BUB_HOME` to a path the current user can write to. | +| `mcp` missing from `bub hooks` | Plugin installed in another Python environment | Check `command -v bub` and re-run `bub install bub-mcp@main` in that environment | +| `bub mcp list` shows `Disconnected` | Server command failed or remote URL is unreachable | Run `uvx mcp-server-time` or `curl` the URL directly to inspect the error | +| MCP tools unavailable in `bub run "..."` | `bub run` does not start `mcp.lifecycle` | Use `bub chat` or `bub gateway` instead | +| `bub mcp add` logs `CancelledError` on exit | Subprocess cleanup log; config is usually saved | Run `bub mcp list` to verify the entry was written | +| `Permission denied` when saving config | `~/.bub/` is not writable | Fix permissions on `~/.bub` or point `BUB_HOME` to a writable directory | diff --git a/website/src/content/docs/docs/integrations/observability.mdx b/website/src/content/docs/docs/integrations/observability.mdx index 96b5ce9a..9ecae67f 100644 --- a/website/src/content/docs/docs/integrations/observability.mdx +++ b/website/src/content/docs/docs/integrations/observability.mdx @@ -1,40 +1,35 @@ --- title: Observability -description: Inspect session Tape context and export model reasoning and tool call traces to Phoenix or Logfire. +description: Inspect session Tape metrics and export OpenTelemetry traces to Arize Phoenix or Pydantic Logfire. --- -Bub's observability follows a "**dual-track**" principle: +Bub provides two complementary ways to inspect and debug Agent runs: -- **State introspection (Tape)**: Inspect **what the Agent remembers**, how the context window is being consumed, and the prompt cache hit rate (built in, no external components required). -- **Run telemetry (Traces)**: Track **how each turn actually executes**, the latency bottlenecks of models and tools, and error call stacks (exported to an external APM through OpenTelemetry). +- **Inspect the session Tape** (built-in): check entry counts, token usage, and prompt cache hit rates, and search historical events with zero external setup. +- **Export OpenTelemetry traces**: track per-step latency and error stacks across model calls and tool executions in platforms such as Arize Phoenix or Pydantic Logfire. ```mermaid flowchart LR Turn["Bub Agent"] - Tape["Tape\n(native context persistence)"] - OTEL["OpenTelemetry SDK\n(OTLP protocol export)"] - Platform["Observability platform\n(Arize Phoenix / Logfire / production APM)"] + Tape["Tape\n(built-in session history)"] + OTEL["OpenTelemetry SDK\n(OTLP export)"] + Platform["Observability platform\n(Phoenix / Logfire / APM)"] - Turn -->|"record session history"| Tape - Turn -->|"report call traces"| OTEL + Turn -->|"record messages & tools"| Tape + Turn -->|"export traces"| OTEL OTEL --> Platform ``` -## Before you start {#before-you-start} +## Inspect the session Tape {#inspect-tape} -- You have [installed the Bub application](/docs/getting-started/install/#app-install) and configured a working model. -- If you are testing Phoenix locally, Docker or Podman must be installed. - -## Inspect the Tape {#inspect-tape} - -The Tape is Bub's built-in session recording mechanism. With no configuration at all, you can use the built-in commands to check the health of the current session: +Tape is Bub's built-in session recording mechanism. With no configuration at all, you can use built-in commands to check the health of the current session: ```bash bub run "What tools do you have, and what is each one good for?" bub run ",tape.info" ``` -Expected terminal output looks similar to: +Example output: ```text name: becda04eb9f7369c__065943a03cbe6395 @@ -46,111 +41,100 @@ last_token_usage: 7458 last_token_cache_hit_rate: 72.50% ``` -![A terminal screenshot showing tape.info output after a Bub task run](/docs/observability/tape-info.png) +![Terminal screenshot of tape.info output](/docs/observability/tape-info.png) -### Interpreting core metrics {#core-metrics} +### Metrics explained {#core-metrics} -| Field | Meaning and troubleshooting value | +| Field | Meaning | |---|---| -| `entries` | Total number of events recorded in the session (including input, output, and tool calls). | -| `anchors` / `last_anchor` | Number of history anchors and the latest context boundary. This determines the starting context for model calls. | -| `entries_since_last_anchor` | Number of new entries since the last anchor; when this is too high, consider a handoff to move the context start forward. | -| `last_token_usage` | Total token consumption of the most recent model call. | -| `last_token_cache_hit_rate` | Prompt cache hit rate. A high hit rate means faster responses and lower cost. | +| `entries` | Total entries recorded in the session (messages, tool calls/results, and events) | +| `anchors` / `last_anchor` | Total anchors and the latest anchor name (the default context start point) | +| `entries_since_last_anchor` | New entries since the latest anchor; run `tape.handoff` when this grows large | +| `last_token_usage` | Total tokens used by the most recent model call | +| `last_token_cache_hit_rate` | Prompt cache hit rate on the most recent model call | -### Quickly search historical events {#search-events} +### Search historical events {#search-events} -When you need to check whether a tool call succeeded or find a specific step, there is no need to page through the full log manually; use `,tape.search`: +When you need to check whether a tool call succeeded or locate a specific step, skip paging through raw logs and search the Tape directly with `,tape.search`: ```bash -# Search for events containing loop steps or tool calls bub run ",tape.search query=loop.step" ``` -## Export traces {#export-traces} - -When you need to analyze model latency, tool execution time, and error reports, you can export traces to a dedicated analysis dashboard through OpenTelemetry (OTLP). +## Export OpenTelemetry traces {#export-traces} -### Arize Phoenix (local deployment) {#arize-phoenix} +When you need to analyze model latency, tool execution time, and error stacks, export traces to an observability platform over OpenTelemetry (OTLP). -[Arize Phoenix](https://github.com/Arize-ai/phoenix) is an excellent open-source AI telemetry tool that starts with a single Docker command: +### Arize Phoenix (local Docker) {#arize-phoenix} -```bash -docker run --rm --name bub-phoenix \ - -p 6006:6006 \ - arizephoenix/phoenix:latest -``` +1. Start a local [Arize Phoenix](https://github.com/Arize-ai/phoenix) container (UI at `http://localhost:6006`): -Once it is running, open the console in your browser at `http://localhost:6006`. + ```bash + docker run --rm --name bub-phoenix -p 6006:6006 arizephoenix/phoenix:latest + ``` -Install the tracing dependencies in the environment where Bub runs: +2. Install the `trace` extra in Bub's environment: -```bash -# Source installation -uv sync --extra app --extra trace + ```bash + # Project or virtual environment + uv add "bub[app,trace]" -# Or distribution installation -uv add "bub[app,trace]" -``` + # Or in a Bub source checkout + uv sync --extra app --extra trace + ``` -Configure the standard OpenTelemetry environment variables and run a task: +3. Set OTLP environment variables and run a task: -```bash -export OTEL_SERVICE_NAME=bub -export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:6006/v1/traces -export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf + ```bash + export OTEL_SERVICE_NAME=bub + export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:6006/v1/traces + export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf -bub run "Use a tool to list the files in the current workspace." -``` + bub run "Use a tool to list the files in the current workspace." + ``` -After the run completes, refresh the Phoenix console, open the Default project, and you will see the complete call waterfall, clearly showing the detailed timing of each model call (`chat `) and tool execution (`execute_tool `): +Open `http://localhost:6006` and select the Default project to inspect the trace waterfall for model calls (`chat `) and tool executions (`execute_tool `): -![A screenshot showing Bub GenAI telemetry exported to Phoenix through OTLP](/docs/observability/phoenix-otel.png) +![Phoenix OTLP trace screenshot](/docs/observability/phoenix-otel.png) ### Pydantic Logfire {#pydantic-logfire} -If you do not want to maintain a Docker container locally, you can use [Pydantic Logfire](https://logfire.pydantic.dev/): +If you prefer not to run a local Docker container, export traces to hosted [Pydantic Logfire](https://logfire.pydantic.dev/): ```bash -# Clear explicit OTLP endpoints (so Logfire takes over automatically) +# Unset custom OTLP endpoints so Logfire takes over unset OTEL_EXPORTER_OTLP_TRACES_ENDPOINT OTEL_EXPORTER_OTLP_ENDPOINT -# Install the logfire dependency uv add "bub[logfire]" - -# Log in and bind a project logfire auth logfire projects use -# Run a task bub run "Inspect this repository and summarize its directory structure." ``` -Log in to the Logfire web console, and on the Agents page you can view Bub's run call stack and sub-Agent chains in real time. +Open the Logfire web console and visit the Agents page to inspect Bub's live call stack and subagent traces. -### Python code configuration {#python-config} +### Enable in Python SDK code {#python-config} -If you are reusing Bub through the Python SDK, you can also start telemetry explicitly when initializing the program: +If you embed Bub through the Python SDK, call `configure_otlp()` at service startup (reads `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and standard OpenTelemetry environment variables): ```python from bub.tracing import configure_otlp -# Automatically reads standard environment variables such as OTEL_EXPORTER_OTLP_TRACES_ENDPOINT configure_otlp() ``` ## Troubleshooting {#troubleshooting} -| Common issue | Possible cause | Solution | +| Symptom | Possible cause | Fix | | --- | --- | --- | -| No traces appear in the Phoenix UI | The OTLP protocol or endpoint is misconfigured | Confirm that `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` includes `/v1/traces` and that the protocol is `http/protobuf`. | -| The terminal reports that the `opentelemetry` dependency is missing | The `trace` optional dependency is missing | Run `uv sync --extra app --extra trace` or `pip install "bub[app,trace]"`. | -| Logfire cannot report data | You are not logged in, or the OTLP variables were not cleared | Explicitly `unset OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and run `logfire auth` to reauthorize. | -| `,tape.info` reports no active Tape | No task has run in the current workspace or session | Run any `bub run "..."` command first to generate a session record. | +| No traces appear in Phoenix | Endpoint path or protocol mismatch | Ensure `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` ends with `/v1/traces` and protocol is `http/protobuf` | +| Missing `opentelemetry` module | `trace` extra is not installed | Run `uv add "bub[app,trace]"` or `pip install "bub[app,trace]"` | +| Logfire receives no data | Conflicting OTLP env vars or unauthenticated | `unset OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and re-run `logfire auth` | ## Cleanup {#cleanup} -Stop and remove the local Phoenix container used for testing: +When finished testing, stop the local Phoenix container and clear the environment variables: ```bash docker rm -f bub-phoenix diff --git a/website/src/content/docs/docs/integrations/reuse-app.mdx b/website/src/content/docs/docs/integrations/reuse-app.mdx index 5ab1e626..7b617c02 100644 --- a/website/src/content/docs/docs/integrations/reuse-app.mdx +++ b/website/src/content/docs/docs/integrations/reuse-app.mdx @@ -1,47 +1,49 @@ --- title: Reuse Bub in a service -description: Choose a reuse layer by ownership, from tools and Agent hooks to BubAgent streams and complete Turns. +description: "Reuse Bub app-layer capabilities in your Python service: from individual plugin tools and Agent loop hooks to BubAgent streams and complete Turns." sidebar: - badge: { text: 'SDK', variant: 'note' } + badge: { text: 'SDK', variant: 'tip' } --- -When embedding Bub in an existing service, the key question is not “which entry point has the most features?” It is **which assembly and lifecycle responsibilities remain with the host**. You can reuse one tool or let Bub process a complete message Turn. +When embedding Bub in an existing Python service, you can use the minimal [`bub.core.Agent`](/docs/sdk/) kernel or reuse capabilities from the Bub app layer — including configuration loading, skill discovery, plugin hooks, built-in tools, and the full Turn message pipeline. -The app-layer entry points on this page require the [`app` optional dependencies](/docs/getting-started/install/#app-install) and configured model credentials (for example, `REPUBLIC_OPENAI_API_KEY`): +The key question is not which entry point has the most features, but **which assembly and lifecycle responsibilities remain with your host service**. + +App-layer entry points require the [`app` optional dependencies](/docs/getting-started/install/#app-install) and configured model credentials (such as `REPUBLIC_OPENAI_API_KEY`): ```bash uv add "bub[app]" ``` -If you only need the model loop, tools, and Tape, start with the [core SDK](/docs/sdk/). +If you only need the core model–tool–Tape loop without app configuration, skills, or plugins, start with the [core SDK](/docs/sdk/). ## Choose a reuse layer {#choose-a-reuse-layer} -| Capability to reuse | Entry point | What the host still owns | -| --- | --- | --- | -| One tool implementation | Import a public tool and pass it to `core.Agent` | Model, Tape, Run, and resource lifetime | -| Plugin hooks for the Agent loop | `AgentPlugins.attach()` | Driving Runs, inbound/outbound messages, and same-session concurrency | -| App configuration, skills, tool policies, and commands | `BubAgent.run_stream()` | Consuming and closing streams, reply delivery, complete Turn state, and same-session concurrency | -| Complete Turn from inbound message to outbound result | `BubFramework.process_inbound()` | Service lifetime, model configuration, exceptions, concurrency, and delivery not delegated to a channel | -| Supplied CLI or gateway | `bub run` / `bub chat` / `bub gateway`, or a custom entry point | Configuration, credentials, deployment, and extensions, but no application-loop code | +Bub offers five reuse entry points depending on which responsibilities remain with your host service. These are parallel entry points rather than a mandatory upgrade path—start at the smallest layer that meets your needs: -These are alternative entry points, not a mandatory upgrade path. Start at the smallest layer that meets your needs. +| Capability to reuse | Entry point | What the host service still owns | +| --- | --- | --- | +| **CLI or persistent gateway** | `bub run` / `bub chat` / `bub gateway`, or a custom CLI wrapper | Config, credentials, and deployment; no Python loop code needed | +| **Complete message Turn** (inbound message to outbound replies) | `BubFramework.process_inbound()` | Service lifetime, top-level error handling, per-session locking, and custom reply delivery | +| **App config, skills, tool allowlists, and commands** (host consumes the stream) | `BubAgent.run_stream()` | Consuming and closing the stream, delivering replies, cross-Turn state persistence, and per-session locking | +| **Plugin hooks for the `core.Agent` loop** | `AgentPlugins.attach()` | Driving `agent.run()`, inbound/outbound messages, and per-session locking | +| **Single tool function** | Import the tool and pass it to `core.Agent(tools=[...])` | Model connection, Tape store, Run loop, and all resource lifetimes | :::note -Installing a plugin package does not mean every entry point executes all its capabilities. Lower layers can reuse tools and Agent hooks; channels, CLI, and the complete message pipeline run only in their corresponding runtimes. A plugin may also depend on other hooks, state fields, or background services, so follow its documentation. +Installing a plugin package only activates the extension points supported by the entry point you call. Lower layers (`AgentPlugins`, `BubAgent`) reuse tools and Agent loop hooks, whereas message channels, CLI commands, and outer Turn hooks run only in `BubFramework` or `bub gateway`. ::: -## Recommended starting point: run a complete Turn {#run-a-complete-turn} +## Run a complete Turn: `BubFramework.process_inbound()` {#run-a-complete-turn} -Use `process_inbound()` when Bub should own session resolution, the initial prompt, model stage, state saving, and outbound-message assembly. +If you want Bub to handle the entire flow—session resolution, prompt construction, model and tool execution, state saving, and outbound message assembly—start with `BubFramework.process_inbound()`. Create `embedded.py`: -```python title="embedded.py" +```python title="embedded.py" {12-17} import asyncio from bub import BubFramework @@ -75,21 +77,22 @@ Run it: uv run python embedded.py ``` -Call `load_hooks()` once at startup to load builtin implementations and installed plugins. `framework.running()` owns resources such as plugin lifetimes, Tape storage, and the `SteeringInbox`; keep it open for the embedded service lifetime rather than entering it once per request. +Key usage rules: -`process_inbound()` returns a complete `TurnResult`, not an event iterator. This example binds no sending channel, so the host reads and delivers `result.outbounds`. If an installed `dispatch_outbound` plugin also sends messages, prevent duplicate delivery between the plugin and host. - -`stream_output=True` selects and consumes the streaming model path, then still returns a `TurnResult`. A bound Router can wrap the event stream with `wrap_stream()`, but **`stream_output=True` does not require a Router**. +- **Call `load_hooks()` once at startup**: loads built-in implementations and installed entry-point plugins. +- **Keep `framework.running()` open for the service lifetime**: this async context manager holds plugin lifespans, the Tape store, and the `SteeringInbox`. Enter it at service startup/shutdown (e.g., FastAPI `lifespan`), not per request. +- **Read replies from `result.outbounds`**: `process_inbound()` returns an aggregated `TurnResult`. If an installed `dispatch_outbound` plugin also sends messages, avoid sending duplicates from your host code. +- **Enable the streaming model path**: passing `stream_output=True` runs `run_model_stream` internally and still returns a `TurnResult` (a bound `ChannelRouter` can also observe incremental events via `wrap_stream()`; **`stream_output=True` works with or without a Router**). -## Reuse only the model stage: BubAgent.run_stream {#model-stage} +## Reuse only the model stage: `BubAgent.run_stream()` {#model-stage} -Use `BubAgent.run_stream()` when you want Bub's configuration, skills, tool policies, and commands but prefer to handle the event stream yourself. +Use `BubAgent.run_stream()` when you want Bub's app configuration, skill discovery, tool filtering, and comma commands, but want to iterate the event stream yourself (for example, to stream SSE frames to a frontend). -`run_stream()` returns `AsyncStreamEvents`. It does not implement the async context-manager protocol, so use `contextlib.aclosing()` to close it on early exit and exceptions: +`run_stream()` returns an `AsyncStreamEvents` async iterator (not a context manager). **Always wrap it with `contextlib.aclosing()`** so the stream closes cleanly on early exit or exceptions: -```python +```python collapse={1-7} {14-19,21} import asyncio import contextlib @@ -121,23 +124,25 @@ if __name__ == "__main__": asyncio.run(main()) ``` -Construct `BubAgent` inside `framework.running()` so it can use storage provided by that scope. Reuse one Agent across sessions; per-Turn tool, skill, and state choices belong in call arguments or TurnState. +Instantiate `BubAgent` inside `async with framework.running():` so it picks up the active Tape store, and reuse the same `BubAgent` instance across sessions. -Compared with a complete Turn, this direct entry point: +Compared with `process_inbound()`, `BubAgent.run_stream()`: -- still resolves the session Tape, binds the runtime Agent, and loads state through hooks when `state=None`; -- can still execute direct commands; -- skips initial inbound `build_prompt`, `save_state`, outbound rendering, and dispatch; -- does not coordinate same-session concurrency; -- does not close the stream for you, and the first `final` ends only one Step. +- **Still runs**: resolves `session_id` to a session Tape, binds the runtime Agent, runs `load_state` hooks when `state=None`, and executes comma commands; +- **Skips**: initial `build_prompt`, `save_state`, `render_outbound`, `dispatch_outbound`, and per-session concurrency locking; +- **Stream rules**: close the stream with `aclosing()`; a `final` event ends only one Step, while the full run finishes when the `async for` loop ends. -Builtin system instructions do not ask the model to reply through channel skills. The channel manager behind `bub gateway` and `bub chat` registers a `system_prompt` hook that adds that instruction only to the Turns it runs. A service calling `process_inbound()` itself can register its own hook to describe how replies are delivered. Replacing `agent.system_prompt` wholesale also removes prompt sections for plugins, skills, deferred tools, and code mode. +:::tip[System prompt note] +Default system instructions do not ask the model to reply via channel skills (such as `telegram`); that instruction is added only by `ChannelManager` in `bub gateway` and `bub chat`. When calling `run_stream()` or `process_inbound()` in your own service, the model replies with normal text. Do not overwrite `agent.system_prompt` directly, as that removes prompt sections for plugins, skills, deferred tools, and code mode. +::: -### Narrow tools and skills per call {#narrow-tools-and-skills} +### Limit tools and skills per request {#narrow-tools-and-skills} + +Pass `allowed_tools` and `allowed_skills` to `BubAgent.run_stream()` to restrict which tools and skills the model can use on a given call: -```python +```python collapse={1-12} ins={27-28} import asyncio import contextlib @@ -177,24 +182,26 @@ if __name__ == "__main__": asyncio.run(main()) ``` -| Parameter | `None` | Empty collection | +| Parameter | `None` (default) | Empty collection (`[]` or `set()`) | | --- | --- | --- | -| `allowed_tools` | Every tool on the instance | No tools | -| `allowed_skills` | Default skill discovery | Skill discovery disabled | +| `allowed_tools` | All tools on the Agent instance | Disable all tools for this call | +| `allowed_skills` | All discovered skills | Disable all skills for this call | -Unknown names raise `ValueError`. Filtering covers direct model calls and code mode, but comma commands use the Agent instance's tools and are not limited by `allowed_tools`; enforce permissions in `before_tool_call` when every execution path must be constrained. +Passing an unknown tool name raises `ValueError`. Keep three rules in mind: -These restrictions are reliable only when host code chooses the arguments. Letting the model generate a subagent's allowlist is not a security boundary. - -Passing `state` explicitly skips `load_state` hooks. When you need normal session recovery plus request metadata, build the state with `framework.build_state()` instead of replacing it with a new dictionary. See the [Python API](/docs/reference/python-api/#framework) for the complete `_runtime_agent` and state form. +1. `allowed_tools` restricts model tool calls and code mode, but **does not restrict direct comma commands** (such as `,fs.read`). Enforce permissions in `before_tool_call` if every execution path must be gated. +2. Allowlists are reliable only when set by **host code**; letting the model generate a subagent's `allowed_tools` in chat is not a security boundary. +3. Passing `state` explicitly to `run_stream(state=...)` skips `load_state` hooks. To combine normal state loading with custom request fields, call `await framework.build_state(message, session_id)` first and add your keys to the returned dict (see [Python API](/docs/reference/python-api/#framework)). -## Reuse only tools or Agent hooks {#reuse-tools-or-hooks} +## Reuse only tools or Agent loop hooks {#reuse-tools-or-hooks} + +### 1. Reuse plugin tools directly in `core.Agent` {#tool-implementations} -### Tool implementations {#tool-implementations} +If your service uses the core `bub.core.Agent` but you want a tool from a Bub plugin, you can import that tool directly and pass it to `Agent(tools=[...])` without starting `BubFramework`. -An existing `core.Agent` can import builtin tools or public constructors supplied by plugins. The example below reuses only the search tool from `bub-web-search`. Install the dependencies and configure search and model credentials first: +The example below reuses only `web.search` from `bub-web-search`. Install the dependencies and set your credentials first: ```bash uv add "bub[app]" \ @@ -205,9 +212,9 @@ export BUB_SEARCH_JINA_API_KEY=jina_... export REPUBLIC_OPENAI_API_KEY=sk-... ``` -Save the following script as `search_agent.py`: +Save as `search_agent.py`: -```python title="search_agent.py" +```python title="search_agent.py" collapse={1-10} {13,19} import asyncio from pathlib import Path @@ -248,17 +255,17 @@ if __name__ == "__main__": asyncio.run(main()) ``` -Run `uv run python search_agent.py` to record the session in `sessions/`. This reuses only the selected search tool; the host still owns the model, Tape, event stream, and resource lifetime. See [`bub-web-search`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-web-search) for more details. +Run `uv run python search_agent.py` to record the session in `sessions/`. Here only the tool function is reused; the host still owns the model, Tape store, and event stream. See [`bub-web-search`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-web-search) for more details. -### Agent-loop hooks {#agent-loop-hooks} +### 2. Attach plugin hooks to `core.Agent` with `AgentPlugins` {#agent-loop-hooks} -`AgentPlugins` connects plugin hooks to a core Agent's events, prompts, tools, and run state: +If you want to reuse not only tools but also loop-related plugin hooks (`system_prompt`, `provide_tools`, `before_llm_call`, `before_tool_call`, etc.) on a `core.Agent`, use `AgentPlugins` (see [Hooks reference: Event mapping](/docs/reference/hooks/#event-mapping)). -The following is a complete minimal plugin example. Save it as `agent_hooks.py`; install `bub[app]` and configure `REPUBLIC_OPENAI_API_KEY` first: +Save the minimal example below as `agent_hooks.py`: -```python title="agent_hooks.py" wrap +```python title="agent_hooks.py" wrap collapse={1-10} {21-25} import asyncio import republic @@ -297,48 +304,43 @@ if __name__ == "__main__": asyncio.run(main()) ``` -`PlainTextPlugin` is a minimal custom plugin: its `system_prompt` hook adds an instruction to the Agent. `AgentPlugins(plugins=[...])` registers only the plugins listed; it does not load Bub's builtin hooks or installed plugins. To load those, create a `BubFramework`, call `load_hooks()`, and pass it to `AgentPlugins`. The mechanisms behind these hooks are described in [Agent events](/docs/concepts/events/#app-hooks). - Run it with `uv run python agent_hooks.py`. -`components()` returns an ordinary kwargs dictionary and does not resolve duplicate arguments. The example explicitly overrides `store` with a dictionary merge; passing the same keyword twice raises an error. - -Resources such as storage and the `SteeringInbox` are available only inside `plugins.running()`. Call `attach()` before registering your own event handlers so those handlers observe hook modifications. - -`attach()` connects the Agent loop; it does not automatically provide the complete Turn's initial `build_prompt`, `run_model` / `run_model_stream`, `save_state`, outbound rendering, or dispatch. Specific paths such as steering can still call `build_prompt`, and builtin error reporting can call `dispatch_outbound`, so plugin hosts should check when each hook executes. - -For example, `bub-context-budget` uses model-call hooks to ask the model to call `tape.handoff` as the context approaches its limit. In addition to `attach()`, provide the `tape.handoff` tool to the Agent; the reminder itself does not enforce compaction. This illustrates why a plugin may need more than `attach()`; see the [`tape.handoff` reference](/docs/reference/tools/#tape-handoff). +Key rules for `AgentPlugins`: -Plugins such as MCP that hold persistent connections have an independent lifecycle; `attach()` does not replace connecting, starting, and stopping them. See [`bub-mcp`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp#embedding) for embedding. +- **Explicit plugin list vs. auto-discovery**: `AgentPlugins(plugins=[...])` registers only the listed plugin instances. To load all installed entry-point plugins and built-in hooks, create `framework = BubFramework()`, call `framework.load_hooks()`, and pass `AgentPlugins(framework)`. +- **Merge `components()`**: `plugins.components()` returns a dict with `store`, `context`, and `sidecars`. Merge overrides with `{**plugins.components(), "store": ...}` before passing to `Agent()`. +- **Run inside `plugins.running()`**: call `plugins.attach(agent)` before registering your own `agent.events.on(...)` handlers so your handlers see hook modifications. +- **Covers loop hooks only**: `attach()` does not run outer Turn stages (`build_prompt`, `save_state`, `render_outbound`, `dispatch_outbound`). If a plugin requires companion tools (e.g., `bub-context-budget` requires the `tape.handoff` tool) or persistent connections (e.g., [`bub-mcp`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp#embedding)), wire those components explicitly. - +## Bind a `ChannelRouter` for channel delivery {#bind-a-router} -## Bind a Router for channel delivery {#bind-a-router} +If your host service already handles reply delivery (for example, returning an HTTP response), reading `TurnResult.outbounds` is all you need—no Router required. -If the host already has sending logic, use `TurnResult.outbounds` directly. Implement and bind a `ChannelRouter` when Bub channels should own outbound delivery and stream wrapping: +Implement `ChannelRouter` and call `framework.bind_channel_router(router)` only when Bub channels should own outbound delivery and stream wrapping: -- `dispatch_output()` performs delivery. Returning `False` does not trigger an automatic retry or fallback; `process_inbound()` still returns the rendered `outbounds`. -- `wrap_stream()` must return an async iterable and preserve the model events Bub should continue processing; `model_output` is aggregated from text deltas yielded by the wrapped stream. -- `admit_channel_message()` belongs to the `ChannelManager` admission path. Calling `process_inbound()` directly does not automatically perform admission or session queueing. +- `dispatch_output()`: delivers outbound messages; returning `False` does not trigger an automatic retry, and `process_inbound()` still returns `outbounds`. +- `wrap_stream()`: wraps the event stream and yields the model events Bub aggregates into `model_output`. +- `admit_channel_message()`: used by `ChannelManager` admission; calling `process_inbound()` directly does not run admission or queueing automatically. See the [Python API](/docs/reference/python-api/#framework) and [Turn concepts](/docs/concepts/turn/) for contracts. -## Lifecycle, failure, and concurrency checklist {#lifecycle-failure-concurrency} +## Production checklist {#lifecycle-failure-concurrency} -Whichever app-layer entry point you choose, verify these boundaries: +Whichever app-layer entry point you choose, verify these seven boundaries before deploying to production: -1. **Initialize once**: call `load_hooks()` during service assembly, not on every request. -2. **Use one running scope**: do not overlap `running()` on one Framework. `ChannelManager.listen_and_run()` already enters it, so do not nest another scope. -3. **Configuration is not an isolation boundary**: separate Frameworks can separate plugin sets, but application configuration remains process-wide and cached. -4. **The host catches exceptions**: both `run_stream()` iteration and `process_inbound()` can raise; complete-Turn error hooks do not replace host exception handling. -5. **Coordinate each session explicitly**: neither direct entry point serializes by `session_id`. Use host locks or ChannelManager admission with `follow_up`. -6. **Close streams**: consume them fully on the normal path and use `aclosing()` on early exit. `temp/` sessions do not merge Tape; ordinary sessions merge on close by default, including partial records. -7. **Side effects are not transactional**: later model failure, cancellation, or discarded Tape records do not undo external tool side effects. +1. **Call `load_hooks()` once at startup**: do not re-register plugins on every request. +2. **Use a single `running()` scope**: do not overlap `running()` scopes on the same `BubFramework` (`ChannelManager.listen_and_run()` enters `running()` internally). +3. **Settings are cached process-wide**: multiple `BubFramework` instances isolate plugin sets, but `Settings` instances are cached per process. +4. **Catch exceptions in the host**: `run_stream()` and `process_inbound()` raise exceptions on failure; `on_error` hooks only log errors and do not suppress exceptions. +5. **Serialize same-session concurrency**: lock per `session_id` in your host (e.g., `asyncio.Lock`), or use `ChannelManager` with `follow_up` admission. +6. **Close event streams**: wrap streams with `contextlib.aclosing()`. Except for `temp/` sessions, ordinary sessions merge written fork records back into the main Tape on stream close. +7. **External side effects do not roll back**: model errors, cancellation, or discarding a Tape fork do not undo file edits, HTTP calls, or database writes already performed by tools. -## Run or publish the CLI {#run-or-publish-cli} +## Run or package the CLI {#run-or-publish-cli} -If you do not need embedded code, use `bub run`, `bub chat`, or `bub gateway` directly. To own the command name, declare `[project.scripts]` that calls the Bub entry point and ship plugins and skills in the same distribution. See [Packaging and distribution](/docs/app/distribution/). +If you do not need to embed Bub inside another Python service, run `bub run`, `bub chat`, or `bub gateway` directly. To package it under your own command name (such as `my-bub`) bundled with custom plugins and skills for your team, see [Packaging and distribution](/docs/app/distribution/). diff --git a/website/src/content/docs/docs/integrations/storage.mdx b/website/src/content/docs/docs/integrations/storage.mdx index bda53a7c..4c1a733c 100644 --- a/website/src/content/docs/docs/integrations/storage.mdx +++ b/website/src/content/docs/docs/integrations/storage.mdx @@ -1,25 +1,16 @@ --- title: Store conversation history in a database -description: Use the SQLAlchemy tape store plugin to save Bub's Tape conversation history to SQLite or another relational database. +description: Use the bub-tapestore-sqlalchemy plugin to store Bub session Tapes in SQLite, PostgreSQL, or MySQL. --- -By default, Bub persists conversation Tapes as local JSONL files. +By default, the Bub app persists conversation Tapes as local JSONL files under `~/.bub/tapes/`. -By installing the [`bub-tapestore-sqlalchemy`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-tapestore-sqlalchemy) plugin, you can switch the application to SQLite, PostgreSQL, or any relational database supported by SQLAlchemy, while keeping `,tape.info`, `,tape.search`, session branching, and Sidecar behavior exactly the same. +By installing [`bub-tapestore-sqlalchemy`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-tapestore-sqlalchemy), you can switch seamlessly to SQLite, PostgreSQL, or any SQLAlchemy-supported relational database while keeping `,tape.info`, `,tape.search`, forks, and sidecars unchanged. -:::caution[Existing data] -Changing the storage backend **does not** migrate existing JSONL files automatically. After switching to the new database, old sessions will not appear in the new database's `tape.search`, and the original files remain under `tapes/` in the Bub directory. +:::caution[Existing files are not migrated] +Switching storage backends **does not** import existing local JSONL files automatically (existing files remain in `~/.bub/tapes/`). ::: -## Before you start {#before-you-start} - -- You have [installed the Bub application](/docs/getting-started/install/#app-install) and configured a working model. -- (Optional) Install the `sqlite3` command line tool for querying and inspecting tables directly. -- Confirm the current Bub home path: - ```bash - printf '%s\n' "${BUB_HOME:-$HOME/.bub}" - ``` - ## 1. Install the plugin {#install} Install the store plugin in the environment where Bub runs: @@ -29,44 +20,41 @@ bub install bub-tapestore-sqlalchemy@main bub hooks ``` -Run `bub hooks` to check that the extension point is mounted: +Verify `tapestore-sqlalchemy` appears before `builtin` under `provide_tape_store`: ```text provide_tape_store: tapestore-sqlalchemy, builtin ``` -Higher-priority implementations are listed first. Seeing `tapestore-sqlalchemy` means the plugin is active and will override the built-in file store. +Higher-priority implementations appear first, so seeing `tapestore-sqlalchemy` confirms the plugin is active and overrides the built-in file store. -## 2. Configure the database {#configure} +## 2. Configure the database URL {#configure} -The plugin uses `/tapes.db` by default. To make demonstration and verification easier, this guide points it at the current working directory: +The plugin defaults to `/tapes.db`. Set `BUB_TAPESTORE_SQLALCHEMY_URL` to any SQLAlchemy connection URL (using a local SQLite file here as an example): ```bash export BUB_TAPESTORE_SQLALCHEMY_URL="sqlite+pysqlite:///$PWD/bub-tapes.db" ``` -- `sqlite+pysqlite` uses the SQLite driver built into the Python standard library, with no extra dependencies. -- The URL must follow standard SQLAlchemy connection string conventions; here `$PWD` is used to build an absolute path. - -### Optional settings {#optional-settings} +Optional settings: | Environment variable | Default | Description | | --- | --- | --- | -| `BUB_TAPESTORE_SQLALCHEMY_ECHO` | `false` | Set to `true` to print executed SQL statements for development and debugging. | -| `BUB_TAPESTORE_SQLALCHEMY_CONNECT_ARGS` | `{}` | JSON object passed to `create_engine(connect_args=...)` (for example, timeout settings). | +| `BUB_TAPESTORE_SQLALCHEMY_ECHO` | `false` | Set `true` to log executed SQL statements | +| `BUB_TAPESTORE_SQLALCHEMY_CONNECT_ARGS` | `{}` | JSON object passed to `create_engine(connect_args=...)` (e.g. timeouts) | -To make the settings persist, add the variables to a `.env` file at the workspace root. The plugin initializes the required table schema automatically on first connection. +To persist these settings across sessions, add them to your workspace `.env` file. Tables are created automatically on first connection. ## 3. Verify writes and reads {#verify} -Run one session, then use the built-in command to check whether the Tape was written to the database: +Run a turn and inspect the Tape: ```bash -bub run "Say hello in one sentence and indicate that this turn of the conversation is stored in the database." +bub run "Say hello in one sentence to verify database storage." bub run ",tape.info" ``` -The output should include the Tape name, entry count, and anchor status for this session: +Example output: ```text name: 86774b31b96845a4__0b871d5e50e7c192 @@ -76,76 +64,63 @@ last_anchor: session/start entries_since_last_anchor: 8 ``` -Use `sqlite3` to inspect the physical records in the database: - -```bash -# Query the Tape session list -sqlite3 "$PWD/bub-tapes.db" \ - "SELECT name, last_entry_id FROM tapes ORDER BY name;" -``` +Inspect the SQLite tables directly with `sqlite3`: ```bash -# Query anchor records -sqlite3 "$PWD/bub-tapes.db" \ - "SELECT entry_id, anchor_name, entry_date FROM tape_entries WHERE kind = 'anchor';" +sqlite3 "$PWD/bub-tapes.db" "SELECT name, last_entry_id FROM tapes ORDER BY name;" +sqlite3 "$PWD/bub-tapes.db" "SELECT entry_id, anchor_name, entry_date FROM tape_entries WHERE kind = 'anchor';" ``` -The `tapes` table maintains metadata for all sessions; the `tape_entries` table records the specific content of each Turn, model answer, and tool call entry by entry. +The `tapes` table tracks session metadata, while `tape_entries` records each Turn, model reply, and tool call entry by entry. -## 4. Connect another database {#other-databases} +## 4. Connect PostgreSQL or MySQL {#other-databases} -The plugin is built on SQLAlchemy and supports connecting to relational databases such as PostgreSQL and MySQL: - -1. **Install the driver** (install the corresponding database driver in the environment where `bub` runs): +1. **Install the database driver in Bub's environment** (PostgreSQL example): ```bash - # For example, PostgreSQL uv add "psycopg[binary]" ``` -2. **Configure the connection string**: +2. **Set the connection URL**: ```bash export BUB_TAPESTORE_SQLALCHEMY_URL="postgresql+psycopg://user:YOUR_DB_PASSWORD@localhost:5432/bub_db" ``` -In production, test concurrent writes and connection pool timeout settings in advance to keep the service stable. +In production, test concurrent writes and connection-pool timeouts ahead of time to keep the service stable. -## Implement your own store backend {#custom-store} +## Implement a custom store backend {#custom-store} -`core.Agent` and the built-in app depend only on the store protocol, so implementing it swaps the backend entirely. For the difference between "the Tape keeps history" and "TapeContext projects context", see [Tape and model context](/docs/concepts/tape/#history-and-context). +`core.Agent` and the built-in app depend only on the store protocol, so you can back Tapes with Redis or another service by implementing it (for the difference between Tape history and context projection, see [Tape and model context](/docs/concepts/tape/#history-and-context)): -| Protocol | Where it is used | +| Protocol / Hook | Where it is used | | --- | --- | -| `bub.core.store.TapeStore` | Synchronous implementation passed to `Agent(store=...)` | -| `bub.core.store.AsyncTapeStore` | Asynchronous implementation; recommended for databases and remote storage | -| `provide_tape_store` | Application-level replacement; the built-in app returns `FuzzyFileTapeStore` | - -Full method signatures are in the [Python API](/docs/reference/python-api/#tape-store). At minimum a backend must isolate entries by Tape name, preserve append order, support `reset()`, and let `TapeQuery`'s anchor filters work. Forks are built on top of any store by `ForkTapeStore`, so the backend does not implement them. +| `bub.core.store.TapeStore` | Synchronous store passed to `Agent(store=...)` | +| `bub.core.store.AsyncTapeStore` | Asynchronous store (recommended for databases and network I/O) | +| `provide_tape_store` | App-layer plugin hook replacing the default `FuzzyFileTapeStore` | -## Storage in the built-in app {#app-storage} +See [Python API: `TapeStore`](/docs/reference/python-api/#tape-store) for method signatures and contracts. Forks are built on top of any store by `ForkTapeStore`, so custom backends do not need to implement branching themselves. -The built-in app supplies `FuzzyFileTapeStore` through `provide_tape_store`, with `~/.bub/tapes/` as the default directory. It derives the Tape name from both workspace path and session ID, so same-named sessions in different workspaces do not share history. +## Store resolution in the built-in app {#app-storage} -`BubAgent` chooses its store in this order: +The built-in app provides `FuzzyFileTapeStore` (`~/.bub/tapes/`) via `provide_tape_store` and hashes the workspace path with the session ID so same-named sessions in different workspaces remain separate. -1. An explicitly supplied `tape_store`; -2. The store returned by `framework.get_tape_store()` when the Agent is created; -3. The in-memory store when neither is available. +`BubAgent` selects its store in this order: -Create `BubAgent` inside `framework.running()` when it should use the store supplied by that scope. Replace storage with `provide_tape_store`, and replace the projection strategy with `build_tape_context`. +1. An explicit `tape_store` passed to `BubAgent(...)`; +2. `framework.get_tape_store()` at instantiation time (must be inside `async with framework.running():`); +3. `InMemoryTapeStore`. -The built-in app restores session settings such as model, reasoning effort, and code mode from the Tape. Persist any other application state explicitly. +The built-in app restores session-level settings—such as model, reasoning effort, and code mode—from the Tape automatically; persist any other custom state explicitly via `load_state` and `save_state`. ## Troubleshooting {#troubleshooting} -| Common issue | Possible cause | Solution | +| Symptom | Possible cause | Fix | | --- | --- | --- | -| `tapestore-sqlalchemy` is missing from `bub hooks` | The plugin was installed into a different Python environment | Check `command -v bub` and make sure `bub install` ran in the virtual environment you are using. | -| SQLite reports that the database is locked (Database is locked) | Concurrent writes from multiple processes exceed what SQLite can handle | Configure a busy timeout, or switch to a relational database better suited to high concurrency, such as PostgreSQL. | -| Connecting to PostgreSQL raises `ModuleNotFoundError` | The corresponding database driver is not installed | Run `uv add "psycopg[binary]"` in the Bub environment to install the driver. | -| Tables cannot be created, or permission is denied | The target path or remote database user lacks permission to create tables | Confirm that the file directory is writable by the current user, or grant the database user `CREATE TABLE` permission. | +| `tapestore-sqlalchemy` missing from `bub hooks` | Installed in a different Python environment | Check `command -v bub` and run `bub install` in that environment | +| SQLite `Database is locked` | High multi-process write concurrency | Increase timeout in `BUB_TAPESTORE_SQLALCHEMY_CONNECT_ARGS` or switch to PostgreSQL | +| `ModuleNotFoundError` | Missing database driver | Install the driver in Bub's environment (e.g. `uv add "psycopg[binary]"`) | ## Cleanup {#cleanup} -To restore Bub's default file storage mode, clear the environment variables and delete the test database: +To switch back to Bub's default local file store, clear the environment variables and remove the test database: ```bash unset BUB_TAPESTORE_SQLALCHEMY_URL BUB_TAPESTORE_SQLALCHEMY_ECHO BUB_TAPESTORE_SQLALCHEMY_CONNECT_ARGS diff --git a/website/src/content/docs/docs/migration/v0-6.mdx b/website/src/content/docs/docs/migration/v0-6.mdx index 0968f6d9..745a5943 100644 --- a/website/src/content/docs/docs/migration/v0-6.mdx +++ b/website/src/content/docs/docs/migration/v0-6.mdx @@ -1,20 +1,18 @@ --- title: Upgrade to 0.6.0 -description: Migration notes for the 0.6.0 split of kernel and application dependencies. +description: "Upgrade Bub to 0.6.0: migrate to the split core kernel (bub) and app extra (bub[app]) with updated pip/uv install commands and verification steps." --- import { Tabs, TabItem } from '@astrojs/starlight/components'; -Before 0.6.0, `bub` covered both the application and the kernel; from 0.6.0 on, installing `bub` gives you the kernel only, and the application moved into the optional `app` dependencies. If you need the Bub application layer (configuration, plugins, hooks, skills, message channels, the gateway, and so on), add `bub[app]` when you install. +Starting in 0.6.0, the `bub` package is split into a core kernel and an app layer: installing `bub` installs only the core kernel (`bub.core`), while the CLI, configuration, plugins, hooks, skills, channels, and gateway live in the `bub[app]` extra. -## Upgrade guide {#upgrade-guide} +If you use the Bub CLI or app-layer capabilities, upgrade and install `bub[app]`. -Pick the upgrade step for your current install: +## Upgrade commands {#upgrade-guide} - - -Installed with `uv tool`: + ```bash uv tool install --upgrade --force "bub[app]" @@ -23,8 +21,6 @@ uv tool install --upgrade --force "bub[app]" -In an activated virtual environment: - ```bash uv pip install --upgrade "bub[app]" ``` @@ -32,7 +28,7 @@ uv pip install --upgrade "bub[app]" -For a plugin or a distribution, change the dependency in `pyproject.toml`: +Update dependencies in your plugin or distribution: ```toml title="pyproject.toml" ins="bub[app]" dependencies = ["bub[app]>=0.6.0"] @@ -43,4 +39,4 @@ dependencies = ["bub[app]>=0.6.0"] ## Verify the upgrade {#verify-upgrade} -Once the upgrade finishes, go to the [terminal](/docs/app/terminal/) and enter `bub --help`, start a quick conversation, and run `bub hooks` to see which plugins loaded. +Run `bub --help` or `bub hooks` to confirm the CLI and plugins load properly. diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 71cf030e..b45fb92e 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -1,9 +1,9 @@ --- title: CLI -description: bub commands, options, defaults, exit codes, and background service installation behavior. +description: "Complete reference for the bub CLI: global options, bub chat, bub run, bub gateway, bub onboard, exit codes, and background service install." --- -The `bub` command is provided by the application layer and requires the `app` optional dependency ([install](/docs/getting-started/install/)). This page lists only built-in commands; plugins can add commands through `register_cli_commands`, so consult `bub --help` and the plugin documentation for the full set. +The `bub` CLI is part of the app layer and requires [installing](/docs/getting-started/install/#app-install) `bub[app]`. This page lists all built-in subcommands; plugins can register additional subcommands via `register_cli_commands` (check `bub --help` for the active list). ## Global options {#global-options} @@ -13,37 +13,35 @@ bub [OPTIONS] COMMAND [ARGS]... | Option | Type | Default | Description | | --- | --- | --- | --- | -| `--workspace`, `-w` | path | current working directory | Sets `BubFramework.workspace` | -| `--version`, `-V` | flag | — | Show the installed Bub version and exit | -| `--help` | flag | — | Show help | +| `--workspace`, `-w` | path | current working directory | Sets `BubFramework.workspace` (affects default tool working directory, skill discovery, and relative paths) | +| `--version`, `-V` | flag | — | Print the installed Bub version and exit | +| `--help` | flag | — | Show help and exit | -`--workspace` affects tools' working directory, skill discovery, and relative-path resolution. It does not change `BUB_HOME` or the location of the configuration file. - -Running `bub` without a command runs `BubFramework.default_command` with its defaults. The builtin plugin sets it to `chat`, so `bub` and `bub -w PATH` start the chat REPL. A plugin can choose another command by setting `default_command` in its `register_cli_commands` hook; the builtin only fills it when no plugin has. - -Before loading the CLI, the command checks for the `app` optional dependency. If it is missing, the process prints the missing package and the install command, then exits without reaching the Typer help page. +- `--workspace` does not change `BUB_HOME` or the location of `~/.bub/config.yml`. +- Running `bub` (or `bub -w PATH`) without a subcommand executes `BubFramework.default_command` (`chat` by default, launching the interactive terminal REPL). +- If `bub[app]` is not installed, running `bub` prints the missing dependency and installation command and exits with code `1`. ## `bub run` {#bub-run} -Runs a complete Turn for one message: resolves the session, builds the prompt, calls the model and tools, saves state, and generates a reply, then prints `TurnResult.outbounds` to stdout. It does not start a channel manager. +Runs a complete Turn for one message (resolves session, builds prompt, runs model and tools, saves state, and renders replies), prints `TurnResult.outbounds` to stdout, and exits. Does not start `ChannelManager`. ```text bub run [OPTIONS] MESSAGE ``` -| Parameter | Type | Default | Description | +| Parameter / Option | Type | Default | Description | | --- | --- | --- | --- | -| `MESSAGE` | text | required | Message body; executes a command when it starts with the command prefix | -| `--channel` | text | `cli` | Inbound channel name | +| `MESSAGE` | text | required | Message body; runs an internal command directly when starting with the command prefix (`,` by default) | +| `--channel` | text | `cli` | Inbound channel identifier | | `--chat-id` | text | `local` | Inbound chat ID | | `--sender-id` | text | `human` | Written to `context.sender_id` | -| `--session-id` | text | `:` | Explicitly overrides the session ID | +| `--session-id` | text | `:` | Explicit session ID override (used to share history across entry points) | Output format: ```text [channel:chat_id] - + ``` Examples: @@ -54,32 +52,32 @@ bub run --channel web --chat-id demo "Continue the previous topic." bub run --session-id shared:demo ",tape.info" ``` -Because it does not start a `ChannelManager`: +Because `bub run` does not start `ChannelManager`: -- It does not start channels or background services such as `mcp.lifecycle` and `acp-server`. -- It does not automatically send model replies to a chat platform. -- The resource scopes for `provide_tape_store`, `provide_lifespan`, and `provide_steering_inbox` still run. -- The model stage uses the non-streaming `HookRuntime.run_model`. +- **Does not start background services**: `mcp.lifecycle`, `acp-server`, and external chat channel listeners do not start; +- **Does not deliver to external platforms**: output is printed only to stdout; +- **Still enters core resource scopes**: `provide_tape_store`, `provide_lifespan`, and `provide_steering_inbox` are initialized and cleaned up on exit; +- **Uses the non-streaming model stage**: calls `HookRuntime.run_model`. -When the model returns no text, `run` prints the inbound content or prompt text as a fallback and logs a `run_model` stage error; the process itself usually still exits with code `0`. To make scripted decisions based on failure, inspect stderr and the actual output rather than relying on the exit code alone. +Note: if the model stage errors or returns empty text, `bub run` logs a `run_model` error and prints fallback text, and the process may still exit with code `0`. In automation scripts, inspect `stderr` and output content rather than relying solely on the exit code. ## `bub chat` {#bub-chat} -Starts an interactive REPL. It always enables the `cli` channel and attaches enabled `Lifecycle` channels. +Starts an interactive terminal session (REPL), enables the `cli` channel, and starts all enabled `Lifecycle` background services (such as MCP connections). ```text bub chat [OPTIONS] [INITIAL_PROMPT] ``` -| Parameter | Type | Default | Description | +| Parameter / Option | Type | Default | Description | | --- | --- | --- | --- | -| `INITIAL_PROMPT` | text | — | Submitted immediately after the REPL starts | +| `INITIAL_PROMPT` | text | — | Optional; sent automatically right after the REPL starts | | `--chat-id` | text | `local` | CLI chat ID | | `--session-id` | text | `cli_session` | Session ID | -`chat` forces streaming output and ignores `BUB_STREAM_OUTPUT`. The attached Lifecycle lets MCP tools and ACP background services work during the chat. - -Without a `cli` channel, the command prints an error and exits with code `1`. This happens when a plugin replaces or removes the CLI channel. +- `bub chat` always streams output (ignoring `BUB_STREAM_OUTPUT`). +- Exits with code `1` if a plugin removes the `cli` channel. +- Direct commands inside the REPL use `BUB_COMMAND_PREFIX` (`,` by default); enter `,help` to list available commands. ```bash bub chat @@ -87,11 +85,9 @@ bub chat "What changed in this repository?" bub chat --session-id shared:demo ``` -Inside the REPL, comma-prefixed commands are controlled by `BUB_COMMAND_PREFIX`, which defaults to `,`. Type `,help` to see the current commands. - ## `bub gateway` {#bub-gateway} -Starts the channel manager and keeps enabled channels running. +Starts `ChannelManager` and keeps all enabled external message channels (such as Telegram, Feishu, and Discord) running. ```text bub gateway [OPTIONS] @@ -99,28 +95,26 @@ bub gateway [OPTIONS] | Option | Type | Default | Description | | --- | --- | --- | --- | -| `--enable-channel` | text, repeatable | empty; reads `BUB_ENABLED_CHANNELS` | Include or exclude channels | -| `--install` | flag | off | Install and start a background service for the current user | -| `--uninstall` | flag | off | Stop and uninstall the background service | +| `--enable-channel` | text (repeatable) | reads `BUB_ENABLED_CHANNELS` | Enable specific channels, or exclude a channel with `!name` | +| `--install` | flag | off | Register and start the gateway as a background user service | +| `--uninstall` | flag | off | Stop and remove the installed background gateway service | -`--install` and `--uninstall` are mutually exclusive; passing both exits with an argument error. +`--install` and `--uninstall` are mutually exclusive; `--enable-channel` overrides `BUB_ENABLED_CHANNELS`. -### Channel selection {#channel-selection} +### Channel selection rules {#channel-selection} -`BUB_ENABLED_CHANNELS` is comma-separated; `--enable-channel` may be repeated, and command-line values take precedence. +`BUB_ENABLED_CHANNELS` accepts comma-separated names; `--enable-channel` can be passed multiple times: -| `enabled_channels` | Result | +| Value | Channels started | | --- | --- | -| `all` | Every `enabled` channel that is not an `Interface`, minus `!name` exclusions | -| Explicit ordinary channels | The listed channels that are `enabled` and not excluded | -| Explicit ordinary channels + Lifecycle | Select the ordinary channels first, then attach every enabled `Lifecycle` | -| Only Lifecycle | Start only those Lifecycle channels | -| Only `!name` | No inclusions, so startup fails | +| `all` (default) | Every channel and `Lifecycle` service with `enabled=True` that is not an `Interface`, minus `!name` exclusions | +| Explicit ordinary channel names | Listed ordinary channels with `enabled=True` (minus exclusions), plus all enabled `Lifecycle` services | +| Only `Lifecycle` names | Only the specified `Lifecycle` background services | +| Only `!name` exclusions | Fails to start (exit code `1`) because no channels are included | -- `Interface` is a user-facing surface that must be selected explicitly, such as `cli`. -- `Lifecycle` is a background service, such as `mcp.lifecycle` or `agent-plugins.mcp`. -- When ordinary channels are selected explicitly, Lifecycle channels are attached automatically by default; use `!name` to exclude one. -- If no channel can be enabled, it prints `No channels are enabled...` and exits with code `1`. +- `Interface` channels are interactive UIs (such as `cli`) that must be selected explicitly and are excluded from `all`. +- `Lifecycle` channels are background services (such as `mcp.lifecycle` and `agent-plugins.mcp`). +- If no channels are enabled, the process prints `No channels are enabled...` and exits with code `1`. ```bash bub gateway @@ -129,29 +123,22 @@ bub gateway --enable-channel telegram --enable-channel discord bub gateway --enable-channel telegram --enable-channel '!mcp.lifecycle' ``` -Quote exclusions so the shell does not treat `!` as history expansion. +Single-quote `!name` exclusions in your shell (e.g., `'!mcp.lifecycle'`) to prevent shell history expansion. -### Background service {#gateway-service} +### Background service installation {#gateway-service} -| Platform | Installation method | Location or behavior | +| OS | Installation method | Location / behavior | | --- | --- | --- | -| Linux | systemd user unit | `${XDG_CONFIG_HOME:-~/.config}/systemd/user/bub-gateway.service` | -| Windows | Scheduled task | Task named `Bub Gateway`, started when the current user logs in | -| macOS | `--install` unsupported | Deploy with launchd, tmux, or a container | +| Linux | systemd user unit | `${XDG_CONFIG_HOME:-~/.config}/systemd/user/bub-gateway.service` (restarts on failure) | +| Windows | Windows Scheduled Task | Task named `Bub Gateway`, starts at user login and restarts on failure | +| macOS | `--install` unsupported | Use `launchd`, `tmux`, or [Docker deployment](/docs/app/deploy/) | -The Linux unit uses `Restart=on-failure`, `RestartSec=5s`, and `WantedBy=default.target`. Installation runs `daemon-reload`, `enable`, and `restart`. - -- The service captures the current Python interpreter, workspace, and explicit `--enable-channel` arguments. -- After changing the virtual environment, moving the workspace, or changing channel arguments, run `bub gateway --install` again. -- To keep it running after logout on Linux, run `loginctl enable-linger "$USER"`. -- Reinstalling replaces the existing unit or task and restarts it. -- `--uninstall` counts as successful even when the service does not exist. - -macOS has no built-in service installation path; [Deployment](/docs/app/deploy/) describes a container approach. +- Installation records the current Python interpreter, workspace directory, and `--enable-channel` flags; re-run `bub gateway --install` after changing environments or moving the workspace. +- On Linux, run `loginctl enable-linger "$USER"` so the service stays running after SSH logout. ## `bub onboard` {#bub-onboard} -Interactively generates configuration: it collects model and plugin options and writes them to `BubFramework.config_file`, which defaults to `~/.bub/config.yml`. It does not start channels. +Runs the interactive configuration wizard and writes settings to `~/.bub/config.yml`. ```text bub onboard [OPTIONS] [PLUGIN_NAME] @@ -159,63 +146,49 @@ bub onboard [OPTIONS] [PLUGIN_NAME] | Parameter | Type | Default | Description | | --- | --- | --- | --- | -| `PLUGIN_NAME` | text | none | Run only that plugin's `onboard_config` | +| `PLUGIN_NAME` | text | none | Optional; run only the specified plugin's `onboard_config` wizard | -Without a plugin name, it runs the built-in model configuration first, then the configuration of every other registered plugin. With a plugin name, it runs only the selected implementation and skips the gateway service installation prompt. +Without `PLUGIN_NAME`, runs the built-in model wizard followed by every registered plugin's wizard; with `PLUGIN_NAME`, runs only that plugin's wizard and skips the gateway service prompt. -| Exit code | Meaning | -| --- | --- | -| `0` | Saved, or the user declined gateway installation | -| `1` | Configuration validation, write, plugin resolution, or gateway installation failed | +Model wizard write rules: -Common write behavior: - -| Choice or action | Result | +| Wizard action | Config result | | --- | --- | -| OpenAI-compatible service or local endpoint | Writes `openai:`, `api_base`, and sets `client_args.api_format: chat` | -| Official OpenAI API selected but the address is not the official one | Resets the address to `https://api.openai.com/v1` | -| Base URL left blank | Keeps the provider's default address and does not write an explicit empty value | -| Base URL entered explicitly | Written even when it equals the default | -| API key left blank | Keeps the key for the current address, or continues using an environment variable | -| Base URL changed | Clears any key entered earlier | -| Codex selected | Skips model discovery and asks for a model ID manually | - -The connection check calls only the model list endpoint, not a generation request, with a 10-second timeout. It does not verify that the model supports tool calls. +| Select OpenAI-compatible or local endpoint | Writes `openai:`, `api_base`, and `client_args.api_format: chat` | +| Select official OpenAI API after a custom URL was set | Resets `api_base` to `https://api.openai.com/v1` | +| Leave Base URL blank | Keeps the provider default without writing an empty value to YAML | +| Enter Base URL explicitly | Writes `api_base` to YAML (changing Base URL clears any previously saved API key) | +| Leave API key blank | Keeps the existing key for that URL or relies on environment variables | +| Select Codex | Skips fetching the online model list and prompts for a model ID directly | -An `onboard_config` implementation receives the current configuration plus modifications from earlier hooks and returns a dictionary that is merged back; returning a non-dictionary raises `TypeError`. After all implementations finish, the result passes through `configure.validate` before being written to disk. +The connectivity check queries only the provider's model-list endpoint (10-second timeout). Settings are validated via `configure.validate` before saving. Exits with `0` on success or `1` on failure. ## `bub install` {#bub-install} -Installs plugins into the `uv` project managed by Bub; with no arguments, it syncs that project. It does not start channels. +Installs plugin packages into Bub's managed `uv` project directory; with no arguments, syncs existing dependencies in that project. ```text bub install [OPTIONS] [SPECS]... ``` -| Parameter | Type | Default | Description | +| Parameter / Option | Type | Default | Description | | --- | --- | --- | --- | -| `SPECS` | positional | empty | Packages or Git sources to install | -| `--project` | path | `$BUB_HOME/bub-project` or `~/.bub/bub-project` | Plugin project directory; also available as `BUB_PROJECT` | +| `SPECS` | positional | empty | PyPI package names, `bub-contrib` plugin names, or Git URLs | +| `--project` | path | `$BUB_HOME/bub-project` (default `~/.bub/bub-project`) | Managed plugin project directory (also configurable via `BUB_PROJECT`) | -Package spec resolution: +Supported package spec formats: -| Form | Resolves to | +| Format | Resolves to | | --- | --- | | `package` | PyPI package name | -| `package@ref` | A package from the configured contrib repository, pinned to `ref` | +| `package@ref` | The `packages/package` subdirectory of [`bub-contrib`](https://github.com/bubbuild/bub-contrib), pinned to branch or tag `ref` | | `owner/repo` | `https://github.com/owner/repo.git` | -| `https://github.com/owner/repo.git@ref` | A prefixed Git URL that preserves the ref | -| `git@...` or `https://...` | Prefixed with `git+` | +| `https://github.com/owner/repo.git@ref` | Git repository URL pinned to `ref` | +| `git@...` or `https://...` | Prefixed with `git+` and passed to `uv` | `package@ref` uses the official `bub-contrib` repository by default. To use a fork or mirror, set the top-level `contrib_repo` in `config.yml` or override it with `BUB_CONTRIB_REPO`. Use a Git URL accepted by `uv`, such as `ssh://git@example.com/org/repo.git#subdirectory=plugins/mcp`. `package@ref` supplies the ref and defaults to `packages/package` unless the URL sets `#subdirectory=` (use `.` for the repository root). For private repositories, use an SSH key or Git credential helper rather than putting credentials in the URL. -To pin any GitHub repository, use the full URL: - -```bash -bub install https://github.com/owner/repo.git@v1.2.0 -``` - -Do not write `owner/repo@v1.2.0`: the current parser accepts only the `owner/repo` shorthand without a ref. Bub's own repository name is also not the same as its package name; when installing a plugin, use the spec given in the plugin's README. +Do not write `owner/repo@v1.2.0`: the current parser accepts only the `owner/repo` shorthand without a ref. To pin any GitHub repository, use the full URL. Bub's own repository name is also not the same as its package name; when installing a plugin, use the spec given in the plugin's README. Examples: @@ -226,36 +199,21 @@ bub install https://github.com/owner/repo.git@v1.2.0 bub install ``` -The first invocation creates `bub-project`: - -```text -uv init --bare --name bub-project --app -uv add --active --no-sync --extra app -``` - -The current Bub source may be an editable path, a local path, a VCS URL, or a PyPI name; source installs and PyPI installs therefore produce different project declarations. - -Subsequent uv calls: +Underlying `uv` commands: -| Command | uv invocation | +| Bub command | `uv` invocation | | --- | --- | -| `bub install` (no specs) | `uv sync --active --inexact` | +| `bub install` (no arguments) | `uv sync --active --inexact` | | `bub install ` | `uv add --active ` | | `bub uninstall ` | `uv remove --active ` | -| `bub update` | `uv sync --active --upgrade --inexact` | +| `bub update` (no arguments) | `uv sync --active --upgrade --inexact` | | `bub update ` | `uv sync --active --inexact --upgrade-package ...` | -Prerequisites: - -- `uv` is on `PATH`, in the current Python scripts directory, or in `~/.local/bin`; -- Bub is running inside a virtual environment (`sys.prefix != sys.base_prefix`); -- An explicitly passed `--project` directory must exist. - -If these are not met, the command exits with code `1`. When uv fails, its exit code is returned. +Prerequisites: `uv` is installed, `bub` is running inside a virtual environment (`sys.prefix != sys.base_prefix`), and any explicit `--project` directory already exists. ## `bub uninstall` {#bub-uninstall} -Uninstalls one or more plugins from the managed project. It does not start channels. Names must match the project declarations. +Uninstalls plugins from the managed plugin project: ```text bub uninstall [OPTIONS] PACKAGES... @@ -265,11 +223,9 @@ bub uninstall [OPTIONS] PACKAGES... bub uninstall bub-discord ``` -It modifies only `bub-project`, not the system Python or other packages in the environment where Bub itself runs. `install`, `uninstall`, and `update` all accept `--project`, and `BUB_PROJECT` can specify the same directory. - ## `bub update` {#bub-update} -Upgrades plugins in the managed project; without package names it upgrades every dependency, and with names it upgrades only those packages. It does not start channels. +Upgrades plugins in the managed plugin project (upgrades all installed plugins when no package names are given): ```text bub update [OPTIONS] [PACKAGES]... @@ -280,12 +236,11 @@ bub update bub update bub-mcp ``` -Upgrading does not automatically migrate plugin configuration or Tape data. -After upgrading across versions, restart `bub chat` or `bub gateway` and check whether `bub hooks` still reports entry-point loading failures. +Restart any running `bub chat` or `bub gateway` process after upgrading. ## `bub login codex` {#bub-login-codex} -Configures ChatGPT plan credentials through the Codex CLI. It does not start channels. +Signs in via the OpenAI Codex CLI to configure ChatGPT plan credentials: ```text bub login codex [OPTIONS] @@ -293,78 +248,53 @@ bub login codex [OPTIONS] | Option | Type | Default | Description | | --- | --- | --- | --- | -| `--executable` | text | `codex` | Codex CLI executable | -| `--device-auth` | flag | off | Use the device authorization flow | -| `--codex-home` | path | `$CODEX_HOME` or `~/.codex` | Credential directory | - -On success it prints: - -```text -login: ok -account_id: -Use BUB_MODEL=codex: for ChatGPT plan access. -``` - -Matching configuration: - -```bash -export BUB_MODEL=codex: -``` +| `--executable` | text | `codex` | Codex CLI executable name or path | +| `--device-auth` | flag | off | Use device-code authorization | +| `--codex-home` | path | `$CODEX_HOME` or `~/.codex` | Directory storing `auth.json` | -Do not set `BUB_API_KEY` at the same time. On failure it prints `login: failed: ...` and exits with code `1`. Credentials are usually written to `$CODEX_HOME/auth.json` or `~/.codex/auth.json`. +After logging in, set `BUB_MODEL=codex:` and **do not** set `BUB_API_KEY`. ## Other account logins {#account-logins} +Reuse credentials from the official Grok CLI or GitHub CLI (`gh`): + ```bash bub login grok [--executable grok] [--device-auth] bub login github-copilot ``` -Grok uses the official Grok CLI; GitHub Copilot uses `gh auth login`. Install the corresponding CLI first. Republic reuses its credentials and handles token refresh or exchange. Bub adds no credential store. - -Select a model with `BUB_MODEL=grok:` or `BUB_MODEL=github-copilot:`, without setting an API key. Login does not change the configured model. GitHub Copilot access requires an eligible account and subscription. +After logging in, set `BUB_MODEL=grok:` or `BUB_MODEL=github-copilot:` (no API key required). ## `bub plugins` {#bub-plugins} -Prints each discovered plugin with the package and version that provide it. +Lists discovered plugins along with their Python distribution name and version: ```text bub plugins [OPTIONS] [NAMES]... ``` -| Option | Type | Default | Description | +| Parameter / Option | Type | Default | Description | | --- | --- | --- | --- | -| `NAMES` | text | all plugins | Plugin names registered in the `bub` entry-point group | -| `--version-only` | flag | off | Print only each plugin's version, one per line | +| `NAMES` | text | all plugins | Query specific plugin entry-point names | +| `--version-only` | flag | off | Print only the version string per line (`-` when no package metadata exists) | -Output is one line per plugin: `name distribution version`. The builtin hooks are listed as `builtin`, provided by `bub`. Plugins that failed to load or initialize are listed with `(failed: )`. An unknown name exits with code `1`. With `--version-only`, each line holds only the version (`-` when the plugin has no package metadata), for example `bub plugins my-plugin --version-only`. +Prints `name distribution version` per line (appending `(failed: )` if loading failed). Exits with code `1` if a requested name does not exist. ## `bub hooks` {#bub-hooks} -Prints the hook implementation map. This is a hidden command that does not appear in `bub --help` and does not start channels. +Prints all hooks and their bound plugin implementations (hidden diagnostic command not shown in `bub --help`): -```text +```bash bub hooks ``` -Each line has this format: - -```text -: , -``` - -Implementations are printed in pluggy registration order, with hook names sorted alphabetically. When there are no implementations it prints `(no hook implementations)`. - -This order is not execution order. Bub reverses pluggy's internal list and then applies `tryfirst` / `trylast`; see [Priority and dispatch](/docs/reference/hooks/#priority-and-dispatch) for diagnosing the actual order. +Format: `: , ...`, listed in **pluggy registration order**. Note that runtime execution order reverses this list; see [Hooks reference: Execution priority](/docs/reference/hooks/#priority-and-dispatch). ## Exit codes {#exit-codes} | Scenario | Exit code | | --- | --- | -| Command succeeds | `0` | -| Typer argument error | `2` | -| `app` optional dependency missing | `1`; the process exits before Typer | -| No channels can be enabled, plugin failure, configuration failure | `1` | -| uv failure in `bub install` / `uninstall` / `update` | uv's exit code | - -Model errors in `bub run` may only be logged and return fallback text, so do not rely on the exit code alone to determine whether the model call succeeded. +| Command succeeded | `0` | +| CLI argument parsing error (Typer) | `2` | +| Missing `bub[app]` extra, no enabled channels, or config/login/plugin lookup failure | `1` | +| `uv` failure in `bub install` / `uninstall` / `update` | Passes through `uv`'s exit code | diff --git a/website/src/content/docs/docs/reference/hooks.mdx b/website/src/content/docs/docs/reference/hooks.mdx index 79d950f3..e5bf6f36 100644 --- a/website/src/content/docs/docs/reference/hooks.mdx +++ b/website/src/content/docs/docs/reference/hooks.mdx @@ -1,32 +1,32 @@ --- title: Hooks -description: Review the overview, source signatures, return values, execution order, and lifecycle of 27 hooks, organized by Turn, App, and Agent. +description: "Complete Bub Hooks reference: overview, function signatures, return values, execution priority, and lifecycle of 27 Turn, App, and Agent hooks." --- This page lists the complete interface of all 27 hooks. A hook is an extension point through which plugins participate in framework flows: the same hook can be implemented by multiple plugins, the framework calls them in the order described below, and it decides what happens next based on their return values. For concrete plugin examples, see [Plugins and hooks](/docs/app/plugins/); to learn which stages a message passes through, see [Turn](/docs/concepts/turn/#stages). -## Understanding dispatch modes {#notation} +## Dispatch modes and base types {#notation} -Every hook's overview and details state its "dispatch mode", that is: **how the framework calls the multiple implementations of the hook and how it handles their return values.** +Every hook specifies a **dispatch mode** that defines how `HookRuntime` calls multiple plugin implementations and handles their return values: | Dispatch mode | Meaning | | --- | --- | -| **First result** | Calls implementations one by one by priority and uses the first non-`None` return value; later implementations are not run. `False`, `""`, and `[]` are also return values and do not equal `None` | -| **Run all** | Calls every implementation and collects the return values. Whether one failure affects the whole depends on the specific hook and call site | -| **Sequential** | Calls implementations one by one by priority; later implementations can see the results modified by earlier ones. Certain return values can end processing early. Used by Agent hooks | +| **First result** | Calls implementations from highest to lowest priority and returns the first non-`None` value, skipping remaining plugins (`False`, `""`, and `[]` count as non-`None` values) | +| **Run all** | Calls every registered implementation and collects the results | +| **Sequential** | Calls implementations in priority order, passing each plugin's modified request to the next; stops early if a plugin returns a termination or denial decision (used by Agent interception hooks) | -These types are also used in the tables: +Common type aliases in hook signatures: | Type | Meaning | | --- | --- | -| `Envelope` | An alias for `Any`. A mapping, dataclass, Pydantic model, or object with attributes can be passed | -| `TurnState` | An alias for `dict[str, Any]`, shared by hooks, tools, and events within the current Turn | +| `Envelope` | Alias for `Any` representing an inbound or outbound message (dict, dataclass, Pydantic model, or object with attributes) | +| `TurnState` | Alias for `dict[str, Any]` shared across hooks, tools, and event handlers within a single Turn | -All signatures below are taken directly from `bub.hooks.specs.BubHookSpecs`, so they uniformly use `def` and keep `self`. When implementing, declare only the parameters you actually use; the framework passes values by parameter name. Whether an asynchronous implementation is available depends on the specific call path; when it is unsupported, that implementation is skipped and `hook.async_not_supported` is logged. +All signatures below come from `bub.hooks.specs.BubHookSpecs`. When implementing a hook with `@hookimpl`, **declare only the parameter names you need**; Bub injects arguments by name. -## With multiple plugins, who runs first {#priority-and-dispatch} +## Execution priority {#priority-and-dispatch} Bub uses pluggy to register hook implementations, and `HookRuntime` to invoke them uniformly. @@ -74,8 +74,12 @@ Determines the `session_id` for a new message so the framework knows which sessi def resolve_session(self, message: Envelope) -> str: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `message` | `Envelope` | Incoming raw message | +| **Returns** | `str` | Session ID; falls back to `:` when empty | + - **Dispatch**: First result. -- **Default fallback**: When the result is empty, `channel:chat_id` is used as the session ID. ### `load_state` {#load_state} @@ -85,8 +89,13 @@ Restores the application state needed for this Turn from the session store. def load_state(self, message: Envelope, session_id: str) -> TurnState: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `message` | `Envelope` | Incoming message | +| `session_id` | `str` | Session ID resolved by `resolve_session` | +| **Returns** | `TurnState` | Turn state dictionary (non-dictionary return values are ignored) | + - **Dispatch**: Run all; lower-priority results are merged first, higher-priority results after. -- **Return value**: Non-dictionary return values are ignored. ### `build_prompt` {#build_prompt} @@ -96,8 +105,14 @@ Builds the prompt sent to the model based on the original message and the restor def build_prompt(self, message: Envelope, session_id: str, state: TurnState) -> list[UserContent] | LegacyPrompt: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `message` | `Envelope` | Incoming message | +| `session_id` | `str` | Current session ID | +| `state` | `TurnState` | Shared Turn state dictionary (write `_command_output` to skip the model stage for internal commands) | +| **Returns** | `list[UserContent] \| LegacyPrompt` | Model prompt content; falls back to the raw message text if the first non-`None` result is `""` or `[]` | + - **Dispatch**: First result. -- **Default fallback**: Uses the first non-`None` return value; if that value is `""` or `[]`, the framework does not try later implementations and instead uses the original message content. #### Prompt content {#prompt-content} @@ -127,8 +142,14 @@ Calls the model and returns the complete text output directly. def run_model(self, prompt: str | list[dict], session_id: str, state: TurnState) -> str: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `prompt` | `str \| list[dict]` | Legacy prompt input (see [Prompt content](#prompt-content)) | +| `session_id` | `str` | Current session ID | +| `state` | `TurnState` | Shared Turn state dictionary | +| **Returns** | `str` | Complete assistant response text | + - **Dispatch**: First result. -- **Prompt format**: Receives the legacy prompt format; see [Prompt content](#prompt-content). ### `run_model_stream` {#run_model_stream} @@ -138,12 +159,16 @@ Calls the model and returns streaming events that can be consumed one at a time. def run_model_stream(self, prompt: str | list[dict], session_id: str, state: TurnState) -> AsyncStreamEvents: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `prompt` | `str \| list[dict]` | Legacy prompt input (see [Prompt content](#prompt-content)) | +| `session_id` | `str` | Current session ID | +| `state` | `TurnState` | Shared Turn state dictionary | +| **Returns** | `AsyncStreamEvents` | Async stream yielding `StreamEvent` items | + - **Dispatch**: First result. -- **Prompt format**: Receives the legacy prompt format; see [Prompt content](#prompt-content). - **Relationship with `run_model`**: You only need to implement one of the two. Plain text can be converted into streaming output, and streaming output can be aggregated into plain text. -- **After replacing the builtin model stage**: The builtin Agent's interception hooks do not run automatically. - -The framework selects the model hook implementation according to the priority rules above; `tryfirst` / `trylast` also apply to these two hooks. +- **After replacing the builtin model stage**: The builtin Agent's interception hooks do not run automatically unless wired in by your implementation. ### `continue_prompt` {#continue_prompt} @@ -153,11 +178,14 @@ Optionally adds a user message when the Agent needs to continue running. def continue_prompt(self, prompt: str | list[dict] | None, tape: Tape, state: StreamState) -> str | None: ``` -- **Dispatch**: First result. -- **When it is called**: When `StepFinished.status == "continue"`. -- **Returning `None`**: The conversation continues directly without adding a new user message. -- **State type**: Receives `StreamState`, not `TurnState`. -- **Prompt format**: Receives the legacy prompt format; see [Prompt content](#prompt-content). +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `prompt` | `str \| list[dict] \| None` | Legacy prompt input for the current step | +| `tape` | `Tape` | Active session Tape | +| `state` | `StreamState` | Active stream state (note: `StreamState`, not `TurnState`) | +| **Returns** | `str \| None` | Extra user prompt for the next step, or `None` to continue without adding a user message | + +- **Dispatch**: First result (called only when `StepFinished.status == "continue"`). ### `save_state` {#save_state} @@ -173,9 +201,14 @@ def save_state( ) -> None: ``` -- **Dispatch**: Run all. -- **When it is called**: In the `finally` block of the model stage. As long as execution has entered the model stage, it runs whether the model succeeds, fails, or is cancelled. -- **Scope**: It only saves application state; it is not responsible for cleaning up resources. +| Parameter | Type | Description | +| --- | --- | --- | +| `session_id` | `str` | Current session ID | +| `state` | `TurnState` | Shared Turn state dictionary | +| `message` | `Envelope` | Incoming message | +| `model_output` | `str` | Final text produced by the model stage (empty string on error) | + +- **Dispatch**: Run all (called in the `finally` block of the model stage; only saves application state, not runtime resources). ### `render_outbound` {#render_outbound} @@ -191,8 +224,15 @@ def render_outbound( ) -> list[Envelope]: ``` -- **Dispatch**: Run all; the message lists returned by each implementation are expanded and concatenated in order. -- **Default fallback**: If no implementation produces a message to send, the framework generates one reply from `model_output`, reusing the original message's `channel` and `chat_id`. +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `message` | `Envelope` | Original incoming message | +| `session_id` | `str` | Current session ID | +| `state` | `TurnState` | Shared Turn state dictionary | +| `model_output` | `str` | Final text produced by the model stage or internal command | +| **Returns** | `list[Envelope]` | List of outbound messages to dispatch | + +- **Dispatch**: Run all; concatenates returned lists in execution order. Falls back to one default reply from `model_output` reusing `channel` and `chat_id` if no implementation produces messages. ### `dispatch_outbound` {#dispatch_outbound} @@ -202,9 +242,12 @@ Hands a message to be sent to an external channel. def dispatch_outbound(self, message: Envelope) -> bool: ``` -- **Dispatch**: Run all; called once per message to be sent. -- **Return value**: Ignored; you cannot prevent other implementations from running through the return value. -- **When you need to filter messages**: Do it in the `render_outbound` stage. +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `message` | `Envelope` | Single outbound message to deliver | +| **Returns** | `bool` | Delivery indicator (does not stop other implementations from running; filter messages in `render_outbound` instead) | + +- **Dispatch**: Run all; called once per outbound message. ## App Hooks {#application-hooks} @@ -235,6 +278,10 @@ Registers custom CLI commands with Bub's root Typer app. def register_cli_commands(self, app: Any) -> None: ``` +| Parameter | Type | Description | +| --- | --- | --- | +| `app` | `typer.Typer` | Root Typer CLI application instance | + - **Dispatch**: Run all. ### `onboard_config` {#onboard_config} @@ -245,10 +292,12 @@ Supplements or modifies configuration during onboarding. def onboard_config(self, current_config: dict[str, Any]) -> dict[str, Any] | None: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `current_config` | `dict[str, Any]` | Currently loaded configuration plus modifications from earlier hooks | +| **Returns** | `dict[str, Any] \| None` | Dictionary recursively merged into the configuration (non-dictionary non-`None` values raise `TypeError`) | + - **Dispatch**: Run all. -- **Input**: The currently loaded configuration, plus the modifications earlier implementations have made to it. -- **Return value**: The returned dictionary is merged into the configuration; the value used for merging must be a dictionary, otherwise a `TypeError` is raised. -- **Plugin filtering**: `collect_onboard_config()` is responsible for filtering by plugin name. ### `provide_model_options` {#provide_model_options} @@ -262,8 +311,13 @@ def provide_model_options( ) -> ModelOptions | None: ``` -- **Dispatch**: Run all; merges model lists and keeps the first `current_model`. -- **Scope**: It only provides candidate models. Whether to show them to the user, and how to persist the current model, is up to the caller. +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `session_id` | `str` | Current session ID | +| `workspace` | `Path \| None` | Active workspace directory | +| **Returns** | `ModelOptions \| None` | Candidate models and `current_model` | + +- **Dispatch**: Run all; merges model lists and keeps the highest-priority `current_model`. ### `provide_environment` {#provide_environment} @@ -273,9 +327,13 @@ Provides the runtime environment for `bash`, file tools, and code execution. def provide_environment(self, session_id: str, workspace: Path) -> Environment | None: ``` -- **Dispatch**: First result. -- **Lifecycle**: One is cached per session and closed when `running()` exits. -- **Default implementation**: When there is no custom implementation, the builtin implementation returns `LocalEnvironment`. +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `session_id` | `str` | Current session ID | +| `workspace` | `Path` | Active workspace directory | +| **Returns** | `Environment \| None` | Session execution environment (defaults to `LocalEnvironment(workspace)`) | + +- **Dispatch**: First result; one instance is cached per session and closed when `running()` exits. ### `on_error` {#on_error} @@ -285,17 +343,13 @@ Observes exceptions from framework stages; useful for logging and error reportin def on_error(self, stage: str, error: Exception, message: Envelope | None) -> None: ``` -- **Dispatch**: Run all; when an implementation fails, it only logs `hook.on_error_failed` and is skipped. -- **Scope**: Only for observing errors; it cannot recover the task or prevent the original exception from propagating. - -Common values of `stage`: +| Parameter | Type | Description | +| --- | --- | --- | +| `stage` | `str` | Stage identifier (`"turn"`, `"run_model"`, `"resolve_session"`, `"admit_message"`) | +| `error` | `Exception` | Raised exception instance | +| `message` | `Envelope \| None` | Associated inbound message, or `None` when outside a message context | -| `stage` | When it appears | -| --- | --- | -| `turn` | An uncategorized exception occurs in a Turn, including exceptions in prompt, model-stage, and reply handling | -| `run_model` | No model implementation is found, or an error is reported in streaming output | -| `resolve_session` | Session resolution fails before a channel decides whether to accept a message | -| `admit_message` | An error occurs while a channel decides whether to accept a message | +- **Dispatch**: Run all; when an implementation fails, it logs `hook.on_error_failed` and is skipped. Only observes errors and cannot suppress exceptions. ### `system_prompt` {#system_prompt} @@ -305,9 +359,13 @@ Provides a system prompt block that is prepended to the model prompt. def system_prompt(self, prompt: str | list[dict], state: TurnState) -> str: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `prompt` | `str \| list[dict]` | Legacy prompt input for the current Turn | +| `state` | `TurnState` | Shared Turn state dictionary | +| **Returns** | `str` | System prompt block to append | + - **Dispatch**: Run all; joins non-empty results with blank lines from low to high priority. -- **Multiple implementations**: All results are kept and do not overwrite one another; even a higher-priority implementation can only append its own content. -- **Prompt format**: Receives the legacy prompt format; see [Prompt content](#prompt-content). ### `provide_tape_store` {#provide_tape_store} @@ -317,10 +375,11 @@ Provides the Tape store used to record conversations. def provide_tape_store(self) -> TapeStore | AsyncTapeStore | None: ``` -- **Dispatch**: First result; may return a generator. -- **When it is called**: Resolved only once during `framework.running()`. Outside that scope, `get_tape_store()` returns `None`. -- **When you need to clean up resources**: Return a generator and release the connection in `finally`. -- **Unsupported form**: Do not return an object decorated with `@contextmanager` / `@asynccontextmanager`; the runtime treats it as an ordinary value. +| Return | Type | Description | +| --- | --- | --- | +| **Returns** | `TapeStore \| AsyncTapeStore \| None` | Tape store instance, or a single-`yield` generator (do not wrap with `@contextmanager` / `@asynccontextmanager`) | + +- **Dispatch**: First result (resolved once on entering `framework.running()`). ### `provide_lifespan` {#provide_lifespan} @@ -330,10 +389,11 @@ Holds resources that need to be started and cleaned up during `framework.running def provide_lifespan(self) -> AsyncIterator[None] | Iterator[None] | None: ``` -- **Dispatch**: Run all; each generator is started as a context manager. -- **Return value**: Must return a generator and `yield` exactly once. -- **Startup failure**: If any generator fails to start, the entire `running()` cannot start. -- **Unsupported form**: Do not return an object decorated with `@contextmanager` / `@asynccontextmanager`; the runtime treats it as an ordinary value. +| Return | Type | Description | +| --- | --- | --- | +| **Returns** | `AsyncIterator[None] \| Iterator[None] \| None` | Sync or async generator that yields once (do not wrap with `@contextmanager` / `@asynccontextmanager`) | + +- **Dispatch**: Run all; each generator is entered on startup and cleaned up in reverse order on exit. ### `provide_tape_sidecar` {#provide_tape_sidecar} @@ -343,9 +403,11 @@ Provides a Sidecar for each session Tape, used to store data or capabilities att def provide_tape_sidecar(self) -> TapeSidecar: ``` -- **Dispatch**: Run all; deduplicates by `name`, keeping the highest-priority result when names collide. -- **Storage name**: The Tape is physically stored under the name `
__sidecar__`. -- **Lifecycle**: It is forked, merged, archived, and reset together with the main Tape. Removing the hook that provides a Sidecar does not delete existing data. +| Return | Type | Description | +| --- | --- | --- | +| **Returns** | `TapeSidecar` | Sidecar paired with the main Tape (`
__sidecar__`) | + +- **Dispatch**: Run all; deduplicates by `name`, keeping the highest-priority implementation. ### `provide_channels` {#provide_channels} @@ -355,9 +417,12 @@ Provides channels for receiving messages. def provide_channels(self, message_handler: MessageHandler) -> list[Channel]: ``` -- **Dispatch**: Run all; deduplicates by `name`, keeping the highest-priority result when names collide. -- **`message_handler`**: An async function `(message) -> None`, called by the channel when a message arrives. -- **Return value**: Must return a list of channels, not a single channel. +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `message_handler` | `MessageHandler` | Async callback `async (message: Envelope) -> None` invoked by the channel on incoming messages | +| **Returns** | `list[Channel]` | List of `Channel` / `Lifecycle` instances | + +- **Dispatch**: Run all; deduplicates by `name`, keeping the highest-priority implementation. ### `build_tape_context` {#build_tape_context} @@ -367,8 +432,11 @@ Builds the Tape context for the current session, used to generate context messag def build_tape_context(self) -> TapeContext: ``` +| Return | Type | Description | +| --- | --- | --- | +| **Returns** | `TapeContext` | Context projection strategy (non-`TapeContext` values raise `TypeError`) | + - **Dispatch**: First result. -- **Return value**: Must be a `TapeContext`, otherwise a `TypeError` is raised. ### `admit_message` {#admit_message} @@ -383,9 +451,14 @@ def admit_message( ) -> AdmitDecision | None: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `session_id` | `str` | Target session ID | +| `message` | `Envelope` | Newly arrived inbound message | +| `turn` | `TurnSnapshot` | Snapshot of the active Turn for this session | +| **Returns** | `AdmitDecision \| None` | Admission decision (`None` falls back to the channel's default policy) | + - **Dispatch**: First result. -- **Returning `None`**: Handles the message according to the channel's default rules. -- **Scope**: It only decides how to handle the new message and does not create tasks; the actual effects are carried out by `ChannelManager`. When it returns an `AdmitDecision`, `ChannelManager` handles the new message according to `action`: @@ -396,8 +469,6 @@ When it returns an `AdmitDecision`, `ChannelManager` handles the new message acc | `follow_up` | Queues it; processes it in arrival order after the current Turn completes | Creates a Turn immediately | | `steer` | Sends the new message to the current Turn to steer the running task; if it cannot be injected or is not handled in time, it is queued instead | Creates a Turn immediately | -In short, `steer` means "adjust the current task to the new requirement", while `follow_up` means "handle the next message after the current task completes". - ### `provide_steering_inbox` {#provide_steering_inbox} Provides an inbox for holding `steer` messages temporarily; `MessagesPending` then delivers those messages to the Agent. @@ -406,9 +477,11 @@ Provides an inbox for holding `steer` messages temporarily; `MessagesPending` th def provide_steering_inbox(self) -> SteeringInbox | None: ``` -- **Dispatch**: First result; may return a generator. -- **When you need to clean up resources**: Return a generator and release the connection in `finally`. -- **Unsupported form**: Do not return an object decorated with `@contextmanager` / `@asynccontextmanager`; the runtime treats it as an ordinary value. +| Return | Type | Description | +| --- | --- | --- | +| **Returns** | `SteeringInbox \| None` | Steering inbox instance, or a single-`yield` generator (do not wrap with `@contextmanager`) | + +- **Dispatch**: First result. ### `provide_tools` {#provide_tools} @@ -418,8 +491,11 @@ Provides custom tools to the Agent. def provide_tools(self) -> list[Tool]: ``` -- **Dispatch**: Run all; deduplicates by `name`, keeping the highest-priority result when names collide. -- **Duplicate tool names**: A tool may be provided multiple times, but only the highest-priority implementation is used and the other tools with the same name are ignored. +| Return | Type | Description | +| --- | --- | --- | +| **Returns** | `list[Tool]` | List of custom `Tool` instances | + +- **Dispatch**: Run all; deduplicates by `name`, keeping the highest-priority implementation. ### When resources are created and released {#runtime-resources} @@ -465,10 +541,13 @@ Observes or modifies the request, or supplies the final text directly, before th def before_llm_call(self, request: LLMCallRequest, state: TurnState) -> LLMCallRequest | LLMCallDecision | None: ``` -- **Dispatch**: Sequential. When it returns a modified `LLMCallRequest`, later implementations see the new value. -- **Modifying the request**: Because this is a frozen dataclass, use `dataclasses.replace()` to create a modified copy. -- **Ending early**: `LLMCallDecision.finish(text)` skips the model provider and uses `text` directly as the model output; it does not trigger `after_llm_call` either. -- **Tool list**: `LLMCallRequest` only exposes tool names and cannot add or remove tools through it. To change the tool set, do it in `Agent.prepare_tools()` or in the application's tool policy. +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `request` | `LLMCallRequest` | Immutable request snapshot about to be sent to the model provider | +| `state` | `TurnState` | Shared Turn state dictionary | +| **Returns** | `LLMCallRequest \| LLMCallDecision \| None` | Return `dataclasses.replace(request, ...)` to modify request parameters, `LLMCallDecision.finish(text)` to skip the model call, or `None` to proceed unchanged | + +- **Dispatch**: Sequential. ### `after_llm_call` {#after_llm_call} @@ -478,9 +557,13 @@ Observes the final result of one model call. def after_llm_call(self, request: LLMCallRequest, result: LLMCallResult, state: TurnState) -> None: ``` -- **Dispatch**: Run all; return values are ignored. -- **When it is called**: Runs whether the call succeeds or fails with an ordinary exception. -- **When it does not run**: When the task is cancelled, the consumer closes the output stream on its own, or `before_llm_call` ends early via `finish(text)`. +| Parameter | Type | Description | +| --- | --- | --- | +| `request` | `LLMCallRequest` | Final request sent to the model provider | +| `result` | `LLMCallResult` | Aggregated model call result (text, tool calls, usage, error, duration) | +| `state` | `TurnState` | Shared Turn state dictionary | + +- **Dispatch**: Run all (runs on success or ordinary failure; skipped when cancelled, when the stream is closed early, or when `before_llm_call` finishes early). ### `before_tool_call` {#before_tool_call} @@ -490,10 +573,13 @@ Modifies arguments, directly replaces the result, or denies the call before the def before_tool_call(self, call: ToolCall, state: TurnState) -> ToolCallDecision | None: ``` +| Parameter / Return | Type | Description | +| --- | --- | --- | +| `call` | `ToolCall` | Tool call about to be executed | +| `state` | `TurnState` | Shared Turn state dictionary | +| **Returns** | `ToolCallDecision \| None` | Return `None` or `proceed(arguments)` to continue, `replace(result)` to skip the tool and supply a result, or `deny(message)` to reject the call | + - **Dispatch**: Sequential. -- **Continuing**: Return `None` or `ToolCallDecision.proceed(arguments)`; the latter can modify arguments, and later implementations see the new values. -- **Replacing the result**: `ToolCallDecision.replace(result)` skips the tool, uses the supplied result, and stops later interception implementations from running. -- **Denying the call**: `ToolCallDecision.deny(message)` skips the tool and returns a tool error, and also stops later interception implementations from running. ### `after_tool_call` {#after_tool_call} @@ -503,10 +589,13 @@ Observes the final result of one tool call, and can also modify the result the m def after_tool_call(self, call: ToolCall, result: ToolCallResult, state: TurnState) -> None: ``` -- **Dispatch**: Run all; all implementations share the same mutable result, and return values are ignored. -- **When it is called**: Runs whether the call succeeds, fails with an ordinary exception, is denied, or is replaced. -- **When it does not run**: When the task is cancelled or the consumer closes the output stream on its own. -- **Modifying the result**: Assigning to `result.result` changes the result the model sees; `result.error` still retains the original error. +| Parameter | Type | Description | +| --- | --- | --- | +| `call` | `ToolCall` | Executed tool call | +| `result` | `ToolCallResult` | Mutable tool result (assigning to `result.result` changes the output the model sees) | +| `state` | `TurnState` | Shared Turn state dictionary | + +- **Dispatch**: Run all (runs on success, failure, denial, or replacement; skipped only on cancellation or early stream closure). ### Interception payload definitions {#interception-payloads} @@ -526,6 +615,14 @@ class LLMCallRequest: max_tokens: int | None = None ``` +| Field | Type | Description | +| --- | --- | --- | +| `run_id` | `str` | Current Agent run ID | +| `model` | `str` | Target model identifier (`provider:model`) | +| `messages` | `list[republic.Message]` | Context messages about to be sent to the model | +| `tool_names` | `tuple[str, ...]` | Read-only tuple of tool names visible in this model call | +| `max_tokens` | `int \| None` | Maximum output tokens for this response | + #### `LLMCallResult` {#llmcallresult} The final result of one model call. For streaming calls, the complete result is aggregated first, and then `after_llm_call` is triggered. @@ -541,6 +638,15 @@ class LLMCallResult: duration_ms: int = 0 ``` +| Field | Type | Description | +| --- | --- | --- | +| `run_id` | `str` | Current Agent run ID | +| `text` | `str \| None` | Aggregated assistant text output | +| `tool_calls` | `list[dict[str, Any]]` | Tool calls requested by the model | +| `usage` | `dict[str, Any] \| None` | Token usage dictionary | +| `error` | `Exception \| None` | Exception raised during the call, or `None` on success | +| `duration_ms` | `int` | Elapsed call time in milliseconds | + #### `LLMCallDecision` {#llmcalldecision} The early-termination decision returned by `before_llm_call`, constructed with `LLMCallDecision.finish(text)`. @@ -550,8 +656,17 @@ The early-termination decision returned by `before_llm_call`, constructed with ` class LLMCallDecision: action: Literal["finish"] = "finish" text: str = "" + + @classmethod + def finish(cls, text: str) -> LLMCallDecision: ... ``` +| Field / Method | Type | Description | +| --- | --- | --- | +| `action` | `Literal["finish"]` | Decision action (`"finish"`) | +| `text` | `str` | Text used directly as the model output | +| `finish(text)` | `LLMCallDecision` | Skip the model provider call and finish with `text` | + #### `ToolCall` {#toolcall} A tool call about to be executed. `context` is the tool runtime's context; it is `None` when no context is available. @@ -565,6 +680,13 @@ class ToolCall: context: ToolContext | None = field(default=None, repr=False, compare=False) ``` +| Field | Type | Description | +| --- | --- | --- | +| `run_id` | `str` | Current Agent run ID | +| `tool` | `str` | Tool name | +| `arguments` | `dict[str, Any]` | Keyword arguments passed to the tool | +| `context` | `ToolContext \| None` | Tool execution context (`tape`, `run_id`, `state`, `call_id`) | + #### `ToolCallDecision` {#toolcalldecision} The handling decision returned by `before_tool_call`, constructed with `proceed()`, `replace()`, and `deny()` respectively. @@ -576,8 +698,27 @@ class ToolCallDecision: arguments: dict[str, Any] | None = None result: Any = None message: str | None = None + + @classmethod + def proceed(cls, arguments: dict[str, Any] | None = None) -> ToolCallDecision: ... + + @classmethod + def replace(cls, result: Any) -> ToolCallDecision: ... + + @classmethod + def deny(cls, message: str) -> ToolCallDecision: ... ``` +| Field / Method | Type | Description | +| --- | --- | --- | +| `action` | `Literal["proceed", "replace", "deny"]` | Decision action | +| `arguments` | `dict[str, Any] \| None` | Replacement argument dictionary when `action == "proceed"` | +| `result` | `Any` | Replacement tool output when `action == "replace"` | +| `message` | `str \| None` | Denial message when `action == "deny"` | +| `proceed(arguments=None)` | `ToolCallDecision` | Allow execution (optionally replacing arguments) | +| `replace(result)` | `ToolCallDecision` | Skip the tool function and return `result` directly | +| `deny(message)` | `ToolCallDecision` | Block execution and report `message` as a tool error | + #### `ToolCallResult` {#toolcallresult} The final result of one tool call. This dataclass is not `frozen=True`, so `after_tool_call` can assign directly to `result.result`. @@ -593,6 +734,15 @@ class ToolCallResult: duration_ms: int = 0 ``` +| Field | Type | Description | +| --- | --- | --- | +| `run_id` | `str` | Current Agent run ID | +| `tool` | `str` | Tool name | +| `arguments` | `dict[str, Any]` | Final arguments used for the call | +| `result` | `Any` | Tool output (mutable in `after_tool_call`) | +| `error` | `Exception \| None` | Exception raised or denial error, or `None` on success | +| `duration_ms` | `int` | Elapsed execution time in milliseconds | + ## App hooks and Agent events {#app-hooks} The concept page explains who intervenes in which direction; this section covers the adapter details. For the relationship between the three kinds of data and the decision semantics, see [Agent events](/docs/concepts/events/#three-kinds). @@ -629,26 +779,49 @@ A security policy written as a hook therefore cannot block a call by raising; it `PluginAgentHooks(runtime).subscribe(events)` attaches the four interception hooks to an existing or new event bus; `AgentPlugins.attach(agent)` subscribes automatically and also wires `continue_prompt`, the steering inbox, and the system prompt. For embedding and lifecycle requirements, see [Reusing Bub](/docs/integrations/reuse-app/#agent-loop-hooks). -### PluginAgentHooks {#pluginagenthooks} +## PluginAgentHooks {#pluginagenthooks} -`PluginAgentHooks` converts Agent events into the hooks above: +```python +class PluginAgentHooks: + def __init__(self, runtime: HookRuntime) -> None: ... -| Agent event | Corresponding hook | -| --- | --- | -| `LLMCallStarted` | `before_llm_call` | -| `LLMCallFinished` | `after_llm_call` | -| `ToolCallStarted` | `before_tool_call` | -| `ToolCallFinished` | `after_tool_call` | + def subscribe(self, events: EventBus | None = None) -> EventBus: ... -The difference between listening on the EventBus directly and using interception hooks is as follows: + async def before_llm_call( + self, + request: LLMCallRequest, + state: TurnState, + ) -> tuple[LLMCallRequest, LLMCallDecision | None]: ... -| Item | Interception hook | Direct EventBus handler | -| --- | --- | --- | -| Exception handling | Logged and skipped | Propagated to the `emit()` caller | -| Control | Returns a decision | Modifies event fields | -| Execution order | Determined by pluggy priority | Handler registration order | + async def after_llm_call( + self, + request: LLMCallRequest, + result: LLMCallResult, + state: TurnState, + ) -> None: ... -`PluginAgentHooks.subscribe(events)` attaches the adapter to an existing event bus, or creates a new one. `AgentPlugins.attach(agent)` subscribes automatically and connects `continue_prompt`, the steering inbox (`SteeringInbox`), and system prompts to the Agent. + async def before_tool_call( + self, + call: ToolCall, + state: TurnState, + ) -> tuple[ToolCall, ToolCallDecision]: ... + + async def after_tool_call( + self, + call: ToolCall, + result: ToolCallResult, + state: TurnState, + ) -> None: ... +``` + +| Method | Description | +| --- | --- | +| `__init__(runtime)` | Bind to a `HookRuntime` instance | +| `subscribe(events=None)` | Register the four interception hooks on `events` (or a new `EventBus`) and return the bus | +| `before_llm_call(request, state)` | Run `before_llm_call` hooks sequentially and return `(request, decision)` | +| `after_llm_call(request, result, state)` | Run all `after_llm_call` hooks | +| `before_tool_call(call, state)` | Run `before_tool_call` hooks sequentially and return `(call, decision)` | +| `after_tool_call(call, result, state)` | Run all `after_tool_call` hooks | ## AgentPlugins {#agentplugins} @@ -661,6 +834,12 @@ class AgentComponents(TypedDict, total=False): sidecars: Sequence[TapeSidecar] ``` +| Key | Type | Description | +| --- | --- | --- | +| `store` | `TapeStore \| AsyncTapeStore` | Store resolved from `provide_tape_store` (omitted when none is provided) | +| `context` | `TapeContext` | Context strategy resolved from `build_tape_context` | +| `sidecars` | `Sequence[TapeSidecar]` | Sidecars resolved from `provide_tape_sidecar` | + ### `AgentPlugins` {#agentplugins-class} ```python @@ -686,3 +865,12 @@ class AgentPlugins: agent: Agent | None = None, ) -> TurnState: ... ``` + +| Parameter / Method | Description | +| --- | --- | +| `framework` | Existing `BubFramework` to reuse (mutually exclusive with `plugins`; when both are omitted, installed entry-point plugins are loaded) | +| `plugins` | Explicit collection of plugin objects to register without loading other entry points | +| `running()` | Async context manager managing `provide_lifespan`, `provide_tape_store`, and `provide_steering_inbox` | +| `components()` | Return `AgentComponents` suitable for `Agent(**plugins.components())` | +| `attach(agent, *, tools=True)` | Wire interception hooks, `continue_prompt`, steering inbox, `system_prompt`, and plugin tools onto `agent` | +| `build_state(session_id, *, message=None, agent=None)` | Call `load_state` and populate runtime keys (`_session_id`, `_runtime_agent`, `_steering_inbox`) | diff --git a/website/src/content/docs/docs/reference/python-api.mdx b/website/src/content/docs/docs/reference/python-api.mdx index 75bfe4c6..6d72d3cc 100644 --- a/website/src/content/docs/docs/reference/python-api.mdx +++ b/website/src/content/docs/docs/reference/python-api.mdx @@ -1,196 +1,520 @@ --- title: Python API -description: Public types and entry-point signatures for bub.core and the application layer. +description: "Complete Bub Python API reference: public classes, function signatures, and parameter tables for bub.core (Agent, Tool, Tape) and the app layer." --- -Look up public interfaces by package. For usage, see the [SDK](/docs/sdk/), [Tape](/docs/concepts/tape/), [Events](/docs/concepts/events/), and [Turn](/docs/concepts/turn/). +This page lists the public Python classes and function signatures exposed by Bub, followed by tables explaining their parameters, fields, and methods. For step-by-step usage guides, see the [SDK guide](/docs/sdk/), [Tape](/docs/concepts/tape/), [Events](/docs/concepts/events/), and [Turn](/docs/concepts/turn/). -- **`bub.core`**: Agent loop, model adaptation, tools, Tape, and events. Does not read YAML / `BUB_*`. -- **Application layer**: `BubFramework`, `BubAgent`, channels, and configuration. Requires [installing](/docs/getting-started/install/) the `app` optional dependencies. +- **`bub.core`**: Core layer containing the `Agent` loop, model client protocols, tools, Tape, and the event bus. Importing only `bub.core` never reads YAML files or `BUB_*` environment variables and does not load the CLI or plugins. +- **`bub`**: Application layer containing `BubFramework`, `BubAgent`, channels, and configuration loading. Requires [installing](/docs/getting-started/install/) the `bub[app]` optional dependency. -`republic.…` names in signatures come from the external Republic dependency, not the Bub package; this page does not expand those types. +`republic.*` types appearing in signatures come from the underlying Republic library and are not expanded separately on this page. -```python -import bub.core as core -from bub import BubFramework -``` - -Importing only `bub.core` does not load the CLI, settings, or plugins. +--- ## Core {#core} -### Agent {#agent} +### `Agent` {#agent} ```python from bub.core import Agent -Agent( - *, - model=None, - store=None, - tools=(), - system_prompt=(), - context=None, - sidecars=(), - max_steps=sys.maxsize, - max_tool_concurrency=None, - name="agent", - command_prefix=None, -) +class Agent: + tools: dict[str, Tool] + builtin_tools: list[BuiltinTool] + system_prompt: SystemPrompt + events: EventBus + + def __init__( + self, + *, + model: Model | None = None, + store: TapeStore | AsyncTapeStore | None = None, + tools: Iterable[Tool | BuiltinTool] = (), + system_prompt: SystemPrompt | PromptSection | Iterable[PromptSection] = (), + context: TapeContext | None = None, + sidecars: Sequence[TapeSidecar] = (), + max_steps: int = sys.maxsize, + max_tool_concurrency: int | None = None, + name: str = "agent", + command_prefix: str | None = None, + ) -> None: ... + + def tape(self, name: str, *, state: TurnState | None = None) -> Tape: ... + + @asynccontextmanager + async def session( + self, + name: str, + *, + state: TurnState | None = None, + merge_back: bool = True, + ) -> AsyncGenerator[Tape]: ... + + @asynccontextmanager + async def run( + self, + prompt: str | list[UserContent], + *, + model: Model | None = None, + options: Mapping[str, Any] | None = None, + tape: str, + state: TurnState | None = None, + merge_back: bool = True, + metadata: dict[str, Any] | None = None, + ) -> AsyncGenerator[AsyncStreamEvents]: ... + + async def start( + self, + prompt: str | list[UserContent], + *, + model: Model | None = None, + options: Mapping[str, Any] | None = None, + tape: str, + state: TurnState | None = None, + merge_back: bool = True, + metadata: dict[str, Any] | None = None, + ) -> AsyncStreamEvents: ... + + async def run_on( + self, + tape: Tape, + prompt: list[UserContent], + *, + model: Model | None = None, + options: Mapping[str, Any] | None = None, + metadata: dict[str, Any] | None = None, + span: Span | None = None, + on_close: Callable[[], Awaitable[None]] | None = None, + ) -> AsyncStreamEvents: ... + + async def run_once( + self, + prompt: list[UserContent] | None, + *, + model: Model | None = None, + options: Mapping[str, Any] | None = None, + tape: Tape, + state: StreamState | None = None, + pending: Sequence[list[UserContent]] = (), + ) -> AsyncGenerator[StreamEvent, None]: ... + + async def run_command(self, tape: Tape, line: str) -> str: ... + + async def prepare_tools( + self, + tape: Tape, + prompt: list[UserContent] | None, + ) -> list[Tool]: ... ``` -| Parameter | Default | Description | -| --- | --- | --- | -| `model` | `None` | Default model: a Republic chat model (`republic.ChatModel`) or `ModelClient`; can also be supplied for each `run` | -| `store` | New `InMemoryTapeStore` | Synchronous `TapeStore` or `AsyncTapeStore` | -| `tools` | `()` | Initial `Tool` objects and provider-executed tools such as `republic.tools.WebSearch()`; later entries override earlier entries with the same name | -| `system_prompt` | `()` | Text, `PromptSection`, or `SystemPrompt`; rendered once per Run before the first model Step, then reused by later Steps | -| `context` | `default_tape_context()` | Strategy for selecting Tape entries as model messages | -| `sidecars` | `()` | Sidecars mounted with the Tape | -| `max_steps` | `sys.maxsize` | Maximum model Steps per Run | -| `max_tool_concurrency` | `None` | Tool concurrency limit within one model response; `1` executes tools sequentially | -| `name` | `"agent"` | Name of the Agent trace span | -| `command_prefix` | `None` | `None` disables commands; otherwise it must be non-empty and contain no whitespace, and once set it allows calling tools directly | - -`agent.tools` stores `Tool` objects by name, while `agent.builtin_tools` stores provider tools. `max_tool_concurrency` does not coordinate concurrency between different Runs; the host must do that. Construction attaches `TapeRecorder` to `events`. See [Run an Agent in Python](/docs/sdk/) for a complete example. - -Main entry points: +**Constructor parameters** (`Agent.__init__`): + +| Parameter | Type | Default | Description | +| --- | --- | --- | --- | +| `model` | `Model \| None` | `None` | Default model (`republic.ChatModel` or `ModelClient`); can also be passed per `run()` call | +| `store` | `TapeStore \| AsyncTapeStore \| None` | New `InMemoryTapeStore()` | Synchronous or asynchronous session history store | +| `tools` | `Iterable[Tool \| BuiltinTool]` | `()` | Local `Tool` objects (stored in `agent.tools`) and provider-executed tools such as `republic.tools.WebSearch()` (stored in `agent.builtin_tools`); later entries override earlier ones with the same name | +| `system_prompt` | `SystemPrompt \| PromptSection \| Iterable[PromptSection]` | `()` | System prompt; rendered once per Run before the first model Step and reused by later Steps | +| `context` | `TapeContext \| None` | `default_tape_context()` | Strategy for projecting Tape entries into model context messages | +| `sidecars` | `Sequence[TapeSidecar]` | `()` | Sibling `TapeSidecar` instances mounted alongside the main Tape | +| `max_steps` | `int` | `sys.maxsize` | Maximum model Steps per Run | +| `max_tool_concurrency` | `int \| None` | `None` | Maximum concurrent local tool calls within one model response (`1` runs tools sequentially; does not coordinate concurrency across separate Runs) | +| `name` | `str` | `"agent"` | Name used for the Agent's OpenTelemetry trace span | +| `command_prefix` | `str \| None` | `None` | Direct command prefix (`None` disables commands; when enabled, must be a non-empty string with no whitespace, such as `","`) | + +**Run parameters** (`Agent.run` / `Agent.start`): + +| Parameter | Type | Default | Description | +| --- | --- | --- | --- | +| `prompt` | `str \| list[UserContent]` | Required | User prompt text or multimodal content blocks for this Run | +| `model` | `Model \| None` | `self.model` | Model connection overriding the Agent's default model for this Run | +| `options` | `Mapping[str, Any] \| None` | `None` | Generation options passed to the underlying model call (`republic.ChatOptions`, such as `max_tokens` or `reasoning_effort`) | +| `tape` | `str` | Required | Name of the conversation Tape used by this Run | +| `state` | `TurnState \| None` | `None` | Request-scoped dictionary shared by tools and event handlers during this Run | +| `merge_back` | `bool` | `True` | Whether to merge entries recorded on the Run's Tape fork back into the main Tape when the stream closes (see [forks and merges](/docs/sdk/tape/#forks-and-merges)) | +| `metadata` | `dict[str, Any] \| None` | `None` | Run metadata emitted on `RunStarted`; never enters model context | + +**Methods**: | Method | Description | | --- | --- | -| `run(...)` / `start(...)` | Executes one Run on a named Tape; `run` closes the stream on exit, while `start` requires the caller to call `aclose()` | -| `tape(name, *, state=None)` | Reads and writes a Tape in storage directly | -| `session(name, *, state=None, merge_back=True)` | Opens a branch and merges it on exit | -| `run_on(tape, prompt, ...)` | Runs on an already opened Tape | -| `run_once(...)` | Executes only one model Step and its tool calls | -| `run_command(tape, line)` | Executes a command directly without calling the model | -| `prepare_tools(tape, prompt)` | Subclasses can override this to choose tools once per Run; later Steps reuse them, and calls outside the prepared set use a fresh `prepare_tools(tape, None)` lookup | +| `run(...)` | Async context manager: runs on a fork of the named Tape, automatically closing the stream and merging according to `merge_back` on exit | +| `start(...)` | Same parameters as `run(...)`, but returns `AsyncStreamEvents` directly; the caller must call `await stream.aclose()` | +| `tape(name, *, state=None)` | Returns a read-write `Tape` view for the given name without automatically writing an initial `session/start` anchor | +| `session(name, *, state=None, merge_back=True)` | Async context manager: opens a fork of the named Tape and merges it on exit according to `merge_back` | +| `run_on(tape, prompt, ...)` | Executes a Run on an already opened `Tape` instance | +| `run_once(...)` | Executes a single model Step and all tool calls requested by that response | +| `run_command(tape, line)` | Executes a direct command line without calling the model | +| `prepare_tools(tape, prompt)` | Overridable hook called once at the start of each Run to select active tools; calls outside the prepared set trigger a fresh `prepare_tools(tape, None)` lookup | -`run` / `start` share these parameters: `prompt`, `model`, `options` (external `republic.ChatOptions`), required `tape` name, `state`, `merge_back`, and `metadata`. See [forks and merges](/docs/sdk/tape/#forks-and-merges) for how a Run's Tape fork merges on close. +--- -### Model {#model} +### `Model`, `ModelClient`, and `ChatModelClient` {#model} ```python -from bub.core import Model, ModelClient, ChatModelClient +from bub.core import ChatModelClient, Model, ModelClient + +type Model = republic.ChatModel | ModelClient + +class ModelClient(Protocol): + max_tokens: int | None + + @property + def spec(self) -> str: ... + + def open_stream( + self, + messages: list[republic.Message], + *, + spec: str, + options: Mapping[str, Any], + ) -> AbstractAsyncContextManager[tuple[str, republic.Stream[Any]]]: ... + +class ChatModelClient: + max_tokens: int | None = None + + def __init__(self, model: republic.ChatModel) -> None: ... + + @property + def spec(self) -> str: ... + + @asynccontextmanager + async def open_stream( + self, + messages: list[republic.Message], + *, + spec: str, + options: Mapping[str, Any], + ) -> AsyncIterator[tuple[str, republic.Stream[Any]]]: ... ``` -| Name | Description | -| --- | --- | -| `Model` | `republic.ChatModel \| ModelClient` | -| `ModelClient` | Bub protocol: `spec`, `max_tokens`, `open_stream(...)` | -| `ChatModelClient` | Adapts `republic.ChatModel` to `ModelClient`; the caller owns the model lifecycle | +| Member / Parameter | Type | Description | +| --- | --- | --- | +| `spec` | `str` | Model identifier string (`provider:model`) | +| `max_tokens` | `int \| None` | Default maximum output tokens; overridden by call-level `options["max_tokens"]` | +| `open_stream(messages, *, spec, options)` | Async context manager | Opens a streaming model call and yields `(resolved_spec, republic_stream)` | +| `ChatModelClient(model)` | `republic.ChatModel` | Adapts a `republic.ChatModel` to `ModelClient`; the caller still owns the underlying model lifecycle | + +--- -### Tools {#tools} +### `Tool`, `ToolContext`, and `@tool` {#tools} ```python from bub.core import Tool, ToolContext, tool +from bub.core.tools import ToolExposure, content_result, result_content + +type ToolExposure = Literal["auto", "direct", "code", "command"] + +@dataclass(frozen=True) +class ToolContext: + tape: Tape + run_id: str | None = None + state: dict[str, Any] = field(default_factory=dict) + code_mode: bool = False + command: bool = False + events: EventBus | None = field(default=None, repr=False, compare=False) + step_messages: list[republic.Message] = field(default_factory=list, repr=False, compare=False) + call_id: str | None = None + +@dataclass(frozen=True) +class Tool: + name: str + handler: Callable[..., Any] + description: str = "" + parameters: dict[str, Any] = field(default_factory=dict) + context: bool = False + exposure: ToolExposure = "auto" + renderer: Callable[[Any], str] | None = None + output_schema: dict[str, Any] | None = None + deferred: bool = False + + async def run(self, *args: Any, **kwargs: Any) -> Any: ... + def render(self, result: Any) -> str: ... + def to_schema(self) -> dict[str, Any]: ... + + @classmethod + def from_callable( + cls, + func: Callable[..., Any], + *, + name: str | None = None, + description: str | None = None, + context: bool = False, + exposure: ToolExposure = "auto", + renderer: Callable[[Any], str] | None = None, + deferred: bool = False, + ) -> Tool: ... + +def tool( + func: Callable | None = None, + *, + name: str | None = None, + model: type[BaseModel] | None = None, + description: str | None = None, + context: bool = False, + exposure: ToolExposure = "auto", + renderer: Callable[[Any], str] | None = None, + deferred: bool = False, +) -> Tool | Callable[[Callable], Tool]: ... + +def content_result(content: Sequence[UserContent]) -> dict[str, Any]: ... +def result_content(result: Any) -> list[UserContent]: ... ``` -`Tool` fields: `name`, `handler`, `description`, `parameters`, `context`, `exposure` (`auto` / `direct` / `code` / `command`), `renderer`, `output_schema`, and `deferred`. +**`@tool` / `Tool` parameters and fields**: -`@tool` / `tool(...)` constructs a `Tool` from a callable; `@tool(model=...)` uses a Pydantic parameter model. The decorator does not register globally; provide tools through `Agent(tools=[...])` or `provide_tools`. `ToolContext` contains `tape`, `run_id`, `state`, `code_mode`, `command`, `events`, `step_messages` (the user messages the calling model step sent, which the Tape records only after its tool calls finish), and `call_id` (the model's ID of the call; calls from code mode share the `run_code` call's ID). +| Parameter / Field | Type | Default | Description | +| --- | --- | --- | --- | +| `func` / `handler` | `Callable[..., Any]` | Required | Synchronous or asynchronous Python callable implementing the tool | +| `name` | `str \| None` | `func.__name__` | Tool name (dots are converted to underscores in model-facing schemas) | +| `model` | `type[BaseModel] \| None` | `None` | Optional Pydantic parameter model (used with `@tool(model=...)`) | +| `description` | `str \| None` | Function docstring | Description shown to the model | +| `parameters` | `dict[str, Any]` | Derived from type annotations | JSON Schema dictionary of the tool's input parameters | +| `context` | `bool` | `False` | When `True`, Bub injects `context: ToolContext` as a keyword argument (excluded from the model-facing schema) | +| `exposure` | `ToolExposure` | `"auto"` | Where the tool is callable: `"auto"` (model, code mode, and commands), `"direct"` (model only), `"code"` (`run_code` only), or `"command"` (text commands only) | +| `renderer` | `Callable[[Any], str] \| None` | `None` | Custom serializer converting the tool return value to a string | +| `output_schema` | `dict[str, Any] \| None` | Derived from return annotation | Output JSON Schema used when generating code mode type stubs | +| `deferred` | `bool` | `False` | When `True`, only the tool name and description are shown initially; the model loads the full schema on demand via `tool.describe` | -```python -from bub.core.tools import content_result, result_content -``` +**`ToolContext` fields**: + +| Field | Type | Description | +| --- | --- | --- | +| `tape` | `Tape` | Read-write `Tape` view for the current session | +| `run_id` | `str \| None` | Unique identifier of the current Run | +| `state` | `dict[str, Any]` | Request-scoped `TurnState` dictionary | +| `code_mode` | `bool` | Whether the call originated inside code mode (`run_code`) | +| `command` | `bool` | Whether the call originated from a direct command | +| `events` | `EventBus \| None` | The Agent's `EventBus` | +| `step_messages` | `list[republic.Message]` | User messages sent by the calling model Step (recorded onto the Tape after the Step's tool calls finish) | +| `call_id` | `str \| None` | Call ID assigned by the model (calls inside code mode share the outer `run_code` call's ID) | -`content_result(content)` constructs a tool result containing text and media, and `result_content(result)` converts it back into model content. Ordinary results are converted to text by `Tool.render()`. See [Custom tools and code mode](/docs/sdk/tools/) for usage, and [media](/docs/sdk/tape/#media) for how such results are recorded on the Tape. +Use `content_result(content)` to return text together with images, audio, or video from a tool; `result_content(result)` reconstructs the multimodal content blocks during context projection (see [Media storage boundaries](/docs/sdk/tape/#media)). -### System prompt {#system-prompt} +--- + +### `SystemPrompt`, `PromptSection`, and `PromptContext` {#system-prompt} ```python -from bub.core import SystemPrompt, PromptSection, PromptContext +from bub.core import PromptContext, PromptSection, SystemPrompt + +@dataclass(frozen=True) +class PromptContext: + agent: Agent + tape: Tape + prompt: list[UserContent] + tools: list[Tool] + model: str + + @property + def state(self) -> TurnState: ... + + @property + def available_tools(self) -> list[Tool]: ... + +type PromptSection = str | Callable[[PromptContext], str | Awaitable[str | None] | None] + +class SystemPrompt: + def __init__(self, sections: Iterable[PromptSection] = ()) -> None: ... + + @classmethod + def of( + cls, + value: SystemPrompt | PromptSection | Iterable[PromptSection], + ) -> SystemPrompt: ... + + @property + def sections(self) -> tuple[PromptSection, ...]: ... + + def add(self, section: S) -> S: ... + def remove(self, section: PromptSection) -> None: ... + async def render(self, context: PromptContext) -> str: ... ``` -- `PromptSection`: Fixed text, or `(PromptContext) -> str | None` (may be async) -- `SystemPrompt`: Ordered sections; `add` / `remove` / `render` -- `PromptContext`: Current Run's `agent`, `tape`, `prompt`, `tools`, and `model` +| Class / Member | Description | +| --- | --- | +| `PromptSection` | Fixed string, or a sync/async callable `(PromptContext) -> str \| None` | +| `SystemPrompt.add(section)` / `remove(section)` | Add or remove a prompt section in order | +| `await SystemPrompt.render(context)` | Evaluates all sections and joins non-empty results with newlines | +| `PromptContext` | Context passed during rendering, exposing `agent`, `tape`, `prompt`, `tools`, `model`, `state`, and `available_tools` | + +--- -### Prompt content {#prompt} +### `bub.prompt` {#prompt} ```python -from bub.prompt import UserContent +from bub.prompt import LegacyPrompt, UserContent, prompt_text, to_content, to_legacy_prompt + +type UserContent = str | republic.Image | republic.Audio | republic.Video +type LegacyPrompt = str | list[dict[str, Any]] + +def to_content(prompt: list[UserContent] | LegacyPrompt) -> list[UserContent]: ... +def to_legacy_prompt(content: list[UserContent]) -> LegacyPrompt: ... +def prompt_text(content: list[UserContent]) -> str: ... ``` -`UserContent` is a Bub-defined alias for text or media. See the [prompt contract](/docs/reference/hooks/#prompt-content) for media forms and conversion to legacy hook inputs. +| Type / Function | Description | +| --- | --- | +| `UserContent` | Single user input block: plain text or a Republic media object | +| `LegacyPrompt` | Legacy hook prompt format (`str` when text-only, or a list of content-block dicts when media is present; see [prompt content](/docs/reference/hooks/#prompt-content)) | +| `to_content(prompt)` | Normalizes a string, content-block list, or `list[UserContent]` into `list[UserContent]` | +| `to_legacy_prompt(content)` | Converts `list[UserContent]` back into `LegacyPrompt` | +| `prompt_text(content)` | Extracts and joins the plain-text portions of `list[UserContent]` | + +--- -### Tape and store {#tape} +### `Tape`, `TapeContext`, and Stores {#tape} ```python from bub.core import Tape, TapeContext, default_tape_context, session_tape_name -from bub.core.store import ( - AsyncTapeStore, - AsyncTapeStoreAdapter, - FileTapeStore, - InMemoryQueryMixin, - InMemoryTapeStore, - TapeQuery, - TapeStore, - is_async_tape_store, -) from bub.core.tape import AnchorSummary, TapeEntry, TapeInfo -``` -A `Tape` is a read-write view of a named Tape, made of three parts: `store` (`AsyncTapeStore`, which persists entries), `context` (`TapeContext`, which decides the entries `read_messages()` selects), and `sidecars` (sibling tapes mounted on the Tape). When constructing one directly, bind a name with `scoped(name)` first: +@dataclass(frozen=True) +class TapeContext: + anchor: AnchorSelector = LAST_ANCHOR + select: ContextSelector | None = None + state: dict[str, Any] = field(default_factory=dict) + + def build_query(self, query: TapeQuery) -> TapeQuery: ... + +def default_tape_context() -> TapeContext: ... +def session_tape_name(session_id: str, workspace: Path) -> str: ... + +@dataclass(frozen=True) +class TapeInfo: + name: str + entries: int + anchors: int + last_anchor: str | None + entries_since_last_anchor: int + last_token_usage: int | None + last_token_cache_hit_rate: float | None + +@dataclass(frozen=True) +class AnchorSummary: + name: str + state: dict[str, object] + +@dataclass(frozen=True) +class Tape: + store: AsyncTapeStore + context: TapeContext + sidecars: tuple[TapeSidecar, ...] = field(default=(), repr=False) -```python -tape = Tape( - store=AsyncTapeStoreAdapter(InMemoryTapeStore()), - context=default_tape_context(), -).scoped("demo") + @property + def name(self) -> str: ... + + def with_context(self, context: TapeContext) -> Tape: ... + def scoped(self, name: str, context: TapeContext | None = None) -> Tape: ... + def query(self) -> TapeQuery[AsyncTapeStore]: ... + async def info(self) -> TapeInfo: ... + async def anchors(self, limit: int = 20) -> list[AnchorSummary]: ... + async def search(self, query: TapeQuery[AsyncTapeStore]) -> list[TapeEntry]: ... + async def append_event(self, name: str, payload: dict[str, Any], **meta: Any) -> None: ... + async def read_messages(self) -> list[republic.Message]: ... + + async def handoff( + self, + *, + name: str, + state: dict[str, Any] | None = None, + **meta: Any, + ) -> list[TapeEntry]: ... + + async def reset( + self, + *, + state: dict[str, Any] | None = None, + keep_sidecars: Iterable[str] = (), + ) -> None: ... + + @asynccontextmanager + async def fork_tape(self, merge_back: bool = True) -> AsyncGenerator[Tape, None]: ... ``` -| Member | Description | +**`TapeContext` fields**: + +| Field | Type | Default | Description | +| --- | --- | --- | --- | +| `anchor` | `AnchorSelector` | `LAST_ANCHOR` | Anchor filter: read entries after the latest anchor (`LAST_ANCHOR`), after a named anchor string, or pass `None` to disable anchor filtering | +| `select` | `ContextSelector \| None` | `None` | Custom projection selector `(Iterable[TapeEntry], TapeContext) -> list[republic.Message]`. Use `default_tape_context()` to replay full multi-turn conversations and tool round-trips | +| `state` | `dict[str, Any]` | `{}` | Request-scoped `TurnState` dictionary bound to this context | + +**`Tape` properties and methods**: + +| Property / Method | Description | | --- | --- | -| `name` | The Tape's name; accessing it before `scoped` raises `ValueError` | +| `name` | The Tape's bound name; accessing it before calling `scoped(name)` raises `ValueError` | +| `scoped(name, context=None)` | Returns a new `Tape` bound to `name` (and an optional replacement `context`) | +| `with_context(context)` | Returns a new `Tape` with a replaced `TapeContext` | | `query()` | Returns a `TapeQuery` bound to this Tape and store | -| `read_messages()` | Selects entries with `TapeContext` and converts them to model messages; entries with `meta["context"] is False` are skipped | -| `handoff(name=..., state=...)` | Writes an `anchor` and a `handoff` event, moving the default context start forward | -| `reset(*, state=None, keep_sidecars=())` | Clears the Tape and writes a new `session/start` anchor; mounted sidecars are reset too by default | -| `info()` / `anchors(limit=20)` | Return `TapeInfo` (entry count, anchor count, latest token usage, and more) and a list of `AnchorSummary(name, state)` | -| `search(query)` | Runs the given `TapeQuery` and returns matching entries | -| `append_event(name, payload, **meta)` | Appends an `event` entry | -| `scoped(name)` / `with_context(context)` | Returns a new `Tape` with a bound name or a replaced context | -| `fork_tape(merge_back=True)` | Async context manager: read and write on a fork, merged back into the main Tape on exit by default | +| `await read_messages()` | Selects entries through `TapeContext` and projects them into `list[republic.Message]` (skipping entries with `meta["context"] is False`) | +| `await handoff(*, name, state=None, **meta)` | Appends an `anchor` entry and a `handoff` event, moving the default context start forward | +| `await reset(*, state=None, keep_sidecars=())` | Clears the Tape and writes a new `session/start` anchor; resets mounted sidecars by default | +| `await info()` / `await anchors(limit=20)` | Returns `TapeInfo` statistics or a list of `AnchorSummary(name, state)` | +| `await search(query)` | Runs the given `TapeQuery` and returns matching entries | +| `await append_event(name, payload, **meta)` | Appends an `event` entry to the Tape | +| `fork_tape(merge_back=True)` | Async context manager: reads and writes on a fork, merging back into the main Tape on exit by default | -`TapeContext`: `anchor`, `select`, and `state`. Use `default_tape_context()` to replay the complete conversation; a direct `TapeContext()` replays only ordinary `message` entries. - -`session_tape_name(session_id, workspace)` returns a physical Tape name of the form `__`, which the framework uses to map one session to one Tape; SDK callers may also use their own names. +`session_tape_name(session_id, workspace)` returns a physical Tape name of the form `__`. #### `TapeSidecar` {#tapesidecar} ```python from bub.core.sidecars import TapeSidecar, sidecar_tape_name -``` -```python class TapeSidecar(Protocol): @property def name(self) -> str: ... - def sidecar_tape_name(owner: str, sidecar: str) -> str: ... ``` -A sidecar is backed by the sibling Tape `__sidecar__`: it forks, merges, and resets with the main Tape, and its entries never enter the main context. Mounting is covered in [Sidecars](/docs/sdk/tape/#sidecars); the application-level provider is [`provide_tape_sidecar`](/docs/reference/hooks/#provide_tape_sidecar). +A sidecar is backed by the sibling Tape `__sidecar__`: it forks, merges, and resets with the main Tape, and its entries never enter the main context. See [Sidecars](/docs/sdk/tape/#sidecars) and [`provide_tape_sidecar`](/docs/reference/hooks/#provide_tape_sidecar). #### `TapeEntry` {#tapeentry} -The entry type accepted by `append(tape, entry)`: +```python +@dataclass(frozen=True) +class TapeEntry: + id: int + kind: str + payload: dict[str, Any] + meta: dict[str, Any] = field(default_factory=dict) + date: str = field(default_factory=utc_now) + + def copy(self) -> TapeEntry: ... + + @classmethod + def message(cls, message: dict[str, Any], **meta: Any) -> TapeEntry: ... + @classmethod + def system(cls, content: str, **meta: Any) -> TapeEntry: ... + @classmethod + def anchor(cls, name: str, state: dict[str, Any] | None = None, **meta: Any) -> TapeEntry: ... + @classmethod + def tool_call(cls, calls: list[dict[str, Any]], *, content: str = "", **meta: Any) -> TapeEntry: ... + @classmethod + def tool_result(cls, results: list[Any], **meta: Any) -> TapeEntry: ... + @classmethod + def error(cls, error: BubError, **meta: Any) -> TapeEntry: ... + @classmethod + def event(cls, name: str, data: dict[str, Any] | None = None, **meta: Any) -> TapeEntry: ... +``` | Field | Type | Description | | --- | --- | --- | -| `id` | `int` | Sequential ID assigned by the store; new entries carry `0` and are rewritten on `append` | -| `kind` | `str` | Common values: `message`, `system`, `anchor`, `tool_call`, `tool_result`, `error`, `event` | -| `payload` | `dict[str, Any]` | Entry content | -| `meta` | `dict[str, Any]` | Run metadata; `context=False` keeps the entry out of the model context | -| `date` | `str` | ISO time, defaulting to the current UTC time | +| `id` | `int` | Sequential ID assigned by the store (new entries start at `0` and are rewritten on `append`) | +| `kind` | `str` | Entry kind: `message`, `system`, `anchor`, `tool_call`, `tool_result`, `error`, or `event` | +| `payload` | `dict[str, Any]` | Entry payload dictionary | +| `meta` | `dict[str, Any]` | Run metadata; setting `context=False` keeps the entry out of model context | +| `date` | `str` | ISO 8601 timestamp string, defaulting to current UTC time | -Factories: `TapeEntry.message(...)`, `system(content)`, `anchor(name, state=None)`, `tool_call(calls, content="")`, `tool_result(results)`, `error(error)`, and `event(name, data=None)`. Writing through a `Tape` usually means you do not need to construct entries yourself. - -#### Store protocols {#tape-store} +#### `TapeStore` and `AsyncTapeStore` {#tape-store} ```python +from bub.core.store import AsyncTapeStore, TapeStore, is_async_tape_store + class TapeStore(Protocol): def list_tapes(self) -> list[str]: ... def reset(self, tape: str) -> None: ... @@ -202,107 +526,363 @@ class AsyncTapeStore(Protocol): async def reset(self, tape: str) -> None: ... async def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ... async def append(self, tape: str, entry: TapeEntry) -> None: ... + +def is_async_tape_store(store: TapeStore | AsyncTapeStore) -> TypeIs[AsyncTapeStore]: ... ``` | Method | Contract | | --- | --- | -| `list_tapes()` | Returns existing Tape names; internal physical tapes such as sidecars need not be listed | -| `append(tape, entry)` | Appends an entry and assigns an `id` starting at `1` and increasing monotonically within that Tape; do not rely on the caller's `entry.id` | -| `fetch_all(query)` | Returns entries matching `TapeQuery` in recording order; the async version is still `async def` returning `Iterable`, not an async iterator | -| `reset(tape)` | Deletes the Tape's records and ID progression, so the next `append` starts again at `1` | - -`Agent(store=...)` accepts both synchronous and asynchronous implementations; synchronous ones are called through `AsyncTapeStoreAdapter` with `asyncio.to_thread()` to avoid blocking the event loop. `is_async_tape_store(store)` detects the type by checking whether `append` is a coroutine function. Database connections and transactions remain the implementation's responsibility. +| `list_tapes()` | Returns existing session Tape names (internal physical tapes such as sidecars need not be listed) | +| `append(tape, entry)` | Appends an entry and assigns an `id` starting at `1` and increasing monotonically within that Tape | +| `fetch_all(query)` | Returns entries matching `TapeQuery` in recording order (the async version is `async def` returning `Iterable`, not an async generator) | +| `reset(tape)` | Clears the Tape's records and resets its ID counter so the next `append` starts at `1` | #### `TapeQuery` {#tapequery} -`TapeQuery(tape, store)` is an immutable chain of filters; each method returns a new object and `all()` executes the query: +```python +@dataclass(frozen=True) +class TapeQuery[T: TapeStore | AsyncTapeStore]: + tape: str + store: T + + def query(self, value: str) -> Self: ... + def after_anchor(self, name: str) -> Self: ... + def last_anchor(self) -> Self: ... + def between_anchors(self, start: str, end: str) -> Self: ... + def between_dates(self, start: str | date_type, end: str | date_type) -> Self: ... + def kinds(self, *kinds: str) -> Self: ... + def limit(self, value: int) -> Self: ... + + @overload + def all(self: TapeQuery[TapeStore]) -> Iterable[TapeEntry]: ... + @overload + async def all(self: TapeQuery[AsyncTapeStore]) -> Iterable[TapeEntry]: ... +``` -| Method | Filter | +| Method | Filter semantics | | --- | --- | -| `query(value)` | Case-insensitive containment in the JSON text of entry kind, date, payload, and meta | -| `after_anchor(name)` / `last_anchor()` | After the named or latest anchor | -| `between_anchors(start, end)` | Between two anchors, excluding the boundaries | -| `between_dates(start, end)` | ISO date or time range, including the boundaries; a date-only bound covers the whole day | -| `kinds(*kinds)` | Specified entry kinds | -| `limit(value)` | Maximum number of entries; applied after the other filters | +| `query(value)` | Case-insensitive substring match against the JSON text of entry `kind`, `date`, `payload`, and `meta` | +| `after_anchor(name)` / `last_anchor()` | Entries strictly after the named or latest anchor (excluding the boundary anchor itself); raises `BubError(kind=NOT_FOUND)` if missing | +| `between_anchors(start, end)` | Entries between two anchors, excluding both boundaries; raises `BubError(kind=NOT_FOUND)` if either is missing | +| `between_dates(start, end)` | Inclusive ISO date or time range; a date-only upper bound covers the full day | +| `kinds(*kinds)` | Entries matching the specified kinds | +| `limit(value)` | Maximum number of entries returned (applied after all other filters) | +| `all()` | Executes the query (returns `Iterable` for sync stores; must be awaited for async stores) | -Multiple conditions are combined with AND. A query for a missing anchor fails with `BubError(kind=NOT_FOUND)`; a malformed date fails with `INVALID_INPUT`. +#### Built-in Stores {#builtin-stores} -`after_anchor` and `last_anchor` return entries after the named or latest anchor, excluding the boundary anchor itself. A missing anchor raises `BubError(kind=NOT_FOUND)`. The default query therefore does not pass the boundary anchor to the projection. When reading without anchor filtering, such as with `anchor=None`, the selector can receive anchor entries; the default selector converts any anchor it receives into an `[Anchor created: …]` assistant message. A raw `TapeQuery` does not apply `TapeContext`'s `context=False` filter. +```python +from bub.core.store import ( + AsyncTapeStoreAdapter, + FileTapeStore, + InMemoryQueryMixin, + InMemoryTapeStore, +) -For a synchronous store, `all()` returns an `Iterable` directly; for an asynchronous store, await it. A query from `Tape.query()` is always bound to an `AsyncTapeStore`: +class InMemoryQueryMixin: + def read(self, tape: str) -> list[TapeEntry] | None: ... + def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ... -```python -query = tape.query().query("error").kinds("event", "error").limit(20) -entries = list(await query.all()) -``` +class InMemoryTapeStore(InMemoryQueryMixin): + def __init__(self) -> None: ... + def list_tapes(self) -> list[str]: ... + def reset(self, tape: str) -> None: ... + def read(self, tape: str) -> list[TapeEntry] | None: ... + def append(self, tape: str, entry: TapeEntry) -> None: ... -`InMemoryQueryMixin` can provide the filters above for simple backends that implement only `read(tape) -> list[TapeEntry] | None`; database backends should usually push filtering down into the query itself. +class FileTapeStore(InMemoryQueryMixin): + def __init__(self, directory: Path) -> None: ... + def list_tapes(self) -> list[str]: ... + def reset(self, tape: str) -> None: ... + def append(self, tape: str, entry: TapeEntry) -> None: ... + def read(self, tape: str) -> list[TapeEntry] | None: ... -#### Built-in stores {#builtin-stores} +class AsyncTapeStoreAdapter: + def __init__(self, store: TapeStore) -> None: ... + async def list_tapes(self) -> list[str]: ... + async def reset(self, tape: str) -> None: ... + async def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ... + async def append(self, tape: str, entry: TapeEntry) -> None: ... +``` -| Class | Constructor | Behavior | -| --- | --- | --- | -| `InMemoryTapeStore` | `InMemoryTapeStore()` | In-process dictionary; `read()` returns copies of entries; lost when the process exits | -| `FileTapeStore` | `FileTapeStore(directory: Path)` | One `.jsonl` per Tape; creates the directory in the constructor; one thread lock per file; `list_tapes()` returns only files whose name contains exactly one `__` (framework session names), excluding sidecars and unqualified names; no cross-process lock | -| `AsyncTapeStoreAdapter` | `AsyncTapeStoreAdapter(store)` | Adapts a synchronous `TapeStore` to `AsyncTapeStore` | -| `InMemoryQueryMixin` | Mixin | Provides in-memory filtering for a store that implements only `read()` | +| Class | Description | +| --- | --- | +| `InMemoryTapeStore` | In-process dictionary; `read()` returns copies of entries; cleared when the process exits | +| `FileTapeStore(directory)` | One `.jsonl` file per Tape with a per-file thread lock (no cross-process lock); `list_tapes()` returns only files containing exactly one `__`. Validate user-supplied Tape names before use (see [Tape and memory](/docs/sdk/tape/#storage)) | +| `AsyncTapeStoreAdapter(store)` | Wraps a synchronous `TapeStore` with `asyncio.to_thread()` to satisfy `AsyncTapeStore` | +| `InMemoryQueryMixin` | Provides in-memory `fetch_all(query)` filtering for stores that implement `read(tape)` | -`FileTapeStore` uses the Tape name directly as a file name, so names must be safe as paths; multi-tenant or web services should use controlled identifiers. See [Tape and memory](/docs/sdk/tape/#storage). +--- -### `EventBus` {#events} +### `EventBus` and Event Classes {#events} ```python -from bub.core import EventBus, ToolCallStarted, ToolCallFinished -``` +from bub.core.events import ( + AgentEvent, + ChatFinished, + CommandFinished, + Event, + EventBus, + LLMCallFinished, + LLMCallStarted, + MessagesPending, + RunFinished, + RunStarted, + StepFinished, + StepStarted, + TapeEvent, + ToolCallFinished, + ToolCallStarted, +) + +class Event: + @property + def stopped(self) -> bool: ... + +class EventBus: + @overload + def on(self, event_type: type[E]) -> Callable[[EventHandler[E]], EventHandler[E]]: ... + @overload + def on(self, event_type: type[E], handler: EventHandler[E]) -> EventHandler[E]: ... + + def off(self, event_type: type[E], handler: EventHandler[E]) -> None: ... + async def emit(self, event: E) -> E: ... + +@dataclass(kw_only=True) +class AgentEvent(Event): + state: TurnState + +@dataclass(kw_only=True) +class TapeEvent(AgentEvent): + tape: Tape + +@dataclass(kw_only=True) +class RunStarted(TapeEvent): + model: str + prompt: list[UserContent] + metadata: dict[str, Any] = field(default_factory=dict) + +@dataclass(kw_only=True) +class RunFinished(TapeEvent): + status: str + steps: int + elapsed_ms: int + error: str | None = None + +@dataclass(kw_only=True) +class StepStarted(TapeEvent): + step: int + prompt: list[UserContent] | None + +@dataclass(kw_only=True) +class StepFinished(TapeEvent): + step: int + status: str + elapsed_ms: int + error: str | None = None + prompt: list[UserContent] | None = None + stream: StreamState = field(default_factory=StreamState) + next_prompt: list[UserContent] | None = None + +@dataclass(kw_only=True) +class MessagesPending(TapeEvent): + prompt: list[UserContent] | None + messages: list[list[UserContent]] = field(default_factory=list) + +@dataclass(kw_only=True) +class CommandFinished(TapeEvent): + line: str + name: str + status: str + elapsed_ms: int + output: str + +@dataclass(kw_only=True) +class LLMCallStarted(TapeEvent): + request: LLMCallRequest + decision: LLMCallDecision | None = None + + @property + def stopped(self) -> bool: ... + +@dataclass(kw_only=True) +class LLMCallFinished(TapeEvent): + request: LLMCallRequest + result: LLMCallResult + +@dataclass(kw_only=True) +class ToolCallStarted(AgentEvent): + call: ToolCall + decision: ToolCallDecision = field(default_factory=lambda: ToolCallDecision.proceed()) -`EventBus`: `on` / `off` / `emit`. Public event types include `RunStarted` / `RunFinished`, `StepStarted` / `StepFinished`, `LLMCallStarted` / `LLMCallFinished`, `ToolCallStarted` / `ToolCallFinished`, `MessagesPending`, `ChatFinished`, `CommandFinished`, and others. + @property + def stopped(self) -> bool: ... + +@dataclass(kw_only=True) +class ToolCallFinished(AgentEvent): + call: ToolCall + result: ToolCallResult + +@dataclass(kw_only=True) +class ChatFinished(TapeEvent): + run_id: str + model: str + system_prompt: str | None + new_messages: list[republic.Message] + response_text: str | None + tool_calls: list[dict[str, Any]] = field(default_factory=list) + tool_results: list[Any] | None = None + usage: dict[str, Any] | None = None + provider: str | None = None + assistant_fields: dict[str, Any] = field(default_factory=dict) + error: BubError | None = None + context_error: BubError | None = None +``` -### Events at a glance {#event-reference} +#### Events at a glance {#event-reference} | Event | When it fires | What a handler can read or change | | --- | --- | --- | -| `RunStarted` | A model Run begins | `model`, `prompt`, `metadata` | -| `RunFinished` | The Run's stream closes | `status` (`ok` / `error` / `cancelled`), `steps`, elapsed time, error | +| `RunStarted` | A model Run begins | `model`, `prompt`, `metadata`, `tape`, `state` | +| `RunFinished` | The Run's stream closes | `status` (`ok` / `error` / `cancelled`), `steps`, `elapsed_ms`, `error` | | `StepStarted` | A Step begins | `step`, optional `prompt` | -| `StepFinished` | A Step ends | Progress, usage; set `next_prompt` when continuing | -| `MessagesPending` | While a request is built, or when a Step ends without tool calls (`step_ended=True`) | Append user content to `messages`; at a Step end, messages continue the Run | -| `LLMCallStarted` | Before calling the provider | Replace `request`; set `LLMCallDecision.finish()` | -| `LLMCallFinished` | After success or an ordinary provider failure | `request` and the aggregated `result` | -| `ToolCallStarted` | Before a tool runs | Replace `call`; set `deny` or `replace` | -| `ToolCallFinished` | Tool success, ordinary failure, denial, or replacement | Assign `event.result.result` to change the model-facing result | -| `ChatFinished` | When a Step's exchange can be recorded | Messages, tool round-trips, usage, errors | -| `CommandFinished` | A direct command succeeds or fails | Command, status, output | - -`RunFinished` fires when the stream closes; a Run closed before iterating ends as `cancelled` with zero steps, and Finished events do not cover every cancellation path, so billing and cleanup must not rely on them alone. `StepFinished.next_prompt` supplies the next Step's user message, and `MessagesPending.messages` receives messages that arrived during the Run. Exceeding `max_steps` (set by `BUB_MAX_STEPS` in the app) raises `max_steps_reached`. A direct command emits tool events and `CommandFinished` but no `RunStarted` or `RunFinished`. Every event carries `state`, and `TapeEvent` subclasses also carry `tape`. +| `StepFinished` | A Step ends | `step`, `status`, `elapsed_ms`, `stream`; set `next_prompt` when continuing | +| `MessagesPending` | Before building a request, or when a Step ends without tool calls | Append user content to `messages`; at Step end, appended messages continue the Run | +| `LLMCallStarted` | Before calling the model provider | Replace `request`; set `LLMCallDecision.finish(text)` | +| `LLMCallFinished` | After success or an ordinary provider failure | `request` and the aggregated `result` (`LLMCallResult`) | +| `ToolCallStarted` | Before a local tool runs | Replace `call`; set `decision` (`proceed` / `deny` / `replace`) | +| `ToolCallFinished` | Tool success, failure, denial, or replacement | `call` and `result` (assign `event.result.result` to change the model-facing result) | +| `ChatFinished` | When a Step's exchange is ready to be recorded | `new_messages`, `response_text`, `tool_calls`, `tool_results`, `usage`, `error` | +| `CommandFinished` | A direct command succeeds or fails | `line`, `name`, `status`, `elapsed_ms`, `output` | + +- `RunFinished` fires when the stream closes; a Run closed before iterating ends as `cancelled` with zero steps. `LLMCallFinished` and `ToolCallFinished` do not cover every cancellation path. +- Exceeding `max_steps` (set by `BUB_MAX_STEPS` in the app) raises `max_steps_reached`. +- Direct commands emit tool events and `CommandFinished`, but no `RunStarted` or `RunFinished`. +- See [Agent events](/docs/concepts/events/#call-control) for decision semantics and [Hooks reference](/docs/reference/hooks/#event-mapping) for app-hook mapping. -Interception payloads (`LLMCallRequest`, `LLMCallDecision`, `ToolCall`, `ToolCallDecision`, and others) are also exported from `bub.core`. See [Agent events](/docs/concepts/events/#call-control) for the decision semantics, and [Hooks reference](/docs/reference/hooks/#event-mapping) for the app-hook mapping. +--- -### Streams {#streams} +### `bub.streaming` {#streams} ```python from bub.streaming import AsyncStreamEvents, StreamEvent, StreamState + +@dataclass +class StreamState: + error: BubError | None = None + usage: dict[str, Any] | None = None + system_prompt: str | None = None + tools: list[Tool] = field(default_factory=list) + +@dataclass(frozen=True) +class StreamEvent: + kind: Literal["text", "reasoning", "tool_call", "tool_result", "usage", "error", "final"] + data: dict[str, Any] + +class AsyncStreamEvents: + def __init__( + self, + iterator: AsyncIterator[StreamEvent], + *, + state: StreamState | None = None, + on_close: Callable[[], Awaitable[None]] | None = None, + span: Span | None = None, + ) -> None: ... + + def __aiter__(self) -> AsyncIterator[StreamEvent]: ... + async def __anext__(self) -> StreamEvent: ... + async def aclose(self) -> None: ... + + @property + def error(self) -> BubError | None: ... + @property + def usage(self) -> dict[str, Any] | None: ... ``` -`StreamEvent.kind`: `text`, `reasoning`, `tool_call`, `tool_result`, `usage`, `error`, and `final`. A `tool_result` event carries `data["tool_results"]`, one entry per tool call in the Step; a failed call's entry is its `BubError`, which the Tape and model receive as a dictionary. `AsyncStreamEvents` is an async iterator with `aclose()` / `error` / `usage`. See [SDK output streams](/docs/sdk/#consume-the-stream) for consumption conventions. +| Class / Member | Description | +| --- | --- | +| `StreamEvent.kind` | Event kind: `"text"`, `"reasoning"`, `"tool_call"`, `"tool_result"`, `"usage"`, `"error"`, or `"final"` (see [SDK output streams](/docs/sdk/#consume-the-stream)) | +| `StreamEvent.data` | Event payload dictionary; for `tool_result`, `data["tool_results"]` aligns with the Step's tool calls and holds a `BubError` for failed calls | +| `await AsyncStreamEvents.aclose()` | Explicitly closes the stream and runs `on_close` cleanup and Tape fork merging | +| `AsyncStreamEvents.error` / `usage` | Latest recorded `BubError` or token usage dictionary | + +--- -### Errors {#errors} +### `bub.errors` {#errors} ```python from bub.errors import BubError, ErrorKind + +class ErrorKind(StrEnum): + INVALID_INPUT = "invalid_input" + CONFIG = "config" + PROVIDER = "provider" + TOOL = "tool" + TEMPORARY = "temporary" + NOT_FOUND = "not_found" + UNKNOWN = "unknown" + +@dataclass +class BubError(Exception): + kind: ErrorKind + message: str + details: dict[str, Any] | None = None + + def as_dict(self) -> dict[str, Any]: ... ``` -`ErrorKind`: `invalid_input`, `config`, `provider`, `tool`, `temporary`, `not_found`, and `unknown`. `BubError(kind, message, details=None)`; `as_dict()` is suitable for transport. +| Field / Method | Type | Description | +| --- | --- | --- | +| `kind` | `ErrorKind` | Error category enum | +| `message` | `str` | Human-readable error message | +| `details` | `dict[str, Any] \| None` | Optional structured error context | +| `as_dict()` | `dict[str, Any]` | Converts the error into a JSON-serializable dictionary | + +--- -### Code mode {#code-mode} +### `CodeMode` {#code-mode} ```python from bub.core.codemode import CodeMode + +type CodeTools = Iterable[Tool] | Callable[[TurnState], Iterable[Tool] | None] +type ModelResolver = Callable[[str | None, ToolContext], tuple[str, Mapping[str, Any]]] + +class CodeMode: + run_code: Tool + + def __init__( + self, + tools: CodeTools = (), + *, + environment: Environment | Callable[[TurnState], Environment] | None = None, + models: str | ModelResolver | None = None, + stub_dir: Path | Callable[[TurnState], Path] | None = None, + media_tools: bool = True, + name: str = "run_code", + ) -> None: ... + + def code_tools(self, state: TurnState) -> list[Tool] | None: ... + def environment(self, state: TurnState) -> Environment: ... + def prompt(self, context: PromptContext) -> str | None: ... ``` -`CodeMode(tools, *, environment=None, models=None, ...)` provides the model-facing `run_code` tool and a `prompt` section describing callable tools. See [Custom tools and code mode](/docs/sdk/tools/) for usage. +| Parameter / Member | Type | Default | Description | +| --- | --- | --- | --- | +| `tools` | `CodeTools` | `()` | Tools callable inside `run_code` via `await tools.(...)` (or a callable returning tools per `TurnState`) | +| `environment` | `Environment \| Callable \| None` | `LocalEnvironment()` in cwd | Execution environment (or factory) used to run Python code | +| `models` | `str \| ModelResolver \| None` | `None` | Model spec or resolver exposed inside code mode | +| `stub_dir` | `Path \| Callable \| None` | `None` | Directory where generated tool type stubs are written | +| `media_tools` | `bool` | `True` | Whether to expose `attach_image`, `attach_audio`, and `attach_video` inside `run_code` | +| `name` | `str` | `"run_code"` | Name of the model-facing tool | +| `code_mode.run_code` | `Tool` | — | Generated `Tool` instance to pass to `Agent(tools=[code_mode.run_code])` | +| `code_mode.prompt` | `PromptSection` | — | Prompt section describing callable tools for `Agent(system_prompt=[..., code_mode.prompt])` | + +See [Custom tools and code mode](/docs/sdk/tools/#compose-tools-with-codemode) for usage. + +--- -### Environment {#environment} +### `Environment`, `Process`, and `LocalEnvironment` {#environment} ```python from bub.environment import ( @@ -313,177 +893,563 @@ from bub.environment import ( LocalEnvironment, Process, ) -``` - -`Environment` is the abstraction through which tools run processes and read or write files. The built-in `bash`, `fs.read` / `fs.write` / `fs.edit`, and code mode's `run_code` all execute through it. The default implementation, `LocalEnvironment`, runs everything directly on the host without isolation. -Paths passed to an environment are paths **inside** that environment: relative paths resolve against `workspace`, which need not be a host path. +ENVIRONMENT_STATE_KEY = "_runtime_environment" +type CallTool = Callable[[str, dict[str, Any]], Awaitable[Any]] + +class Environment(abc.ABC): + workspace: str | None = None + python: str = "python3" + + @abc.abstractmethod + async def spawn( + self, + command: str | Sequence[str], + *, + cwd: str | None = None, + env: Mapping[str, str] | None = None, + ) -> Process: ... + + @abc.abstractmethod + async def read_text(self, path: str) -> str: ... + async def read_bytes(self, path: str) -> bytes: ... + + @abc.abstractmethod + async def write_text(self, path: str, content: str) -> None: ... + def resolve_path(self, path: str) -> str: ... + + @abc.abstractmethod + async def run_code( + self, + code: str, + *, + tools: Sequence[str], + call_tool: CallTool, + write: Callable[[str], None], + ) -> None: ... + + async def close(self) -> None: ... + +class LocalEnvironment(Environment): + def __init__(self, workspace: str | Path | None = None) -> None: ... +``` -#### Members {#environment-members} +#### `Environment` members {#environment-members} | Member | Signature | Description | | --- | --- | --- | | `workspace` | `str \| None` | Working directory inside the environment; relative paths are rejected when `None` | -| `python` | `str` | Python executable inside the environment, `"python3"` by default; `LocalEnvironment` uses the current `sys.executable` | -| `spawn` | `async (command, *, cwd=None, env=None) -> Process` | Abstract. A string runs through the shell, a sequence runs as an argument vector; `cwd` defaults to `workspace`, `env` is layered over the environment's default variables | -| `read_text` | `async (path) -> str` | Abstract. Read a UTF-8 text file | -| `read_bytes` | `async (path) -> bytes` | Read bytes. The default reads the file with `python` inside the environment; implementations with direct filesystem access should override it | -| `write_text` | `async (path, content) -> None` | Abstract. Write a UTF-8 text file, creating missing parent directories | -| `resolve_path` | `(path) -> str` | Resolve a relative path against `workspace`; raises `ValueError` without a workspace. The base class uses POSIX rules; `LocalEnvironment` also expands `~` and resolves absolute paths | -| `run_code` | `async (code, *, tools, call_tool, write) -> None` | Abstract. Run model-written Python code; contract below | -| `close` | `async () -> None` | Release the environment's resources; called when `framework.running()` exits | - -A custom environment must implement at least `spawn`, `read_text`, `write_text`, and `run_code`; the other members have defaults. +| `python` | `str` | Python executable inside the environment, `"python3"` by default (`LocalEnvironment` uses `sys.executable`) | +| `spawn` | `async (command, *, cwd=None, env=None) -> Process` | **Abstract**. Runs a string through the shell or a sequence as an argument vector; `cwd` defaults to `workspace` | +| `read_text` | `async (path) -> str` | **Abstract**. Reads a UTF-8 text file | +| `read_bytes` | `async (path) -> bytes` | Reads raw bytes (defaults to reading via `python` inside the environment; override when direct filesystem access is available) | +| `write_text` | `async (path, content) -> None` | **Abstract**. Writes a UTF-8 text file, creating missing parent directories | +| `resolve_path` | `(path) -> str` | Resolves a relative path against `workspace`; raises `ValueError` without a workspace | +| `run_code` | `async (code, *, tools, call_tool, write) -> None` | **Abstract**. Executes model-written Python code | +| `close` | `async () -> None` | Releases environment resources; called when `framework.running()` exits | #### `Process` {#process} -`spawn` returns a `Process`, which exposes the process as streams: +```python +class Process(abc.ABC): + @property + @abc.abstractmethod + def stdout(self) -> asyncio.StreamReader: ... + @property + @abc.abstractmethod + def stderr(self) -> asyncio.StreamReader: ... + @property + @abc.abstractmethod + def returncode(self) -> int | None: ... + + @abc.abstractmethod + async def wait(self) -> int: ... + @abc.abstractmethod + async def write_stdin(self, data: bytes) -> None: ... + @abc.abstractmethod + def close_stdin(self) -> None: ... + @abc.abstractmethod + def signal(self, *, kill: bool) -> None: ... + def is_running(self) -> bool: ... +``` | Member | Description | | --- | --- | -| `stdout` / `stderr` | `asyncio.StreamReader` | -| `returncode` | Exit code, or `None` while running | -| `await wait()` | Wait for exit and return the exit code | -| `await write_stdin(data)` | Write to standard input and wait until flushed | -| `close_stdin()` | Close standard input | -| `signal(*, kill)` | Ask the process and its descendants to exit, or force them to end when `kill=True`; must not raise once the process has exited | -| `is_running()` | Whether the process or its descendants are still alive; the default checks only the process itself | - -`LocalProcess` is the implementation used by `LocalEnvironment`: on POSIX the process runs in its own session, and `signal` targets the whole process group. +| `stdout` / `stderr` | `asyncio.StreamReader` streams | +| `returncode` | Process exit code, or `None` while running | +| `await wait()` | Waits for exit and returns the exit code | +| `await write_stdin(data)` / `close_stdin()` | Writes and flushes standard input, or closes standard input | +| `signal(*, kill)` | Requests termination of the process and its descendants (or forces termination when `kill=True`); must not raise once exited | +| `is_running()` | Whether the process or its descendants are still alive | #### `run_code` contract {#run-code-contract} -```python -async def run_code( - self, - code: str, - *, - tools: Sequence[str], - call_tool: CallTool, - write: Callable[[str], None], -) -> None: -``` - -- `code` may use top-level `await`. -- Each name in `tools` appears in the code as `tools.(**kwargs)`; calls forward to `await call_tool(name, kwargs)`, and exceptions from `call_tool` surface in the code as exceptions. -- The code may also call `call_tool` with names prefixed `republic.` for media loading and model calls. -- Everything the code writes to standard output must be passed to `write` as soon as it is produced, so output that has already been produced survives a timeout. -- Raise `CodeFailed` when the code itself raises; any other exception indicates a runtime failure. When cancelled (for example on timeout), stop the code before returning. - -`LocalEnvironment.run_code` uses `bub.core.codemode.runner.run_code_in_subprocess(self, ...)`: it runs the code in a Python process started with `spawn`, then terminates that process and everything it started. Custom environments with a Python interpreter can reuse it directly. +- `code` may use top-level `await`; each tool in `tools` is exposed as `await tools.(**kwargs)` forwarding to `await call_tool(name, kwargs)` (and `republic.` prefixed names are forwarded for media and model helpers). +- Standard output must be passed to `write(chunk)` immediately as produced so output survives timeouts. +- Raise `CodeFailed(error, traceback)` when the code itself raises; custom environments with a Python interpreter can reuse `bub.core.codemode.runner.run_code_in_subprocess(self, ...)`. #### `CodeFailed` {#codefailed} -`CodeFailed(error, traceback="")`: `error` is `": "`, and `traceback` is a formatted traceback containing only the code's own stack frames. Code mode turns it into a tool error for the model. - -#### Where the environment comes from {#provide-an-environment} - -The application layer provides one environment per session through the `provide_environment` hook (first result wins): - ```python -def provide_environment(self, session_id: str, workspace: Path) -> Environment | None: +class CodeFailed(Exception): + def __init__(self, error: str, traceback: str = "") -> None: ... ``` -The framework caches the returned environment per session and calls `Environment.close()` when `framework.running()` exits. The builtin implementation returns `LocalEnvironment(workspace)`; a higher-priority plugin can replace it. +`error` is `": "`, and `traceback` contains only the model code's own stack frames. -The environment is written to Turn state under `ENVIRONMENT_STATE_KEY` (`"_runtime_environment"`), and builtin tools read it through `bub.builtin.environment.environment_from_state`. When the state has no environment (for example when using an SDK `Agent` directly), the fallback is a `LocalEnvironment` based on `_runtime_workspace`. Without a workspace, relative paths raise `ValueError`. +#### Where the environment comes from {#provide-an-environment} -Constructing `CodeMode` directly in the SDK does not read the environment from Turn state: `CodeMode(tools, environment=...)` accepts an `Environment` or `(TurnState) -> Environment`, and defaults to a `LocalEnvironment()` in the current working directory. The builtin code mode already wires it to `environment_from_state`. +The application layer caches one `Environment` per session via the `provide_environment(session_id, workspace)` hook (defaulting to `LocalEnvironment(workspace)`), stores it in `TurnState[ENVIRONMENT_STATE_KEY]`, and calls `close()` when `framework.running()` exits. :::caution -`LocalEnvironment` executes directly on the host, and **a separate process is not a security sandbox**. When running untrusted model code, implement an environment with filesystem, network, and permission isolation. +`LocalEnvironment` executes directly on the host, and **a separate subprocess is not a security sandbox**. Implement an isolated `Environment` when running untrusted code. ::: -## Application {#application} +--- + +## Application (`bub`) {#application} -### Framework and BubAgent {#framework} +### `BubFramework` and `BubAgent` {#framework} ```python from bub import BubFramework from bub.builtin.agent import BubAgent + +class BubFramework: + workspace: Path + config_file: Path + default_command: str | None + events: EventBus + + def __init__(self, config_file: Path = DEFAULT_CONFIG_FILE) -> None: ... + + @property + def plugin_manager(self) -> pluggy.PluginManager: ... + + def load_builtin_hooks(self) -> None: ... + def load_hooks(self) -> None: ... + def create_cli_app(self) -> typer.Typer: ... + + async def build_prompt( + self, + message: Envelope, + session_id: str, + state: dict[str, Any], + ) -> list[UserContent]: ... + + async def continue_prompt( + self, + prompt: list[UserContent] | None, + tape: Tape, + state: StreamState, + ) -> str | None: ... + + async def build_state(self, message: Envelope, session_id: str) -> TurnState: ... + async def process_inbound(self, inbound: Envelope, stream_output: bool = False) -> TurnResult: ... + async def resolve_session(self, message: Envelope) -> str: ... + def plugin_report(self) -> dict[str, PluginStatus]: ... + def hook_report(self) -> dict[str, list[str]]: ... + def bind_channel_router(self, router: ChannelRouter | None) -> None: ... + async def dispatch_via_channel_router(self, message: Envelope) -> bool: ... + async def quit_via_channel_router(self, session_id: str) -> None: ... + + async def admit_message( + self, + *, + session_id: str, + message: Envelope, + turn: TurnSnapshot, + ) -> AdmitDecision | None: ... + + async def get_model_options( + self, + *, + session_id: str, + workspace: str | Path | None = None, + ) -> ModelOptions: ... + + async def steer_message( + self, + *, + message: Envelope, + session_id: str, + state: TurnState, + reason: str | None = None, + ) -> bool: ... + + def get_channels(self, message_handler: MessageHandler) -> dict[str, Channel]: ... + + @asynccontextmanager + async def running(self) -> AsyncGenerator[contextlib.AsyncExitStack, None]: ... + + async def get_environment(self, session_id: str) -> Environment | None: ... + def get_tape_store(self) -> TapeStore | AsyncTapeStore | None: ... + def get_tape_sidecars(self) -> tuple[TapeSidecar, ...]: ... + def get_tools(self) -> tuple[Tool, ...]: ... + def get_steering_inbox(self) -> SteeringInbox | None: ... + def get_agent_hooks(self) -> PluginAgentHooks: ... + def get_system_prompt(self, prompt: list[UserContent], state: dict[str, Any]) -> str: ... + def build_tape_context(self) -> TapeContext: ... + def collect_onboard_config(self, plugin_name: str | None = None) -> dict[str, Any]: ... + +class BubAgent(core.Agent): + command_prefix: str + + def __init__( + self, + framework: BubFramework, + *, + tools: Collection[Tool] | None = None, + tape_store: TapeStore | AsyncTapeStore | None = None, + skill_dirs: Collection[Path] | None = None, + command_prefix: str | None = None, + ) -> None: ... + + async def run_stream( + self, + *, + session_id: str, + prompt: list[UserContent] | LegacyPrompt, + state: TurnState | None = None, + model: str | None = None, + allowed_skills: Collection[str] | None = None, + allowed_tools: Collection[str] | None = None, + reasoning_effort: str | None = None, + ) -> AsyncStreamEvents: ... + + async def prepare_tools( + self, + tape: Tape, + prompt: list[UserContent] | None, + ) -> list[Tool]: ... ``` -| Entry point | Description | -| --- | --- | -| `BubFramework(config_file=...)` | Loads application configuration; the initial workspace is the cwd | -| `framework.load_hooks()` | Registers builtin and installed plugin hooks | -| `framework.load_builtin_hooks()` | Registers only builtin implementations | -| `framework.running()` | Async scope managing the store, execution environments, and steering inbox (`SteeringInbox`) | -| `framework.process_inbound(inbound, stream_output=False)` | Executes a complete Turn and returns `TurnResult` | -| `framework.get_tools()` / `get_channels(handler)` / `get_tape_store()` | Plugin-host collection entry points | -| `framework.get_model_options(...)` / `get_agent_hooks()` / `bind_channel_router(...)` | Model options, event bridge, and channel routing | -| `BubAgent(framework, *, tools=None, tape_store=None, skill_dirs=None, command_prefix=None)` | Application Agent with settings, skills, and code mode | -| `await agent.run_stream(session_id=..., prompt=..., state=None, ...)` | Prepares the model stage and returns a stream | +**`BubFramework` key methods**: -Configuration is cached process-wide. To use the framework's active store, construct `BubAgent` inside `async with framework.running():`. An explicit `tape_store` takes precedence and remains the caller's lifecycle responsibility. See [Reuse the Bub app](/docs/integrations/reuse-app/) for embedding. +| Method | Description | +| --- | --- | +| `BubFramework(config_file=...)` | Loads application configuration; `workspace` defaults to the current working directory | +| `load_hooks()` / `load_builtin_hooks()` | Registers builtin hooks and all installed entry-point plugins (or builtin hooks only) | +| `running()` | Async context manager managing `provide_lifespan`, `TapeStore`, session `Environment` instances, and `SteeringInbox` | +| `await process_inbound(inbound, stream_output=False)` | Executes a complete 7-stage Turn and returns `TurnResult` | +| `await build_state(message, session_id)` | Runs `load_state` hooks and populates `_runtime_*` keys to build `TurnState` | +| `get_tools()` / `get_channels(handler)` / `get_tape_store()` | Collects registered tools, channels, or the active Tape store | +| `bind_channel_router(router)` | Binds a `ChannelRouter` for outbound delivery, stream wrapping, and session cancellation | + +**`BubAgent` constructor and `run_stream()` parameters**: + +| Parameter | Type | Default | Description | +| --- | --- | --- | --- | +| `framework` | `BubFramework` | Required | Associated `BubFramework` (construct `BubAgent` inside `async with framework.running():` to use the active store) | +| `tools` | `Collection[Tool] \| None` | `framework.get_tools()` | Overrides the base tool collection for this Agent instance | +| `tape_store` | `TapeStore \| AsyncTapeStore \| None` | `framework.get_tape_store()` | Explicit store taking precedence over the framework's store | +| `session_id` | `str` | Required (`run_stream`) | Session ID (a `temp/` prefix prevents the Tape fork from merging back on close) | +| `prompt` | `list[UserContent] \| LegacyPrompt` | Required (`run_stream`) | User input sent to the model | +| `state` | `TurnState \| None` | `None` | Loaded via `framework.build_state()` when `None`; passing a dict skips `load_state` hooks | +| `model` | `str \| None` | Session or configured model | Overrides `provider:model` for this call | +| `allowed_tools` / `allowed_skills` | `Collection[str] \| None` | `None` | Limits allowed tools or skills for this call (`[]` disables all; unknown names raise `ValueError`) | +| `reasoning_effort` | `str \| None` | Session or configured effort | Overrides reasoning effort for this call | + +See [Reuse Bub in a service](/docs/integrations/reuse-app/) for embedding patterns and [Turn](/docs/concepts/turn/#stages) for the differences from a complete Turn. -`run_stream` parameters: `session_id` (a `temp/` prefix prevents the branch from merging), `prompt`, `state` (loaded through hooks when `None`), `model`, `allowed_skills`, `allowed_tools`, and `reasoning_effort`. Await it before iterating; it does not handle outbound rendering, `save_state`, or serialization of concurrent runs in the same session. See [Turn](/docs/concepts/turn/#stages) for the differences from a complete Turn. +--- -### Messages and TurnResult {#messages} +### `bub.envelope` and `bub.turn` {#messages} ```python from bub.envelope import Envelope, content_of, field_of, normalize_envelope, unpack_batch from bub.turn import TurnResult, TurnState + +type Envelope = Any +type TurnState = dict[str, Any] + +def field_of(message: Envelope, key: str, default: Any = None) -> Any: ... +def content_of(message: Envelope) -> str: ... +def normalize_envelope(message: Envelope) -> dict[str, Any]: ... +def unpack_batch(batch: Any) -> list[Envelope]: ... + +@dataclass(frozen=True) +class TurnResult: + session_id: str + prompt: list[UserContent] + model_output: str + outbounds: list[Envelope] = field(default_factory=list) + state: TurnState = field(default_factory=dict) ``` -`Envelope` accepts mappings, dataclasses, Pydantic models, and objects with attributes. `field_of` / `content_of` read keys or attributes; `normalize_envelope` produces a mutable dictionary; `unpack_batch` expands a hook's outbound batch. +| Function / Field | Description | +| --- | --- | +| `field_of(message, key, default=None)` | Reads a key or attribute from a mapping, dataclass, Pydantic model, or object | +| `content_of(message)` | Reads the `"content"` string field from a message (returns `""` if absent) | +| `normalize_envelope(message)` | Converts any `Envelope` into a mutable Python dictionary | +| `unpack_batch(batch)` | Expands a single outbound message or list returned by `render_outbound` into `list[Envelope]` | +| `TurnResult` | Result of `process_inbound()`, containing `session_id`, `prompt`, `model_output`, rendered `outbounds`, and final `state` | -`TurnState` is `dict[str, Any]`. `TurnResult` fields: `session_id`, `prompt`, `model_output`, `outbounds`, and `state`. +--- -### Model options {#model-options} +### `bub.model_selection` {#model-options} ```python from bub.model_selection import ModelChoice, ModelOptions + +@dataclass(frozen=True) +class ModelChoice: + id: str + name: str | None = None + description: str | None = None + meta: dict[str, Any] | None = None + +@dataclass(frozen=True) +class ModelOptions: + models: list[ModelChoice] = field(default_factory=list) + current_model: str | None = None ``` -`ModelChoice`: required `id`, optional `name` / `description` / `meta`. `ModelOptions`: `models` and `current_model`. `BubFramework.get_model_options` merges the results of each `provide_model_options` implementation. +| Class / Field | Type | Description | +| --- | --- | --- | +| `ModelChoice.id` | `str` | Required model identifier (e.g. `"openai:gpt-5-mini"`) | +| `ModelChoice.name` / `description` / `meta` | Optional | Display name, description, and metadata dictionary | +| `ModelOptions.models` | `list[ModelChoice]` | Candidate models merged across `provide_model_options` hooks | +| `ModelOptions.current_model` | `str \| None` | Currently active model ID | + +--- -### Channels {#channels} +### `bub.channels` {#channels} ```python from bub.channels import Channel, ChannelManager, ChannelMessage, Interface, Lifecycle +from bub.channels.admission import AdmitDecision, SteeringInbox, TurnAdmissionAction, TurnSnapshot from bub.channels.contracts import ChannelRouter, MessageHandler -from bub.channels.admission import AdmitDecision, SteeringInbox, TurnSnapshot -``` +from bub.channels.message import MediaItem, MediaType, MessageKind + +type MediaType = Literal["image", "audio", "video", "document"] +type MessageKind = Literal["error", "normal", "command"] +type MessageHandler = Callable[[Envelope], Coroutine[Any, Any, None]] +type TurnAdmissionAction = Literal["process", "drop", "follow_up", "steer"] + +@dataclass +class MediaItem: + type: MediaType + mime_type: str + filename: str | None = None + url: str | None = None + data_fetcher: Callable[[], Awaitable[bytes | None]] | None = None + + async def get_url(self) -> str | None: ... + +@dataclass +class ChannelMessage: + session_id: str + channel: str + content: str + chat_id: str = "default" + is_active: bool = False + kind: MessageKind = "normal" + context: dict[str, Any] = field(default_factory=dict) + media: list[MediaItem] = field(default_factory=list) + lifespan: contextlib.AbstractAsyncContextManager | None = None + output_channel: str = "" -`ChannelMessage` contains `session_id`, `channel`, `chat_id`, `content`, `kind`, `context`, `media`, `is_active`, `output_channel`, and optional message-level `lifespan`. `MediaItem` provides `type`, `mime_type`, and either `url` or an async `data_fetcher`; builtin prompt construction supports `image`, `audio`, and `video`. See [Gateway](/docs/app/gateway/#custom-channels) for custom channels. + @property + def context_str(self) -> str: ... + + @classmethod + def from_batch(cls, batch: list[ChannelMessage]) -> ChannelMessage: ... + +class Channel(ABC): + name: ClassVar[str] = "base" -`Channel` implements at least `start` / `stop`; `send`, `stream_events`, and `admit_message` are optional. `Interface` is a user entry point, and `Lifecycle` is a background service. + @abstractmethod + async def start(self, stop_event: asyncio.Event) -> None: ... + @abstractmethod + async def stop(self) -> None: ... + + @property + def needs_debounce(self) -> bool: ... + @property + def enabled(self) -> bool: ... + + async def send(self, message: ChannelMessage) -> None: ... + + def stream_events( + self, + message: ChannelMessage, + stream: AsyncIterable[StreamEvent], + ) -> AsyncIterable[StreamEvent]: ... + + async def admit_message( + self, + session_id: str, + message: Envelope, + turn: TurnSnapshot, + ) -> AdmitDecision | None: ... + +class Interface(Channel): ... +class Lifecycle(Channel): ... + +class ChannelRouter(Protocol): + async def dispatch_output(self, message: Envelope) -> bool: ... + def wrap_stream( + self, + message: Envelope, + stream: AsyncIterable[StreamEvent], + ) -> AsyncIterable[StreamEvent]: ... + async def quit(self, session_id: str) -> None: ... + async def admit_channel_message( + self, + session_id: str, + message: Envelope, + turn: TurnSnapshot, + ) -> AdmitDecision | None: ... + +class ChannelManager: + def __init__( + self, + framework: BubFramework, + enabled_channels: Collection[str] | None = None, + stream_output: bool | None = None, + system_prompt: str | None = CHANNEL_SYSTEM_PROMPT, + ) -> None: ... + + async def on_receive(self, message: ChannelMessage) -> None: ... + def get_channel(self, name: str) -> Channel | None: ... + async def dispatch_output(self, message: Envelope) -> bool: ... + def wrap_stream( + self, + message: Envelope, + stream: AsyncIterable[StreamEvent], + ) -> AsyncIterable[StreamEvent]: ... + async def quit(self, session_id: str) -> None: ... + def enabled_channels(self) -> list[Channel]: ... + async def listen_and_run(self) -> None: ... + async def shutdown(self) -> None: ... + async def admit_channel_message( + self, + session_id: str, + message: Envelope, + turn: TurnSnapshot, + ) -> AdmitDecision | None: ... + +@dataclass(frozen=True) +class AdmitDecision: + action: TurnAdmissionAction + reason: str | None = None + +@dataclass(frozen=True) +class TurnSnapshot: + session_id: str + is_running: bool + running_count: int + pending_count: int + steering_count: int = 0 + +class SteeringInbox(Protocol): + async def enqueue_message(self, message: Envelope, state: TurnState) -> None: ... + async def drain_messages(self, state: TurnState) -> list[Envelope]: ... + def message_count(self, state: TurnState) -> int: ... +``` -`ChannelRouter`: `dispatch_output`, `wrap_stream`, `quit`, and `admit_channel_message`. `ChannelManager` implements this protocol and is bound through `bind_channel_router`. +| Class | Description | +| --- | --- | +| `ChannelMessage` | Standard channel message object; `media` holds `MediaItem` objects (providing image, audio, or video bytes via `url` or async `data_fetcher`). See [Gateway: Custom channels](/docs/app/gateway/#custom-channels) | +| `Channel` / `Interface` / `Lifecycle` | `Channel` subclasses implement at least `start(stop_event)` and `stop()`; `Interface` marks an explicit user surface (such as `cli`), while `Lifecycle` marks a background service attached to the gateway (such as `mcp.lifecycle`) | +| `ChannelManager` | Implements `ChannelRouter` and manages channel lifecycles, debounce batching, message admission, and outbound delivery | +| `AdmitDecision` / `TurnSnapshot` / `SteeringInbox` | Message admission decision (`process` / `drop` / `follow_up` / `steer`), session activity snapshot, and steering inbox protocol (see [Hooks reference: `admit_message`](/docs/reference/hooks/#admit_message)) | -Admission types: `AdmitDecision(action, reason=None)` (`process` / `drop` / `follow_up` / `steer`), `TurnSnapshot`, and `SteeringInbox`. `follow_up` processes the message after the current Turn, while `steer` injects it into the running Turn; see the [Hooks reference](/docs/reference/hooks/#application-hooks) and [Turn](/docs/concepts/turn/) for complete behavior. +--- -### Hooks {#hooks} +### `bub.hooks` {#hooks} ```python -from bub.hooks import hookimpl, hookspec, BubHookSpecs +from bub.hooks import BubHookSpecs, hookimpl, hookspec ``` -See the [Hooks reference](/docs/reference/hooks/) for signatures and priority. +See the [Hooks reference](/docs/reference/hooks/) for all 27 hook signatures, dispatch modes, and return contracts. -### Application events {#application-events} +--- + +### `bub.application` and `bub.program_status` {#application-events} ```python -from bub.application import CommandChanged, PromptChanged, WorkChanged +from bub.application import CommandChanged, Outcome, PromptChanged, PromptKind, WorkChanged +from bub.program_status import ProgramStatus + +type Outcome = Literal["succeeded", "failed", "cancelled"] +type PromptKind = Literal["question", "permission", "auth"] + +@dataclass(frozen=True) +class CommandChanged(Event): + outcome: Outcome | None = None + +@dataclass(frozen=True) +class WorkChanged(Event): + busy: bool + completed: Outcome | None = None + +@dataclass(frozen=True) +class PromptChanged(Event): + kind: PromptKind | None + +class ProgramStatus: + def __init__(self, output: TextIO | None) -> None: ... + def __call__(self, event: Event) -> None: ... ``` -These events are published on `framework.events`, independently of `agent.events`: +These events are published on `framework.events` (independently of `agent.events`) to drive status bars and external UIs: -| Type | Fields | Trigger | +| Class | Fields | Description | | --- | --- | --- | -| `CommandChanged` | `outcome` | `None` when CLI invocation starts; `succeeded` / `failed` / `cancelled` when it ends | -| `WorkChanged` | `busy`, `completed` | Channel busy-state changes; may carry the result of a newly completed message | -| `PromptChanged` | `kind` | `question` / `permission` / `auth` when a modal prompt opens; `None` when it closes | - -They are suitable for status bars and external UIs and do not carry detailed model-call payloads. +| `CommandChanged` | `outcome` | `None` when a CLI command starts; `"succeeded"` / `"failed"` / `"cancelled"` when it ends | +| `WorkChanged` | `busy`, `completed` | Channel busy-state changes; may carry the outcome of a completed message | +| `PromptChanged` | `kind` | `"question"` / `"permission"` / `"auth"` when a modal prompt opens; `None` when it closes | +| `ProgramStatus` | `output` | Builtin terminal status handler: emits OSC 7501 states (`idle`, `working`, `blocked`, `done`, `error`) on a TTY and clears with `state=clear` when a command ends | -`bub.program_status.ProgramStatus` is the builtin application event handler. The CLI automatically registers it on `framework.events` to emit OSC 7501 states on a TTY: `idle`, `working`, `blocked`, `done`, and `error`; prompt states also carry `kind`. When a command ends it reports its final state and then `state=clear`, so a shell left in the terminal is not shown as an agent. Non-TTY output does not produce these control sequences. +--- -### Interactive input {#inquirer} +### `bub.inquirer` {#inquirer} ```python -from bub.inquirer import ask_checkbox, ask_confirm, ask_fuzzy, ask_secret, ask_select, ask_text +from bub.inquirer import ( + CheckboxValidator, + ask_checkbox, + ask_confirm, + ask_fuzzy, + ask_prompt, + ask_secret, + ask_select, + ask_text, +) + +type CheckboxValidator = Callable[[list[str]], bool | str] + +def ask_prompt( + prompt: Callable[..., InquirerResult[Any]], + message: str, + *, + kind: PromptKind = "question", + **kwargs: Any, +) -> Any: ... + +def ask_text(message: str, default: str = "") -> str: ... +def ask_secret(message: str) -> str: ... +def ask_confirm(message: str, default: bool = False, *, kind: PromptKind = "question") -> bool: ... +def ask_select(message: str, choices: list[str], default: str = "") -> str: ... +def ask_fuzzy(message: str, choices: list[str], default: str | None = None) -> str: ... +def ask_checkbox( + message: str, + choices: list[str], + enabled: list[str] | None = None, + validate: CheckboxValidator | None = None, +) -> list[str]: ... ``` -These synchronous functions collect multi-select, confirmation, fuzzy single-select, secret, ordinary single-select, and text input for plugin CLIs and `onboard_config`. When called through the Bub CLI, they publish `PromptChanged`; user cancellation raises `typer.Abort`. See [Collect interactive input](/docs/app/plugins/#prompt-for-input) for usage. +| Function | Parameters | Return type | Description | +| --- | --- | --- | --- | +| `ask_text` | `message`, `default=""` | `str` | Single-line text input | +| `ask_secret` | `message` | `str` | Masked password or token input | +| `ask_confirm` | `message`, `default=False`, `*, kind="question"` | `bool` | Yes/no confirmation prompt | +| `ask_select` | `message`, `choices`, `default=""` | `str` | Single-choice selection list | +| `ask_fuzzy` | `message`, `choices`, `default=None` | `str` | Fuzzy-filtered single-choice selection | +| `ask_checkbox` | `message`, `choices`, `enabled=None`, `validate=None` | `list[str]` | Multi-select checkbox list with optional `validate` callback | + +When called through the Bub CLI, these synchronous helpers emit `PromptChanged` on `framework.events`; user cancellation raises `typer.Abort`. See [Collect interactive input](/docs/app/plugins/#prompt-for-input). diff --git a/website/src/content/docs/docs/reference/settings.mdx b/website/src/content/docs/docs/reference/settings.mdx index df6e85f3..c26de249 100644 --- a/website/src/content/docs/docs/reference/settings.mdx +++ b/website/src/content/docs/docs/reference/settings.mdx @@ -1,51 +1,40 @@ --- title: Settings -description: Application environment variables, YAML fields, defaults, and resolution order. +description: "Complete reference for Bub app configuration: BUB_* environment variables, YAML config fields, defaults, precedence rules, and Telegram settings." --- -These settings belong to the **Bub application**. `bub.core.Agent` does not read YAML or `BUB_*`; it receives constructor arguments only. Plugins can register their own sections, with fields defined by each plugin's documentation. For setup steps, see [Configuration](/docs/app/configure/). +This page lists all built-in settings for the **Bub app layer**. The core `bub.core.Agent` class does not read YAML files or `BUB_*` environment variables (it takes constructor arguments only). Third-party plugins can register their own configuration sections; see each plugin's documentation. For initial setup steps, see [Configuration](/docs/app/configure/). ## Precedence {#precedence} -Settings classes resolve fields in this order, from highest to lowest priority: +Settings classes resolve fields in this order (highest priority first): -| Order | Source | Description | +| Priority | Source | Description | | --- | --- | --- | -| 1 | Environment variables | `BUB_*`; read when a settings instance is created | -| 2 | `.env` in the current directory | `find_dotenv(usecwd=True)`; does not overwrite existing environment variables | -| 3 | YAML file | `~/.bub/config.yml` by default, loaded by `configure.load` | -| 4 | Field defaults | Defaults declared in code | +| 1 | Environment variables | `BUB_*`; read when the settings class is instantiated | +| 2 | `.env` in current directory | `find_dotenv(usecwd=True)`; does not override existing system environment variables | +| 3 | YAML config file | Defaults to `~/.bub/config.yml`, loaded via `configure.load` | +| 4 | Field defaults | Default values declared in code | -`--workspace`, `--project`, and `--enable-channel` are **command arguments**, not layers in this common settings table. They respectively change the framework workspace, plugin project path, and channel selection for the invocation. +- `--workspace`, `--project`, and `--enable-channel` are **CLI flags**, not settings fields. +- Settings instances are cached process-wide. Modifying `os.environ` after `ensure_config()` has been called will not update cached instances; restart the process to apply changes. -Settings instances are cached within the process. After the first `ensure_config()`, changing `os.environ` usually does not affect instances that have already been created; start a new process when configuration must change. +## Config file and runtime paths {#config-file} -## Config file {#config-file} - -| Path | Source | -| --- | --- | -| `~/.bub/config.yml` | `DEFAULT_CONFIG_FILE` in `src/bub/framework.py` | -| `BubFramework(config_file=Path(...))` | Constructor argument, resolved to an absolute path | - -`BUB_HOME` changes only `bub.home` (history, Tapes, the plugin project, code mode files, and similar paths); it **does not move** the default `~/.bub/config.yml`. Pass `config_file` explicitly to use a different configuration file. - -## Runtime paths {#runtime-paths} - -| Variable | Default | Description | +| Path / Variable | Default | Description | | --- | --- | --- | -| `BUB_HOME` | `~/.bub` | `bub.home`; setting it in `.env` also works | -| `BUB_PROJECT` | `/bub-project` | Project directory for `bub install` / `uninstall` / `update` | - -Typer reads `BUB_PROJECT`. The default project directory is created automatically when missing; an explicitly selected alternative directory should already exist. +| `~/.bub/config.yml` | `DEFAULT_CONFIG_FILE` | Default YAML config file (override via `BubFramework(config_file=Path(...))`) | +| `BUB_HOME` | `~/.bub` | Runtime data directory (stores session Tapes, managed plugin project, and temporary code-mode files). **Note: `BUB_HOME` does not move the default `~/.bub/config.yml` location** | +| `BUB_PROJECT` | `/bub-project` | Managed plugin project directory for `bub install` / `uninstall` / `update` (created automatically at the default path; custom paths must already exist) | ## Environment variable index {#env-index} -Every YAML key has a corresponding environment variable, which takes precedence. This table is ordered by prefix; names beginning with `BUB_` can be set directly in `.env`. +Every YAML setting has a corresponding environment variable (all `BUB_*` variables can be placed in `.env`): -| Variable | Default | YAML path | Details | +| Variable | Default | YAML path | Section | | --- | --- | --- | --- | -| `BUB_HOME` | `~/.bub` | — | [Runtime paths](#runtime-paths) | -| `BUB_PROJECT` | `/bub-project` | — | [Runtime paths](#runtime-paths) | +| `BUB_HOME` | `~/.bub` | — | [Runtime paths](#config-file) | +| `BUB_PROJECT` | `/bub-project` | — | [Runtime paths](#config-file) | | `BUB_MODEL` | `openrouter:openrouter/free` | `model` | [AgentSettings](#agent-settings) | | `BUB_COMMAND_PREFIX` | `,` | `command_prefix` | [Command prefix](#command-prefix) | | `BUB_FALLBACK_MODELS` | `null` | `fallback_models` | [Models and fallback](#model-routing) | @@ -62,7 +51,7 @@ Every YAML key has a corresponding environment variable, which takes precedence. | `BUB_CLIENT_ARGS` | `{}` | `client_args` | [`client_args`](#client-args) | | `BUB_COMPLETION_ARGS` | `{}` | `completion_args` | [`completion_args`](#completion-args) | | `BUB_VERBOSE` | `0` | `verbose` | [AgentSettings](#agent-settings) | -| `BUB_ENABLED_CHANNELS` | `all` | `enabled_channels` | [Channel selection](#channel-selection) | +| `BUB_ENABLED_CHANNELS` | `all` | `enabled_channels` | [ChannelSettings](#channel-settings) | | `BUB_DEBOUNCE_SECONDS` | `1.0` | `debounce_seconds` | [ChannelSettings](#channel-settings) | | `BUB_MAX_WAIT_SECONDS` | `10.0` | `max_wait_seconds` | [ChannelSettings](#channel-settings) | | `BUB_ACTIVE_TIME_WINDOW` | `60.0` | `active_time_window` | [ChannelSettings](#channel-settings) | @@ -74,11 +63,9 @@ Every YAML key has a corresponding environment variable, which takes precedence. | `BUB_TELEGRAM_PROXY` | unset | `telegram.proxy` | [TelegramSettings](#telegram-settings) | | `CODEX_HOME` | `~/.codex` | — | [Third-party login](#login-env) | -Flat keys such as `BUB_MODEL`, `BUB_COMMAND_PREFIX`, and `BUB_ENABLED_CHANNELS` go at the YAML root; keys under `spill:` and `telegram:` go in nested sections. `BUB_TELEGRAM_*` maps to fields of the same name under `telegram:`, and `BUB_SPILL_*` maps to fields under `spill:`. - ## AgentSettings {#agent-settings} -`src/bub/builtin/settings.py` +Defined in `src/bub/builtin/settings.py` (top-level YAML fields): ```python @config() @@ -104,91 +91,82 @@ class AgentSettings(Settings): verbose: int = 0 ``` -| Environment variable | Default | YAML | Description | +| Environment variable | Default | YAML key | Description | | --- | --- | --- | --- | -| `BUB_MODEL` | `openrouter:openrouter/free` | `model` | Must be `provider:model` | -| `BUB_COMMAND_PREFIX` | `,` | `command_prefix` | Non-empty with no whitespace; may contain multiple characters | -| `BUB_FALLBACK_MODELS` | `null` | `fallback_models` | JSON array; used only for the configured default model | -| `BUB_API_KEY` | unset | `api_key` | String, or a mapping from providers to keys | -| `BUB_API_BASE` | unset | `api_base` | String, or a mapping from providers to addresses | -| `BUB__API_KEY` | unset | — | For example, `BUB_OPENAI_API_KEY` | -| `BUB__API_BASE` | unset | — | For example, `BUB_OPENROUTER_API_BASE` | -| `BUB_PROVIDERS` | `{}` | `providers` | JSON object defining custom providers | -| `BUB_MAX_STEPS` | `sys.maxsize` | `max_steps` | Maximum model Steps per Run; must be a positive integer | -| `BUB_MAX_TOKENS` | `16384` | `max_tokens` | Default output limit; omitted for Codex calls | -| `BUB_SUBAGENT_MAX_CONCURRENCY` | `4` | `subagent_max_concurrency` | Maximum [subagents](/docs/app/subagents/) running at once in the process; later ones wait in a queue | -| `BUB_SUBAGENT_TIMEOUT_SECONDS` | `null` | `subagent_timeout_seconds` | Default time limit of one subagent run; `null` means no limit | -| `BUB_MODEL_TIMEOUT_SECONDS` | `null` | `model_timeout_seconds` | Seconds for one model call, including streaming | -| `BUB_CLIENT_ARGS` | `{}` | `client_args` | JSON object passed to the model client | -| `BUB_COMPLETION_ARGS` | `{}` | `completion_args` | JSON object passed to each generation | -| `BUB_VERBOSE` | `0` | `verbose` | `0` is INFO, `1` is DEBUG, and `2` is TRACE | - -A `null` value for `client_args` or `completion_args` is treated as `{}`. +| `BUB_MODEL` | `openrouter:openrouter/free` | `model` | Model identifier (`provider:model`) | +| `BUB_COMMAND_PREFIX` | `,` | `command_prefix` | Direct command prefix (non-empty, no whitespace) | +| `BUB_FALLBACK_MODELS` | `null` | `fallback_models` | Fallback model list (JSON array in env vars); applies only to the default primary model | +| `BUB_API_KEY` | unset | `api_key` | Global API key string, or provider-to-key mapping dict | +| `BUB_API_BASE` | unset | `api_base` | Global API base URL string, or provider-to-URL mapping dict | +| `BUB__API_KEY` | unset | — | Provider-specific API key (e.g. `BUB_OPENAI_API_KEY`) | +| `BUB__API_BASE` | unset | — | Provider-specific API base URL (e.g. `BUB_OPENROUTER_API_BASE`) | +| `BUB_PROVIDERS` | `{}` | `providers` | Custom provider definitions (JSON object in env vars) | +| `BUB_MAX_STEPS` | `sys.maxsize` | `max_steps` | Maximum model Steps per Run (positive integer) | +| `BUB_MAX_TOKENS` | `16384` | `max_tokens` | Default max output tokens per model call (omitted for `codex:` models) | +| `BUB_SUBAGENT_MAX_CONCURRENCY` | `4` | `subagent_max_concurrency` | Maximum concurrent [subagents](/docs/app/subagents/) per process | +| `BUB_SUBAGENT_TIMEOUT_SECONDS` | `null` | `subagent_timeout_seconds` | Default timeout in seconds for a subagent run (`null` means no limit) | +| `BUB_MODEL_TIMEOUT_SECONDS` | `null` | `model_timeout_seconds` | Timeout in seconds for one model call (including streaming) | +| `BUB_CLIENT_ARGS` | `{}` | `client_args` | Extra kwargs passed to the model client constructor (JSON object) | +| `BUB_COMPLETION_ARGS` | `{}` | `completion_args` | Extra kwargs passed to each model generation call (JSON object) | +| `BUB_VERBOSE` | `0` | `verbose` | Log level: `0` (INFO), `1` (DEBUG), `2` (TRACE) | ### Command prefix {#command-prefix} -| Setting | Effect | +| `command_prefix` | Example | | --- | --- | -| `,` | `,help` and `,tape.info` are commands | -| `!` | `!help` is a command, while `,help` is ordinary text | -| `/` | In Telegram, enter a command with `/bub /help` | - -CLI `quit`, `exit`, `thinking`, completion, and shell mode share this prefix. Telegram also handles its own slash commands; these are not the same parser. +| `,` (default) | `,help` and `,tape.info` are direct commands | +| `!` | `!help` is a direct command; `,help` is ordinary text | +| `/` | In Telegram, invoke via `/bub /help` | ### Credential resolution {#credentials} -Model calls use the first non-empty value in this order: - -| Order | Source | -| --- | --- | -| 1 | `providers..api_key` / `.api_base` | -| 2 | Settings fields `api_key` / `api_base`: the provider's key in the mapping, or the field value when it is a string | -| 3 | `_API_KEY` / `_API_BASE` without the `BUB_` prefix, such as `OPENAI_API_KEY` | +For each model call, Bub resolves the first non-empty `api_key` and `api_base` in this order: -`BUB__API_KEY` / `_API_BASE` is not read directly in step 3 above. At startup, Bub scans `^BUB_(.+)_(API_KEY|API_BASE)$` and writes matches into the settings field mappings, with lower priority than `BUB_API_KEY` / `BUB_API_BASE` in the environment and YAML. Names matching registered Republic providers use their canonical names; others remain lowercase. The client also receives `env_prefix=BUB_` so Republic can read again if the value supplied by Bub is empty. +1. `providers..api_key` and `providers..api_base` (custom providers); +2. The provider entry in the `api_key` / `api_base` mapping (`BUB__API_KEY` and `BUB__API_BASE` scanned at startup populate this mapping with lower priority than explicit `BUB_API_KEY` / `BUB_API_BASE` and YAML values), or the string value if `api_key` / `api_base` is a plain string; +3. Standard provider environment variables without the `BUB_` prefix (such as `OPENAI_API_KEY` or `OPENROUTER_API_KEY`). -If YAML or `BUB_API_KEY` / `BUB_API_BASE` contains a single string, it applies to every provider and prevents mapping and step-3 fallback. Use a mapping or `BUB__…` to configure providers separately. +:::caution +Setting `BUB_API_KEY` / `BUB_API_BASE` (or YAML `api_key` / `api_base`) to a **single string** applies that string to every provider, overriding per-provider mappings and step-3 fallbacks. When using multiple providers (e.g., primary on OpenAI and fallback on OpenRouter), use a mapping or `BUB__API_KEY`. +::: ### Models and fallback {#model-routing} -Common prefixes for `BUB_MODEL`: +Common `BUB_MODEL` prefixes (see [Republic providers](https://getrepublic.org/providers/) for the full list): -| Prefix | Purpose | +| Prefix | Provider | | --- | --- | -| `openai:` | OpenAI or an OpenAI-compatible endpoint | -| `codex:` | ChatGPT plan login | +| `openai:` | OpenAI or any OpenAI-compatible endpoint | +| `codex:` / `grok:` / `github-copilot:` | Account credentials configured via `bub login` | | `openrouter:` | OpenRouter | -| `anthropic:` / `google:` / `azure-openai:` | Native protocols for each provider | -| `ollama:` / `magpie:` | Local services | +| `anthropic:` / `google:` / `azure-openai:` | Native provider APIs | +| `ollama:` / `magpie:` | Local model servers | -See [Republic providers](https://getrepublic.org/providers/) for the complete list. +`fallback_models` applies only when the active model matches the default `model` setting (it is skipped when `model=` is passed in code or after switching models with `,model`). Fallbacks are tried in order only when **connecting or opening the request stream fails**; errors after streaming has started do not retry on another model. -`fallback_models` applies only when the current model identifier matches the configured `model`; it does not apply when `model=` is passed explicitly or the session switches to another model. Fallback attempts to **open** each request in sequence and stops retrying once stream consumption has begun. +### `client_args` and `completion_args` {#client-args} -### `client_args` {#client-args} +Common `client_args` keys: -| Key | Behavior | +| Key | Description | | --- | --- | -| `headers` | Merged with the default `User-Agent: bub/`; explicit values win | -| `api_format` | Usually set to `chat` for an OpenAI-compatible Chat Completions endpoint | -| `env_prefix` | Defaults to `BUB_`, allowing the client to read provider-specific environment variables | -| `timeout` / `max_retries` | Passed to the underlying client; the overall call timeout still comes from `model_timeout_seconds` | -| `api_key` / `api_base` | Supplied by Bub and not read from `client_args` | +| `headers` | Merged with the default `User-Agent: bub/` header (explicit headers win) | +| `api_format` | Set to `"chat"` for OpenAI-compatible `/v1/chat/completions` endpoints | +| `timeout` / `max_retries` | HTTP client request timeout and retry count (overall call timeout is controlled by `model_timeout_seconds`) | -An injected HTTP client must be an `httpx2.AsyncClient` and remains caller-owned. + -### `completion_args` {#completion-args} +Common `completion_args` keys (call-level `options` override matching keys): -| Key | Rule | +| Key | Description | | --- | --- | -| `max_tokens` | Uses `BUB_MAX_TOKENS` when not specified for a call; removed for Codex | -| `reasoning_effort` | Session or per-Turn values override this setting | -| `tools` | Supplied by the Agent for the current Step | -| `extra_body` | Passed to the provider unchanged; Anthropic adds ephemeral cache control by default | +| `max_tokens` | Defaults to `BUB_MAX_TOKENS` when unset (omitted for `codex:` calls) | +| `reasoning_effort` | Overridden by session `,reasoning_effort` or call-level `options` | +| `extra_body` | Passed through to the provider request body | -Call-level `options` override generation options of the same name in `completion_args` before provider encoding. `completion_args.max_tokens` is superseded by `BUB_MAX_TOKENS` or call-level `max_tokens`; do not treat it as an independent limit. Providers may rewrite some fields. If a parameter must apply consistently, prefer an explicit Bub setting over relying on `extra_body`. +### Custom providers (`providers`) {#custom-providers} -### Custom providers {#custom-providers} +Define custom provider prefixes under `providers` when connecting to multiple endpoints that share the same protocol (such as internal gateways or relays): ```yaml model: proxy:gpt-5.5 @@ -208,138 +186,71 @@ providers: | Field | Required | Description | | --- | --- | --- | -| `type` | Yes | Republic provider to emulate; configuration validation fails if it is not registered | -| `api_base` | No | Falls back to the general `api_base` or `BUB__API_BASE` when omitted | -| `api_key` | No | Falls back to the general `api_key` or `BUB__API_KEY` when omitted | - -`proxy:gpt-5.5` and `openai:gpt-5.5` use the same protocol but can use different addresses and keys. +| `type` | Yes | Underlying Republic provider protocol name (e.g. `openai`, `anthropic`) | +| `api_base` | No | Endpoint URL; falls back to `api_base` mapping or `BUB__API_BASE` | +| `api_key` | No | Endpoint API key; falls back to `api_key` mapping or `BUB__API_KEY` | ## ChannelSettings {#channel-settings} -`src/bub/channels/manager.py` - -```python -@config() -class ChannelSettings(Settings): - model_config = SettingsConfigDict( - env_prefix="BUB_", - extra="ignore", - env_file=".env", - ) - enabled_channels: str = "all" - debounce_seconds: float = 1.0 - max_wait_seconds: float = 10.0 - active_time_window: float = 60.0 - stream_output: bool = False -``` +Defined in `src/bub/channels/manager.py` (top-level YAML fields): -| Environment variable | Default | YAML | Description | +| Environment variable | Default | YAML key | Description | | --- | --- | --- | --- | -| `BUB_ENABLED_CHANNELS` | `all` | `enabled_channels` | Comma-separated names, `all`, or `!name` | -| `BUB_DEBOUNCE_SECONDS` | `1.0` | `debounce_seconds` | Batch wait reset after each active message | -| `BUB_MAX_WAIT_SECONDS` | `10.0` | `max_wait_seconds` | Used only while waiting for inactive follow-up messages; not a total batch cap | -| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | `active_time_window` | Seconds after the last active message during which inactive messages may join | -| `BUB_STREAM_OUTPUT` | `false` | `stream_output` | Whether the gateway pushes streaming events to channels; `bub chat` forces `true` | +| `BUB_ENABLED_CHANNELS` | `all` | `enabled_channels` | Channels to enable (comma-separated names, `all`, or `!name` exclusions; see [CLI channel selection](/docs/reference/cli/#channel-selection)) | +| `BUB_DEBOUNCE_SECONDS` | `1.0` | `debounce_seconds` | Debounce wait timer reset after each active message | +| `BUB_MAX_WAIT_SECONDS` | `10.0` | `max_wait_seconds` | Max wait seconds when buffering unmentioned follow-up messages in a group | +| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | `active_time_window` | Seconds after an active message during which unmentioned group messages join the current batch | +| `BUB_STREAM_OUTPUT` | `false` | `stream_output` | Push streaming events to gateway channels (`bub chat` always forces `true`) | -The name `BUB_MAX_WAIT_SECONDS` can be misleading: it is used only when an inactive follow-up message starts a waiting batch. Active-message batches are still timed by `BUB_DEBOUNCE_SECONDS`; continued active messages do not force the batch to end after 10 seconds. Only channels with `needs_debounce=True`, such as Telegram, use this buffering. + -### Channel selection {#channel-selection} - -| `enabled_channels` | Result | -| --- | --- | -| Contains `all` | Every enabled non-`Interface` channel, minus `!name` exclusions | -| Explicit ordinary channels | Listed channels that are enabled and not excluded | -| List contains a non-Lifecycle channel | Also attaches every enabled `Lifecycle` channel | -| Lifecycle channels only | Starts only those Lifecycle channels | -| Only `!name` | No included channels; startup fails | - -`bub gateway --enable-channel` overrides the environment selection and can be repeated. An `Interface` must be selected explicitly, such as `cli` or `acp-server`. See [CLI › Channel selection](/docs/reference/cli/#channel-selection) for more examples. +Debouncing applies only to channels with `needs_debounce=True` (such as Telegram). ## TelegramSettings {#telegram-settings} -`src/bub/channels/telegram.py` +Defined in `src/bub/channels/telegram.py` (under `telegram:` in YAML): -```python -@config(name="telegram") -class TelegramSettings(Settings): - model_config = SettingsConfigDict( - env_prefix="BUB_TELEGRAM_", - extra="ignore", - env_file=".env", - ) - token: str = "" - allow_users: str | None = None - allow_chats: str | None = None - proxy: str | None = None -``` - -| Environment variable | Default | YAML | Description | +| Environment variable | Default | YAML key | Description | | --- | --- | --- | --- | -| `BUB_TELEGRAM_TOKEN` | `""` | `token` | The channel is enabled only when non-empty | -| `BUB_TELEGRAM_ALLOW_USERS` | unset | `allow_users` | Comma-separated user IDs or usernames; empty means unrestricted | -| `BUB_TELEGRAM_ALLOW_CHATS` | unset | `allow_chats` | Comma-separated chat IDs; empty means unrestricted | -| `BUB_TELEGRAM_PROXY` | unset | `proxy` | `http://user:@host:port` or `socks5://host:port` | +| `BUB_TELEGRAM_TOKEN` | `""` | `token` | Telegram bot token; enables the Telegram channel when non-empty | +| `BUB_TELEGRAM_ALLOW_USERS` | unset | `allow_users` | Allowed numeric user IDs or usernames (comma-separated; empty allows all) | +| `BUB_TELEGRAM_ALLOW_CHATS` | unset | `allow_chats` | Allowed chat/group IDs (comma-separated; empty allows all) | +| `BUB_TELEGRAM_PROXY` | unset | `proxy` | HTTP or SOCKS5 proxy URL (e.g. `http://127.0.0.1:7890` or `socks5://host:port`) | -| Match | Ordinary message | `/start` | -| --- | --- | --- | -| Chat ID is not in `allow_chats` | Silently ignored | Replies with fixed rejection text | -| Neither user ID nor username is in `allow_users` | Replies `Access denied.` | Does not check the user | -| Both are configured | Both must match | Checks only the chat | - -See [Gateway › Telegram](/docs/app/gateway/#telegram) for deployment and group-chat behavior. +See [Gateway: Configure Telegram](/docs/app/gateway/#configure-telegram) for allowlist and group-chat rules. ## SpillSettings {#spill-settings} -`src/bub/builtin/spill.py` +Defined in `src/bub/builtin/spill.py` (under `spill:` in YAML): -```python -@config(name="spill") -class SpillSettings(Settings): - model_config = SettingsConfigDict( - env_prefix="BUB_SPILL_", - extra="ignore", - env_file=".env", - ) - threshold: int = 4096 -``` - -| Environment variable | Default | YAML | Description | +| Environment variable | Default | YAML key | Description | | --- | --- | --- | --- | -| `BUB_SPILL_THRESHOLD` | `4096` | `threshold` | Estimated token limit at four characters per token; `0` disables new spills | - -Rendered results of successful tool calls above the threshold are written to the `spill` sidecar, and the model receives a preview and read handle. Negative values violate `ge=0` and fail configuration validation. Preview length, chunk size, and similar values are implementation constants, not settings. +| `BUB_SPILL_THRESHOLD` | `4096` | `threshold` | Estimated token threshold (4 chars ≈ 1 token) for spilling large tool outputs (`0` disables new spills; must be `>= 0`) | -| Situation | Behavior | -| --- | --- | -| Current tool set has no `spill.read` | Does not create a new spill; returns the result unchanged | -| Result is already `spill.read` output | Does not spill it again | -| Threshold is `0` | Stops creating new spills; existing sidecar results remain readable | +When a tool output exceeds this threshold and `spill.read` is available, the full text is written to the `spill` sidecar and the model receives a short preview and handle (`spill.read` outputs are not spilled again). ## Third-party login variables {#login-env} -| Variable | Default | Read by | Description | -| --- | --- | --- | --- | -| `CODEX_HOME` | `~/.codex` | `bub login codex` | Directory containing `auth.json`; can be overridden by `--codex-home` | - -These variables belong to third-party CLIs and are not `AgentSettings` fields. +| Variable | Default | Description | +| --- | --- | --- | +| `CODEX_HOME` | `~/.codex` | Directory storing `auth.json` for `bub login codex` (overridable via `--codex-home`) | -## Session settings {#session-settings} +## Session-persisted settings {#session-settings} -The following are neither environment variables nor YAML fields. Commands write them to the current session Tape, and they are restored for the next Turn and after a restart: +These three settings are modified via comma commands inside a session and stored in the session Tape (taking effect on the **next Turn** and persisting across restarts): -| Key | Switch command (default prefix `,`) | Purpose | +| Setting | Command (default prefix `,`) | Effect | | --- | --- | --- | -| `model` | `,model openai:gpt-5.5` | Overrides the session's default model; configured `fallback_models` does not apply after switching to another model | -| `reasoning_effort` | `,reasoning_effort high` | Overrides `completion_args.reasoning_effort` | -| `code_mode` | `,code_mode enable=true` | Enables or disables code mode for this session | +| `model` | `,model openai:gpt-5.5` | Overrides the session model (`fallback_models` does not apply when switched away from the default model) | +| `reasoning_effort` | `,reasoning_effort high` | Overrides reasoning effort for the session | +| `code_mode` | `,code_mode enable=true` | Enables or disables code mode for the session | -The actual prefix follows `command_prefix`. These values take effect from the next Turn and persist in the session Tape. +## Plugin custom settings {#plugin-settings} -## Plugin settings {#plugin-settings} +Plugins can register their own settings classes with `@config`: ```python from pydantic_settings import SettingsConfigDict - from bub import Settings, config @@ -352,28 +263,13 @@ class OrderSettings(Settings): timeout: int = 30 ``` -| Item | Description | -| --- | --- | -| `@config(name="x")` | Registers under `CONFIG_MAP["x"]`; a section can have multiple classes | -| YAML | Reads from the top-level `x:` section | -| `@config()` | Registers at the root and reads top-level fields | -| Environment variables | Determined by the subclass's `env_prefix` | -| Validation | `configure.validate()` instantiates every registered class with its YAML section data | -| Reading | `ensure_config(cls)` returns the process-cached instance | - -| Function | Purpose | -| --- | --- | -| `configure.load(path)` | Reads YAML and replaces the current configuration data | -| `configure.get_config_data()` | Returns a deep copy; excludes defaults and environment overrides | -| `configure.merge(base, *updates)` | Recursively merges, with later values taking precedence | -| `configure.save(path, data)` | Validates and writes to disk, creating parent directories | -| `configure.get_value(path, default)` | Reads a registered setting by dotted path, then falls back to the root | - -Plugin settings usually support YAML, environment variables, and `.env`. If plugin documentation lists only one variable, do not assume it also has a synonymous `BUB_` name. See [Storage](/docs/integrations/storage/) and [Observability](/docs/integrations/observability/) for common plugin variables. Tracing variables such as `OTEL_*` and `LOGFIRE_TOKEN` are also documented on the observability page and do not belong to the `Settings` classes on this page. +- `@config(name="x")` reads from the top-level `x:` section in `config.yml`; `@config()` reads from the YAML root. +- Call `ensure_config(OrderSettings)` to get the process-cached instance. +- `bub.configure` provides `load(path)`, `get_config_data()`, `merge(base, *updates)`, `save(path, data)`, `validate()`, and `get_value(path, default)`. -## Complete example {#example} +## Full configuration file example {#example} -The following `~/.bub/config.yml` lists every currently writable setting. Every key except `model` can be removed to use its default. +Every field except `model` is optional: ```yaml title="~/.bub/config.yml" model: openrouter:openrouter/free @@ -388,9 +284,11 @@ providers: proxy: type: openai api_base: https://llm-proxy.example.com/v1 - api_key: sk-proxy-... + api_key: "your-provider-api-key" max_steps: 100 max_tokens: 16384 +subagent_max_concurrency: 4 +subagent_timeout_seconds: 600 model_timeout_seconds: 120 client_args: timeout: 60 @@ -409,17 +307,8 @@ spill: threshold: 4096 telegram: - token: "123456:abcdef..." + token: "your-telegram-bot-token" allow_users: "123456789,your_username" allow_chats: "-1001234567890" proxy: socks5://127.0.0.1:7890 ``` - -Settings that do not belong in this file: - -| Setting | Location | Environment variable | -| --- | --- | --- | -| `bub.home` | Runtime path; not written to YAML | `BUB_HOME` | -| Plugin project directory | Command argument `--project` | `BUB_PROJECT` | -| Codex login directory | Third-party CLI | `CODEX_HOME` | -| Session-level `model` / `reasoning_effort` / `code_mode` | Written to the session Tape and switched by commands | — | diff --git a/website/src/content/docs/docs/reference/tools.mdx b/website/src/content/docs/docs/reference/tools.mdx index 443220b1..d4eb6979 100644 --- a/website/src/content/docs/docs/reference/tools.mdx +++ b/website/src/content/docs/docs/reference/tools.mdx @@ -1,18 +1,17 @@ --- title: Built-in tools -description: Parameters, defaults, and results for Bub application's built-in tools and text commands. +description: "Reference manual for Bub app built-in tools and session commands: parameters, defaults, and return values for files, shell, web, Tape, and subagents." --- -This page lists the tools and commands included with the Bub application. Model-facing names use underscores, so `fs.read` becomes `fs_read`; text commands keep the original name, as in `,fs.read path=README.md`. Plugins can add or replace tools, so use `,help`, `,tool.describe`, and `bub hooks` to inspect the actual collection. +This page lists all built-in tools and session commands included in the Bub app layer. -Arguments can be positional or use `key=value`. Write booleans as `true` / `false` and lists as JSON strings. Quote values containing spaces: - -```text -,bash command='printf "hello world"' timeout_seconds=10 -,tool.describe names='["web.fetch", "tape.search"]' -``` - -File, Shell, and code mode operations use the session's `Environment`. By default, they run on the host, not in a security sandbox. +- **Naming convention**: dots in tool names are converted to underscores when exposed to the model (e.g., `fs.read` becomes `fs_read`), while direct terminal commands keep the dotted name (e.g., `,fs.read path=README.md`). +- **Command argument syntax**: supports positional arguments and `key=value` pairs; write booleans as `true` / `false`, lists as JSON strings, and quote values containing spaces: + ```text + ,bash command='printf "hello world"' timeout_seconds=10 + ,tool.describe names='["web.fetch", "tape.search"]' + ``` +- **Execution environment**: `fs.*`, `bash*`, and `run_code` run through the session's `Environment`, which defaults to running directly on the host under the current user (no security sandbox). ## Processes {#processes} @@ -22,14 +21,14 @@ File, Shell, and code mode operations use the session's `Environment`. By defaul bash(command, cwd=None, timeout_seconds=30, background=False) ``` -| Parameter | Description | -| --- | --- | -| `command` | Shell command to execute | -| `cwd` | Working directory; relative paths are resolved by the current environment | -| `timeout_seconds` | Time to wait in the foreground; on timeout, the command continues in the background and returns a `shell_id` | -| `background` | Start in the background immediately; this mode ignores `timeout_seconds` | +| Parameter | Type | Description | +| --- | --- | --- | +| `command` | `str` | Shell command string to execute | +| `cwd` | `str \| None` | Working directory; relative paths resolve against `Environment.workspace` | +| `timeout_seconds` | `float` | Foreground wait timeout in seconds (default 30); on timeout, the process moves to the background and returns a `shell_id` instead of failing | +| `background` | `bool` | Start directly in the background and return `shell_id` immediately (ignores `timeout_seconds`) | -A non-zero exit status produces a tool error and preserves the output. An empty foreground result returns `(no output)`. +A non-zero foreground exit code returns a tool error containing any captured output; a successful foreground command with no output returns `(no output)`. ### `bash.output` {#bash-output} @@ -37,11 +36,13 @@ A non-zero exit status produces a tool error and preserves the output. An empty bash.output(shell_id, offset=0, limit=None) ``` -Read the output buffer by character position. `offset` is clamped between `0` and the current output length; `limit` bounds the characters returned. The result includes `status`, `exit_code`, `output`, and `next_offset` for the following read. `exit_code` is `null` while the process is running. +| Parameter | Type | Description | +| --- | --- | --- | +| `shell_id` | `str` | Background process ID returned by `bash` (e.g. `bsh-12345678`) | +| `offset` | `int` | Starting **character offset** (not line number; clamped between `0` and current buffer length) | +| `limit` | `int \| None` | Maximum characters to read | -```text -,bash.output shell_id=bsh-12345678 offset=0 limit=4000 -``` +Returns `status`, `exit_code` (`null` while running), `output`, and `next_offset` for the next incremental read. ### `bash.kill` {#bash-kill} @@ -49,7 +50,7 @@ Read the output buffer by character position. `offset` is clamped between `0` an bash.kill(shell_id) ``` -Terminate a background process and return its final status and exit code. You can also call it after the process has finished to read its status. +Terminates the specified background Shell process and returns its final status and exit code. ## Files {#files} @@ -59,9 +60,13 @@ Terminate a background process and return its final status and exit code. You ca fs.read(path, offset=0, limit=None) ``` -Read UTF-8 text. `offset` is a zero-based line number and `limit` is the maximum number of lines, not characters. Omit both to return the whole file. +| Parameter | Type | Description | +| --- | --- | --- | +| `path` | `str` | File path to read | +| `offset` | `int` | Zero-based starting line number (default `0`) | +| `limit` | `int \| None` | Maximum number of lines to read (reads to end of file when omitted) | -`.png`, `.jpg`, `.jpeg`, `.webp` and `.gif` files are returned as an image the model can see, up to 10 MiB; `offset` and `limit` are ignored for them. +In addition to UTF-8 text files, `.png`, `.jpg`, `.jpeg`, `.webp`, and `.gif` files up to 10 MiB are returned as multimodal image objects for the model to inspect (`offset` and `limit` are ignored for images). ### `fs.write` {#fs-write} @@ -69,7 +74,7 @@ Read UTF-8 text. `offset` is a zero-based line number and `limit` is the maximum fs.write(path, content) ``` -Write the complete text and create missing parent directories. Existing files are overwritten; this operation does not append or apply patches. +Writes complete UTF-8 text to `path` (creates missing parent directories automatically and overwrites existing files). ### `fs.edit` {#fs-edit} @@ -77,7 +82,7 @@ Write the complete text and create missing parent directories. Existing files ar fs.edit(path, old, new, start=0) ``` -Search from the zero-based `start` line and replace every `old` occurrence in that range with `new`. A missing match produces an error. This is literal text replacement, not syntax-aware code editing. +Replaces all exact literal occurrences of `old` with `new` starting from line `start` (zero-based); returns a tool error if no match is found. ## Web {#web} @@ -87,7 +92,13 @@ Search from the zero-based `start` line and replace every `old` occurrence in th web.fetch(url, headers=None, timeout=10) ``` -Make an HTTP GET request. The default `Accept: text/markdown` header can be overridden through `headers`. `timeout` is the total request time in seconds. The result contains the final `url`, HTTP `status`, `content_type`, and response body; unsuccessful statuses raise tool errors. It fetches one URL and does not provide web search, crawling, or browser interaction. +| Parameter | Type | Description | +| --- | --- | --- | +| `url` | `str` | Target HTTP/HTTPS URL | +| `headers` | `dict \| None` | Optional request headers (overrides default `Accept: text/markdown`) | +| `timeout` | `float` | Total request timeout in seconds (default 10) | + +Sends an HTTP GET request and returns the final `url`, HTTP `status`, `content_type`, and response body (non-2xx statuses return a tool error). ## Skill and tool discovery {#discovery} @@ -97,7 +108,7 @@ Make an HTTP GET request. The default `Accept: text/markdown` header can be over skill(name=None) ``` -Without `name`, list skills available in the current context. With a name, return its location and body. A missing skill returns `(no such skill)` without calling a model. +Lists available skills and descriptions when `name` is omitted; returns the skill path and variable-expanded `SKILL.md` body when `name` is provided (`(no such skill)` if not found). ### `tool.describe` {#tool-describe} @@ -105,13 +116,13 @@ Without `name`, list skills available in the current context. With a name, retur tool.describe(names) ``` -`names` is a list of runtime names or model aliases. The result contains each tool's name, description, and parameter schema, with unrecognized names under `unknown`. Deferred definitions become callable from the next Step, and later Turns offer loaded tools directly until the Tape is reset. Loading is recorded in the current Tape. Requesting a tool that is already loaded returns its name under `already_loaded` instead of its definition. +Loads the full description and JSON Schema for deferred tools (`deferred=True`). Loaded tools become callable from the **next Step** and stay loaded until the session Tape is reset (unrecognized names are returned under `unknown`, and previously loaded tools under `already_loaded`). -## Tape {#tape} +## Session Tape management {#tape} ### `tape.info` {#tape-info} -No parameters. Return the Tape name, entry and anchor counts, latest anchor, entries after it, and the latest recorded token usage and cache hit rate. The last two values are `None` when the provider does not return those details. +No parameters. Returns the physical Tape name, total entry count (`entries`), anchor count (`anchors`), latest anchor (`last_anchor`), entries since the latest anchor (`entries_since_last_anchor`), and the latest token usage and cache hit rate. ### `tape.search` {#tape-search} @@ -119,20 +130,18 @@ No parameters. Return the Tape name, entry and anchor counts, latest anchor, ent tape.search(query, limit=20, start=None, end=None, kinds=["message", "tool_result"]) ``` -| Parameter | Description | -| --- | --- | -| `query` | Case-insensitive substring match against the JSON text of entry kind, date, payload, and meta | -| `limit` | Maximum number of matching entries to read | -| `start` / `end` | Optional inclusive ISO date or time bounds | -| `kinds` | Entry kinds: `message`, `tool_call`, `tool_result`, `event`, `anchor`, `system`, or `error` | - -The result contains `matches` and a `filtered` count. Output produced by the search command itself is filtered so repeated searches do not recursively include earlier results. +| Parameter | Type | Description | +| --- | --- | --- | +| `query` | `str` | Search keyword (case-insensitive; `FuzzyFileTapeStore` searches newest-first, deduplicates identical text, and supports fuzzy matching for queries of 3+ chars) | +| `limit` | `int` | Maximum matching entries to return (default 20) | +| `start` / `end` | `str \| None` | Optional inclusive ISO date or timestamp bounds | +| `kinds` | `list[str]` | Entry kinds to search | -The builtin application uses `FuzzyFileTapeStore`: text searches walk backward from the newest entry, deduplicate identical content, and try fuzzy matches in addition to direct substrings. Queries shorter than three characters use substring matching only. `kinds` and dates are filtered first, then `limit` applies to the deduplicated results. Other Tape backends define their own fuzzy matching and ordering. +Returns `matches` and the count of `filtered` duplicate/self-search entries. ### `tape.anchors` {#tape-anchors} -No parameters. List anchor names in recording order, or return `(no anchors)`. +No parameters. Lists all anchor names in the current session Tape in recording order (`(no anchors)` if empty). ### `tape.handoff` {#tape-handoff} @@ -140,15 +149,15 @@ No parameters. List anchor names in recording order, or return `(no anchors)`. tape.handoff(name="handoff", summary="") ``` -Write an anchor that moves the default context start to this point. Earlier entries remain in storage. Bub does not generate a summary. The default context reads after the anchor, so the boundary anchor itself does not enter model input; when reading with `anchor=None`, the default selector converts it into the assistant message `[Anchor created: ]: `. +Appends a new anchor named `name` (storing `summary` in `state.summary`), advancing the default model context start point to this anchor. Does not automatically generate a summary. ### `tape.reset` {#tape-reset} ```text -tape.reset(archive=false) +tape.reset(archive=False) ``` -Clear the current Tape. With `archive=true`, first archive the main Tape and sidecars into the backup directory under Bub home's `tapes/`; the default does not archive. Reset creates a new `session/start` anchor and does not automatically restore backups. +Clears the current session Tape and writes a new `session/start` anchor. When `archive=True`, backs up the main Tape and sidecars to `/tapes/` with a UTC timestamp and `.bak` suffix before clearing. ## Subagents {#subagent} @@ -161,51 +170,17 @@ subagent(prompt, agent=None, description=None, model=None, reasoning_effort=None | Parameter | Type and default | Description | | --- | --- | --- | -| `prompt` | String or content-block list, required | The task for the subagent | -| `agent` | `str \| None`, default `None` | Name of a [subagent profile](/docs/app/subagents/#profiles); its settings apply unless given here | -| `description` | `str \| None`, default `None` | Short label shown in task lists; defaults to the prompt's first line | -| `model` | `str \| None`, default `None` | `provider:model` for the child run; by default, the profile's model or the current configuration | -| `reasoning_effort` | `str \| None`, default `None` | Reasoning effort of the child's model | -| `session` | `str`, default `"temp"` | Session strategy for the subagent | -| `allowed_tools` | `list[str] \| None`, default `None` | Tools the subagent may use; by default, the parent run's tools | -| `allowed_skills` | `list[str] \| None`, default `None` | Skills the subagent may use; by default, the parent run's skills | -| `timeout_seconds` | `int \| None`, default `None` | Stop the child after this many seconds; defaults to the profile's limit, then `BUB_SUBAGENT_TIMEOUT_SECONDS` | - -Tool names can be runtime names or model aliases, so both `fs.read` and `fs_read` work. A child never gets more than its parent: the tools default to the parent run's allowed tools, and naming a tool outside them is an error. Skill names are case-insensitive and are likewise narrowed to the parent's; `allowed_skills=[]` disables skill discovery. Children cannot start or manage subagents, so `subagent` and `subagent.*` are always excluded. - -`session` determines what the subagent starts from and what is kept: - -| Value | Behavior | -| --- | --- | -| `temp` | Creates an empty `temp/` session that is discarded afterwards | -| `fork` | Starts from a copy of the current conversation, including the current turn so far, and is discarded afterwards; `inherit` is accepted as an alias | -| Any other string | Uses that session ID; the session is kept and can be continued later with `subagent.send` | - -A fork copies the parent's Tape when the call is made, so the child does not see what the parent records later. Each child gets its own turn state: a shallow copy of the parent's without the parent's steering key, tool scope or running Tape, so messages steered into the parent stay with the parent. - -The tool returns: - -```python -{ - "task_id": "sub-1a2b3c4d", - "session_id": "temp/sub-1a2b3c4d", - "status": "completed", # queued, running, completed, failed or cancelled - "output": "...", - "errors": [], -} -``` - -The subagent runs in the background: the tool returns at once with status `queued` or `running` and an empty `output`. When the task ends, the parent receives its result as a message: - -```text - -... - -``` - -`output` is the child's final answer: the text of its last step that made no tool calls. A run that started subagents does not end while their results are outstanding: when a step ends without tool calls, the run waits for the next task to finish and continues with its notification. A task that ends after its run, because the run failed, was cancelled or reached `max_steps`, reports through the session's steering inbox: before the next step of a running turn, or with the next turn. Results read with `subagent.wait` send no notification. - -At most `BUB_SUBAGENT_MAX_CONCURRENCY` subagents run at once in the process; later ones wait with status `queued`. Ending the runtime, or the `quit` command for a session, cancels running subagents. When a `temp` or `fork` subagent ends, the background shells it started are stopped. +| `prompt` | `str \| list` (required) | Task instructions for the subagent | +| `agent` | `str \| None` (`None`) | [Subagent profile](/docs/app/subagents/#profiles) name; explicit call arguments override profile settings | +| `description` | `str \| None` (`None`) | Short task label; defaults to the first line of `prompt` | +| `model` | `str \| None` (`None`) | Model for the subagent (`provider:model`); defaults to profile model or parent model | +| `reasoning_effort` | `str \| None` (`None`) | Reasoning effort for the subagent | +| `session` | `str` (`"temp"`) | Session mode: `"temp"` (blank session discarded on exit), `"fork"` / `"inherit"` (snapshot copy of current conversation discarded on exit), or a custom session ID string (persisted) | +| `allowed_tools` | `list[str] \| None` (`None`) | Allowed tool names (must be a subset of the parent's tools; `subagent*` is always excluded) | +| `allowed_skills` | `list[str] \| None` (`None`) | Allowed skill names (subset of parent's skills; `[]` disables skills) | +| `timeout_seconds` | `int \| None` (`None`) | Timeout in seconds; defaults to profile timeout, then `BUB_SUBAGENT_TIMEOUT_SECONDS` | + +`subagent` starts the task asynchronously in the background and returns `task_id` with initial status `queued` or `running`. When the child finishes, the parent receives a `` containing the child's final answer before its next Step. The parent run waits for all subagents it started to finish before completing. ### `subagent.wait` {#subagent-wait} @@ -213,7 +188,7 @@ At most `BUB_SUBAGENT_MAX_CONCURRENCY` subagents run at once in the process; lat subagent.wait(task_ids=None, timeout_seconds=60) ``` -Return task results, waiting up to `timeout_seconds` for the tasks to finish; `0` checks without waiting. Without `task_ids`, it covers the session's tasks whose results were not read yet. Tasks still running after the timeout are returned with their current status. +Waits for and returns subagent results (`task_ids` defaults to all unread tasks in the session; `timeout_seconds=0` checks status without blocking). Tasks read via `subagent.wait` do not send a duplicate ``. ### `subagent.send` {#subagent-send} @@ -221,7 +196,7 @@ Return task results, waiting up to `timeout_seconds` for the tasks to finish; `0 subagent.send(task_id, message) ``` -Send a message to a task. A running task receives it before its next step. A finished task with a named session continues that conversation as a new background task, bounded by the current run's tools; a finished `temp` or `fork` task cannot be continued. +Sends a follow-up instruction to a running task (read before its next Step), or resumes a finished task that used a custom named session (finished `temp` / `fork` tasks cannot be resumed). ### `subagent.cancel` {#subagent-cancel} @@ -229,25 +204,19 @@ Send a message to a task. A running task receives it before its next step. A fin subagent.cancel(task_id) ``` -Stop a running task. Its status becomes `cancelled`, and any partial output is kept. +Cancels a running subagent task, setting its status to `cancelled` and preserving partial output. -### Events {#subagent-events} +### Subagent events {#subagent-events} -Every task publishes events on the agent's event bus (`agent.events`), with the starting run's turn state as `state`: +Subagents emit three events on `agent.events` (importable from `bub.builtin.subagents`, each carrying `event.task: SubagentTask`): -| Event | When | +| Event class | When it fires | | --- | --- | -| `SubagentStarted` | The task left the queue and its child run is starting | -| `SubagentOutput` | The child run produced a stream event, available as `event` | -| `SubagentFinished` | The task ended as `completed`, `failed` or `cancelled` | - -Each carries `task`, a `SubagentTask` with `task_id`, `session_id`, `parent_session_id`, `parent_call_id`, `description`, `model`, `profile`, `status`, `output`, `errors`, `usage`, step and tool-call counts, and timestamps. They are importable from `bub.builtin.subagents`. A failing handler is logged and does not fail the child run. - -The subagent shares its `BubAgent`, plugin hooks, model credentials, workspace, `Environment`, files, and external systems with the parent Agent. A session strategy isolates **conversation records and model context**, not file, network, or process side effects. To isolate execution, provide a separate [execution environment](/docs/app/tools/#environment); for approval, use [tool interception](/docs/sdk/events/#control-tool-call). In chat, **the model generates the arguments**, so `allowed_tools` is not a security boundary on its own. - -See [Subagents](/docs/app/subagents/) for complete usage examples. +| `SubagentStarted` | Task leaves the queue and begins running | +| `SubagentOutput` | Child run yields a `StreamEvent` (stored on `event.event`) | +| `SubagentFinished` | Task finishes as `completed`, `failed`, or `cancelled` | -## Code mode and large results {#code-and-spill} +## Code mode and large outputs (Spill) {#code-and-spill} ### `run_code` {#run-code} @@ -255,7 +224,7 @@ See [Subagents](/docs/app/subagents/) for complete usage examples. run_code(code, timeout_seconds=120) ``` -Execute Python in code mode. Call tools with `await tools.(key=value)` using keyword arguments. Only printed output and explicitly attached media enter the result. See [Custom tools and code mode](/docs/sdk/tools/) for complete usage. +Executes Python code in code mode. Call other tools inside the code via `await tools.(key=value)` (keyword arguments); only `print()` output and explicitly attached media are returned. ### `attach_image` / `attach_audio` / `attach_video` {#attach-media} @@ -265,32 +234,31 @@ attach_audio(audio) attach_video(video) ``` -Attach an image, audio clip, or video to the current `run_code` result. The corresponding parameter accepts a `republic.Image`, `republic.Audio`, or `republic.Video` object, or a string containing a file path in the current `Environment`, an `http(s)` or `gs` URL, or a data URL. Local files are resolved and read through the current environment. - -These tools have `exposure="code"` and can only be called inside `run_code`. Each call appends the media to the result and returns a confirmation string. +Attaches a Republic media object, local file path, or URL to the current `run_code` result (`exposure="code"`, callable only inside `run_code`). ### `spill.read` {#spill-read} ```text -spill.read(handle, cursor=0, count=1, from_end=false) +spill.read(handle, cursor=0, count=1, from_end=False) ``` -Read a large tool result moved into the spill sidecar. `handle` comes from the original tool output, `cursor` is the chunk position, and `count` can read at most four chunks per call. With `from_end=true`, read backward from the end. Use `next_cursor` for the following page; `complete=true` marks the boundary in that direction. - -New spills are created only when the current model tools include `spill.read`. Configure the threshold with [`BUB_SPILL_THRESHOLD`](/docs/reference/settings/#spill-settings). Setting it to `0` stops new spills but leaves existing results readable. +| Parameter | Type | Description | +| --- | --- | --- | +| `handle` | `str` | Spill handle ID from the truncated tool output preview | +| `cursor` | `int` | Starting chunk cursor | +| `count` | `int` | Number of consecutive chunks to read (up to 4) | +| `from_end` | `bool` | Read backward from the end | -Results above the threshold are written to the `spill` sidecar, and the main conversation keeps only a preview and a handle. A sidecar is a separate Tape paired with the session Tape: it forks, merges, and resets with it, but its entries never enter the main context. See [Sidecars](/docs/sdk/tape/#sidecars) for the concept. +Returns `next_cursor` and `complete`. The spill threshold is controlled by [`BUB_SPILL_THRESHOLD`](/docs/reference/settings/#spill-settings). -## Session commands {#session-commands} +## Session control commands {#session-commands} -These tools have `exposure="command"`: they are available as text commands and are not exposed directly to the model. +These tools have `exposure="command"` and can only be called directly with the command prefix (`,` by default); they are not exposed to the model: | Command | Parameters | Purpose | | --- | --- | --- | -| `,help` | None | List internal commands and the command prefix | -| `,model` | `model_id` | Switch the session model from the next Turn and record it in the Tape | -| `,reasoning_effort` | `reasoning_effort` | Set session reasoning effort; supported values depend on the provider | -| `,code_mode` | `enable=true` / `false` | Toggle session code mode from the next Turn | -| `,quit` | None | Clear pending messages, running tasks, and background Shell processes for the session | - -Session settings are recorded in the Tape and restored after a restart. They are not `BUB_*` environment variables; see [Settings](/docs/reference/settings/#session-settings) for configuration precedence. +| `,help` | None | List available internal commands and the active command prefix | +| `,model` | `model_id` | Switch the session model starting from the next Turn (recorded in the Tape) | +| `,reasoning_effort` | `reasoning_effort` | Set session reasoning effort starting from the next Turn | +| `,code_mode` | `enable=true` / `false` | Enable or disable code mode for the session (from the next Turn) | +| `,quit` | None | Clear pending messages, cancel active subagents, and terminate background Shell processes for the session | diff --git a/website/src/content/docs/docs/sdk/events.mdx b/website/src/content/docs/docs/sdk/events.mdx index 8be4dbe5..f78571e8 100644 --- a/website/src/content/docs/docs/sdk/events.mdx +++ b/website/src/content/docs/docs/sdk/events.mdx @@ -1,114 +1,103 @@ --- title: Events -description: Register and remove Agent event handlers, modify arguments, deny or replace tool calls, and publish custom events. +description: "Intercept and customize Bub SDK Agent runs in Python: register event handlers, modify tool arguments, deny or replace calls, and emit events." --- -Tools hold the business logic, such as looking up an order or updating its status. Real applications often need extra logic around those calls: logging, sanitizing arguments, checking permissions, or measuring latency. +Tools hold your business logic (such as looking up an order or updating its status), while real applications often need extra cross-cutting logic around those calls—logging, argument sanitization, permission checks, or latency metrics. With the `agent.events` event bus, you can hook into model and tool calls without modifying the tool functions themselves. -Agent events provide hooks into these stages. By listening to and handling them, you can extend the Agent's behavior without changing the tools themselves. For how the three kinds of data differ and which delivery rules apply, see [Agent events](/docs/concepts/events/#three-kinds). +For the difference between the three event/record types and synchronous delivery rules, see [Agent events](/docs/concepts/events/#three-kinds); for a comparison with App hooks (`@hookimpl`), see [Agent events vs. App hooks](/docs/concepts/events/#app-hooks). -## Agent events vs. App Hooks {#events-and-app-hooks} +## Register and remove handlers {#register} -For the division of responsibilities, see [Division of labor with App hooks](/docs/concepts/events/#app-hooks). In the SDK, use `agent.events` to add logic around model or tool calls. +`agent.events.on()` can be called directly or used as a decorator; `off()` removes a handler: -## Registering and removing handlers {#register} - -`EventBus.on()` both registers directly and works as a decorator; `off()` removes a handler: - -```python -from bub.core.events import StepFinished, ToolCallStarted +```python "agent.events.on" "agent.events.off" +from bub.core.events import ToolCallStarted def record_tool_start(event: ToolCallStarted) -> None: print(f"Calling: {event.call.tool}") -# Register +# Direct registration agent.events.on(ToolCallStarted, record_tool_start) -# The decorator form is equivalent + +# Decorator registration @agent.events.on(ToolCallStarted) def log_tool_start(event: ToolCallStarted) -> None: print(f"Arguments: {event.call.arguments}") -# Remove +# Unregister agent.events.off(ToolCallStarted, record_tool_start) ``` -A handler registered for a base class also receives its subclasses: listening for `AgentEvent` covers everything, and `TapeEvent` gives you `event.tape`. Handlers may be plain functions or `async def`. +Handlers can be synchronous functions or `async def` coroutines. A handler registered on a base class receives all its subclasses (`AgentEvent` receives every event; `TapeEvent` receives every event with `event.tape`). ## Listen for tool calls {#listen-to-tool-calls} -Using the order-lookup tool as an example, here is how to log calls. The tool function only performs the lookup; the event handler records the call. +Using an order-lookup tool as an example, let's decouple business logic from logging: the tool only looks up the order, while an event handler records each call. First, define the tool and initialize the Agent: ```python from bub.core import Agent -from bub.core.events import ToolCallStarted from bub.core.tools import tool @tool def get_order(order_id: str) -> dict[str, str]: - """Look up an order's status by its ID.""" + """Look up an order's status by ID.""" return {"order_id": order_id, "status": "shipped"} agent = Agent( tools=[get_order], - system_prompt="Use the get_order tool to answer order status questions.", + system_prompt="Use get_order to answer order status questions.", ) - ``` -When the tool finishes, `ToolCallFinished` provides the result, any error, and the duration: +Listen to `ToolCallFinished` to log the status and duration of each call: ```python from bub.core.events import ToolCallFinished + @agent.events.on(ToolCallFinished) def log_tool_finish(event: ToolCallFinished) -> None: status = "error" if event.result.error else "ok" - print( - f"Finished: {event.result.tool}, " - f"{status}, {event.result.duration_ms}ms" - ) - + print(f"Finished: {event.result.tool}, {status}, {event.result.duration_ms}ms") ``` -## Tool call flow {#tool-call-order} +## Tool event execution order {#tool-call-order} In the Agent loop, a tool call follows this path: ```mermaid flowchart TD - A[The model requests a tool] --> B[ToolCallStarted is emitted] - B --> C[Started handlers run in registration order] - C --> D{Handler decisions} - D -->|Proceed| E[Run the tool function] - D -->|Deny| F[Skip the tool; produce a tool error] - D -->|Replace| G[Skip the tool; use the given result] - E --> H[ToolCallFinished is emitted] + A[Model requests tool call] --> B[Emit ToolCallStarted] + B --> C[Run handlers in registration order] + C --> D{Handler decision} + D -->|Proceed| E[Execute tool function] + D -->|Deny| F[Skip tool; produce tool error] + D -->|Replace| G[Skip tool; use replacement result] + E --> H[Emit ToolCallFinished] F --> H G --> H - H --> I[The result returns to the model loop] - I --> J{Does the Run end?} + H --> I[Return result to model loop] + I --> J{Did the Run finish?} J -->|No| A - J -->|Yes| K[Close the stream and emit RunFinished] - + J -->|Yes| K[Close stream and emit RunFinished] ``` -`ToolCallStarted` handlers run before the tool does. Several handlers run in registration order; if one sets a deny or replace decision, the remaining handlers and the tool function are skipped. - -`ToolCallFinished` is emitted whether the tool ran normally, was denied, or was replaced. A finished tool call does not end the Agent run; listen for `RunFinished` to judge the final state. - -Tool calls made through code mode's `tools.()` and through text commands emit the same two events. +- Multiple `ToolCallStarted` handlers run in registration order; if a handler sets a `deny` or `replace` decision, subsequent handlers and the tool function are skipped. +- `ToolCallFinished` fires whether the tool ran normally, was denied, or was replaced. Note that a finished tool call does not end the Agent run; listen for `RunFinished` to check the final outcome. +- Tool calls triggered via code mode (`tools.()`) and direct commands emit the same two events. ## Modify arguments before execution {#modify-tool-call} -Handlers can also change arguments before the tool runs. For example, strip whitespace from an order ID and uppercase it: +Beyond observing calls, handlers can also sanitize or rewrite arguments before execution. Because `ToolCall` is immutable, use `dataclasses.replace()` in a `ToolCallStarted` handler to update `event.call` (for example, trimming whitespace and uppercasing an order ID): -```python +```python {14} from dataclasses import replace from bub.core.events import ToolCallStarted @@ -122,59 +111,44 @@ def normalize_order_id(event: ToolCallStarted) -> None: **event.call.arguments, "order_id": event.call.arguments["order_id"].strip().upper(), } - # ToolCall is immutable; build a new object with replace and reassign it event.call = replace(event.call, arguments=arguments) - ``` -## Permission checks and decisions {#control-tool-call} +## Deny or replace calls {#control-tool-call} -By setting `event.decision`, a handler can proceed, deny, or use a replacement result before execution. For the semantics of all four outcomes, see [Decisions come before side effects](/docs/concepts/events/#call-control); the examples below show how to write them. +Before a tool runs, you can also set `event.decision` to enforce permissions, block a call, or return a cached result (see [Pre-call interception and decisions](/docs/concepts/events/#call-control)): -### 1. Deny a call {#deny-a-call} +### 1. Deny a tool call {#deny-a-call} -To block certain operations by argument (for example, disallow a special order): - -```python +```python "ToolCallDecision.deny" from bub.core.events import ToolCallDecision, ToolCallStarted @agent.events.on(ToolCallStarted) def check_order_access(event: ToolCallStarted) -> None: - if ( - event.call.tool == "get_order" - and event.call.arguments.get("order_id") == "A123" - ): - event.decision = ToolCallDecision.deny("This order may not be looked up.") - + if event.call.tool == "get_order" and event.call.arguments.get("order_id") == "A123": + event.decision = ToolCallDecision.deny("Access to this order is not permitted.") ``` -After `ToolCallDecision.deny(...)`, the tool function does not run. The model loop hands the denial back to the model as a tool error; a direct command has no model to receive it, so the error is raised to the caller instead. +When denied, the tool function does not run. The model loop returns the denial message to the model as a tool error; for direct commands, the error is raised to the caller. -### 2. Use a replacement result {#replacement-result} +### 2. Return a replacement result {#replacement-result} -When the data is already available (for example, a cache hit), skip the tool and return it: +Skip the tool function and return a cached or mocked result directly: -```python +```python "ToolCallDecision.replace" @agent.events.on(ToolCallStarted) def use_cached_order(event: ToolCallStarted) -> None: - if ( - event.call.tool == "get_order" - and event.call.arguments.get("order_id") == "A123" - ): - event.decision = ToolCallDecision.replace( - {"order_id": "A123", "status": "shipped"} - ) - + if event.call.tool == "get_order" and event.call.arguments.get("order_id") == "A123": + event.decision = ToolCallDecision.replace({"order_id": "A123", "status": "shipped"}) ``` -### 3. Change a model call {#control-llm-call} +### 3. Modify or short-circuit a model call {#control-llm-call} -`LLMCallStarted` supports replacing the whole request or producing output without calling the provider: +In `LLMCallStarted`, replace `event.request` (e.g., to cap `max_tokens`) or set `LLMCallDecision.finish(text)` to return text without calling the model provider: -```python +```python "LLMCallDecision.finish" from dataclasses import replace - from bub.core.events import LLMCallDecision, LLMCallStarted @@ -186,13 +160,12 @@ def guard_llm_call(event: LLMCallStarted) -> None: event.decision = LLMCallDecision.finish("Offline demo mode is active.") ``` -## Custom events {#custom-events} +## Emit custom events {#custom-events} -Events are ordinary dataclasses: subclass `AgentEvent` to publish one, or `TapeEvent` when it needs the current Tape: +Besides listening to built-in events, you can define and emit your own. Events are plain Python dataclasses—subclass `AgentEvent` (or `TapeEvent` when you need the current Tape): -```python +```python "class OrderReviewed(TapeEvent):" "await agent.events.emit" from dataclasses import dataclass - from bub.core.events import TapeEvent @@ -213,18 +186,17 @@ async def mark_reviewed() -> None: ) ``` -Conventions: +Notes: -- `TapeRecorder` does not record custom events automatically; the example writes one explicitly. -- Tracing and Tape recording are independent: turning tracing off stops neither `TapeRecorder` nor the Tape records of conversation and tool round-trips. -- Custom events have no built-in `decision` protocol. Define mutable fields to return data, and override the `stopped` property if a decision should end delivery. -- Tools can emit events through `context.events`. +- **Record to the Tape explicitly**: `TapeRecorder` does not write custom events to the Tape automatically; call `event.tape.append_event(...)` if you want them persisted. +- **Custom fields and early stop**: custom events have no built-in `decision` attribute. Define mutable fields to collect handler results, and override `stopped` to stop further handlers early. +- **Emit from tools**: tools can emit events via `context.events.emit(...)`. -## Model, Step, and Run events {#other-events} +## Listen to Model, Step, and Run events {#other-events} -A run is made of three granularities — model calls (LLMCall), steps (Step), and the run itself (Run) — each worth listening to for metrics, usage statistics, and audit logs. +Beyond tool calls, an Agent run exposes three lifecycle levels—model calls, Steps, and the Run itself—useful for metrics, token usage tracking, and audit logs. -### 1. Model calls {#model-calls} +### 1. Model call events {#model-calls} ```python from bub.core.events import LLMCallFinished, LLMCallStarted @@ -232,7 +204,7 @@ from bub.core.events import LLMCallFinished, LLMCallStarted @agent.events.on(LLMCallStarted) def log_llm_start(event: LLMCallStarted) -> None: - print(f"Calling the model with {len(event.request.messages)} messages") + print(f"Calling model with {len(event.request.messages)} messages") @agent.events.on(LLMCallFinished) @@ -240,13 +212,12 @@ def log_llm_finish(event: LLMCallFinished) -> None: if event.result.error: print(f"Model call failed: {event.result.error}") else: - print(f"Model call succeeded, token usage: {event.result.usage}") - + print(f"Model call succeeded, usage: {event.result.usage}") ``` ### 2. Step events {#step-events} -A Step is one model inference plus the tool calls it requested. `StepFinished.status` says whether the run continues after this step (`continue`) or ends (`ok`): +`StepFinished` fires after each pass of model inference + tool execution. `event.status` is `"continue"` when another Step follows, or `"ok"` when the model produced a final reply: ```python from bub.core.events import StepFinished, StepStarted @@ -260,14 +231,13 @@ def log_step_start(event: StepStarted) -> None: @agent.events.on(StepFinished) def log_step_finish(event: StepFinished) -> None: print(f"--- Step {event.step} finished: {event.status}, {event.elapsed_ms}ms ---") - ``` -Setting `StepFinished.next_prompt` gives the next step of a continuing run a user message; a `MessagesPending` handler adds messages that arrived during the run through `event.messages`. +Set `StepFinished.next_prompt` (when `status == "continue"`) to append a user prompt to the next Step, or listen to `MessagesPending` and append to `event.messages` to inject steering messages that arrived during execution. ### 3. Run events {#run-events} -`RunStarted` and `RunFinished` bracket the whole task. Note especially that `RunFinished` fires when the run's stream closes, including on normal completion, an exception, or an early cancel. A Run closed before it is iterated ends as `cancelled` with zero steps. +`RunStarted` and `RunFinished` bracket the entire Run. `RunFinished` fires **when the stream closes**; a Run closed before iteration ends with `status="cancelled"` and `steps=0`: ```python from bub.core.events import RunFinished, RunStarted @@ -275,12 +245,12 @@ from bub.core.events import RunFinished, RunStarted @agent.events.on(RunStarted) def log_run_start(event: RunStarted) -> None: - print("Agent run started...") + print("Run started...") @agent.events.on(RunFinished) def log_run_result(event: RunFinished) -> None: - print(f"Agent run finished: status={event.status}, steps={event.steps}") + print(f"Run finished: status={event.status}, steps={event.steps}") ``` -The full event list, fields, and trigger points are in the [Python API: events](/docs/reference/python-api/#events). +See [Python API: Events](/docs/reference/python-api/#events) for all event classes and fields. diff --git a/website/src/content/docs/docs/sdk/index.md b/website/src/content/docs/docs/sdk/index.md index 2082efe1..54c03d9f 100644 --- a/website/src/content/docs/docs/sdk/index.md +++ b/website/src/content/docs/docs/sdk/index.md @@ -1,25 +1,27 @@ --- -title: The Agent Loop -description: "Drive bub.core.Agent from your own code: consume the run stream, read stream events, and manage Tape memory." +title: Run the Agent Loop with the SDK +description: Embed bub.core.Agent in your Python application to drive the model-tool loop, consume async event streams, and manage Tape session memory. +sidebar: + label: The Agent Loop --- -`bub.core.Agent` is the minimal core of `bub`. It drives the interaction loop between the model and your local tools, and you can embed it directly in any Python service, backend framework, or custom script. +`bub.core.Agent` is Bub's minimal kernel. It drives the interaction loop between a model and your local tools, and can be embedded directly in any Python service, backend framework, or script. In [Quickstart](/docs/getting-started/quickstart/), we already saw how to initialize and run an Agent: -```py +```py title="main.py" {8, 13} import asyncio import republic from bub.core import Agent async def main() -> None: - # Create the core Agent and give it a system prompt + # Create the core Agent with a system prompt agent = Agent(system_prompt="Be concise.") - # Use republic to get the underlying model connection + # Connect to the model via republic async with republic.get_model("openai:gpt-5-mini") as model: - # Start a Run and name the conversation Tape + # Start a Run on the named Tape async with agent.run("What can you do?", model=model, tape="demo") as stream: async for event in stream: if event.kind == "text": @@ -29,29 +31,29 @@ async def main() -> None: asyncio.run(main()) ``` -This page covers consuming run streams, handling stream events, and managing Tapes. For the definitions of Runs, Steps, and Turns, see [The Agent loop](/docs/concepts/agent/#loop). +Next, we will walk through consuming the event stream, handling stream events, and managing Tapes. For definitions of Runs, Steps, and Turns, see [The Agent loop](/docs/concepts/agent/#loop). -## 1. Runs and Steps {#run-and-step} +## 1. Run and Step flow {#run-and-step} -The diagram below shows a multi-step Run that calls a tool: +A multi-step Run that calls tools progresses as follows: ```mermaid flowchart TD - Start["Enter agent.run() and initialize a Tape fork"] --> Consume["Caller iterates the event stream with async for"] + Start["Enter agent.run(), create Tape fork"] --> Consume["Caller iterates stream with async for"] Start --> RunStarted["Emit RunStarted"] - Consume --> Step["Start a Step: send context to the model"] + Consume --> Step["Start Step: send context to model"] Step --> Output["Yield reasoning / text / usage"] Output --> Decision{"Did the model request tools?"} - Decision -->|"Yes"| Call["Yield tool_call and run the local tool"] - Call --> Result["Yield tool_result and the Step's final"] + Decision -->|"Yes"| Call["Yield tool_call and execute local tools"] + Call --> Result["Yield tool_result and Step final"] Result --> Step - Decision -->|"No"| Final["Yield the final text and a final event"] - Final --> Close["Close the stream, emit RunFinished, merge the Tape fork"] + Decision -->|"No"| Final["Yield final text and Step final"] + Final --> Close["Close stream, emit RunFinished, merge Tape fork"] ``` -## 2. Consuming the stream {#consume-the-stream} +## 2. Consuming the event stream {#consume-the-stream} -After you enter `agent.run()`, `bub` initializes the session and emits `RunStarted`. The underlying model and tool loop uses **lazy evaluation**: the Agent starts stepping and working only when you consume the event stream. Creating the context without consuming the stream does not run the task. A simple example: +Entering `agent.run()` initializes the session and emits `RunStarted`, but execution is **lazy**: model calls and tool executions advance only as you iterate the event stream with `async for`—simply entering the context without consuming the stream does not run the task. ```python async with agent.run(prompt, model=model, tape="quickstart") as stream: @@ -59,39 +61,36 @@ async with agent.run(prompt, model=model, tape="quickstart") as stream: ... ``` -Always put `agent.run()` inside an `async with` block. That guarantees the underlying connection and stream are cleaned up whether the Run completes normally, raises partway through, or is cancelled from outside. A Run that does not complete normally ends with the `cancelled` status. - -You can read the type of every event from `event.kind`. +Always wrap `agent.run()` in an `async with` block so the stream and underlying resources are cleaned up on normal completion, exceptions, or cancellation. A Run closed before completion ends with `status="cancelled"`. :::caution -A `final` event marks the end of the **current Step**, not the end of the Run. -If the model requested tools in the current Step, the Agent must run them and then enter another Step with the results, producing more events. So whether you are streaming a response to a client or tracking task completion, wait for the entire `async for event in stream` loop to finish before acting on it. +An `event.kind == "final"` event marks the end of the **current Step**, not the end of the Run. If the model requested tools in that Step, the Agent runs them and enters another Step, emitting further events. Wait for the `async for event in stream` loop to finish to know the whole Run is complete. ::: -## 3. Event types and payloads {#stream-events} +## 3. Stream event types {#stream-events} -As you iterate over `stream`, you receive events with different `kind` values. Each event's `event.data` has the following shape: +As you iterate over `stream`, you receive events with different `kind` values. Inspect `event.kind` and `event.data` as they arrive: -| Event type | Example `event.data` | Meaning | +| `event.kind` | `event.data` shape | Meaning | | --- | --- | --- | -| `reasoning` | `{"delta": "..."}` | Text deltas from the model's chain of thought or reasoning | -| `text` | `{"delta": "..."}` | Text deltas of the user-facing reply | -| `tool_call` | `{"tool_calls": [{"id", "name", "arguments"}, ...]}` | Tools the model asked to call (`arguments` is a JSON string) | -| `tool_result` | `{"tool_results": [...]}` | Execution results in call order; error details are also returned to the model here | -| `usage` | `{"usage": {...}, "elapsed_seconds": ...}` | Token usage and elapsed time for the current Step | -| `final` | `{"ok": True, "text": ...}` or a tool summary | Summary of the current Step | +| `reasoning` | `{"delta": "..."}` | Incremental reasoning / chain-of-thought text | +| `text` | `{"delta": "..."}` | Incremental user-facing reply text | +| `tool_call` | `{"tool_calls": [{"id", "name", "arguments"}, ...]}` | Tools requested by the model (`arguments` is a JSON string) | +| `tool_result` | `{"tool_results": [...]}` | Tool execution results in call order (including tool errors) | +| `usage` | `{"usage": {...}, "elapsed_seconds": ...}` | Token usage and duration for the current Step | +| `final` | `{"ok": True, "text": ...}` or tool summary | Summary of the current Step | -A host program typically branches on `event.kind` as events arrive. That is why this is called the Agent loop: it is really one loop that dispatches a stream of events: +In your host code, you typically branch on `event.kind` inside the loop to handle the events you care about: ```python async for event in stream: if event.kind == "tool_call": for call in event.data["tool_calls"]: - print(f"[{event.step_index}] Model requested tool: {call['name']}") + print(f"Calling tool: {call['name']}") elif event.kind == "text": print(event.data["delta"], end="", flush=True) ``` -## 4. Tape and memory branches {#tape-management} +## 4. Tape and session memory {#tape-management} -The `tape="demo"` argument in the example selects the history used by this Run. For continuous conversations, persistence, and fork merging, see [SDK: Tape & Memory](/docs/sdk/tape/); for the difference between history and model context, see [Tape concepts](/docs/concepts/tape/). +The `tape="demo"` argument selects the conversation history used for the Run. For multi-turn persistence, custom context selectors, and fork merging, continue to [SDK: Tape & Memory](/docs/sdk/tape/); for how history differs from model context, see [Tape concepts](/docs/concepts/tape/). diff --git a/website/src/content/docs/docs/sdk/tape.mdx b/website/src/content/docs/docs/sdk/tape.mdx index 3999838a..84a64636 100644 --- a/website/src/content/docs/docs/sdk/tape.mdx +++ b/website/src/content/docs/docs/sdk/tape.mdx @@ -1,21 +1,17 @@ --- title: Tape & Memory -description: Give an Agent memory across turns and understand history, model context, and Tape storage. +description: "Manage multi-turn memory in the Bub Python SDK: persist Tape history to disk or databases, customize TapeContext, and use sidecars and forks." --- -If every request sends only the current message to the model, the Agent cannot continue a previous conversation. To remember what you said earlier, it must save the conversation and pass the relevant history to the model on the next turn. +If every request sent only the latest message to the model, an Agent could never continue a conversation. To remember what you said earlier, it needs to record the exchange and pass relevant history on the next turn. Bub uses a Tape to store messages, tool round-trips, and events so an Agent maintains memory across turns. For how the Tape relates to model context, see [Tape and model context](/docs/concepts/tape/#history-and-context). -Bub uses a Tape to save conversations, tool inputs and outputs, and run records, giving your Agent memory and multi-turn continuity. For why history and model context are separate, and where `TapeContext` starts reading, see [Tape and model context](/docs/concepts/tape/#history-and-context). +## Multi-turn conversations {#remember-previous-turn} -## Remember previous turns {#remember-previous-turn} +To let the model continue a conversation and remember your preferences, reuse the same `tape` name across `agent.run()` calls: -To let the model continue a conversation or remember what you said, reuse the same Tape name in `agent.run()`: - -```python +```python 'tape="demo-user"' import asyncio - import republic - from bub.core import Agent @@ -24,7 +20,7 @@ async def run_turn(agent: Agent, model, prompt: str) -> None: async for event in stream: if event.kind == "text": print(event.data["delta"], end="", flush=True) - print("DONE") + print("\nDONE") async def main() -> None: @@ -42,15 +38,14 @@ if __name__ == "__main__": asyncio.run(main()) ``` -Both calls use the `demo-user` Tape, so the second can continue the first. Bub uses `InMemoryTapeStore` by default, which is lost when the process exits. Also, creating a new Agent for every request does not share default in-memory history, even when the Tape name is unchanged. +`Agent` defaults to `InMemoryTapeStore`, which lives only in the current `Agent` instance and process. Exiting the process or creating a new `Agent` per request loses in-memory history. -## Persist memory {#persist-memory} +## Persist to disk or a database {#persist-memory} -Bub includes `FileTapeStore` to persist Tapes locally, so history can be restored after the process exits. Configure it when creating the Agent: +To keep conversation history across process restarts, pass Bub's built-in `FileTapeStore` to persist each Tape as a local `.jsonl` file: -```python +```python "FileTapeStore" from pathlib import Path - from bub.core import Agent from bub.core.store import FileTapeStore @@ -60,73 +55,61 @@ agent = Agent( ) ``` -Run the program again with the same storage directory and Tape name to read the history back. The conversation above is saved in `sessions/demo-user.jsonl`. - -### Tape names decide continuity {#tape-names} +With this configuration, `tape="demo-user"` is saved to `sessions/demo-user.jsonl`. -`agent.run(..., tape="customer-42")` selects a Tape by name. Reusing a name continues its record; different names stay independent. Naming is the caller's job: `core.Agent` adds no workspace, tenant, or user prefix. +### Tape naming and isolation {#tape-names} -`FileTapeStore` uses the Tape name directly as a file name. Validate names that come from users or external identifiers — restrict characters and length, or use random identifiers — and include tenant and user identity in the session namespace for multi-tenant services. +`agent.run(..., tape="customer-42")` selects a Tape by name: reusing a name continues its history, while a new name starts an isolated session. `core.Agent` adds no workspace or tenant prefix automatically. -### Which store should I use? {#storage} +### Choosing a store {#storage} | Store | Lifetime | Best for | | --- | --- | --- | -| `InMemoryTapeStore` (default) | Current Agent instance and process | Tests and temporary scripts | -| `FileTapeStore` | One `.jsonl` file per Tape | Single-machine CLIs, development, and single-node services | -| Custom `TapeStore` / `AsyncTapeStore` | Defined by the host | Redis, SQL, and distributed storage | +| `InMemoryTapeStore` (default) | Current `Agent` instance and process | Tests and one-off scripts | +| `FileTapeStore` | One `.jsonl` file per Tape | Local CLIs, development, and single-node services | +| Custom `TapeStore` / `AsyncTapeStore` | Defined by the backend | Production SQL databases, Redis, or distributed stores | -:::note[Notes] - -- `FileTapeStore` uses the Tape name as a file name. If the name comes from users, validate it strictly, such as restricting characters and length or using randomly generated identifiers; multi-tenant services should also include tenant and user identity in the session namespace. -- For production, implement a custom Tape store. See the [Python API](/docs/reference/python-api/#tape) for the complete protocol, and [Storage integration](/docs/integrations/storage/) for a database example. +:::note[Security and production notes] +- `FileTapeStore` uses the Tape name directly as a filename. If the name comes from user input, **validate its character set and length** (or map it to a random UUID); in multi-tenant services, include tenant and user IDs in the name to prevent cross-tenant access. +- For store protocols, see [Python API: `TapeStore`](/docs/reference/python-api/#tape-store); for SQL databases, see [Store conversation history in a database](/docs/integrations/storage/). ::: -### Inspect the record outside a Run {#inspect} +### Inspect history outside a Run {#inspect} -Outside a Run, `agent.tape(name)` returns the same record, and you can inspect both views: +Use `agent.tape(name)` to read either the selected model messages or the raw Tape entries: ```python async def inspect_history(agent: Agent) -> None: tape = agent.tape("customer-42") - messages = await tape.read_messages() - entries = list(await tape.query().all()) - print(f"model messages: {len(messages)}, stored entries: {len(entries)}") + messages = await tape.read_messages() # Model messages built via TapeContext + entries = list(await tape.query().all()) # Raw stored TapeEntry items + print(f"model messages: {len(messages)}, raw entries: {len(entries)}") ``` -`read_messages()` applies the projection; `query()` returns raw entries. - -## TapeContext {#history-and-context} - -For the difference between the Tape and model context, and how to read raw entries and projected messages, see [One record, two views](/docs/concepts/tape/#history-and-context). The sections below explain how to customize the projection. +## Customize `TapeContext` {#history-and-context} -### Default context and customization {#default-context} - -Every Agent is bound to a `context` (by default `default_tape_context()`). The `agent` above is equivalent to: +Every `Agent` is bound to a `context` (`default_tape_context()` by default): ```python from bub.core import Agent, default_tape_context agent = Agent( - context=default_tape_context(), # default; every agent.tape(name) carries it - # ... + context=default_tape_context(), ) ``` -### What TapeContext contains {#tape-context-fields} - -`TapeContext` is a data class controlling how context is trimmed and converted. Its core fields are: +### `TapeContext` fields {#tape-context-fields} | Field | Default | Purpose | | --- | --- | --- | -| `anchor` | `LAST_ANCHOR` | Anchor filter (see below): read entries after the latest anchor; pass an anchor name, or `None` for no anchor filter. | -| `select` | `None` | Custom conversion function: converts selected Tape entries into a model message list. When `None`, the built-in standard conversion applies (supports ordinary messages, tool round-trips, and more). | -| `state` | `{}` | Temporary state dictionary. Each `agent.run(state=...)` or `agent.tape(state=...)` writes it here; `ToolContext.state` inside tools is the same dictionary. | +| `anchor` | `LAST_ANCHOR` | Read start point: entries after the latest anchor (`LAST_ANCHOR`), after a named anchor string, or `None` for all entries | +| `select` | `None` | Custom selector function converting Tape entries into model messages (`None` uses the built-in selector) | +| `state` | `{}` | Request-scoped state dictionary (shared with `agent.run(state=...)` and `ToolContext.state`) | -:::tip[Class vs. factory] -Calling `TapeContext()` directly builds a minimal low-level context (typically handling only basic text messages), while `default_tape_context()` is the official **full-featured factory** that handles multi-turn conversations, tool calls (`tool_call` / `tool_result`), and anchors. +:::tip[`TapeContext()` vs. `default_tape_context()`] +Calling `TapeContext()` directly builds a minimal low-level context, whereas `default_tape_context()` is the full-featured factory preconfigured for multi-turn conversations, tool round-trips, and anchors. -If you want to keep all default features and only change the starting `anchor`, use the standard-library `dataclasses.replace()`: +If you want to keep all the default behavior and only change the starting `anchor`, use `dataclasses.replace()` on `default_tape_context()`: ```python from dataclasses import replace @@ -134,30 +117,25 @@ from bub.core import Agent, default_tape_context agent = Agent( context=replace(default_tape_context(), anchor="order-reviewed"), - # ... ) ``` ::: -### Choose another start point {#custom-anchors} - -`TapeContext.anchor` controls the query range: +### Choose a different start anchor {#custom-anchors} -| Value | Query range | +| `anchor` value | Entries read | | --- | --- | -| `LAST_ANCHOR` (default) | After the most recent anchor | -| `"order-reviewed"` | After the anchor with that name | -| `None` | No anchor filter | +| `LAST_ANCHOR` (default) | Entries after the most recent anchor | +| `"order-reviewed"` | Entries after the anchor named `"order-reviewed"` | +| `None` | All entries from the beginning of the Tape | -### Custom selectors {#custom-selectors} +### Custom selectors (`select`) {#custom-selectors} -To change the projection, pass a function to `TapeContext(select=...)`. It receives the selected entries and the context, and returns Republic messages or an awaitable: +Pass a selector function to `TapeContext(select=...)` to include custom business events (`kind="event"`) in model messages: -```python +```python showLineNumbers {23} from collections.abc import Iterable - import republic - from bub.core import Agent, TapeContext, default_tape_context from bub.core.tape import TapeEntry, build_messages @@ -165,7 +143,7 @@ from bub.core.tape import TapeEntry, build_messages def with_order_notes( entries: Iterable[TapeEntry], _context: TapeContext ) -> list[republic.Message]: - """Add order notes as a system reminder on top of the default projection.""" + """Append order notes as a system reminder on top of the default messages.""" entries = list(entries) messages = build_messages(entries, default_tape_context()) notes = [ @@ -181,40 +159,37 @@ def with_order_notes( agent = Agent(context=TapeContext(anchor=None, select=with_order_notes)) ``` -Two easy mistakes: +Two common gotchas to watch out for when writing a custom selector: -- The `entries` you receive are an `Iterable` and may be a generator. Materialize them with `list()` before traversing, or a second pass sees nothing. -- To reuse the default projection, pass a fresh `default_tape_context()` rather than the `context` holding the current selector; passing it back would make the selector call itself. +1. **Materialize `entries` with `list(entries)` first**: `entries` is an `Iterable` that may be a single-pass generator. +2. **Pass a fresh `default_tape_context()` to `build_messages()`**: never pass `_context` (which holds your custom `select`) back into `build_messages()`, or it will recurse infinitely. -A custom selector **replaces** the default one, so conversation messages, tool round-trips, anchors, and the business events you care about must all be composed deliberately. Entries with `context=False` are still filtered before your selector runs. +A custom selector replaces the default selector; entries written with `context=False` are filtered out before your selector runs. -### Switch read mode temporarily {#read-with-another-context} +### Switch context for a single read {#read-with-another-context} -If you do not want to change the Agent's default context and only want a different view for one read (for example, ignoring the anchor to see the full conversation), use `tape.with_context()`: +If you want a different view for a single read without changing the Agent's default context (for example, bypassing the anchor to inspect the full conversation), use `tape.with_context(...)`: ```python from dataclasses import replace - from bub.core import default_tape_context tape = agent.tape("demo-user") - -# Temporarily build a context with no anchor filter and the default conversion rules -full_messages = await tape.with_context(replace(default_tape_context(), anchor=None)).read_messages() +full_messages = await tape.with_context( + replace(default_tape_context(), anchor=None) +).read_messages() ``` -This changes only this read; it does not modify the Tape's records or the context later Agent calls use. - -### anchor and handoff {#anchors-and-handoff} +### Anchors and handoffs {#anchors-and-handoff} -For the concepts and boundaries of anchors and handoffs, see [Tape and model context](/docs/concepts/tape/#anchors). Two initialization behaviors are worth noting when using them: +For the concepts behind anchors and handoffs, see [Moving the context start with anchors and handoffs](/docs/concepts/tape/#anchors). Two initialization rules apply in code: -- When `agent.run()`, `agent.start()`, or `agent.session()` starts a session and the Tape has no anchor, the system writes an initial anchor named `session/start` automatically. -- Calling `agent.tape(name)` only gets a reference and does not create an anchor. If a manually initialized empty Tape has no anchor, reading it with the default `LAST_ANCHOR` raises `BubError [not_found]` (`No anchors found in tape`). For a completely blank Tape, either run once, call `handoff()` explicitly, or read with `TapeContext(anchor=None)`. +- Starting a session via `agent.run()`, `agent.start()`, or `agent.session()` writes an initial `session/start` anchor automatically if the Tape has no anchors yet. +- Calling `agent.tape(name)` does not write an anchor. Reading a blank Tape that has no anchors with the default `LAST_ANCHOR` raises `BubError [not_found]` (`No anchors found in tape`). Run once, call `handoff()`, or read with `anchor=None`. -### Run handoff manually {#manual-handoff} +### Perform a manual handoff {#manual-handoff} -You can write anchors at key business points (for example, order confirmation or a step transition): +Write an anchor at phase transitions to advance the default context start: ```python tape = agent.tape("demo-user") @@ -225,48 +200,39 @@ await tape.handoff( ) ``` -- `name`: later usable as a starting point via `TapeContext(anchor="order-reviewed")`. -- `state`: can carry a structured snapshot of the phase for the application to read. - -After the handoff, the default `read_messages()` loads only the conversation after that anchor, while the historical data remains intact: +After the handoff, `tape.read_messages()` reads only entries after `order-reviewed`, while earlier history remains available via `anchors()` and `query()`: ```python -# All historical anchors and their state anchors = await tape.anchors() - -# The original, complete history is still queryable history = list(await tape.query().all()) ``` -### When to use them {#when-to-use-anchors} +### Common anchor patterns {#when-to-use-anchors} -| Need | Recommended approach | +| Scenario | Approach | | --- | --- | -| Business phase transition (for example, from tracking to after-sales) | Call `await tape.handoff(name="after-shipping")` when the current phase ends | -| Resume context from a historical checkpoint | Configure `TapeContext(anchor="checkpoint-name")` | -| Get the complete, unfiltered history | Configure `TapeContext(anchor=None)` | -| Handle context-window overflow | When the model reports a length error, the Agent automatically writes `handoff(name="auto_handoff/context_overflow")` and retries the original prompt once | -| Compress proactively by budget | Use the [`bub-context-budget` plugin](/docs/integrations/reuse-app/#agent-loop-hooks) to let the model call `tape.handoff` near the limit | - -## Sidecars keep parallel records out of context {#sidecars} +| Phase transition (e.g., shipping check to after-sales) | Call `await tape.handoff(name="after-shipping")` | +| Resume context from a specific checkpoint | Configure `replace(default_tape_context(), anchor="checkpoint-name")` | +| Read full unfiltered history | Configure `replace(default_tape_context(), anchor=None)` | +| Automatic recovery on context overflow | On a model context-length error, the Agent writes `auto_handoff/context_overflow` and retries once | +| Proactive compaction by token budget | Attach the [`bub-context-budget` plugin](/docs/integrations/reuse-app/#agent-loop-hooks) and provide the `tape.handoff` tool | -A `TapeSidecar` is a capability backed by a sibling Tape mounted beside the session Tape. Mounted through `Agent(sidecars=...)`, it forks, merges, and resets with the main Tape, but its entries never enter the main Tape's model context. +## Sidecars: keep large payloads out of main context {#sidecars} -The Bub app uses a spill sidecar for large tool results. The main conversation retains a preview and a handle, and the model reads the full result in chunks through `spill.read`. [`BUB_SPILL_THRESHOLD`](/docs/reference/settings/#spill-settings) configures the trigger; see [code mode and spill](/docs/reference/tools/#code-and-spill) for behavior. +Sometimes you need to store large companion data alongside a session—such as ten-thousand-line command output or scraped web pages—without filling up the main conversation's model context. Bub provides `TapeSidecar` for this: mounted beside the main Tape via `Agent(sidecars=...)`, it **forks, merges, and resets with the main Tape**, while keeping its entries out of the main model context. -A custom sidecar is provided by a plugin through `provide_tape_sidecar`; the protocol is in the [Hooks reference](/docs/reference/hooks/#provide_tape_sidecar). +For example, the Bub app uses a `spill` sidecar for large tool outputs: when a tool result exceeds [`BUB_SPILL_THRESHOLD`](/docs/reference/settings/#spill-settings), the full output is written to the `spill` sidecar while the main conversation keeps only a short preview and a handle for `spill.read` (see [Built-in tools](/docs/reference/tools/#code-and-spill)). Plugins can register custom sidecars via [`provide_tape_sidecar`](/docs/reference/hooks/#provide_tape_sidecar). -## Media has a separate storage boundary {#media} +## Multimodal media storage boundaries {#media} -Model requests can contain images, audio, and video, but the Tape is not a media file store. When a normal Agent Run writes a record, it drops non-text blocks from the prompt's `content` / `prompt`, keeping only text, so inline media never reaches the stored history. Do not assume the original user media can be read back from the Tape later. +The Tape is designed for text and event records, not raw media storage: -When media must be replayed or audited, the host saves it to object storage or a filesystem and records a resolvable reference in text. +- **User-supplied media is stripped before writing to the Tape**: when recording a user prompt, Bub strips non-text blocks and writes only plain text so large Base64 payloads do not bloat session storage. To audit or replay user media, save files to object storage or disk in your host code and record a path or URL reference in text or an event. +- **Tool-returned media can be passed to the model**: tools can use [`content_result()`](/docs/reference/python-api/#tools) to return text together with images, audio, or video (as `fs.read` does for image files). These are recorded in `tool_result` and reconstructed into multimodal content blocks by `result_content()`. -To return media together with text to the current model call, a tool uses [`content_result()`](/docs/reference/python-api/#tools). Tool results follow a separate path from inbound prompt stripping: the media they return is recorded as a tool result and turned back into images, audio, or video by `result_content()` during projection. +## Combine temporary `state` with persistent events {#state-and-metadata} -## Where should data live? {#state-and-metadata} - -For the lifetimes and purposes of `state`, `metadata`, Tape entries, and anchor `state`, see [Where data belongs](/docs/concepts/tape/#state). The example below shows how to combine temporary data with a persistent record: +Here is how a tool can combine request-scoped `state` (such as `request_id`) with a persistent business event on the Tape: ```python from bub.core.tools import ToolContext, tool @@ -282,30 +248,32 @@ async def add_order_note(note: str, *, context: ToolContext) -> str: return "Note recorded." ``` -Ordinary business events written to the Tape do not automatically become model input. To let the model see them in later calls, use TapeContext to select them appropriately. +As a reminder, custom business events written via `append_event()` are persisted on the Tape but do not enter the model context automatically—pair them with a [custom selector](#custom-selectors) if you want the model to see them. For a comparison of data lifetimes, see [Where data belongs](/docs/concepts/tape/#state). -## What happens to conversation history when a call ends {#forks-and-merges} +## Tape forks and `merge_back` {#forks-and-merges} -Each `agent.run()` records new entries on a Tape fork. When the stream closes, Bub merges the written records back into the main Tape by default: +Each `agent.run()` does not write directly to the main Tape; instead, it creates a temporary Tape fork for the Run and merges it back into the main Tape when the stream closes: ```mermaid sequenceDiagram participant Host as Host - participant Fork as Run fork + participant Fork as Run Tape fork participant Main as Main Tape - Host->>Fork: Enter agent.run(), start recording - Host->>Fork: Model output, tool I/O, and run events - alt Consumed normally - Host->>Fork: Leave async with, close the stream + Host->>Fork: Enter agent.run(), record on fork + Host->>Fork: Append model output, tool I/O, and events + alt Normal completion + Host->>Fork: Exit async with, close stream else Exception, cancellation, or early exit - Host->>Fork: Close the unfinished stream + Host->>Fork: Close unfinished stream end - Fork->>Main: Merge the written records by default + Fork->>Main: Merge written records into Main Tape by default ``` -The merge happens when the stream closes, not when the call succeeds. After a network error, cancellation, or early exit, the parts of the conversation and run record already written to the fork may still remain on the main Tape. To discard a Run's records, pass `merge_back=False`: +One important detail: **merging happens when the stream closes, not only when the task succeeds**. Even if a Run fails partway, is cancelled, or exits early, steps already recorded on the fork still merge into the main Tape by default. -```python +To discard a Run's records on exit (e.g., for dry runs or previews), pass `merge_back=False`: + +```python ins={5} async with agent.run( prompt, model=model, @@ -316,14 +284,14 @@ async with agent.run( ... ``` -This discards the Run's fork records, but does **not** undo tool operations or other external side effects already performed. You can also manage the scope yourself with `agent.session(name, merge_back=...)` or `tape.fork_tape(merge_back=...)`. +You can also control fork scope explicitly with `agent.session(name, merge_back=...)` or `tape.fork_tape(merge_back=...)`. :::caution -A fork is not a transaction over the outside world. Even with `merge_back=False`, tool changes to files, sent requests, and external writes are not rolled back. +Tape forks manage conversation history only and **do not roll back external side effects**. Even with `merge_back=False`, file edits, HTTP calls, or database writes performed by tools are not undone. ::: -## Session constraints {#concurrency} +## Same-session concurrency and locking {#concurrency} -When two different Agents use the same Tape name at the same time, each forks from the history it can see at start. Bub does not decide for you whether those requests should queue, overwrite, or interleave. If a later request in the same session depends on the result of an earlier one, the host should serialize work per session; across processes or workers, consider a session lock. +If two concurrent requests call `agent.run()` with the same Tape name, each forks from the history visible at start and merges back on close. `core.Agent` does not queue same-session requests automatically. -`FileTapeStore` does not provide a cross-worker session lock; the [FastAPI example](/docs/sdk/web-service/) demonstrates locking within one process. When concurrent Runs need to consume one another's completed results, the application coordinates their order. +In a web service where requests in the same session depend on prior turns, **serialize requests per `session_id` with a lock**. `FileTapeStore` includes only a per-file thread lock within one process; see the [FastAPI capstone](/docs/sdk/web-service/#concurrency) for an in-process session lock example. diff --git a/website/src/content/docs/docs/sdk/tools.mdx b/website/src/content/docs/docs/sdk/tools.mdx index eb8f00b2..f6b19d5a 100644 --- a/website/src/content/docs/docs/sdk/tools.mdx +++ b/website/src/content/docs/docs/sdk/tools.mdx @@ -1,17 +1,17 @@ --- title: Tools -description: Give the Agent lookup and action capabilities, and learn about tool arguments, results, errors, and run context. +description: Build custom Python tools for the Bub SDK with @tool, Pydantic argument validation, ToolContext injection, concurrency limits, and code mode. --- -An Agent can understand a user's request, but to query real data or perform actions it needs a way to call external capabilities. Tools are the Agent's **hands and feet**: you can wrap any piece of processing logic as a tool, and the Agent then decides from the user's request whether to call it. +A model can understand a user's request, but to query real data or take action it needs external capabilities. Tools are the Agent's **hands and feet**: you can wrap any Python function as a tool and let the Agent call it on demand. -This section starts with an order-lookup example and then walks through how to define a tool, how the model calls it, and how to handle arguments, results, and runtime data. +This guide starts with an order-lookup example and walks through defining tools, how the model calls them, and how to handle validation, runtime context, and concurrency. -## Add a custom tool {#add-a-tool} +## Define a custom tool {#add-a-tool} -Suppose we already have a Python function that looks up orders. For the Agent to call it, mark the function with the `@tool` decorator from the Bub SDK and pass it when creating the Agent: +Suppose you already have a Python function that looks up orders. To let the Agent call it, decorate the type-annotated function with `@tool` and pass it to `Agent(tools=[...])`: -```python +```python "@tool" "tools=[get_order]" from bub.core import Agent from bub.core.tools import tool @@ -40,69 +40,63 @@ agent = Agent( ) ``` -The `@tool` decorator turns a type-annotated Python function into a tool the Agent can use. The function contains the actual business logic; the tool name, argument types, and description help the model decide when and how to call it. +`@tool` derives the parameter JSON Schema from the function's type annotations and uses its docstring as the tool description shown to the model. ## Tool call flow {#tool-call-flow} -The model never executes Python directly. It first requests a tool call; Bub then validates the arguments and runs the matching function; finally, the result goes back to the model: +The model does not execute Python directly. It emits a tool call request; Bub validates the arguments, runs the function, and sends the result back to the model: ```mermaid flowchart LR - A[User makes a request] --> B[Model decides to call a tool] - B --> C[Bub validates arguments and runs the function] - C --> D[Tool result goes back to the model] - D --> E[Model continues and answers] + A[User prompt] --> B[Model requests tool call] + B --> C[Bub validates args and runs function] + C --> D[Result returned to model] + D --> E[Model generates final answer] ``` -So when we call `agent.run()`, the stream shows both the calls the model requested and the results the tools returned: +You can observe both the tool call and its result in the stream (1 tool Step + 1 answer Step = 2 Steps total): ```python async with agent.run(prompt, model=model, tape="tools-demo") as stream: async for event in stream: if event.kind == "tool_call": for call in event.data["tool_calls"]: - print(f"Model requested: {call['name']}, arguments: {call['arguments']}") + print(f"Model requested: {call['name']}, args: {call['arguments']}") elif event.kind == "tool_result": print(f"Tool result: {event.data['tool_results']}") elif event.kind == "text": print(event.data["delta"], end="", flush=True) ``` -A tool call takes two Steps: - -1. The model requests the `get_order` tool; Bub runs the function and returns the result to the model. -2. The model uses that result to produce its answer. - -Whether to call a tool is still up to the model. +As you can see, a tool call takes two Steps: first the model requests `get_order` and receives the result, then it uses that result to produce the final answer. Whether to call a tool is still up to the model. -## Tool descriptions and constraints {#tool-schema} +## Parameter schemas and Pydantic validation {#tool-schema} -For a Python function marked with `@tool`, the argument types become a JSON Schema and the [docstring](https://peps.python.org/pep-0257/) becomes the tool's description. Parameter names and descriptions are therefore part of the tool's interface. Write an accurate signature and description so the model can call it correctly. +With `@tool`, parameter types become a JSON Schema and the [docstring](https://peps.python.org/pep-0257/) becomes the tool's manual for the model. Clear names, type annotations, and docstrings help the model call the tool accurately: ```python @tool def get_order(order_id: str) -> dict[str, str | float]: - """Look up an order by ID. order_id is the complete customer-provided ID, such as A123.""" + """Look up an order by ID. order_id is the full ID, such as A123.""" ... ``` -When the input has many parameters or needs constraints such as ranges and lengths, a validation library such as [Pydantic](https://pydantic.dev/) can help. Pass the model to the `@tool` decorator's `model` argument: +When a tool takes multiple parameters or requires value constraints (such as numeric bounds or string lengths), pass a [Pydantic](https://pydantic.dev/) model via `@tool(model=...)`: ```python from pydantic import BaseModel, Field - from bub.core.tools import tool class RefundInput(BaseModel): - order_id: str = Field(description="Complete order ID, such as A123") + order_id: str = Field(description="Full order ID, such as A123") amount: float = Field(gt=0, description="Refund amount; must be greater than zero") reason: str = Field(min_length=1, description="Refund reason supplied by the user") @tool(name="refund_order", model=RefundInput) def refund_order(param: RefundInput) -> dict[str, str | float]: - """Request a refund for a paid order; run the authorization check before executing.""" + """Request a refund for a paid order.""" return { "order_id": param.order_id, "amount": param.amount, @@ -110,24 +104,20 @@ def refund_order(param: RefundInput) -> dict[str, str | float]: } ``` -During execution, if an argument has the wrong type or fails Pydantic validation, Bub returns the error to the model as a tool error. The model can correct the arguments and try again, though a successful retry is not guaranteed. - -When writing the actual business function, distinguish a business outcome from an execution error: +When writing real tools, separate **expected business outcomes** from **execution errors**—returning a structured dict such as `{"error": "order_not_found"}` lets the model and caller recognize known business states cleanly: -| Situation | Default behavior | +| Outcome | Behavior | | --- | --- | -| An argument does not match its type or a Pydantic constraint | Converted to a validation tool error and returned to the model | -| The tool raises an ordinary exception | Converted to a tool error and returned to the model | -| The tool returns a business error object, such as `order_not_found` | Returned to the model as a normal tool result | -| Storage, the model, or an event handler interrupts the call | The exception may propagate from stream iteration; handle it in the integration layer | +| Argument type mismatch or Pydantic validation error | Returned to the model as a tool error so it can adjust arguments and retry | +| Tool raises an ordinary exception | Returned to the model as a tool error | +| Tool returns a structured dict (e.g. `{"error": "order_not_found"}`) | Returned to the model as a normal result (recommended for expected business outcomes) | +| Store, model client, or event handler raises an exception | Propagates out of stream iteration to the host caller | -A business error object is not a Python exception. Returning a stable structured result lets both the model and the caller recognize business states such as "order not found". +## Inject `ToolContext` {#tool-context} -## Inject context into a tool {#tool-context} +Sometimes a tool needs more than its arguments—such as the current session Tape, request-scoped `state`, or the event bus. Set `@tool(context=True)` so Bub injects `context: ToolContext`: -Sometimes a tool needs the current session, request-scoped permissions, or the event bus. The `ToolContext` object injected by Bub provides them: - -```python +```python "context=True" "context: ToolContext" from bub.core.tools import ToolContext, tool @@ -141,7 +131,7 @@ async def add_order_note(note: str, *, context: ToolContext) -> str: return f"Note written to session {context.tape.name}" ``` -Pass `state` when calling the Agent, and the tool can read it through `context.state`: +Pass `state` to `agent.run()`, and read it inside the tool via `context.state`: ```python async with agent.run( @@ -154,19 +144,23 @@ async with agent.run( ``` :::tip -Bub injects the `context` argument, so it does not appear in the argument Schema the model sees. `context.state` is shared only within the current call and is not persisted or restored automatically. +`context` is injected by Bub and is hidden from the model-facing parameter schema. `context.state` lives only for the current call and is not persisted automatically. ::: -## Async and concurrent calls {#concurrency} +## Async functions and concurrency limits {#concurrency} -The `@tool` decorator works with plain functions and with async functions. In general, any logic that might block the program should run as an async function, and should be moved to a separate thread when necessary: +`@tool` supports both synchronous functions and `async def` coroutines. Use `async def` for I/O-bound work, or offload blocking calls with `asyncio.to_thread()`: ```python -import time import asyncio +import time +from bub.core.tools import tool -def build_report_blocking(order_id: str) -> None: + +def build_report_blocking(order_id: str) -> str: time.sleep(3) + return f"https://example.com/reports/{order_id}.pdf" + @tool async def export_order_report(order_id: str) -> str: @@ -174,45 +168,21 @@ async def export_order_report(order_id: str) -> str: return await asyncio.to_thread(build_report_blocking, order_id) ``` -The model may request several tools in a single response. To avoid hitting the host's own resource limits, Bub lets you cap this with the `max_tool_concurrency` argument: +A model may request multiple tool calls in a single response. To protect downstream services and host resources, cap concurrent local executions per Step with `max_tool_concurrency`: ```python -from bub.core import Agent -from bub.core.tools import tool - - -ORDERS = { - "A123": { - "order_id": "A123", - "status": "shipped", - "item": "Mechanical keyboard", - "amount": 399.0, - } -} - - -@tool -def get_order(order_id: str) -> dict[str, str | float]: - """Look up an order's status, item, and amount by order ID.""" - if order := ORDERS.get(order_id): - return order - return {"order_id": order_id, "error": "order_not_found"} - - agent = Agent( tools=[get_order], - system_prompt="When the user asks about an order, use the tool; never guess order status.", + system_prompt="Use the tool when asked about an order.", max_tool_concurrency=2, ) - ``` -`Agent(tools=[...])` also accepts tools from other libraries, such as `republic.tools.WebSearch()`. The model provider runs those tools, so they bypass the local `ToolExecutor` and are not subject to the local `max_tool_concurrency` limit. - +`Agent(tools=[...])` also accepts provider-executed tools (such as `republic.tools.WebSearch()`), which execute remotely on the provider side and are not subject to local `max_tool_concurrency`. -## Call a tool directly {#call-a-tool-without-a-model} +## Call tools directly without the model {#call-a-tool-without-a-model} -If you have a clear idea of which command you want to run, set a `command_prefix` on the Agent. Commands use the same tool implementations and argument validation, but skip the model: +If you already know which tool you want to run and want to skip model inference (and token usage), configure `command_prefix` on the Agent. Input starting with that prefix bypasses the model and invokes the tool directly: ```python agent = Agent(tools=[get_order], command_prefix=",") @@ -223,13 +193,14 @@ async with agent.run(",get_order A123", model=model, tape="tools-demo") as strea print(event.data["delta"], end="") ``` -The difference from an ordinary function call is that a direct command emits Bub-defined events, so your existing Agent flow can handle it the same way. If the command fails, however, the error is not sent back to the model for correction the way a model tool error is. +Direct commands still run through `agent.run()` and emit tool events, but if execution fails, the error is raised directly to the caller rather than returned to a model. ## Code mode {#compose-tools-with-codemode} -When there are many tools or the task needs conditional logic, let the model write Python through the `run_code` tool. This gives it more flexibility and lets it compose several tools in one execution: +When an Agent has many tools or needs loops and conditionals, wrap tools with `CodeMode` so the model can write Python via `run_code` to compose multiple tool calls in one pass: ```python +from bub.core import Agent from bub.core.codemode import CodeMode code_mode = CodeMode([get_order]) @@ -237,21 +208,19 @@ code_mode = CodeMode([get_order]) agent = Agent( tools=[code_mode.run_code], system_prompt=[ - "Use the available tools to complete the task; you can write Python that calls tools.*.", + "Use available tools to complete the task; you can write Python calling tools.*.", code_mode.prompt, ], ) ``` -The model then generates and runs Python such as: +Example Python generated by the model inside `run_code`: ```python order = await tools.get_order(order_id="A123") print(order) ``` -## Secure and isolated execution environments {#choose-an-execution-environment} - -By default, every tool or piece of code used by the Agent runs on the host machine executing the Python process. That is not an isolated or secure sandbox. When necessary, isolate execution and configure limits for the filesystem, network, and permissions. +## Custom execution environments {#choose-an-execution-environment} -Bub lets you use a remote or isolated environment as the execution container by providing a custom `Environment`. See [Environment](/docs/reference/python-api/#environment) for the complete protocol. +By default, tools and code mode execute directly on the host machine running the Python process (no sandbox). To isolate filesystem, network, and process access, implement a custom [`Environment`](/docs/reference/python-api/#environment). diff --git a/website/src/content/docs/docs/sdk/web-service.mdx b/website/src/content/docs/docs/sdk/web-service.mdx index 5deabd9e..f84895ba 100644 --- a/website/src/content/docs/docs/sdk/web-service.mdx +++ b/website/src/content/docs/docs/sdk/web-service.mdx @@ -1,45 +1,42 @@ --- title: Integrating a Bub Agent with FastAPI -description: Build a Todo Agent with the Bub SDK and integrate it with FastAPI. +description: Build a production-style FastAPI Todo Agent with the Bub Python SDK, featuring custom tools, human-in-the-loop approval hooks, and SSE streaming. sidebar: label: Capstone --- -import { FileTree, Steps } from '@astrojs/starlight/components'; +import { Code, FileTree, Steps } from '@astrojs/starlight/components'; +import fullMainPy from '../../../../../public/examples/bub-todo-agent/main.py?raw'; -With the basics of the Bub SDK behind us, this section introduces no new concepts. Instead, it ties everything together in one complete example that builds a working Agent demo application. +With the basics of the Bub SDK behind us, this guide introduces no new concepts. Instead, it ties `Agent`, tools, event interception, and Tape storage together into a working FastAPI Todo Agent with Server-Sent Events (SSE) streaming and human-in-the-loop delete confirmation. :::tip[Ask when something is unclear] -This section covers only the backend logic; the frontend UI is not discussed. If you run into a concept, a piece of code, or an error you do not understand, ask Bub directly, or ask the Agent tool you are using to explain it using this tutorial and the current code. +This guide focuses on the backend logic; the frontend UI is not covered in detail. If you run into a concept, a piece of code, or an error you are unsure about, ask Bub directly or have your coding assistant explain it alongside the source code. ::: -The complete example lives in [bub-todo-agent](https://github.com/bubbuild/bub/blob/main/website/public/examples/bub-todo-agent/). You can download it and modify it yourself, or build along with the tutorial. The core files are laid out like this: +The complete example is available in [bub-todo-agent](https://github.com/bubbuild/bub/blob/main/website/public/examples/bub-todo-agent/). Download it to experiment, or build along step by step: - bub-todo-agent/ - - main.py # the focus of this chapter - - index.html # demo UI, not covered here + - **main.py** # Backend service (covered in this guide) + - index.html # Frontend demo UI - static/ - uno.global.js - alpine.min.js - - sessions/ # created automatically at runtime + - sessions/ # Tape storage directory created at runtime - :::caution -This project is for demonstration and teaching only. It is not production-ready; do not expose it to the public internet. +This example is for demonstration only and omits production authentication and database backing. Do not expose it directly to the public internet. ::: -## 1. Configure the Agent and start the FastAPI service {#lifespan} - -First, let's set up the application skeleton: configure the Bub Agent and create it when FastAPI starts. That means: +## 1. Initialize the Agent in FastAPI Lifespan {#lifespan} -1. Import the dependencies and load configuration into variables. -2. Customize FastAPI's [lifespan](https://fastapi.tiangolo.com/advanced/events/#lifespan) logic so the Bub Agent is configured at startup. +First, let's build the application skeleton: create the model client and `Agent` inside FastAPI's [lifespan](https://fastapi.tiangolo.com/advanced/events/#lifespan) and attach them to `app.state` so all requests reuse a single instance: -```python title="main.py" +```python title="main.py" showLineNumbers collapse={1-33} {50-58} #!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.12" @@ -79,13 +76,11 @@ BASE_DIR = Path(__file__).resolve().parent load_dotenv() -# ===== Override with environment variables or .env, or edit these defaults directly ===== MODEL = os.getenv("BUB_MODEL", "openai:gpt-4o-mini") BASE_URL = os.getenv("BUB_API_BASE", "https://api.openai.com/v1") API_KEY = os.getenv("BUB_API_KEY") or os.getenv("REPUBLIC_OPENAI_API_KEY") HOST = os.getenv("BUB_HOST", "127.0.0.1") PORT = int(os.getenv("BUB_PORT", "8000")) -# ========================================================== @asynccontextmanager @@ -104,7 +99,7 @@ async def lifespan(app: FastAPI): app.state.model = model app.state.agent = agent app.state.session_locks = defaultdict(asyncio.Lock) - # request_id -> future; the delete hook waits here, and POST /chat/confirm wakes it. + # request_id -> future; delete hook awaits confirmation here, woken by POST /chat/confirm app.state.pending_confirms = {} yield @@ -112,28 +107,19 @@ async def lifespan(app: FastAPI): app = FastAPI(title="Bub Todo Agent", lifespan=lifespan) ``` -Notes: +- Mounting `agent` on `app.state` avoids re-creating the Agent on every request. +- `max_steps=6` caps the steps per Run. +- `FileTapeStore` persists conversation history under `sessions/`. -- To avoid creating the Agent repeatedly and to share one instance, mount the created Agent and its related attributes on FastAPI's state object, `app.state`. -- `max_steps` caps how many steps a single Run can take, preventing the model from looping forever. -- The `store` parameter gives the Agent Tape capabilities, so it can remember the conversation across turns. +So far this is just a minimal skeleton—the model can only chat and cannot act yet. Next, let's give it tools to do real work. -For now this is still a very basic setup: the model can only answer. Next we'll give it the ability to do real work. +## 2. Define business tools {#tools} -## 2. Give it business capabilities through tools {#tools} - -Now that the Agent is in place, let's make it actually useful: every Todo operation becomes a Python function wrapped as a tool that the Agent can call. That means: - -- Store task data in a Python dictionary. -- Provide the usual create, read, update, and delete operations so the Agent can view, add, complete, and delete tasks. +With the Agent in place, let's make it genuinely useful by wrapping todo list, create, complete, and delete operations with `@tool`: ```python title="main.py" -# ... - from itertools import count - from pydantic import BaseModel, Field - from bub.core.tools import tool TASKS: dict[str, dict[str, object]] = {} @@ -176,23 +162,17 @@ def delete_task(task_id: str) -> dict[str, object]: return {"task_id": task_id, "error": "task_not_found"} ``` -The code above is fairly basic Python, so we won't go through it line by line. In short: - -- The function's docstring and type annotations become the tool schema. The Agent reads them before deciding whether to call the tool. -- Return values must be JSON-serializable. Return `{"error": ...}` for business failures; don't throw exceptions and abort the whole flow for every failure. -- `delete_task` is irreversible, so we'll add an interception event later to require a second confirmation. +The code above is straightforward Python, so we won't walk through every line—just keep three things in mind: -Now update the Agent configuration: +- Each function's docstring and type annotations become the tool schema the model reads before calling it. +- Return values must be JSON-serializable; return `{"error": ...}` for expected business failures instead of raising exceptions. +- `delete_task` is irreversible, so we'll intercept it in a moment to ask for confirmation. -```python title="main.py" - -# Code snippet.. +Now pass the tools to `Agent` and set `max_tool_concurrency=2`: +```python title="main.py" ins={6,13} @asynccontextmanager async def lifespan(app: FastAPI): - - # ... - async with republic.get_model(MODEL, api_base=BASE_URL, api_key=API_KEY) as model: agent = Agent( store=FileTapeStore(BASE_DIR / "sessions"), @@ -207,13 +187,9 @@ async def lifespan(app: FastAPI): ) ``` -Here we pass all task tools in `tools` and set `max_tool_concurrency` to cap how many tools can run at once. - -## 3. Wrap Agent calls {#tape} - -The Bub Agent now has tools — its "hands and feet" — and can interact with the user. +## 3. Wrap `agent.run()` {#tape} -Before calling it, we may want to do some light argument handling so each Run receives correct arguments. Our logic here is simple: +Now that the Agent has tools — its "hands and feet" — let's write a small helper `run_agent` that passes `ChatRequest`, `session_id`, and the `confirm_delete` callback into `agent.run()`: ```python ConfirmDelete = Callable[[dict[str, object]], Awaitable[bool]] @@ -236,38 +212,17 @@ def run_agent(agent: Agent, model, req: ChatRequest, confirm_delete: ConfirmDele ) ``` -Notes: - -- `tape=req.session_id` shares history within one session; a new `session_id` starts a new conversation. -- `state` holds temporary per-call data shared with the event hooks that follow. - -## 4. Register event hooks {#events} - -Bub offers several hook points, which we can use to customize specific stages: for example, logging tool calls or intercepting delete commands that have not been confirmed. - -The core logic: - -1. On `ToolCallFinished`, record the tool name, status, and duration. -2. On `ToolCallStarted`, intercept `delete_task` first. -3. Read the confirmation callback from `state`; deny if there is none. -4. If the user declines, set `deny` and tell the model what to do instead. - -So, after creating the Agent, add the following inside FastAPI's `lifespan`: - -```python title="main.py" -# ... - -from bub.core.events import ToolCallDecision, ToolCallFinished, ToolCallStarted - - -@asynccontextmanager -async def lifespan(app: FastAPI): - async with republic.get_model(MODEL, api_base=BASE_URL, api_key=API_KEY) as model: +- `tape=req.session_id` shares history across turns in the same session (validated by regex so it is safe as a filename). +- `state` passes the per-request confirmation callback to the event handlers. +## 4. Register event handlers (logging & delete approval) {#events} - # ... +With tools wired up, we can also use the event bus to step in at key moments—such as logging every tool call or pausing before a deletion to ask the user. Register two handlers in `lifespan`: +1. `ToolCallFinished`: logs tool name, status, and duration. +2. `ToolCallStarted`: intercepts `delete_task` and awaits user confirmation; denies the call with `ToolCallDecision.deny(...)` if rejected or timed out. +```python title="main.py" "@agent.events.on(ToolCallFinished)" "@agent.events.on(ToolCallStarted)" "ToolCallDecision.deny" @agent.events.on(ToolCallFinished) def audit_tool(event: ToolCallFinished) -> None: logger.info( @@ -277,11 +232,8 @@ async def lifespan(app: FastAPI): event.result.duration_ms, ) - @agent.events.on(ToolCallStarted) async def authorize_tool(event: ToolCallStarted) -> None: - # Async handlers are awaited, so the Run can pause here until the user answers in the UI. - # If nobody answers, denying by default is the safer failure mode. if event.call.tool != "delete_task": return confirm: ConfirmDelete | None = event.state.get("confirm_delete") @@ -292,33 +244,19 @@ async def lifespan(app: FastAPI): ) ``` -Notes: - -- An async handler pauses the current Agent call until the user answers. -- `deny` skips only this tool call; it does not stop the whole flow. The model receives the denial reason and adjusts its answer. +Because `EventBus` awaits async handlers synchronously, the Run pauses at `await confirm(...)` until the user responds in the UI. Note that `deny` skips only this tool call rather than aborting the whole Run—the model receives the denial reason and adjusts its response. -## 5. Session locks and confirmations {#concurrency} +## 5. Session locks and confirmation endpoint {#concurrency} -The previous section pauses the flow before deleting a task, but two pieces are still missing for that pause to actually work: - -1. Requests for the same session must queue, so the Tape session is not taken over by another request while one is waiting. -2. The user's answer about the deletion must reach the paused hook. - -So we need a "lock" that ensures only one request holds a given Tape record at a time. Both pieces of state are initialized in `lifespan`: +In the previous step we paused the handler before deleting a task, but two pieces are needed for that pause to work reliably in a web service: same-session requests must queue, and the user's answer from the browser must reach the waiting handler. Two dictionaries on `app.state` handle this: ```python app.state.session_locks = defaultdict(asyncio.Lock) -# request_id -> future; the delete hook waits here, and POST /chat/confirm wakes it. app.state.pending_confirms = {} ``` -Then, at the request entry point, take the lock by `session_id`, so requests in the same session run one after another: - -```python -lock: asyncio.Lock = state.session_locks[req.session_id] -``` - -For the confirmation interaction, use a separate endpoint: +- `session_locks`: serializes requests per `session_id` so two requests never mutate the same Tape concurrently. +- `pending_confirms`: maps `request_id -> asyncio.Future` so `POST /chat/confirm` can wake the paused `ToolCallStarted` handler: ```python class Confirmation(BaseModel): @@ -335,20 +273,13 @@ async def confirm_tool_call(req: Confirmation, request: Request): return {"approved": req.approved} ``` -Now let's do the final piece. +With locks and confirmations in place, let's wire up the final piece. -## 6. Build the API and stream over SSE {#sse} +## 6. Stream responses over SSE {#sse} -With locks and confirmations in place, we can wire them into the Agent conversation: +Now we can bring everything together in `/chat/stream`: a background task drives the Agent Run and pushes text deltas, tool calls, confirmation requests, and the final completion frame onto an `asyncio.Queue` yielded as [SSE](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/) events: -1. The frontend makes an HTTP request to `/chat/stream`. -2. FastAPI handles the request and uses the Agent to generate content. -3. FastAPI serializes the Agent's output as [SSE](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/) events and returns them to the frontend. -4. The frontend handles and displays each event by type. - -Here is the complete code: - -```python title="main.py" +```python title="main.py" collapse={1-8} import asyncio from collections.abc import AsyncIterable from contextlib import suppress @@ -362,8 +293,6 @@ from fastapi.sse import EventSourceResponse, ServerSentEvent async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[ServerSentEvent]: state = request.app.state lock: asyncio.Lock = state.session_locks[req.session_id] - # Advance the Run in a background task so hooks can also push frames onto the queue; - # hooks run inside the Agent event stream, where the response generator cannot yield directly. queue: asyncio.Queue[ServerSentEvent | None] = asyncio.Queue() async def confirm_delete(arguments: dict[str, object]) -> bool: @@ -382,8 +311,7 @@ async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[Serve ) ) try: - # Fail closed: if there is no answer within two minutes, or the client disconnects, - # do not delete. + # Fail closed on 120s timeout or client disconnect return await asyncio.wait_for(future, timeout=120) except TimeoutError: return False @@ -402,7 +330,7 @@ async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[Serve names = [call["name"] for call in event.data["tool_calls"]] queue.put_nowait(ServerSentEvent(data={"names": names}, event="tool")) - # Send done only after the whole Run ends; final marks the end of just one Step. + # Emit done only after the full Run finishes (final marks a single Step) queue.put_nowait( ServerSentEvent(data={"last_step_usage": stream.usage}, event="done") ) @@ -424,81 +352,88 @@ async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[Serve await task ``` -## Full walkthrough: one interaction {#wiring} +You can also inspect the complete `bub-todo-agent/main.py` file directly below (helper and route boilerplate is collapsed by default—click to expand): -Let's quickly recap the chapter. A complete interaction in this demo looks like this: + + +## Interaction sequence {#wiring} + +Let's quickly recap what we built. A complete interaction in this demo flows like this: ```mermaid sequenceDiagram participant C as Client participant S as /chat/stream participant A as Agent - participant H as Event hooks + participant H as Event handlers participant K as /chat/confirm C->>S: POST {session_id, prompt} S->>S: Lock by session_id S->>A: agent.run(...) - A->>A: Call the model and run tools as needed + A->>A: Call model and execute tools A-->>S: text / tool_call events S-->>C: SSE message / tool frames - opt delete_task needs confirmation + opt delete_task requires confirmation A->>H: ToolCallStarted H->>S: Request user confirmation S-->>C: SSE confirm frame (request_id) C->>K: POST {request_id, approved} - K->>H: Return the confirmation result - H-->>A: Allow or deny + K->>H: Resolve Future + H-->>A: Proceed or deny end A-->>S: Event stream ends S-->>C: SSE done frame ``` -In summary, the demo has three parts: +In summary, the demo comes together in three parts: -- **Configuration and integration**: configure the Bub Agent and integrate it with FastAPI. -- **Custom logic through tools and events**: wrap the actual operations as tools the Agent can call, then customize what happens at specific event stages during tool calls. -- **Interaction over HTTP**: expose an HTTP endpoint that combines these parts and completes the interaction. +- **Configuration and integration**: initialize the Bub Agent and Tape store in FastAPI's `lifespan`. +- **Custom logic via tools and events**: wrap todo operations as tools, then layer audit logging and delete confirmation on top with event handlers. +- **HTTP and streaming**: tie everything together with session locks, the confirmation endpoint, and SSE streaming. -## Run and try it {#run} +## Run the example {#run} -Your complete demo is now ready. You can run the whole service from [bub-todo-agent](https://github.com/bubbuild/bub/blob/main/website/public/examples/bub-todo-agent/) and try it in the browser: +And with that, our complete demo is ready! Download [bub-todo-agent](https://github.com/bubbuild/bub/blob/main/website/public/examples/bub-todo-agent/) and run it locally to try it out in your browser: -1. Rename `.env.example` to `.env` and fill in the model settings or port: - - ```bash title=".env" - BUB_MODEL=openai:gpt-4o-mini - BUB_API_BASE=https://api.openai.com/v1 +1. Copy `.env.example` to `.env` and fill in your model settings: - BUB_API_KEY=sk-... + ```bash title=".env" + BUB_MODEL=openai:gpt-4o-mini + BUB_API_BASE=https://api.openai.com/v1 + BUB_API_KEY=sk-... + BUB_HOST=127.0.0.1 + BUB_PORT=8000 + ``` - BUB_HOST=127.0.0.1 - BUB_PORT=8000 - ``` +2. Start the server with `uv`: -2. Run `main.py` with uv: + ```shell + uv run main.py + ``` - ```shell - uv run main.py - ``` +3. Open `http://127.0.0.1:8000` in your browser: -3. When the logs appear, click or copy the URL and open the page in your browser: + ```text + $ uv run main.py + INFO: Started server process [85377] + INFO: Waiting for application startup. + INFO: Application startup complete. + INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) + ``` - ``` - $ uv run main.py - INFO: Started server process [85377] - INFO: Waiting for application startup. - INFO: Application startup complete. - INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) - ``` - - ![Bub Todo Agent Screenshot](/docs/sdk/bub-todo-agent-screenshot.png) + ![Bub Todo Agent Screenshot](/docs/sdk/bub-todo-agent-screenshot.png) - Enjoy! diff --git a/website/src/content/docs/zh-cn/docs/app/configure.mdx b/website/src/content/docs/zh-cn/docs/app/configure.mdx index afe06373..f2e6b795 100644 --- a/website/src/content/docs/zh-cn/docs/app/configure.mdx +++ b/website/src/content/docs/zh-cn/docs/app/configure.mdx @@ -1,26 +1,24 @@ --- title: 配置 -description: 介绍如何配置 Bub 应用。 +description: 配置 Bub 应用:通过初始化向导、YAML 文件与 BUB_* 环境变量设置模型、API 密钥、备选 Fallback 模型及 Telegram 渠道。 --- -Bub 按以下顺序读取配置,优先级从高到低: +Bub 按以下优先级(从高到低)读取配置: -1. 环境变量(以 `BUB_` 前缀开头); -2. `.env` 文件:CLI 启动时自动从当前工作区中加载,或读取声明了 `env_file=".env"` 的配置类; -3. `~/.bub/config.yml`,由 `bub onboard` 创建。 +1. 环境变量(`BUB_` 前缀); +2. 当前工作区的 `.env` 文件; +3. `~/.bub/config.yml`(由 `bub onboard` 生成)。 -对于配置中未声明的字段将使用配置类的默认值。完整的可写配置项见 [配置项](/zh-cn/docs/reference/settings/)。 +未配置的字段使用默认值。所有可用字段见 [配置项参考](/zh-cn/docs/reference/settings/)。 :::note[开始之前] - -- 确保 Bub CLI 应用[已安装](/zh-cn/docs/getting-started/install/)。 -- 已有某个模型提供商的 API 密钥,或通过 `bub login codex` 完成 OAuth 认证(限 OpenAI)。 - +- 已[安装 Bub CLI](/zh-cn/docs/getting-started/install/#app-install)。 +- 准备好模型提供商的 API Key,或通过 `bub login codex` 登录(仅限 OpenAI)。 ::: -## 1. 完成初始配置 {#initial-setup} +## 1. 运行配置向导 {#initial-setup} -在终端命令行中执行如下命令进入交互式配置流程,完成后写入 `~/.bub/config.yml` 配置文件中。 +在终端中执行下面的命令,进入交互式配置向导,完成后会自动生成 `~/.bub/config.yml`: ```bash bub onboard @@ -28,7 +26,7 @@ bub onboard ## 2. 检查配置文件 {#check-the-config} -现在可以检查 `~/.bub/config.yml`,示例如下: +现在可以检查一下生成的 `~/.bub/config.yml`,内容大概长这样: ```yaml title="~/.bub/config.yml" model: openrouter:openrouter/free @@ -39,55 +37,56 @@ telegram: ``` :::danger -**默认情况下你的密钥会直接以明文写入到配置文件中**;如果你有更高的安全要求,避免模型供应商 API 密钥以明文存储到本地,那么在运行 Bub 时可以直接传递环境变量进行设置或覆盖 +`bub onboard` 默认将 API Key 以明文写入 `~/.bub/config.yml`。若不希望在配置文件中保存明文密钥,可在向导中留空,改用环境变量传入。 ::: -## 3. 用环境变量覆盖 {#environment-variables} +## 3. 使用环境变量 {#environment-variables} -常用的环境变量如下所示: +常用环境变量: | 变量 | 说明 | |---|---| -| `BUB_MODEL` | 模型标识,如 `openrouter:openrouter/free`、`codex:`。 | -| `BUB_API_KEY` | 当前提供商的 API 密钥;使用 `bub login codex` 时无需设置。 | -| `BUB_API_BASE` | 提供商的服务 URL;留空则使用默认端点。 | -| `BUB_HOME` | 运行时数据目录,默认为 `~/.bub` | -| `BUB__API_KEY` | 指定提供商的密钥,如 `BUB_OPENROUTER_API_KEY`。 | -| `BUB__API_BASE` | 指定提供商的服务 URL。 | +| `BUB_MODEL` | 模型标识,格式为 `provider:model`(如 `openrouter:openrouter/free`、`codex:`) | +| `BUB_API_KEY` | 当前提供商的 API Key(使用 `bub login` 时无需设置) | +| `BUB_API_BASE` | 提供商 API 地址;留空使用默认地址 | +| `BUB_HOME` | 运行时数据目录,默认 `~/.bub` | +| `BUB__API_KEY` | 指定提供商的 API Key,如 `BUB_OPENROUTER_API_KEY` | +| `BUB__API_BASE` | 指定提供商的 API 地址 | -完整变量表见 [配置项](/zh-cn/docs/reference/settings/)。 +完整列表见 [配置项参考](/zh-cn/docs/reference/settings/)。 ## 4. 配置模型与备用模型 {#configure-models} -`model` 配置使用 `provider:model` 格式设置。如主模型不可用时按顺序尝试备用模型(fallback model),在 `~/.bub/config.yml` 中配置 可进行修改: +配置 `fallback_models` 可在主模型不可用时按顺序尝试备用模型: -```yaml +```yaml title="~/.bub/config.yml" ins={2-3} model: openai:gpt-5-mini fallback_models: - openrouter:openrouter/free ``` -每个候选提供商都需要自己的有效凭据。fallback 只覆盖创建客户端和打开请求的失败;消息流已经开始后发生的错误不会换一个模型重放,以免重复产生副作用。完整规则见[模型与 fallback](/zh-cn/docs/reference/settings/#model-routing)。 +每个候选模型对应的提供商都需要配置有效凭据。备用模型仅在建立连接或打开请求流失败时触发;一旦流已经开始输出,中途报错不会切换模型重试,以免重复执行工具产生副作用。详见[模型与 fallback](/zh-cn/docs/reference/settings/#model-routing)。 ## 5. 配置 Telegram 渠道(可选) {#telegram-channel} -如果你打算把 Bub 当做一个 Telegram 机器人来使用,可以使用内置的 Telegram 渠道,配置示例如下: +如果你打算把 Bub 当作一个 Telegram 机器人来使用,可以在 `.env` 中配置内置的 Telegram 渠道: -```bash +```bash title=".env" BUB_TELEGRAM_TOKEN=123456789:your-telegram-bot-token BUB_TELEGRAM_ALLOW_USERS=123456789,your_username BUB_TELEGRAM_ALLOW_CHATS=-1001234567890 BUB_TELEGRAM_PROXY=http://127.0.0.1:7890 # 可选 ``` -点击查阅更多有关于 [Telegram 渠道](/zh-cn/docs/app/gateway/#telegram) 的配置项。 +详细用法见 [Telegram 网关](/zh-cn/docs/app/gateway/#telegram)。 + +## 6. 验证配置 {#verify} -## 6. 验证 {#verify} +配置完成后,现在可以试着与 Bub 对话,看看配置是否已经生效: -现在可以试着与 Bub 进行对话: ```bash wrap $ bub run "Can you introduce yourself?" [cli:local] -I'm a virtual assistant designed to support a wide range of tasks including coding, design, research, and automation. I can integrate with code repositories, access web resources, leverage specialized skills, and streamline workflows. If you have specific tasks or questions about my capabilities, feel free to ask! +I'm a virtual assistant designed to support a wide range of tasks... ``` diff --git a/website/src/content/docs/zh-cn/docs/app/deploy.mdx b/website/src/content/docs/zh-cn/docs/app/deploy.mdx index 77e1bcb5..7b3be200 100644 --- a/website/src/content/docs/zh-cn/docs/app/deploy.mdx +++ b/website/src/content/docs/zh-cn/docs/app/deploy.mdx @@ -1,45 +1,39 @@ --- title: 部署 -description: 运行 Bub 常驻服务与云端沙箱,涵盖 Docker Compose 与 Daemon 守护进程模式。 +description: 使用 Docker Compose 或系统后台服务(Daemon)在生产环境部署 Bub 常驻网关与隔离沙箱,并核对安全检查清单。 --- import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; -Bub 既能在本地终端交互使用(见[终端交互](/zh-cn/docs/app/terminal/)),也可以部署到服务器常驻运行: +Bub 既能在本地终端里随开随用(见[终端交互](/zh-cn/docs/app/terminal/)),也可以部署到服务器上常驻运行: -- **常驻网关(Gateway)**:7×24 小时监听 Telegram、飞书等渠道并响应消息。 -- **云端隔离沙箱(Remote Workspace)**:在独立容器内提供完整的开发工具链,并通过终端接入 `bub chat` 交互,保障宿主机安全。 +- **常驻消息网关**:7×24 小时监听 Telegram、飞书等渠道并响应消息; +- **容器隔离沙箱**:在容器内运行开发工具链并通过 `bub chat` 交互,隔离宿主机环境。 -两种主流部署方式: +两种部署方式对比: -| 方式 | 场景 | 优势 | +| 方式 | 适用场景 | 特点 | | --- | --- | --- | -| **Docker Compose**(推荐) | 云服务器、VPS、NAS、本地容器 | 开箱即用,自带 Node/pnpm/Python/Git 等工具链;环境隔离,易于备份与升级 | -| **Daemon 模式** | 已有 Python 环境的 Linux / Windows 宿主机 | 资源占用低,通过 `bub gateway --install` 一键注册为系统后台服务 | - ---- +| **Docker Compose**(推荐) | 云服务器、VPS、NAS、本地容器 | 自带 Python、`uv`、Git、Node.js 等完整工具链,环境隔离,易于备份升级 | +| **Daemon 系统服务** | 已有 Python 环境的 Linux / Windows 主机 | 资源占用低,通过 `bub gateway --install` 一键注册为后台服务 | ## 开始之前 {#before-you-start} -部署前需完成以下准备: - -1. **模型配置**:在 `.env` 中指定 `BUB_MODEL` 和 `BUB_API_KEY`,详见[配置](/zh-cn/docs/app/configure/)。 -2. **渠道凭据与白名单**:接入 Telegram 等渠道时,**务必配置白名单**(如 `BUB_TELEGRAM_ALLOW_USERS`),防止未授权访问消耗 Token。 -3. **数据持久化**:会话状态(Tape)、历史记录与插件保存在数据目录(宿主机 `~/.bub`,容器内 `/data`),部署时需确保持久化存储。 +1. **配置模型**:在 `.env` 中配置 `BUB_MODEL` 和 `BUB_API_KEY`(见[配置](/zh-cn/docs/app/configure/))。 +2. **配置渠道白名单**:接入聊天平台时**必须配置白名单**(如 `BUB_TELEGRAM_ALLOW_USERS`),防止未授权访问。 +3. **持久化数据目录**:会话 Tape 和托管插件保存在数据目录(宿主机 `~/.bub`,容器内 `/data`),请确保挂载到持久卷。 :::caution[安全提示] -生产部署中切勿留空白名单!若白名单为空,任何能搜索到机器人的用户都能向其发送指令并调用 Agent 工具。 +生产环境中切勿将白名单留空!若白名单为空,任何能搜到机器人的用户均可调用你的 Agent 工具。 ::: ---- - -## Docker Compose {#docker-compose} +## Docker Compose 部署 {#docker-compose} -官方镜像(`ghcr.io/bubbuild/bub`)内置 Python 3.12、`uv`、Git、Node.js、pnpm 及常用命令行工具,宿主机只需提供配置文件与存储卷。 +官方镜像 `ghcr.io/bubbuild/bub` 已内置 Python 3.12、`uv`、Git、Node.js 和 pnpm。 -### 1. 配置环境 {#configure} +### 1. 准备配置文件 {#configure} -在部署目录中获取 [`docker-compose.yml`](https://github.com/bubbuild/bub/blob/main/docker-compose.yml) 与 [`env.example`](https://github.com/bubbuild/bub/blob/main/env.example): +下载 [`docker-compose.yml`](https://github.com/bubbuild/bub/blob/main/docker-compose.yml) 和 [`env.example`](https://github.com/bubbuild/bub/blob/main/env.example): ```bash mkdir -p bub-deploy && cd bub-deploy @@ -48,9 +42,9 @@ curl -O https://raw.githubusercontent.com/bubbuild/bub/main/env.example cp env.example .env ``` -在 `.env` 中填入核心参数: +编辑 `.env`: -```bash +```bash title=".env" # 模型 BUB_MODEL=openrouter:openrouter/free BUB_API_KEY=sk-or-... @@ -59,60 +53,50 @@ BUB_API_KEY=sk-or-... BUB_TELEGRAM_TOKEN=123456789:your-telegram-bot-token BUB_TELEGRAM_ALLOW_USERS=123456789,your_telegram_username -# 宿主机数据目录与工作区(可选) +# 可选:宿主机数据目录与工作区路径 # BUB_HOME_HOST=~/.bub # BUB_WORKSPACE_PATH=. ``` -`docker compose` 会自动读取当前目录的 `.env`。切勿将包含 Token 的 `.env` 提交到公开仓库。 +### 2. 检查挂载目录 {#volumes} -### 2. 挂载目录 {#volumes} +默认 `docker-compose.yml` 挂载三个目录: -默认 `docker-compose.yml` 包含三个卷挂载: - -```yaml +```yaml title="docker-compose.yml" volumes: - ${BUB_WORKSPACE_PATH:-.}:/workspace - ${BUB_HOME_HOST:-${HOME}/.bub}:/data - ${BUB_AGENT_HOME:-${HOME}/.agents}:/root/.agents ``` -| 容器路径 | 宿主机对应路径 | 说明 | +| 容器路径 | 宿主机路径 | 用途 | | --- | --- | --- | -| `/workspace` | `BUB_WORKSPACE_PATH`(默认当前目录) | **工作区**:Agent 执行命令与读写文件的目录 | -| `/data` | `BUB_HOME_HOST`(默认 `~/.bub`) | **数据目录**:保存 Tape、历史记录和托管插件(`/data/bub-project`) | -| `/root/.agents` | `BUB_AGENT_HOME`(默认 `~/.agents`) | **全局技能**:跨项目复用的 Agent 技能目录 | - -容器内设置了 `BUB_HOME=/data`,容器销毁重建不会丢失会话数据与插件。 +| `/workspace` | `BUB_WORKSPACE_PATH`(默认当前目录) | **工作区**:Agent 读写文件和执行命令的目录 | +| `/data` | `BUB_HOME_HOST`(默认 `~/.bub`) | **数据目录**(`BUB_HOME=/data`):保存 Tape 历史与托管插件 | +| `/root/.agents` | `BUB_AGENT_HOME`(默认 `~/.agents`) | **全局技能目录**:跨工作区复用的技能 | -:::danger[隔离防范] -工作区决定了 Agent 能触及的文件范围。**切勿**将宿主机根目录 `/` 或含有敏感密钥的目录挂进 `/workspace`。 +:::danger[切勿挂载敏感目录] +工作区决定了 Agent 可访问的文件范围。**切勿**将宿主机根目录 `/` 或包含密钥的目录挂载到 `/workspace`。 ::: -### 3. 启动 {#start} +### 3. 启动容器 {#start} - - 拉取镜像并在后台启动: - + ```bash docker compose pull docker compose up -d docker compose logs -f app ``` - 生产环境建议在 `.env` 中固定具体 Tag(如 `BUB_IMAGE=ghcr.io/bubbuild/bub:0.6.0`)。 + 生产环境建议在 `.env` 中固定镜像版本(如 `BUB_IMAGE=ghcr.io/bubbuild/bub:0.6.0`)。 - 从源码构建并启动: - ```bash docker compose up -d --build ``` - - 不依赖 Compose 时的等价命令: - + ```bash docker run -d --name bub --restart unless-stopped \ --env-file .env \ @@ -127,31 +111,25 @@ volumes: -### 4. 验证 {#verify} +### 4. 验证状态 {#verify} -检查容器状态与网关日志: +查看容器状态与日志: ```bash docker compose ps docker compose logs -f app ``` -Telegram 网关启动正常时会输出: +Telegram 渠道启动成功时会打印: ```text telegram.start allow_users_count=1 allow_chats_count=0 proxy_enabled=False telegram.start polling ``` -检查环境变量是否注入(不输出明文): - -```bash -docker compose exec app sh -c 'test -n "$BUB_TELEGRAM_TOKEN" && echo token-present' -``` - -### 5. 交互式 Chat {#chat} +### 5. 进入容器交互式对话 {#chat} -Compose 默认开启了 `stdin_open` 与 `tty`。即使容器在后台运行网关,你也可以随时进入容器开启交互式对话: +Compose 默认开启了 `stdin_open` 与 `tty`。即使容器正在后台运行网关,你也可以随时进入容器开启交互式对话: ```bash docker compose exec -it app bub chat @@ -159,59 +137,46 @@ docker compose exec -it app bub chat 这让你能在云端完全隔离的沙箱环境中,直接调用预装的工具链与 Agent 结对编程。 -### 6. 定制启动与依赖 {#entrypoint} +### 6. 自定义启动脚本与依赖 {#entrypoint} -容器启动时,`entrypoint.sh` 依次执行: +容器启动时,`entrypoint.sh` 按顺序执行: -1. **安装 Python 依赖**:若 `/workspace/bub-reqs.txt` 存在,自动通过 `uv pip install` 安装。 - -2. **同步插件**:激活虚拟环境并执行 `bub install`,同步 `/data/bub-project` 中的托管插件。 - -3. **执行入口**:若 `/workspace/startup.sh` 存在,用 `bash` 执行它;否则执行 `bub gateway`。 +1. 若 `/workspace/bub-reqs.txt` 存在,执行 `uv pip install` 安装额外 Python 依赖; +2. 激活虚拟环境并运行 `bub install`,同步 `/data/bub-project` 中的托管插件; +3. 若 `/workspace/startup.sh` 存在则执行该脚本,否则执行 `bub gateway`。 -#### 覆盖启动命令示例 {#override-command} - -在工作区创建 `startup.sh` 并赋予可执行权限: +如需自定义启动参数,可在工作区创建 `startup.sh`(注意使用 `exec` 以便传递停止信号): ```bash #!/bin/bash # /workspace/startup.sh set -euo pipefail - -# 必须使用 exec 替换进程,确保系统信号正常传递给网关 exec /app/.venv/bin/bub gateway --enable-channel telegram ``` -### 7. 插件管理 {#plugins} +### 7. 在容器内管理插件 {#plugins} -托管插件存放在持久卷 `/data/bub-project` 中,直接在容器内安装无需重建镜像: +托管插件保存在持久卷 `/data/bub-project` 中,可直接安装或更新,无需重建镜像: ```bash -# 安装插件 docker compose exec app bub install https://github.com/owner/repo.git@v1.2.0 - -# 更新插件 docker compose exec app bub update - -# 重启使新插件生效 docker compose restart app ``` ### 8. 备份与升级 {#upgrade} -Tape 是追加写入的 JSONL 文件。升级前建议先暂停写入并备份: +升级前建议先停止容器并备份数据目录: ```bash -# 1. 停止写入并备份 docker compose stop app tar -czf "bub-data-$(date +%Y%m%d-%H%M%S).tar.gz" "$HOME/.bub" cp .env ".env.bak-$(date +%Y%m%d-%H%M%S)" -# 2. 拉取新镜像并启动 docker compose pull docker compose up -d ``` @@ -220,54 +185,46 @@ docker compose up -d --- -## Daemon 模式 {#daemon} +## Daemon 系统服务模式 {#daemon} -在已有 Python 环境的主机上,可使用 `bub gateway` 内置的 `--install` 命令直接注册为系统后台服务: +在已有 Python 环境的 Linux 或 Windows 主机上,可使用 `bub gateway --install` 一键注册为系统后台服务: - **Linux**:注册为 systemd 用户级服务 `~/.config/systemd/user/bub-gateway.service`。 - **Windows**:注册为当前用户的计划任务(登录自启,失败自动重启)。 -- **macOS**:暂不支持 `--install`,建议使用 launchd、tmux 或上述 Docker 方案。 +- **macOS**:暂不支持 `--install`,建议使用 `launchd`、`tmux` 或上述 Docker 方案。 ### 1. 安装服务 {#daemon-install} 在包含 `.env` 的工作区目录下执行: ```bash -# 创建环境并安装应用 uv venv && source .venv/bin/activate uv pip install 'bub[app]' - -# 一键安装并启动后台服务 bub gateway --install ``` -安装程序会自动记录当前 Python 解释器路径、工作区目录与环境变量。 +安装程序会自动记录当前的 Python 解释器路径、工作区目录与环境变量。 -### 2. 保活与管理 {#daemon-manage} +### 2. 管理服务(Linux) {#daemon-manage} -Linux 用户注销 SSH 后,默认会挂起用户级服务。如需保持 7×24 小时运行,需启用 linger: +Linux 用户注销 SSH 后,默认会挂起用户级服务。如需保持 7×24 小时运行,请启用 linger: ```bash loginctl enable-linger $USER ``` -常用管理命令: +常用 `systemctl` 命令: ```bash -# 查看状态 systemctl --user status bub-gateway - -# 实时查看日志 journalctl --user -u bub-gateway -f - -# 重启与停止 systemctl --user restart bub-gateway systemctl --user stop bub-gateway ``` ### 3. 卸载服务 {#daemon-uninstall} -如需移除后台服务: +如需移除后台服务,运行: ```bash bub gateway --uninstall @@ -275,10 +232,10 @@ bub gateway --uninstall --- -## 安全建议 {#security-checklist} +## 安全检查清单 {#security-checklist} -- **严格白名单**:配置 `BUB_TELEGRAM_ALLOW_USERS` 或 `BUB_TELEGRAM_ALLOW_CHATS`,未通过验证的消息将被拒绝或静默丢弃。 -- **最小化工作区**:工作区仅挂载所需项目目录,不要让 Agent 访问包含主机密钥或系统关键路径的目录。 -- **轮数上限**:通过 `BUB_MAX_STEPS` 限制单次任务的最大模型步数,防范死循环与 API 额度消耗。该值默认不设上限(`sys.maxsize`),生产部署应显式设置,例如 50。 -- **凭据安全**:通过 `.env` 或环境变量注入密钥,不要将 Token 提交至版本管理。 -- **定期备份**:定期归档备份 `~/.bub`(或容器 `/data`)目录中的 Tape 文件。 +- **配置白名单**:设置 `BUB_TELEGRAM_ALLOW_USERS` 或 `BUB_TELEGRAM_ALLOW_CHATS`。 +- **最小化工作区目录**:仅挂载必要的项目目录,隔离主机密钥与系统目录。 +- **限制最大步数**:设置 `BUB_MAX_STEPS`(默认无上限 `sys.maxsize`,生产环境建议设为 `50` 左右),防止死循环耗尽额度。 +- **保护密钥**:通过 `.env` 或环境变量注入凭据,切勿提交到 Git 仓库。 +- **定期备份**:定期备份 `~/.bub`(或容器 `/data`)中的 Tape 记录。 diff --git a/website/src/content/docs/zh-cn/docs/app/distribution.mdx b/website/src/content/docs/zh-cn/docs/app/distribution.mdx index 89be5625..3286ef3a 100644 --- a/website/src/content/docs/zh-cn/docs/app/distribution.mdx +++ b/website/src/content/docs/zh-cn/docs/app/distribution.mdx @@ -1,68 +1,66 @@ --- title: 打包与分发 -description: 将 Bub 应用、自有命令、插件与技能打包为标准 Python 发行包并进行发布验证。 +description: 将自定义 Bub CLI 命令、插件与技能一起打包为标准 Python Wheel 发行包,并在发布前完成本地安装与验证。 --- import { FileTree, Steps } from '@astrojs/starlight/components'; -当你基于 Bub 构建了自定义工具、通道插件、特定工作流技能,甚至想要打造专属的定制 CLI 时,可以将它们打包为标准的 Python 发行包(Wheel),发布至 PyPI 或私有镜像源供团队与用户安装。 +当你基于 Bub 构建了自定义工具、渠道插件、特定工作流技能,甚至想打造一个专属的定制 CLI 时,可以将它们打包为标准的 Python Wheel,发布到 PyPI 或私有源供团队与用户安装。 -在 Bub 架构中,打包分发通常对应三种场景: +常见的三种打包形态: -| 分发形态 | 交付物 | 适用场景 | +| 形态 | 包含内容 | 适用场景 | | --- | --- | --- | -| **扩展能力包** | 插件入口点 + 技能命名空间 | 为现有 Bub 生态贡献自定义工具、生命周期服务或专业技能 | -| **专属业务 CLI** | 自定义命令行脚本(如 `my-bub`) | 包装 Bub 为特定业务场景的专属 Agent,固定工作区或封装默认配置 | -| **一体化套件** | 自有命令 + 插件 + 技能(All-in-One) | 一键交付完整的垂直领域智能体,用户安装即可直接使用 | +| **扩展插件包** | 插件入口点 + 技能目录 | 为现有 Bub 应用补充工具、渠道或技能 | +| **定制 CLI** | 自定义命令脚本(如 `my-bub`) | 封装专属命令名或固定默认工作区 | +| **一体化套件** | 自有命令 + 插件 + 技能 | 交付开箱即用的垂直领域 Agent | :::note -本页侧重于**作为独立可安装包的构建与分发**。若你是在已有的 Web 框架或后台服务中以代码形式集成 Bub,请参阅[复用 Bub 应用](/zh-cn/docs/integrations/reuse-app/)。 +本页介绍如何构建**独立可安装的 Python 包**。若要在现有 Web 服务或后端代码中嵌入 Bub,请阅读[复用 Bub 应用](/zh-cn/docs/integrations/reuse-app/)。 ::: -## 发布自有命令 {#publish-a-command} +## 封装自有 CLI 命令 {#publish-a-command} -发行包可以提供自己的命令名,并在内部调用 Bub 的 CLI 入口。通过这种方式,你可以为 Agent 打造专属品牌或固化默认行为: +发行包可以注册自己的命令名,并在内部调用 Bub 的 CLI 入口,为你的 Agent 打造专属品牌或固定默认工作区: ```python title="src/my_bub/cli.py" -from pathlib import Path import os +from pathlib import Path from bub.__main__ import main as bub_main def main() -> None: - # 可选:固化默认工作区。Bub 的工作区默认取当前目录,没有对应的 BUB_* 环境变量, - # 因此在调用 bub_main() 之前先切换目录;用户传入的 --workspace 仍可覆盖它。 + # 可选:设置默认工作区(用户传入的 --workspace 仍可覆盖它) if workspace := os.getenv("MY_BUB_WORKSPACE"): os.chdir(Path(workspace).expanduser()) - # 调用 Bub 核心 CLI 调度器,自动支持 chat, run, gateway 等完整子命令 bub_main() ``` -在 `pyproject.toml` 中通过 `[project.scripts]` 注册命令: +在 `pyproject.toml` 中通过 `[project.scripts]` 声明命令: -```toml +```toml title="pyproject.toml" [project.scripts] my-bub = "my_bub.cli:main" ``` -用户安装后,即可直接运行 `my-bub chat`、`my-bub gateway` 或 `my-bub run`。Bub 的 Typer CLI 会自动挂载所有原生子命令并支持 `--workspace` 等标准参数。 +安装完成后,用户就可以直接运行 `my-bub chat`、`my-bub run` 或 `my-bub gateway`,所有原生子命令和 `--workspace` 等参数都会一并生效。 -## 分发插件与技能 {#bundle-plugins-and-skills} +## 同时打包插件与技能 {#bundle-plugins-and-skills} -一个 Wheel 发行包可以同时提供插件入口点、标准技能命名空间包以及自定义 CLI 命令: +一个 Wheel 包可以同时包含 CLI 命令、插件入口点和 `skills` 命名空间包: - my-bub/ - - pyproject.toml + - **pyproject.toml** - src/ - my_bub/ - \_\_init\_\_.py - - cli.py # 自有 CLI 入口 - - plugin.py # 插件与 Hook 实现 + - **cli.py** # 自定义 CLI 入口 + - **plugin.py** # 插件与 Hook 实现 - tools.py # 自定义工具 - - skills/ # 技能命名空间包(切勿放置 \_\_init\_\_.py) + - **skills/** # 技能命名空间包(切勿创建 \_\_init\_\_.py) - repo-reviewer/ - SKILL.md - references/ @@ -70,13 +68,11 @@ my-bub = "my_bub.cli:main" -:::caution[命名空间包规范] -`src/skills/` 必须作为 **PEP 420 隐式命名空间包** 分发,**绝对不能**在 `src/skills/` 目录下创建 `__init__.py`。只有保持命名空间包结构,用户安装此包后,其目录下的技能才能与 Bub 内置技能及其他扩展包中的技能在 `skills.__path__` 中自动合流。技能编写规范详见[技能](/zh-cn/docs/app/skills/)。 +:::caution[技能目录不得包含 `__init__.py`] +`src/skills/` 必须作为 **PEP 420 隐式命名空间包** 打包,**切勿**在 `src/skills/` 下创建 `__init__.py`。只有保持隐式命名空间结构,该包中的技能才能与 Bub 内置技能及其他插件包中的技能共同合并到 `skills.__path__` 下。 ::: -### 配置 pyproject.toml {#configure-packaging} - -在 `pyproject.toml` 中配置入口点与 Hatch 构建包含规则: +### 配置 `pyproject.toml` {#configure-packaging} ```toml title="pyproject.toml" mark={14-15,17-18,20-21} [build-system] @@ -89,7 +85,7 @@ version = "0.1.0" description = "My Custom Bub Agent Distribution" requires-python = ">=3.12" dependencies = [ - "bub[app]>=0.6.0", # 必须声明 app 依赖以支持 CLI、插件装载与技能 + "bub[app]>=0.6.0", ] [project.scripts] @@ -102,59 +98,54 @@ my_plugin = "my_bub.plugin:plugin" packages = ["src/my_bub", "src/skills"] ``` -#### 配置要点 {#key-settings} +配置要点: -1. **依赖声明**:务必声明 `bub[app]`。自 0.6.0 起,核心包 `bub` 仅包含轻量内核,CLI、插件装载与技能运行时均由 `app` 额外依赖提供,遵循 [0.6 迁移说明](/zh-cn/docs/migration/v0-6/) 中的包结构调整。插件所依赖的三方库(如 `httpx`、`pydantic` 等)也应一并声明在发行包的 `dependencies` 中。 -2. **入口点格式**:插件入口点组必须为 `"bub"`,具体语法参见[插件注册规则](/zh-cn/docs/app/plugins/#entry-point-forms)。 -3. **打包包含范围**:在 `[tool.hatch.build.targets.wheel]` 的 `packages` 中明确包含 `"src/skills"`,确保技能资产随 Wheel 打包并正确安装至环境中的 `site-packages/skills/`。 +1. **依赖 `bub[app]`**:核心包 `bub` 仅含内核,CLI、插件和技能加载均需 `bub[app]`(见 [0.6.0 升级说明](/zh-cn/docs/migration/v0-6/))。 +2. **声明 `"bub"` 入口点**:在 `[project.entry-points."bub"]` 下注册插件(语法见[入口点形式](/zh-cn/docs/app/plugins/#entry-point-forms))。 +3. **打包 `src/skills`**:在 `[tool.hatch.build.targets.wheel]` 的 `packages` 中显式列入 `"src/skills"`。 -## 构建与分发 {#build-and-distribute} +## 构建与安装 {#build-and-distribute} -推荐使用 [`uv`](/zh-cn/docs/getting-started/install/) 快速构建标准的 Wheel 和源码包: +使用 `uv` 构建 Wheel 和源码包: ```bash uv build ``` -构建完成后,产物将生成在 `dist/` 目录下(如 `my_bub-0.1.0-py3-none-any.whl`)。你可以将其发布至 PyPI,或在组织内部通过私有源分发。 +构建产物位于 `dist/` 目录下。下游用户可通过以下方式安装: -对于下游用户: -- **作为全局 CLI 安装**:推荐使用 `uv tool install my-bub`; -- **作为受管插件安装**:若需要将该包安装至 Bub 管理的独立项目或容器环境中,使用 [`bub install`](/zh-cn/docs/reference/cli/#bub-install)。 +- **作为独立 CLI 工具安装**:`uv tool install my-bub` +- **作为 Bub 托管插件安装**:[`bub install `](/zh-cn/docs/reference/cli/#bub-install) ## 发布前验证 {#verify-a-release} -发布到公开或生产环境前,务必在全新的虚拟环境中完成验证。 +发布到公开或生产环境前,建议在全新的虚拟环境中从构建好的 `.whl` 文件安装并走一遍验证: -1. **创建独立环境并安装 Wheel**: +1. **创建干净环境并安装 Wheel**: ```bash uv venv .test-env && source .test-env/bin/activate uv pip install dist/*.whl ``` - 务必从打包生成的 wheel 安装,而不是直接在开发源码目录下运行。 -2. **验证插件与 Hooks 加载**: +2. **验证插件加载**: ```bash my-bub hooks ``` - 检查终端输出中是否正确列出了你的插件标识,确认入口点加载成功且没有弃用警告或导入异常。 + 确认输出中包含你的插件标识,且无导入报错。 3. **验证技能发现**: ```bash my-bub run ",skill" + my-bub run ",skill name=repo-reviewer" ``` - 确认分发的技能(如 `repo-reviewer`)出现在已发现列表中,并使用 `my-bub run ",skill name=repo-reviewer"` 检查变量插值与正文展开是否正常。 + 确认打包的技能已被发现且正文能正常展开。 -4. **验证自有命令与交互链路**: +4. **验证对话与工具调用**: ```bash - my-bub run "测试模型与自定义工具调用" + my-bub run "测试模型与自定义工具" my-bub chat ``` - 验证模型交互、自定义工具执行、内部命令调度以及会话历史持久化。 - -5. **验证网关与宿主集成(如适用)**: - 若该发行包提供了渠道扩展或被宿主系统集成,按 [部署](/zh-cn/docs/app/deploy/) 与 [复用 Bub 应用](/zh-cn/docs/integrations/reuse-app/) 接入宿主服务,验证并发、关闭流和退出清理。 diff --git a/website/src/content/docs/zh-cn/docs/app/gateway.mdx b/website/src/content/docs/zh-cn/docs/app/gateway.mdx index 2af4fd53..1615960c 100644 --- a/website/src/content/docs/zh-cn/docs/app/gateway.mdx +++ b/website/src/content/docs/zh-cn/docs/app/gateway.mdx @@ -1,44 +1,40 @@ --- title: 网关 -description: 配置和运行 Bub 网关,接入聊天平台,并管理消息与会话。 +description: 配置并运行 Bub 常驻网关,接入 Telegram 或自定义消息渠道,管理多平台会话路由并将其部署为后台服务。 --- import { Steps } from '@astrojs/starlight/components'; -Bub 最初的灵感就是来源于 Openclaw、nanobot 这样的常驻型 Agent,所以除了终端交互之外,Bub 还提供了网关(Gateway)功能。 +Bub 最初的灵感源于 OpenClaw、nanobot 这类常驻型 Agent。因此除了在终端里对话,Bub 也自带了网关(Gateway)模式,可以一直挂在后台响应聊天软件里的消息。 -执行 `bub gateway` 子命令 Bub 将运行已启用的渠道并作为网关启动。 - -目前 Bub 仅内置 Telegram 渠道,其他平台需通过 Bub 社区 [插件](https://hub.bub.build/) 接入。因此本文档主要以 Telegram 渠道的配置和使用为例。 +运行 `bub gateway` 即可启动所有已启用的消息渠道。Bub 内置了 Telegram 渠道,其他平台可通过社区[插件](https://hub.bub.build/)接入。 ## 启动 Telegram 网关 {#telegram} :::note -先确认 Bub 应用已正确安装和配置,并从 [@BotFather](https://t.me/BotFather) 取得机器人 token。 +开始前请确认已安装并配置 Bub,且已从 [@BotFather](https://t.me/BotFather) 获取机器人 Token。 ::: 1. **配置 `.env`** - 在工作区根目录的 `.env` 中设置: + 在工作区根目录的 `.env` 中填入 Token 和允许访问的用户 ID(可通过 [@userinfobot](https://t.me/userinfobot) 查询你的数字 ID): ```bash title=".env" BUB_TELEGRAM_TOKEN=123456789:your-telegram-bot-token BUB_TELEGRAM_ALLOW_USERS=123456789 ``` - 将 `BUB_TELEGRAM_ALLOW_USERS` 设为你的数字 ID,可用 [@userinfobot](https://t.me/userinfobot) 查询。 - 2. **启动网关** - 在包含 `.env` 文件的工作区中运行: + 在工作区目录中运行: ```bash bub gateway ``` - 启动成功的日志示例: + 启动成功后会输出如下日志: ```text telegram.start allow_users_count=1 allow_chats_count=0 proxy_enabled=False @@ -47,85 +43,87 @@ Bub 最初的灵感就是来源于 Openclaw、nanobot 这样的常驻型 Agent 3. **验证私聊** - 试着向机器人发一条私聊,等待片刻后看是否收到回复。如无回复时见 [配置回复](#telegram-outbound) 和 [故障排查](#troubleshooting)。 + 试着向机器人发一条私聊消息,稍等片刻看是否收到回复。若无响应,请参考 [回复发送机制](#telegram-outbound) 和 [故障排查](#troubleshooting)。 -Bub 作为网关运行要求至少已启用一个渠道。当 `BUB_TELEGRAM_TOKEN` 非空时,Telegram 渠道即为启用状态。 +网关要求至少启用一个渠道。只要 `BUB_TELEGRAM_TOKEN` 非空,Telegram 渠道就会自动启用。 ## 配置 Telegram {#configure-telegram} -### 限制访问 {#restrict-access} +### 访问白名单 {#restrict-access} -设置 `BUB_TELEGRAM_ALLOW_USERS` 限制可访问用户,设置 `BUB_TELEGRAM_ALLOW_CHATS` 限制可访问的聊天会话。 - -多个值用逗号分隔,用户名区分大小写: +使用 `BUB_TELEGRAM_ALLOW_USERS` 限制可访问的用户,使用 `BUB_TELEGRAM_ALLOW_CHATS` 限制可访问的群组或会话(多个值用逗号分隔,用户名区分大小写): ```bash BUB_TELEGRAM_ALLOW_USERS=123456789,your_username BUB_TELEGRAM_ALLOW_CHATS=-1001234567890,-1009876543210 ``` -| 白名单配置 | 通过条件 | 未通过时 | +| 白名单配置 | 放行条件 | 未通过时的行为 | | --- | --- | --- | -| `BUB_TELEGRAM_ALLOW_USERS` | 数字 ID 或用户名匹配 | 用户收到 `Access denied.` | -| `BUB_TELEGRAM_ALLOW_CHATS` | 聊天 ID 匹配 | 消息被静默丢弃 | +| `BUB_TELEGRAM_ALLOW_USERS` | 用户数字 ID 或用户名匹配 | 回复 `Access denied.` | +| `BUB_TELEGRAM_ALLOW_CHATS` | 聊天 ID 匹配 | 静默丢弃消息 | + +两项同时配置时,必须同时满足才放行。**两项均为空时,任何用户都能调用你的机器人**——公网部署前请至少配置一项。 -两项都设置时,必须全部通过。两个白名单都**为空**时,任何用户都能使用机器人;公开部署前至少设置一个。 +### 群聊触发规则 {#telegram-inbound} -### 配置群聊 {#telegram-inbound} +将机器人拉入群聊前,需先在 [@BotFather](https://t.me/BotFather) 中关闭 **Privacy Mode**(隐私模式),否则机器人只能收到 `/` 开头的斜杠命令,看不到普通群消息。 -在 BotFather 中关闭 **Privacy Mode**,否则机器人只能看到命令,读不到普通群消息。 +为了避免机器人在群里对所有人的闲聊都随便插话,Bub 按以下规则决定是否接收群消息: -| 消息来源或类型 | 接收条件 | +| 消息类型 | 触发条件 | | --- | --- | -| 私聊中的非命令消息 | 全部接收 | -| 群聊中的文本消息 | 提及 `@`、包含 `bub`,或回复机器人 | -| 群聊中带文字说明的图片和文件 | 与文本消息相同 | -| 群聊中无文字说明的非文本消息 | 仅回复机器人时接收 | -| `/bub ` | 去掉 `/bub ` 前缀,剩余内容作为提示词 | +| 私聊非命令消息 | 全部接收 | +| 群聊文本消息 | `@`、正文包含 `bub`(不区分大小写,子串匹配,故 `bubble` 也会命中),或直接回复机器人的消息 | +| 群聊带文字说明的图片/文件 | 与群聊文本消息相同 | +| 群聊无文字说明的图片/贴纸/文件 | 仅在直接回复机器人的消息时接收 | +| `/bub ` | 去掉 `/bub ` 前缀后作为提示词交给 Bub | -不满足条件的群消息会被忽略。若会话仍在 `BUB_ACTIVE_TIME_WINDOW` 内,这些消息也可能并入当前批次。`bub` 使用子串匹配,因此 `bubble` 也会命中。 +未命中的群消息默认忽略;但如果该群刚触发过机器人、仍处于活跃窗口(`BUB_ACTIVE_TIME_WINDOW`)内,后续跟进消息也会并入当前批次(见[合并连续消息](#merge-consecutive-messages))。 -### 配置回复 {#telegram-outbound} +### 回复发送机制 {#telegram-outbound} -| 输入 | `output_channel` | 发送方式 | +在 Telegram 渠道中,**普通对话消息**和**逗号命令**走不同的回复路径: + +| 输入类型 | `output_channel` | 回复方式 | | --- | --- | --- | -| 普通消息 | `"null"` | 内置 `telegram` 技能发送回复、进度和编辑 | -| 逗号命令 | `"telegram"` | 工具输出发到原 `chat_id` | +| 普通对话消息 | `"null"`(关闭框架自动直发) | 由模型调用内置的 `telegram` 技能发送回复、引用消息或更新进度 | +| 逗号命令(如 `,help`) | `"telegram"` | 不经过模型,框架直接把工具输出发回原 `chat_id` | + +为什么要这样设计?因为在群聊或长任务中,Agent 往往需要先发一条状态提示、中途原地编辑那条消息,或者判断某条群消息根本不需要插话。把普通消息交给内置的 `telegram` 技能,模型就能自主决定何时以及如何回复。 -普通消息的模型输出不会自动发到 Telegram;模型必须调用 `telegram` 技能,否则用户收不到回复。typing 每 4 秒续期,只表示 Turn 尚未结束。 +:::note +对于普通消息,**模型必须调用 `telegram` 技能,用户才会在 Telegram 中收到回复**。Turn 运行期间顶部的 `typing...` 状态每 4 秒自动续期一次,仅表示后台仍在运行。 +::: -逗号命令输出为含 `message` 字段的 JSON 时,只发该字段;其他非空输出原样发送,空输出丢弃。 +逗号命令(如 `,tape.info`)不经过模型,框架直接发回输出:若返回的是带 `message` 字段的 JSON,则只发送 `message` 内容;其他非空文本原样发送;空输出直接忽略。 ### 合并连续消息 {#merge-consecutive-messages} -Telegram 会把短时间内的连续消息合并进一个 Turn,你可以通过以下环境变量调整合并策略: +在即时通讯软件里,大家经常习惯把一句话拆成好几条短消息连着发(比如先发一句「帮我看看这个报错」,紧接着再贴一段日志)。如果每条都立刻触发一次模型调用,不仅浪费 Token,上下文也会支离破碎。因此,Telegram 渠道会自动将短时间内连续到达的消息用换行符拼接,合并为同一个 Turn 处理: -| 变量 | 默认值 | 说明 | +| 环境变量 | 默认值 | 说明 | | --- | --- | --- | -| `BUB_DEBOUNCE_SECONDS` | `1.0` | 每条活跃消息都会重置的短暂等待 | -| `BUB_MAX_WAIT_SECONDS` | `10.0` | 等待非活跃跟进消息的上限 | -| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | 非活跃消息可并入批次的时间窗口 | +| `BUB_DEBOUNCE_SECONDS` | `1.0` | **活跃消息防抖秒数**:收到私聊或群内直接提及机器人的活跃消息时重置倒计时,等待用户把话说完 | +| `BUB_MAX_WAIT_SECONDS` | `10.0` | **跟进消息最大等待秒数**:收到群内未直接 @ 机器人的跟进消息时,最多等待多久触发合并 | +| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | **群聊活跃窗口秒数**:触发机器人后的多少秒内,同群未 @ 机器人的普通消息也会并入当前批次 | -私聊和群聊中明确发给机器人的消息是活跃消息;同会话后续未提及的群消息是非活跃消息。两者按会话暂存,计时结束后用换行合并。命令前缀(默认 `,`)开头的输入不参与合并,会立即分发。 +以命令前缀(默认 `,`)开头的直接命令不参与合并,收到后立即执行。 -### 代理 {#telegram-reference} - -可为 Telegram 渠道配置代理: +### 配置代理 {#telegram-reference} ```bash BUB_TELEGRAM_PROXY=http://127.0.0.1:7890 # 也支持 socks5://:@host:port ``` -## 接入其他平台 {#other-platforms} - -尽管 Bub 只内置了 Telegram 渠道,但社区提供了多种 [插件](https://hub.bub.build/) 以接入其他平台。 +## 接入其他聊天平台 {#other-platforms} -安装其他平台插件后需重启网关,重启完成后用 `bub hooks` 确认 `provide_channels` 下是否出现对应名称。在启动时未配置凭据的渠道会被跳过。 +社区提供了多个平台的渠道[插件](https://hub.bub.build/)。安装插件后重启网关,运行 `bub hooks` 确认 `provide_channels` 下已出现对应名称(未配置凭据的渠道在启动时会自动跳过): -| 平台 | 渠道名 | 插件 | +| 平台 | 渠道名 | 插件包 | | --- | --- | --- | | Discord | `discord` | [`bub-discord`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-discord) | | Slack | `slack` | [`bub-slack`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-slack) | @@ -135,13 +133,13 @@ BUB_TELEGRAM_PROXY=http://127.0.0.1:7890 | 钉钉 | `dingtalk` | [`bub-dingtalk`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-dingtalk) | | QQ | `qq` | [`bub-qq`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-qq) | -相关渠道的配置以各插件说明文档为准。 +各渠道所需的环境变量见对应插件仓库的 README。 -## 自定义渠道 {#custom-channels} +## 开发自定义渠道 {#custom-channels} -无现成插件可用时,可自己实现渠道:通过 Python 代码来继承 `Channel` 类,设置 `name` 属性并实现 `start`、`stop` 以及 `send` 方法即可。以下是一个最小示例: +如果没有现成的社区插件可用,也可以自己实现一个渠道:继承 `Channel` 类并实现 `start`、`stop` 和 `send` 方法即可: -```python +```python showLineNumbers collapse={1-6} {8, 30-37} import asyncio from bub.channels.base import Channel @@ -149,7 +147,7 @@ from bub.channels.message import ChannelMessage class MyChannel(Channel): - name = "myapp" # 渠道名称 + name = "myapp" def __init__(self, on_receive, token: str) -> None: self._on_receive = on_receive @@ -161,7 +159,7 @@ class MyChannel(Channel): return bool(self._token) async def start(self, stop_event: asyncio.Event) -> None: - # start 方法不允许阻塞主循环,否则网关无法接收后续消息 + # start 不能阻塞主事件循环,需放入后台 Task self._listener = asyncio.create_task(self._listen(stop_event)) async def stop(self) -> None: @@ -170,7 +168,7 @@ class MyChannel(Channel): async def _listen(self, stop_event: asyncio.Event) -> None: while not stop_event.is_set(): - chat_id, text = await self._next_message() # 平台消息 + chat_id, text = await self._next_message() await self._on_receive( ChannelMessage( session_id=f"myapp:{chat_id}", @@ -184,63 +182,55 @@ class MyChannel(Channel): await self._post(message.chat_id, message.content) ``` -注意: +实现要点: -- 每条入站消息都调用框架传入的 `on_receive` 事件方法。 -- `session_id` 使用 `:` 格式,避免不同平台的会话冲突。 -- 配置不完整时让 `enabled` 默认返回 `False`,网关会跳过该渠道。 -- 需要合并连续短消息时,让 `needs_debounce` 返回 `True`。 +- 收到平台消息时调用框架传入的 `on_receive` 回调。 +- `session_id` 建议使用 `:` 格式,防止跨平台会话冲突。 +- 缺少必要配置时让 `enabled` 返回 `False`,网关会自动跳过该渠道。 +- 需要防抖合并连续短消息时,将 `needs_debounce` 属性设为 `True`。 -完成后,在插件入口模块中通过 `provide_channels` 暴露渠道: +通过插件的 `provide_channels` Hook 注册该渠道: ```python import os - from bub import hookimpl -# 前面的代码片段 -# class MyChannel(Channel): -# ... - @hookimpl def provide_channels(message_handler): return [MyChannel(on_receive=message_handler, token=os.environ.get("MYAPP_TOKEN", ""))] ``` -安装插件后运行对应渠道 `bub gateway --enable-channel myapp`。 +安装插件后即可通过 `bub gateway --enable-channel myapp` 启动。 -## 以 Daemon 方式运行 {#daemon} +## 注册为后台系统服务 {#daemon} -如果想 Bub 常驻系统运行,可按如下命令进行配置: +如果你想让 Bub 作为后台服务常驻运行,可以直接运行下面的命令: ```bash bub gateway --install -# 卸载 +# 卸载服务 # bub gateway --uninstall ``` -不同系统可能略有差异: - -| 系统 | 行为 | +| 操作系统 | 行为 | | --- | --- | -| Linux | systemd user unit `bub-gateway.service`;退出登录仍需运行时执行 `loginctl enable-linger $USER` | -| Windows | 当前用户计划任务;登录启动,失败后重启 | -| macOS | 不支持 `--install`;用 launchd、tmux 或[容器部署](/zh-cn/docs/app/deploy/) | - -安装会记录当前 Python 解释器、工作区和显式 `--enable-channel`。更换环境或工作区后需要重新安装。 +| Linux | 注册 systemd 用户服务 `bub-gateway.service`;退出 SSH 后仍需保活请执行 `loginctl enable-linger $USER` | +| Windows | 注册当前用户的计划任务,登录时自启、失败自动重启 | +| macOS | 不支持 `--install`;请使用 `launchd`、`tmux` 或 [Docker 部署](/zh-cn/docs/app/deploy/) | +`--install` 会记录当前的 Python 解释器路径、工作区目录和 `--enable-channel` 参数。更换虚拟环境或移动工作区后,请重新运行 `bub gateway --install`。 ## 故障排查 {#troubleshooting} | 现象 | 可能原因 | 解决方法 | | --- | --- | --- | -| 提示 `No channels are enabled` | 没有可用渠道 | 检查 token 和 `.env` 位置;用 `bub hooks` 检查插件 | -| 日志无 `telegram.start` | Telegram token 为空 | 设置 token,确认已传入 `bub` 进程 | -| 私聊收到 `Access denied.` | 未通过用户白名单 | 把数字 ID 或用户名加入 `BUB_TELEGRAM_ALLOW_USERS` | -| 私聊无响应 | 未通过聊天白名单 | 把聊天 ID 加入 `BUB_TELEGRAM_ALLOW_CHATS` | -| 群聊无响应 | Privacy Mode 未关,或不满足接收条件 | 关闭 Privacy Mode;测试时直接 @ 机器人 | -| 一直 typing 无回复 | 模型未调用 `telegram` 技能 | 见[回复规则](#telegram-outbound) | -| `409 Conflict` | 同一 token 有多个长轮询进程 | 停掉重复实例 | -| 重启后没有离线消息 | 启动时丢弃积压更新 | 预期行为 | +| `No channels are enabled` | 未启用任何渠道 | 检查 Token 和 `.env` 路径;运行 `bub hooks` 检查渠道插件 | +| 日志无 `telegram.start` | `BUB_TELEGRAM_TOKEN` 为空 | 检查环境变量是否已传入 `bub` 进程 | +| 私聊收到 `Access denied.` | 用户不在白名单中 | 将用户数字 ID 或用户名加入 `BUB_TELEGRAM_ALLOW_USERS` | +| 私聊无任何响应 | 聊天 ID 不在白名单中 | 将聊天 ID 加入 `BUB_TELEGRAM_ALLOW_CHATS` | +| 群聊无响应 | 未关闭 Privacy Mode 或未触发接收条件 | 在 BotFather 关闭 Privacy Mode;测试时直接 @ 机器人 | +| 一直显示 typing 但无回复 | 模型未调用 `telegram` 技能 | 见[回复发送机制](#telegram-outbound) | +| `409 Conflict` | 同一 Token 启动了多个网关实例 | 停止重复的网关进程 | +| 重启后未处理离线期间的消息 | 启动时默认丢弃积压的历史更新 | 预期行为 | diff --git a/website/src/content/docs/zh-cn/docs/app/plugins.mdx b/website/src/content/docs/zh-cn/docs/app/plugins.mdx index 5ff16a7e..5efcf286 100644 --- a/website/src/content/docs/zh-cn/docs/app/plugins.mdx +++ b/website/src/content/docs/zh-cn/docs/app/plugins.mdx @@ -1,31 +1,31 @@ --- title: 插件与 Hooks -description: 编写、安装和调试 Bub 插件,掌握入口点声明、常用 Hook 实战与系统扩展能力。 +description: 编写、安装和调试 Bub 插件,通过 Entry Points 与 Hooks 扩展工具、常驻服务、消息流程与 CLI 命令。 --- import { FileTree } from '@astrojs/starlight/components'; -插件(Plugin)是 Bub 应用核心的能力之一。Bub 基于标准 [Python Entry Points](https://packaging.python.org/en/latest/specifications/entry-points/)(入口点)机制自动发现插件,并通过 Hook 契约将自定义逻辑注入应用的各个运行阶段。 +Bub 基于标准 [Python Entry Points](https://packaging.python.org/en/latest/specifications/entry-points/) 自动发现插件,并通过 Hook 将自定义逻辑接入应用的各个运行阶段。 -通过插件,你可以为 Bub 扩展三类核心能力: -- **自定义工具**:通过 `provide_tools` 为 Agent 提供专属工具函数; -- **常驻后台服务**:通过 `Lifecycle` 挂载随应用运行的常驻守护进程(如 MCP 客户端、外部通道或事件调度器); -- **改写流程逻辑**:通过 Hook 实现拦截消息、改写提示词、审批工具调用或持久化会话状态。 +插件主要提供三类扩展能力: +- **自定义工具**:通过 `provide_tools` 注册工具函数; +- **常驻后台服务**:通过 `Lifecycle` 挂载随网关或交互会话运行的守护服务(如 MCP 客户端、消息渠道); +- **流程改写与拦截**:通过 Hook 改写提示词、拦截或审批工具调用、持久化跨 Turn 状态。 -## 基础:创建插件 {#create-a-plugin} +## 创建最小插件 {#create-a-plugin} -在深入各类复杂能力之前,我们先通过一个无需外部模型凭据的插件示例来初步建立起 Bub 的插件认知。 +在深入了解各种高级 Hook 之前,我们先写一个无需配置模型 API Key 的最小回声(Echo)插件,走通从创建到运行的完整流程。 -### 初始化插件项目 {#initialize-project} +### 1. 初始化项目 {#initialize-project} -使用 [uv](https://docs.astral.sh/uv/) 快速脚手架初始化一个 Python 库项目,并进入项目目录: +使用 `uv` 创建 Python 库项目: ```bash uv init --lib bub-echo-plugin cd bub-echo-plugin ``` -在 `src/bub_echo_plugin/` 源码目录下新建 `plugin.py` 用于编写插件与 Hook 逻辑。初始化后的整体目录结构如下: +在 `src/bub_echo_plugin/` 下新建 `plugin.py`: @@ -34,13 +34,13 @@ cd bub-echo-plugin - src/ - bub_echo_plugin/ - \_\_init\_\_.py - - plugin.py # 新建:存放插件与 Hook 逻辑 + - **plugin.py** # 存放插件与 Hook 实现 -### 声明入口点 {#declare-entry-point} +### 2. 声明入口点 {#declare-entry-point} -在 `pyproject.toml` 中,通过 `[project.entry-points."bub"]` 将插件对象暴露给 Bub: +在 `pyproject.toml` 中添加 `[project.entry-points."bub"]`: ```toml title="pyproject.toml" mark={11-12} [build-system] @@ -57,16 +57,14 @@ dependencies = ["bub[app]"] echo = "bub_echo_plugin.plugin:echo_plugin" ``` -注意: +- 入口点组名必须为 `"bub"`; +- 键名 `echo` 是插件名称,值指向要加载的模块、实例或类。 -- **`entry-points` 命名**:必须为 `"bub"`,Bub 启动时会自动扫描该命名空间下的所有插件; -- **插件标识与路径**:键名 `echo` 为插件的全局唯一标识;值指向待加载的模块、实例或工厂类。 +### 3. 实现 Hook {#implement-hooks} -### 实现 Hook 逻辑 {#implement-hooks} +使用 `@hookimpl` 装饰器标记 Hook 方法: -在模块中编写插件逻辑时,需使用 `@hookimpl` 装饰器标记具体的 Hook 实现: - -```python title="src/bub_echo_plugin/plugin.py" +```python title="src/bub_echo_plugin/plugin.py" "@hookimpl" from bub import hookimpl @@ -79,19 +77,19 @@ class EchoPlugin: echo_plugin = EchoPlugin() ``` -本例通过实现 `run_model` 以替换了内置的模型调用阶段,直接将输入文本拼接会话 ID 后作为结果返回,便于离线验证整个插件链路。 +这里实现了 `run_model` Hook 接管模型执行阶段,直接将会话 ID 与输入拼接返回,方便离线验证插件链路。 -### 入口点声明形式 {#entry-point-forms} +### 入口点的三种目标形式 {#entry-point-forms} -根据插件是否需要维护内部状态或获取宿主上下文,入口点支持三种目标形式: +入口点可指向模块、实例或类(工厂函数): -| 入口点目标语法 | 注册对象 | 适用场景 | +| 目标写法 | 注册对象 | 适用场景 | | --- | --- | --- | -| `bub_myplugin.plugin` | 模块(Module) | Hooks 为纯函数,彼此无状态共享 | -| `bub_myplugin.plugin:plugin` | 已有实例(Instance) | 多个 Hooks 之间需要通过 `self` 维护共享状态 | -| `bub_myplugin.plugin:MyPlugin` | 类或工厂函数(Factory) | 插件需要访问全局 `BubFramework` 实例 | +| `bub_myplugin.plugin` | 模块 | Hook 均为无状态的普通函数 | +| `bub_myplugin.plugin:plugin` | 已有实例 | 多个 Hook 需要通过 `self` 共享内部状态 | +| `bub_myplugin.plugin:MyPlugin` | 类或工厂函数 | 插件初始化时需要访问 `BubFramework` 实例 | -当入口点指向类或工厂函数时,Bub 在实例化该对象时会自动将当前的 `BubFramework` 实例作为第一个参数传入: +当入口点指向类或工厂函数时,Bub 会在实例化时自动传入当前 `BubFramework`: ```python from bub import BubFramework, hookimpl @@ -103,61 +101,60 @@ class MyPlugin: @hookimpl def build_prompt(self, message, session_id, state): - # 通过 framework 访问工作区路径等全局运行时信息 return f"当前工作区路径:{self.framework.workspace}\n{message}" ``` ## 安装与验证 {#install-and-run} -编写完插件后,需要将其安装到 Bub 所在的运行环境中,并验证 Hook 的加载与执行顺序。 +写完插件后,把它安装到 Bub 所在的虚拟环境中,然后验证 Hook 是否正常加载并生效。 ### 本地开发安装 {#local-install} -在插件项目根目录下执行同步,以可编辑模式(Editable Mode)将其安装至当前虚拟环境: +在插件根目录下安装到当前虚拟环境: ```bash uv sync ``` -### 检查 Hook 注册状态 {#check-hook-registration} +### 检查注册状态 {#check-hook-registration} -使用 `bub hooks` 命令检查插件是否已被正确识别: +运行 `bub hooks` 确认插件已被发现: ```bash uv run bub hooks ``` -在终端输出的 Hook 清单中,`run_model` 下应正确列出已注册的 `echo` 插件。 +输出中的 `run_model` 行应包含 `echo`。 ### 运行测试 {#run-tests} -向应用发送一条测试指令,检验插件的实际生效情况: +现在可以向应用发送一条测试消息,看看插件是不是已经生效了: ```bash uv run bub run "hello from my plugin" ``` -控制台将输出被插件拦截后的回声文本: +终端会输出被插件拦截后的回声文本: ```text [echo:cli:local] hello from my plugin ``` -### 排错与调度机制 {#troubleshooting-and-dispatch} +### 排查加载与执行顺序 {#troubleshooting-and-dispatch} -若插件未按预期加载或执行,可依据以下原则排查: +若插件未生效,请依次检查: -1. **检查运行环境**:确认执行 `bub` 命令行时所在的 Python 环境与插件安装环境完全一致; -2. **重新同步元数据**:若修改了 `pyproject.toml` 中的入口点配置,必须重新执行 `uv sync`(或 `pip install -e .`)刷新包的 Entry Points 元数据; -3. **排查 Hook 执行顺序与优先级**:Bub 遵循 Pluggy 规范,先注册内置实现,再加载入口点插件。在相同优先级下,**后注册的插件优先执行**(LIFO 策略)。若需要显式调整执行先后,可在装饰器中指定 `@hookimpl(tryfirst=True)`(尽可能最先执行)或 `@hookimpl(trylast=True)`(尽可能最后执行)。 +1. **Python 环境一致**:确认运行 `bub` 的环境与安装插件的虚拟环境相同; +2. **刷新入口点元数据**:修改 `pyproject.toml` 的 `entry-points` 后,需重新执行 `uv sync` 或 `pip install -e .`; +3. **Hook 优先级**:Bub 先注册内置实现(`builtin`),再加载第三方插件。同优先级下**后注册的插件先执行**(LIFO)。可通过 `@hookimpl(tryfirst=True)` 或 `@hookimpl(trylast=True)` 显式调整顺序,详见 [Hooks 参考:执行优先级](/zh-cn/docs/reference/hooks/#priority-and-dispatch)。 -## 进阶:通过 Hooks 定制行为 {#advanced-hooks} +## 常用 Hook 写法 {#advanced-hooks} -Bub 提供了涵盖入站解析、模型调用、工具拦截、状态与生命周期的全套扩展点(签名见 [Hooks 参考手册](/zh-cn/docs/reference/hooks/))。在实际业务场景中,最常用的定制需求可分为以下四类: +Bub 提供了一整套覆盖入站解析、模型调用、工具拦截、状态与生命周期的扩展点(全部 27 个 Hook 的完整签名见 [Hooks 参考](/zh-cn/docs/reference/hooks/))。日常开发中最常用的扩展可以分为下面四类: ### 1. 提供工具 {#provide-tools} -插件可以通过 `provide_tools` Hook,向 Agent 注册由 `@tool` 声明的 Python 函数: +通过 `provide_tools` 注册由 `@tool` 装饰的工具函数: ```python from bub import hookimpl, tool @@ -166,7 +163,7 @@ from bub.core.tools import Tool @tool(name="orders.get") def get_order(order_id: str) -> dict[str, str]: - """根据订单 ID 查询订单发货状态。""" + """根据订单 ID 查询发货状态。""" return {"id": order_id, "status": "shipped"} @@ -176,27 +173,24 @@ class OrdersPlugin: return [get_order] ``` -#### 延迟加载 {#deferred-loading} +#### 延迟加载工具 Schema {#deferred-loading} -当插件提供了大量工具时,将所有工具的完整 Schema 一次性注入系统提示词会严重消耗上下文窗口。可以在装饰器中启用延迟加载: +若插件提供大量工具,一次性将全部 Schema 注入系统提示词会占用过多上下文。可设置 `deferred=True`: -```python +```python "deferred=True" @tool(name="orders.export", deferred=True) def export_orders(format: str) -> str: - """导出所有历史订单报表。""" + """导出历史订单报表。""" ... ``` -注意: - -- **延迟机制**:带有 `deferred=True` 的工具默认只向系统提示词提供工具名称与简要描述; -- **动态展开**:当模型判断需要调用该工具时,会自动通过内置的 `tool.describe` 临时加载其完整定义,并从下一步开始执行调用。 +带有 `deferred=True` 的工具初始仅向模型展示名称和简短描述;当模型需要调用它时,会自动先调用内置的 `tool.describe` 加载完整参数定义,并在下一步发起调用。 -### 2. 流程改写与拦截 {#rewrite-and-intercept} +### 2. 改写提示词、拦截调用与保存状态 {#rewrite-and-intercept} #### 改写提示词 {#change-the-prompt} -- **改写模型输入**:`build_prompt` 接收入站消息、会话 ID 和本轮状态,返回最终提供给模型的输入内容: +- **改写本轮用户输入**(`build_prompt`): ```python from bub import hookimpl from bub.envelope import content_of @@ -205,21 +199,21 @@ def export_orders(format: str) -> str: @hookimpl def build_prompt(message, session_id, state): text = content_of(message) - return [f"请使用项目专业术语回答:\n\n{text}"] + return [f"请使用项目术语回答:\n\n{text}"] ``` -- **追加系统指令**:如果只想向模型追加全局约束而不改进入站内容,使用 `system_prompt`(多个插件追加的内容按优先级自动换行拼接): +- **追加系统提示词**(`system_prompt`,多个插件的返回值会按优先级换行拼接): ```python @hookimpl def system_prompt(prompt, state): - return "请在回复末尾附带所参考的代码文件路径。" + return "请在回复末尾附上参考的代码文件路径。" ``` -#### 拦截调用 {#control-a-model-or-tool-call} +#### 拦截模型或工具调用 {#control-a-model-or-tool-call} -拦截 Hook 在调用实际触发前执行。抛出的异常会被框架记录并跳过;若要主动干预、修改或阻断执行,必须返回对应的决策对象(Decision): +拦截 Hook 在调用执行前触发。注意:在拦截 Hook 中抛异常只会被记录日志并跳过,**不能阻止调用执行**;如需修改参数或拒绝调用,必须返回对应的决策对象: -- **限制 LLM 采样参数**: +- **修改模型请求参数**(`before_llm_call`): ```python from dataclasses import replace from bub import hookimpl @@ -232,7 +226,7 @@ def export_orders(format: str) -> str: return replace(request, max_tokens=max_tokens) ``` -- **审批或拒绝高危工具调用**: +- **审批或拒绝工具调用**(`before_tool_call`): ```python from bub import hookimpl from bub.hooks.interception import ToolCall, ToolCallDecision @@ -241,15 +235,15 @@ def export_orders(format: str) -> str: @hookimpl def before_tool_call(call: ToolCall, state): if call.tool == "orders.cancel" and not state.get("can_cancel_orders", False): - return ToolCallDecision.deny("当前会话无权执行撤单操作。") + return ToolCallDecision.deny("当前会话无权撤单。") return None ``` -放行、改写、拒绝与替代的语义见[决策先于副作用](/zh-cn/docs/concepts/events/#call-control);完整返回类型见 [Hooks 参考](/zh-cn/docs/reference/hooks/#toolcalldecision)。 +决策语义见[调用前拦截与控制](/zh-cn/docs/concepts/events/#call-control),返回类型见 [`ToolCallDecision`](/zh-cn/docs/reference/hooks/#toolcalldecision)。 -#### 调用审计 {#observe-completed-calls} +#### 记录调用耗时与审计日志 {#observe-completed-calls} -完成类 Hook 在调用结束后触发,适用于统计耗时、上报监控指标或记录审计日志: +完成类 Hook 在调用结束后触发,适合统计耗时、上报指标或记录审计日志: ```python from bub import hookimpl @@ -265,9 +259,9 @@ def after_tool_call(call, result, state): print(f"tool={call.tool} error={result.error!r} elapsed={result.duration_ms}ms") ``` -#### 状态持久化 {#keep-application-state-across-turns} +#### 跨 Turn 保存应用状态 {#keep-application-state-across-turns} -下面通过 `load_state` 与 `save_state` 在多个 Turn 之间保存计数。`TurnState` 的生命周期与数据归属见 [Turn](/zh-cn/docs/concepts/turn/#state) 和[数据应该放在哪里](/zh-cn/docs/concepts/tape/#state)。 +使用 `load_state` 和 `save_state` 在多个 Turn 之间读写应用状态(状态边界见 [TurnState](/zh-cn/docs/concepts/turn/#state)): ```python import asyncio @@ -293,11 +287,11 @@ class TurnCounter: turn_counter = TurnCounter() ``` -### 3. 服务与资源挂载 {#services-and-resources} +### 3. 挂载服务与存储资源 {#services-and-resources} -#### 常驻服务 {#lifecycle} +#### 常驻后台服务 {#lifecycle} -MCP 客户端、通道监听器或定时调度器等需伴随应用常驻运行的组件,继承 `Lifecycle` 基类并通过 `provide_channels` 暴露: +MCP 客户端、外部通道或定时任务等常驻组件,可继承 `Lifecycle` 并通过 `provide_channels` 注册: ```python from bub.channels.base import Lifecycle @@ -313,14 +307,12 @@ class MyRuntime(Lifecycle): await self._close() ``` -注意: +- `Lifecycle` 服务会在 `bub chat` 和 `bub gateway` 启动时自动运行,退出时清理;单次执行的 `bub run` 不会启动它。 +- 可通过 `--enable-channel '!myapp.lifecycle'` 在启动时排除指定服务。 -- **生命周期契约**:常驻服务会在 `bub gateway` 启动或渠道运行时自动初始化,并在退出时执行清理;注意单次执行的 `bub run` 不会激活常驻服务。 -- **命令行过滤**:启动时可通过 `--enable-channel` 单独启用,或使用 `--enable-channel '!myapp.lifecycle'` 显式排除。 +#### 进程级共享资源 {#runtime-resources} -#### 生命周期资源 {#runtime-resources} - -在整个进程生命周期中持有全局数据库连接池、HTTP 客户端等资源时,可通过异步生成器实现 `provide_lifespan`: +使用 `provide_lifespan` 异步生成器管理数据库连接池或共享 HTTP 客户端(覆盖整个 `framework.running()` 周期): ```python from bub import hookimpl @@ -335,9 +327,9 @@ async def provide_lifespan(): await client.close() ``` -#### 会话存储 {#provide-a-tape-store} +#### 替换会话存储 {#provide-a-tape-store} -通过 `provide_tape_store` 可以替换默认的本地文件会话存储(例如接入 PostgreSQL 或云端存储,详见 [SQLAlchemy 集成](/zh-cn/docs/integrations/storage/)): +通过 `provide_tape_store` 替换默认的本地文件存储(见[使用数据库存储会话历史](/zh-cn/docs/integrations/storage/)): ```python from pathlib import Path @@ -350,9 +342,9 @@ def provide_tape_store(): return FileTapeStore(Path("./application-tapes")) ``` -### 4. 扩展 CLI 命令 {#add-an-application-command} +### 4. 注册 CLI 子命令 {#add-an-application-command} -插件可以通过 `register_cli_commands` 直接向 Bub 根 CLI(基于 Typer)注册子命令: +通过 `register_cli_commands` 向 `bub` 注册自定义子命令: ```python import typer @@ -366,9 +358,9 @@ def register_cli_commands(app: typer.Typer): typer.echo(f"执行成功:{name}") ``` -#### 交互式输入 {#prompt-for-input} +#### 终端交互式输入 {#prompt-for-input} -若插件子命令需要在终端中与用户交互确认或获取输入,推荐使用 `bub.inquirer` 提供的交互式输入工具: +在自定义 CLI 命令中向用户请求输入或确认时,可使用 `bub.inquirer`: ```python from bub.inquirer import ask_confirm, ask_text @@ -378,17 +370,15 @@ if ask_confirm("确认继续执行?", kind="permission"): pass ``` -## 分发与扩展 {#share-a-plugin} +## 分发与跨语言扩展 {#share-a-plugin} ### 打包分发 {#package-and-distribute} -开发完成的插件可以打包为标准 Python Wheel 进行分发。一个发行包可以同时包含插件入口点、技能命名空间包以及自定义 CLI 命令,具体打包配置与发布前验证见[打包与分发](/zh-cn/docs/app/distribution/)。跨语言生态包规范见[加载 Agent Plugins](/zh-cn/docs/integrations/agent-plugins/)。 +插件可打包为标准 Python Wheel 分发,并同时包含入口点、技能和自定义 CLI 命令,详见[打包与分发](/zh-cn/docs/app/distribution/)。跨平台的声明式插件规范见[使用 Agent Plugins](/zh-cn/docs/integrations/agent-plugins/)。 ### WASM 插件(实验性) {#wasm-plugins} -借助 [`bub-extism`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-extism) 扩展,可以通过 WebAssembly 将 Go、Rust 等其他语言编译的二进制模块直接挂载为 Bub Hook 处理函数。 - -`extism.json` 指定模块文件和 hook 映射: +借助 [`bub-extism`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-extism),可将 Go、Rust 等语言编译的 WebAssembly 模块挂载为 Bub Hook: ```json title="extism.json" { diff --git a/website/src/content/docs/zh-cn/docs/app/skills.mdx b/website/src/content/docs/zh-cn/docs/app/skills.mdx index 61c0a03a..49ddd20f 100644 --- a/website/src/content/docs/zh-cn/docs/app/skills.mdx +++ b/website/src/content/docs/zh-cn/docs/app/skills.mdx @@ -1,86 +1,86 @@ --- title: 技能 -description: 编写、验证和使用 Bub 技能,并理解技能发现与覆盖规则。 +description: 编写、验证并分发可复用的 Bub 技能(SKILL.md),了解技能发现优先级、内置技能及模板变量插值机制。 --- -[技能](https://agentskills.io/)(Skill)是由 Anthropic 所提出的标准发布的格式,用于扩展 AI 代理能力、补充专业知识与工作流程。一个技能即一个包含 `SKILL.md` 文件的文件夹,写清某类任务该怎么做,模型会按需加载。 +[技能](https://agentskills.io/)(Skill)是由 Anthropic 发起的一项开放标准格式,用于扩展 Agent 的专业知识与任务流程。一个技能就是一个包含 `SKILL.md` 文件的目录,里面写清楚某类任务该怎么做,模型会在需要时按需加载。 -## 发现技能与优先级 {#discovery} +## 发现顺序与优先级 {#discovery} -Bub 按以下优先级顺序自动发现并加载技能。**同名时以最先找到的为准**: +Bub 按以下顺序扫描并加载技能,**同名技能以最先发现的为准**: -1. **工作区目录**:`/.agents/skills/`(旧目录 `.agent/skills/` 仍兼容) +1. **工作区目录**:`/.agents/skills/`(兼容旧路径 `.agent/skills/`) 2. **用户全局目录**:`~/.agents/skills/` -3. **已安装包**:环境中所有已安装的 `skills` 命名空间包(含 Bub 自带的[内置技能](#builtin-skills)) +3. **已安装的 Python 包**:环境中所有 `skills` 命名空间包(含 Bub [内置技能](#builtin-skills)) ## 内置技能 {#builtin-skills} -安装 Bub 应用时自带三个技能: +Bub 应用自带三个技能: | 技能 | 用途 | 外部依赖 | | --- | --- | --- | -| `telegram` | 发送、回复和编辑 Telegram 消息 | Telegram Bot token | -| `gh` | 通过 GitHub CLI 管理仓库、Issue、PR 和 Actions | 安装并认证 `gh` | -| `skill-creator` | 指导创建或更新技能 | 无 | +| `telegram` | 发送、回复和编辑 Telegram 消息 | Telegram Bot Token | +| `gh` | 通过 GitHub CLI 管理仓库、Issue、PR 和 Actions | 安装并登录 `gh` | +| `skill-creator` | 辅助创建或更新技能 | 无 | ## 编写技能 {#write-a-skill} -可以试着在当前工作区或全局用户目录下试着创建一个技能,例如 `.agents/skills/repo-map/SKILL.md`: +你可以在当前工作区或用户全局目录下创建一个技能(`/SKILL.md`),例如 `.agents/skills/repo-map/SKILL.md`: -```markdown +```markdown title=".agents/skills/repo-map/SKILL.md" --- name: repo-map -description: 修改代码前,先阅读本地仓库结构。 +description: 修改代码前,先查看本地仓库目录结构。 --- -1. 运行 `rg --files`,查看仓库结构。 -2. 阅读能够说明本次修改的文件。 -3. 编辑代码前,说明会涉及哪些模块。 +1. 运行 `rg --files` 查看仓库文件结构。 +2. 阅读与本次修改相关的文件。 +3. 修改代码前,先说明涉及哪些模块。 ``` ### 字段与变量规范 {#skill-fields} -`SKILL.md` 的 YAML frontmatter 规范如下: +`SKILL.md` 顶部的 YAML frontmatter 字段要求: | 字段 | 要求 | | --- | --- | -| `name` | 必填;必须与所在的技能目录名完全一致;仅限小写字母、数字和连字符;最多 64 个字符 | -| `description` | 必填;清晰说明适用任务和触发场景,供模型判断何时选用该技能;最多 1,024 个字符 | -| `metadata` | 可选;键值对映射,键和值都必须是字符串 | +| `name` | **必填**。必须与所在目录名完全一致;仅限小写字母、数字和连字符,最多 64 个字符 | +| `description` | **必填**。说明适用任务与触发场景(供模型判断何时选用),最多 1,024 个字符 | +| `metadata` | 可选。字符串到字符串的键值对映射 | -配套的辅助脚本或参考文件可存放在技能目录下的 `scripts/`、`references/` 或 `assets/` 中。技能正文支持以下动态变量插值: +辅助脚本或参考文档可放在技能目录下的 `scripts/`、`references/` 或 `assets/` 中。技能正文支持以下变量插值: -| 变量 | 展开结果 | +| 变量 | 展开值 | | --- | --- | | `$SKILL_DIR` | 当前技能目录的绝对路径 | -| `$PYTHON` | 运行 Bub 的 Python 解释器路径 | -| `${config.path.to.value}` | Bub 配置文件中对应字段的值 | +| `$PYTHON` | 当前运行 Bub 的 Python 解释器路径 | +| `${config.path.to.value}` | Bub 配置文件中对应点号路径的值 | -技能中的脚本不会自动执行。正文中应指引模型调用对应工具执行脚本,并确保环境已安装所需外部依赖(如本例需安装 `rg`)。 +技能中的脚本不会自动运行,需在正文中指引模型调用 `bash` 等工具执行(请确保环境已安装对应命令依赖,如上例中的 `rg`)。 -当然,如果你不想自己手动创建技能,可以委托给你的 Agent 工具或是 Bub 应用来创建技能,例如: +当然,如果你不想自己手动创建技能,也可以直接让 Bub 用内置的 `$skill-creator` 技能帮你生成: ```bash -bub run '使用 $skill-creator 技能,创建一个名为 `repo-map` 的技能,主要流程是: -1. 运行 `rg --files`,查看仓库结构。 -2. 阅读能够说明本次修改的文件。 -3. 编辑代码前,说明会涉及哪些模块。' +bub run '使用 $skill-creator 技能创建名为 `repo-map` 的技能,流程如下: +1. 运行 `rg --files` 查看仓库文件结构。 +2. 阅读与本次修改相关的文件。 +3. 修改代码前,先说明涉及哪些模块。' ``` ## 验证与使用 {#verify-a-skill} -在 Bub 应用中可以通过以下方式调用技能: +创建完成后,可以通过以下方式验证并调用技能: | 命令 | 说明 | | --- | --- | -| `bub run ",skill"` | 列出当前工作区实际发现的技能 | -| `bub run ",skill name=repo-map"` | 打印变量展开后的正文,不调用模型;返回 `(no such skill)` 时检查目录名与 `name` 是否一致 | -| `bub run '使用 $repo-map 技能,然后列出你找到的顶层模块。'` | 把正文展开进本轮对话的系统提示词,模型据此调用工具完成后续步骤 | +| `bub run ",skill"` | 列出当前工作区发现的所有技能 | +| `bub run ",skill name=repo-map"` | 查看变量展开后的技能正文(不调用模型);若返回 `(no such skill)`,请检查目录名与 `name` 是否一致 | +| `bub run '使用 $repo-map 技能,列出顶层模块。'` | 显式将技能正文注入本轮系统提示词 | :::note -未显式写出 `$skill-name` 时,模型仍会依据技能的 `description` 自主判断是否采用。 +即使提示词中不写 `$skill-name`,模型也会根据技能的 `description` 按需调用 `skill` 工具加载正文。 ::: ## 随 Python 包分发 {#include-skills-in-a-wheel} -技能可通过插件包进行分发。关于如何组织插件包目录结构、配置打包以及独立环境发布验证,详见[打包与分发](/zh-cn/docs/app/distribution/#bundle-plugins-and-skills)。 +技能可以打包进 Python Wheel 随插件一起分发,目录结构与打包配置见[打包与分发](/zh-cn/docs/app/distribution/#bundle-plugins-and-skills)。 diff --git a/website/src/content/docs/zh-cn/docs/app/subagents.mdx b/website/src/content/docs/zh-cn/docs/app/subagents.mdx index 4c02d972..9da638d6 100644 --- a/website/src/content/docs/zh-cn/docs/app/subagents.mdx +++ b/website/src/content/docs/zh-cn/docs/app/subagents.mdx @@ -1,15 +1,15 @@ --- title: 子 Agent -description: 使用内置 subagent 工具把任务委派给后台子 Agent、定义可复用的子 Agent 配置,并收窄子 Agent 的可用能力。 +description: 使用内置 subagent 工具将任务委派给后台子 Agent,定义可复用的子 Agent 配置并限制其可用工具与技能边界。 --- -Bub 应用内置 `subagent` 工具,允许当前 Agent 将特定子任务委派给同一个 Agent 的一次子运行。 +Bub 应用内置了 `subagent` 工具,支持将子任务委派给后台运行的子 Agent。 -子 Agent 适合将**大量检索、长文档阅读、独立代码审查**等产生海量中间上下文的任务从主对话中剥离出去,只将最终结论带回主会话,从而防止主会话的上下文窗口被额外信息占用。 +子 Agent 适合处理**大规模检索、长文档阅读、独立代码审查**等会产生大量中间输出的任务。子 Agent 的工具调用和中间推理都隔离在自己的会话中,只有最后一步生成的最终结论会传回主会话,从而节省主会话的上下文窗口。 ## 委派任务 {#delegate} -在 `bub chat` 中,可以直接要求模型调用子 Agent: +在 `bub chat` 中,你可以直接要求模型调用子 Agent: ```text 使用 subagent 工具审查身份验证流程: @@ -18,58 +18,60 @@ Bub 应用内置 `subagent` 工具,允许当前 Agent 将特定子任务委派 3. 返回审查发现并附带相关文件路径。 ``` -父 Agent 随后调用 `subagent` 工具,工具在后台启动子 Agent 并立即返回任务 ID。子 Agent 在其独立循环中调用工具完成分析,最终答案以消息的形式送达父 Agent。返回的只有这个答案,也就是子 Agent 最后一步的文本;中间的叙述和工具调用不会进入父 Agent 的上下文。 +父 Agent 调用 `subagent` 工具后,子 Agent 会在后台立即启动并返回 `task_id`。子 Agent 在独立循环中完成工具调用与分析后,仅将最后一步的最终文本传回父 Agent。 -子 Agent 只能看到 `prompt`(使用 `session="fork"` 时还能看到当前对话),因此 prompt 应当自成一体:写清楚要做什么、返回什么、有哪些限制。 +由于子 Agent 默认只能看到传入的 `prompt`(使用 `session="fork"` 时还能看到调用前的对话),委派任务时的 `prompt` 应当自包含:写清任务目标、期望的返回格式以及限制条件。 -除了人工要求外,也可以在工作区 `AGENTS.md` 或技能中设定规则(例如:「复杂检索或代码审查应先委派给只读子 Agent,主 Agent 仅根据审查结论执行修改」)来实现**自动委派**。 +你也可以在工作区的 `AGENTS.md` 或技能中写入委派规则(例如「复杂检索或代码审查先委派给只读子 Agent」),让父 Agent 自动委派。 -## 选择会话模式 {#sessions} +## 会话模式 {#sessions} -`session` 参数决定子 Agent 从什么开始、结束后保留什么: +`session` 参数决定子 Agent 启动时的初始上下文,以及任务结束后是否保留会话记录: -| 会话模式 | 行为 | 适用场景 | +| `session` 取值 | 行为 | 适用场景 | | --- | --- | --- | -| `temp`(默认) | 新建空的 `temp/` 会话,结束后丢弃 | **最常用**。一次性分析或调研,仅返回结论 | -| `fork` | 从当前对话(包括本轮已有内容)的副本开始,结束后丢弃 | 子任务需要用户和父 Agent 已经说过的内容,又不想让父 Agent 重新复述 | -| 自定义字符串 | 使用指定的固定会话 ID,会话会被保留 | 较长的工作,之后要用 `subagent.send` 继续,或事后查看 | +| `temp`(默认) | 新建空白的 `temp/` 临时会话,结束后丢弃 | **最常用**。一次性检索、分析或审查,只需拿回结论 | +| `fork`(别名 `inherit`) | 复制调用那一刻的当前对话快照作为起点,结束后丢弃 | 子任务依赖刚才讨论过的上下文,省去父 Agent 重新复述 | +| 自定义会话 ID 字符串 | 使用指定的固定会话 ID,结束后保留记录 | 需要分多轮跟进的长任务,后续可用 `subagent.send` 继续对话 | -`inherit` 作为 `fork` 的别名仍可使用。fork 在调用发生时复制对话,子 Agent 看不到父 Agent 之后的动作,子 Agent 的记录也不会写回父会话历史。 +`fork` 仅复制发起调用那一刻的对话快照:子 Agent 看不到父 Agent 此后的新操作,子 Agent 自己的记录也不会合并回父会话。 -## 接收结果 {#background} +## 接收结果与管理子任务 {#background} -子 Agent 总是在后台运行:它们运行期间父 Agent 继续工作,多个子 Agent 可以在父 Agent 做别的事时并行处理: +子 Agent 始终在后台异步运行。父 Agent 可以同时启动多个子 Agent 并行处理子任务,同时自己继续执行其他操作: ```text -启动三个子 Agent,每个服务一个,检查日志中的错误。 -你继续做迁移;它们完成后汇总结论。 +启动三个子 Agent,分别检查三个微服务日志中的错误。 +你继续处理数据库迁移;等它们全部完成后汇总结论。 ``` -任务结束时,结果会以消息的形式送达父 Agent: +子任务结束时,结果会以通知消息的形式送达父 Agent: ```text -自上次部署以来,支付服务日志中没有错误。 +自上次部署以来,支付服务日志中没有发现错误。 ``` -父 Agent 会在下一步之前读到它。由它启动的子 Agent 还在运行时,这一轮不会结束:父 Agent 没有别的事可做时,会等待下一个结果并带着它继续,因此可以在回复前汇总所有结论。只有当这一轮失败、被取消或达到步数上限时,尚未结束的任务才会随会话的下一轮报告。父 Agent 也可以直接管理任务: +父 Agent 会在进入下一个 Step 前读到该通知。只要本轮启动的子任务还有未完成的,当前 Turn 就不会提前结束——当父 Agent 没有其他工具要调时,会自动等待下一个子任务完成并汇总结果。若当前 Turn 因报错、取消或达到 `max_steps` 提前中止,未完成的子任务会在该会话的下一轮对话中汇报结果。 -| 工具 | 作用 | +父 Agent 也可使用以下工具主动管理后台子任务: + +| 工具 | 用途 | | --- | --- | -| `subagent.wait` | 返回结果,最多等待 `timeout_seconds`(默认 60;`0` 只查看不等待)。不传 `task_ids` 时覆盖本会话中尚未读取的任务。在这里读到的结果不会再发通知。 | -| `subagent.send` | 给运行中的任务发消息,它会在下一步之前读到;或者继续一个使用命名会话、已经结束的任务。 | -| `subagent.cancel` | 停止运行中的任务。 | +| `subagent.wait` | 等待并读取子任务结果,最多等待 `timeout_seconds` 秒(默认 60;设为 `0` 时仅查询状态不阻塞)。不传 `task_ids` 时默认覆盖当前会话所有未读任务。已通过 `subagent.wait` 读取的任务不会再发送通知 | +| `subagent.send` | 向运行中的子任务追加指令(在下一步前生效);或唤醒已结束的自定义命名会话子任务继续工作 | +| `subagent.cancel` | 终止运行中的子任务 | -同时运行的子 Agent 最多 `BUB_SUBAGENT_MAX_CONCURRENCY` 个(默认 4),超出的排队等待。调用时的 `timeout_seconds`,或全局的 `BUB_SUBAGENT_TIMEOUT_SECONDS`,会停止运行过久的子 Agent。退出 Bub,或对某个会话执行 `,quit`,都会取消其运行中的子 Agent。 +进程内同时运行的子 Agent 数量上限由 `BUB_SUBAGENT_MAX_CONCURRENCY` 控制(默认 4),超出上限的任务排队等待。单次运行超时可通过调用参数 `timeout_seconds` 或全局环境变量 `BUB_SUBAGENT_TIMEOUT_SECONDS` 设置。退出 Bub 或执行 `,quit` 会取消所有运行中的子 Agent。 -## 定义子 Agent 配置 {#profiles} +## 定义子 Agent 配置文件(Profile) {#profiles} -子 Agent 配置(profile)是一个可复用的子 Agent:放在工作区 `.agents/agents/` 下的 markdown 文件,或放在 `~/.agents/agents/` 下供所有工作区使用。front matter 设定配置,正文会加入子 Agent 的系统提示词: +如果你经常需要委派固定角色的子任务(如代码审查员、日志排查员),可以把它的模型、工具范围和系统提示词保存为一个**子 Agent 配置(Profile)**。只需在工作区的 `.agents/agents/`(或全局 `~/.agents/agents/`)下创建一个 Markdown 文件: ```markdown title=".agents/agents/reviewer.md" --- -description: 审查改动中的 bug 并报告发现,不修改文件 +description: 审查代码改动中的 bug 并报告发现,不修改文件 model: openai:gpt-5-mini tools: [fs.read, bash, tape.search] skills: [] @@ -79,34 +81,34 @@ timeout_seconds: 600 你负责代码审查。阅读相关文件,报告具体问题并附上文件路径和行号,绝不修改文件。 ``` -| 字段 | 含义 | +| 字段 | 说明 | | --- | --- | -| `description` | 必填。告诉父 Agent 何时使用该配置 | -| `name` | 可选;默认为去掉 `.md` 的文件名 | -| `model`、`reasoning_effort` | 子 Agent 的模型和推理强度 | -| `tools`、`skills` | 子 Agent 可用的工具和技能(列表,或逗号分隔的字符串) | -| `timeout_seconds` | 子 Agent 的运行时限 | +| `description` | **必填**。说明该配置的用途,供父 Agent 判断何时选用 | +| `name` | 可选;默认为去掉 `.md` 后缀的文件名(如 `reviewer`) | +| `model`、`reasoning_effort` | 子 Agent 使用的模型与推理强度 | +| `tools`、`skills` | 允许子 Agent 使用的工具与技能(YAML 列表或逗号分隔字符串) | +| `timeout_seconds` | 子 Agent 超时时间(秒) | -当 `subagent` 工具可用时,父 Agent 的系统提示词会列出这些配置,模型通过把配置名传给 `agent` 来使用。调用时显式给出的参数优先于配置。工作区中的配置会覆盖 home 目录下的同名配置。 +父 Agent 的系统提示词会自动列出已发现的 Profile。模型调用 `subagent(agent="reviewer", ...)` 即可启用该配置;调用时显式传入的参数优先级高于 Profile。工作区下的同名 Profile 会覆盖全局目录中的配置。 ## 状态共享与能力边界 {#boundaries} -子 Agent 是父 Agent 所在实例的一次子运行,其继承与隔离边界如下: +子 Agent 是父 Agent 实例的一次子运行,两者的共享与隔离边界如下: -| 资源类别 | 边界关系 | 说明与控制参数 | +| 资源 | 边界 | 说明 | | --- | --- | --- | -| **基础实例** | 完全共享 | 共享插件 Hooks、模型凭据与 `BubAgent` 配置 | -| **执行环境** | 完全共享 | 共享工作区目录、本地文件系统、Shell 进程和网络访问 | -| **模型选择** | 可单独指定 | 默认使用配置中的模型或父模型,可用 `model` 换成轻量模型 | -| **工具与技能** | 不超过父 Agent | 默认沿用父 Agent 本轮的工具和技能,`allowed_tools`、`allowed_skills` 可以进一步收窄。子 Agent 不能再启动子 Agent | -| **轮次状态** | 复制 | 子 Agent 得到父 Agent 轮次状态的副本,并使用自己的 steering 键,发给父 Agent 的消息仍归父 Agent | -| **会话记录** | 视策略而定 | `temp` 和 `fork` 结束后丢弃;命名会话会被保留 | +| **Agent 实例** | 共享 | 共享插件 Hooks、模型凭据与 `BubAgent` 配置 | +| **执行环境** | 共享 | 共享工作区目录、本地文件系统、Shell 进程和网络 | +| **模型选择** | 独立配置 | 默认使用 Profile 模型或父模型,可通过 `model` 指定轻量模型 | +| **工具与技能** | 不超出父 Agent | 默认沿用父 Agent 本轮可用的工具与技能,可通过 `allowed_tools`、`allowed_skills` 进一步限制。子 Agent 不能再调用 `subagent` | +| **TurnState** | 浅拷贝 | 复制父 Agent 的 `TurnState`,但使用独立的 steering 收件箱键,发给父 Agent 的引导消息不会被子 Agent 读取 | +| **会话记录** | 按 `session` 模式隔离 | `temp` 和 `fork` 结束后丢弃;自定义命名会话持久保留 | -各参数的详细类型定义及默认值见 [subagent 参考](/zh-cn/docs/reference/tools/#subagent)。Channel 可以通过[事件](/zh-cn/docs/reference/tools/#subagent-events)观察子 Agent。 +详细参数定义见 [`subagent` 工具参考](/zh-cn/docs/reference/tools/#subagent),子任务生命周期事件见[子 Agent 事件](/zh-cn/docs/reference/tools/#subagent-events)。 -### 安全限制 {#security-limits} +### 安全边界 {#security-limits} -和父 Agent 一样,子 Agent 本质上也运行在当前用户权限下的本地环境中,可能会对当前系统产生影响: +和父 Agent 一样,子 Agent 同样运行在当前用户权限下的本地环境中,使用时请注意以下边界: -1. 会话策略隔离的仅是**对话记录与模型上下文**,而不是文件、网络或系统进程。子 Agent 对文件进行的修改、发送的网络请求均具有真实的系统副作用,不会在退出时回滚。 -2. 在对话中,`subagent` 的参数由模型生成,因此 `allowed_tools` 只能限制模型行为,**不构成强制安全边界**。如需对危险命令或越权工具进行硬性拦截,必须使用[工具拦截 Hooks](/zh-cn/docs/app/plugins/#control-a-model-or-tool-call);如需物理环境隔离,应配置独立的[执行环境](/zh-cn/docs/app/tools/#environment)。 +1. **无文件系统隔离**:`session` 仅隔离**对话历史与模型上下文**。子 Agent 对本地文件的修改、执行的命令和发出的网络请求均具有真实系统副作用,退出时不会回滚。 +2. **`allowed_tools` 不是强制安全边界**:对话中 `subagent` 的参数由模型生成,因此 `allowed_tools` 仅用于约束模型行为。如需强制拦截高危命令,请使用[工具拦截 Hooks](/zh-cn/docs/app/plugins/#control-a-model-or-tool-call);如需环境隔离,请配置独立的[执行环境](/zh-cn/docs/app/tools/#environment)。 diff --git a/website/src/content/docs/zh-cn/docs/app/terminal.mdx b/website/src/content/docs/zh-cn/docs/app/terminal.mdx index 3c627772..d766807f 100644 --- a/website/src/content/docs/zh-cn/docs/app/terminal.mdx +++ b/website/src/content/docs/zh-cn/docs/app/terminal.mdx @@ -1,120 +1,117 @@ --- title: 终端 -description: 使用 Bub 的交互式会话、运行中补充指令、命令和后台进程。 +description: 掌握 Bub 终端交互用法:启动会话、运行中补充指令(Steering)、调整推理输出、管理会话 ID、执行直接命令与后台进程。 --- -Bub 应用提供两种终端交互方式:`bub run` 和 `bub chat`,两者都使用相同的模型、工具和 Tape 能力: +Bub 提供两个终端命令,共享相同的模型、工具和 Tape 存储: -- `bub run` 处理单条消息,适用于一次性任务; -- `bub chat` 则保持会话打开,可以连续对话。 +- `bub run`:处理单条消息并退出,适合单次任务或脚本调用; +- `bub chat`:启动交互式会话(REPL),支持多轮连续对话。 -## 开始交互式会话 {#start-session} +## 启动交互式会话 {#start-session} -在终端输入如下命令会进入到交互式会话界面中,此时你可以输入内容并按回车发送。 +在终端中输入以下命令即可进入交互式会话界面,输入内容并按回车发送: ```bash bub chat ``` -此外,输入 `,help` 指令列出当前可用的内部命令;如需退出,可按下 Ctrl+D 键或使用 `,quit` 或 `,exit` 指令。 - -底部工具栏显示最近一次模型调用的输出速度:从收到第一个流式分片开始计时,到响应结束为止。分子是全部输出 token(含思考 token),分母不含首分片之前的等待时间,也不含工具执行时间;紧跟其后的 `ttft` 就是被排除的首字等待时间。提供商未返回用量时显示 `speed:- tok/s`。 - -当然,你也可以在启动时直接提交第一条消息: +也可以在启动时直接带上第一条消息: ```bash bub chat "Inspect this repository and suggest a first task." ``` -## 在运行中引导 Agent {#steering} +输入 `,help` 查看内置命令;按 Ctrl+D 或输入 `,quit`、`,exit` 退出会话。 + +底部状态栏会显示最近一次模型调用的指标: + +- `ttft`(首字等待时间):从发出请求到收到第一个流式分片的耗时; +- `speed`(生成速度):从收到首个分片到响应结束的平均输出速度(含思考 Token,不含 `ttft` 和工具执行时间;若提供商未返回用量则显示 `speed:- tok/s`)。 -在等待模型回复期间,如果发现模型的输出偏离了你的预期,或者你想补充一些约束条件,可以在界面中直接输入新指令以引导 Agent 的行为。 +## 运行中补充指令(Steering) {#steering} -**引导**(Steering)用于在当前 Turn 尚未结束时补充指令,让 Agent 调整正在执行的任务。生成过程中不必等待回复结束,直接输入并回车即可: +在等待模型回复或执行工具期间,如果发现它的处理方向偏离了预期,或者你想临时补充一些约束条件,不必等当前回复结束——直接在终端输入新指令并回车即可: ```text 先不要修改文件,只列出问题和建议。 ``` -Bub 应用会把消息放到引导收件箱中。Agent 在后续构建模型请求时读取它,正在执行的模型或工具调用不会被强制中断。 +这种在运行期间动态追加指令的机制称为 **Steering**。新消息会进入引导收件箱;当前正在执行的模型请求或工具调用不会被强制打断,Agent 会在进入下一个 Step 时读入这条新指令。 -Bub 的准入动作称为 `steer` 和 `follow_up`,区别在于消息何时生效: +当会话正忙时,Bub 支持两种消息准入策略: -| 方式 | 处理方式 | 适合什么 | +| 策略 | 生效时机 | 适用场景 | | --- | --- | --- | -| 引导(Steering) | 注入当前对话的后续模型请求;来不及消费时转为待处理消息 | 纠正方向、补充约束、提供与当前任务有关的新信息 | -| 后续处理(Follow up) | 等当前 Turn 结束后,再作为后续任务处理 | 追加另一项任务、按顺序执行多个需求 | +| `steer` | 注入当前 Turn 的下一个 Step;若当前 Turn 已结束,自动转为下一轮待处理消息 | 纠正方向、补充约束或提供与当前任务直接相关的新信息 | +| `follow_up` | 等当前 Turn 完整结束后,再按顺序开启新 Turn | 追加另一项独立任务 | -默认情况下,Bub 应用对运行期间的普通输入使用引导,没有单独的后续处理快捷键。未被当前消费的引导消息会自动进入待处理队列,不会直接丢失。 +`bub chat` 在运行期间对普通输入默认采用 `steer` 策略。如需立即中止当前正在运行的任务,输入 `,quit`(会清空待处理队列并取消运行中的任务)。 -需要停止当前会话的任务时,使用 `,quit`;它会清理待处理消息并取消运行中的任务。 +## 查看与调整思考过程 {#reasoning} -## 查看推理过程 {#reasoning} - -输入 `,thinking` 以展开和折叠模型思考过程: +展开或折叠模型的思考过程(仅切换终端显示,不改变模型推理强度): ```text ,thinking ``` -它只控制终端是否显示模型返回的 `reasoning` 增量,不会改变模型或推理力度。如需调整推理力度请使用: +调整模型的推理强度(从下一轮起生效,并保存在当前会话 Tape 中): ```text ,reasoning_effort high ``` -具体可选值由模型提供商决定。该设置从下一轮对话起生效,并保存在当前会话的 Tape 中。 - -## 指定会话 {#choose-session} +## 指定会话 ID {#choose-session} -`bub run` 默认使用 `cli:local` 作为会话 ID,`bub chat` 则默认使用 `cli_session`。显式指定相同的会话 ID,可以在两个入口之间延续历史: +`bub run` 默认会话 ID 为 `cli:local`,`bub chat` 默认为 `cli_session`。通过 `--session-id` 指定相同 ID 可在两个命令间共享会话历史: ```bash bub chat --session-id cli:echo bub run --session-id cli:echo "Summarize what we discussed." ``` -## 使用命令 {#commands} +## 执行直接命令 {#commands} -命令前缀默认为 `,`,用于跳过模型调用、直接执行工具: +以 `,`(默认命令前缀)开头的输入会跳过模型,直接调用对应工具: ```bash bub run ",help" bub run ",fs.read path=README.md" ``` -交互式会话中也可以直接输入命令。按 Ctrl-X 在 Agent 与 Shell 输入模式之间切换;Shell 模式会自动为输入添加命令前缀。常用命令如下: +交互式会话中也可以直接输入命令。在 `bub chat` 中,按 Ctrl+X 可在 Agent 模式与 Shell 模式之间切换(Shell 模式会自动为输入加上 `,` 前缀)。常用命令如下: | 命令 | 用途 | | --- | --- | | `,model openai:gpt-5-mini` | 切换当前会话的模型 | -| `,reasoning_effort high` | 设置当前会话的推理力度 | +| `,reasoning_effort high` | 设置当前会话的推理强度 | | `,code_mode enable=true` | 开启代码模式 | -| `,tape.info` | 查看条目、anchor 和 token 用量 | -| `,tape.search query=error` | 搜索当前会话记录 | -| `,tape.anchors` | 列出上下文分界点 | -| `,tape.handoff name=reviewed summary='...'` | 移动默认上下文起点,并保存摘要 | -| `,tape.reset archive=true` | 归档当前 Tape 后重新开始 | -| `,thinking` | 展开或折叠推理输出 | +| `,tape.info` | 查看条目数、anchor 与 Token 用量 | +| `,tape.search query=error` | 搜索当前会话历史 | +| `,tape.anchors` | 列出所有上下文锚点 | +| `,tape.handoff name=reviewed summary='...'` | 前移默认上下文起点并保存摘要 | +| `,tape.reset archive=true` | 备份并清空当前会话历史 | +| `,thinking` | 展开或折叠思考输出 | 注意: -- `,tape.reset archive=true` 会把主 Tape 和 sidecar 备份到 `/tapes/`,文件名带有 UTC 时间戳和 `.bak` 后缀。使用 `archive=false` 或直接 `,tape.reset` 则不备份。重置后会产生新的 `session/start` anchor,旧文件不会被自动恢复。 -- 交接(handoff)不会自动生成或注入摘要。`summary` 保存在 anchor 的 `state` 中;后续是否读取它,取决于提示词或上下文策略。详见 [Tape](/zh-cn/docs/concepts/tape/#anchors)。 +- `,tape.reset archive=true` 会将主 Tape 和 Sidecar 备份到 `/tapes/`(带 UTC 时间戳和 `.bak` 后缀),再重置并写入新的 `session/start` 锚点;不传 `archive=true` 则直接清空不备份。 +- `,tape.handoff` 仅前移上下文读取起点并将 `summary` 存入 anchor 的 `state`,不会自动调用模型生成摘要。详见 [Tape](/zh-cn/docs/concepts/tape/#anchors)。 :::caution -未注册的命令会交给 `bash` 执行。输入未知命令前,确认它确实是你允许运行的 Shell 命令。 +未注册为内置工具的逗号命令会交给 `bash` 执行。输入前请确认该命令是安全的 Shell 命令。 ::: -## 运行后台进程 {#background-shell} +## 管理后台进程 {#background-shell} -在 `bub chat` 中,用 `background=true` 使用单独的后台进程来运行相关命令: +在 `bub chat` 中,传入 `background=true` 可在后台启动长耗时进程: ```text ,bash command='npm run dev' background=true ``` -执行返回结果中包含 `shell_id`。我们使用它增量读取输出或终止进程: +命令会立即返回 `shell_id`,可用于增量读取输出或终止进程: ```text ,bash.output shell_id=bsh-12345678 @@ -122,7 +119,5 @@ bub run ",fs.read path=README.md" ,bash.kill shell_id=bsh-12345678 ``` -注意: - -- `offset` 是已缓冲输出的字符位置,不是行号;返回值中的 `next_offset` 可用于下一次读取。`limit` 限制本次返回的字符数。 -- 前台 `bash` 默认**等待 30 秒**。超时后进程不会被直接判定失败,而是转为后台并返回 `shell_id`;可通过 `timeout_seconds` 调整。后台任务应在同一个 `bub chat` 或网关进程中管理,退出应用时会执行清理。 +- `offset` 和 `limit` 按**字符数**(非行号)计算;每次读取返回的 `next_offset` 可直接作为下一次读取的 `offset`。 +- 前台 `bash` 默认等待 **30 秒**(可通过 `timeout_seconds` 修改)。超时后进程不会报错退出,而是自动转为后台运行并返回 `shell_id`。应用退出时会自动清理后台进程。 diff --git a/website/src/content/docs/zh-cn/docs/app/tools.mdx b/website/src/content/docs/zh-cn/docs/app/tools.mdx index 32aeac84..492423e9 100644 --- a/website/src/content/docs/zh-cn/docs/app/tools.mdx +++ b/website/src/content/docs/zh-cn/docs/app/tools.mdx @@ -1,70 +1,68 @@ --- title: 工具 -description: 了解 Bub 应用内置工具、工具调用方式以及如何配置 代码模式 与扩展。 +description: 了解 Bub 应用内置工具的用法:覆盖文件读写、命令执行、网页抓取、代码模式(Code Mode)以及执行安全边界与工具扩展。 --- -工具(Tool)为 Bub 应用执行具体的外部动作,负责实际执行(如读写文件、运行命令、管理会话等)。 +工具让 Bub 能够执行读写文件、运行命令和管理会话等外部操作。 ## 内置工具 {#builtin-tools} -安装 Bub 应用后自带以下核心工具: +Bub 应用自带以下内置工具: | 类别 | 工具 | 用途 | | --- | --- | --- | -| **进程管理** | `bash` | 执行 Shell 命令;支持工作目录、超时与后台执行 | -| | `bash.output`、`bash.kill` | 增量读取后台进程输出,或终止正在运行的进程 | -| **文件操作** | `fs.read`、`fs.write`、`fs.edit` | 分页读取、覆盖写入与文本精准替换 | -| **网络抓取** | `web.fetch` | 发起 GET 请求抓取网页(优先返回 Markdown) | -| **能力发现** | `skill` | 列出工作区发现的技能,或读取指定技能正文 | -| | `tool.describe` | 动态加载延迟工具的完整定义 | -| **会话管理** | `tape.info`、`tape.search` | 查看 Token 用量、检索历史会话记录 | -| | `tape.handoff`、`tape.reset` | 移动上下文起点以压缩会话,或归档并重置上下文 | -| | `spill.read` | 分块读取超出上下文上限的大型工具输出 | -| **多任务协作**| [`subagent`](/zh-cn/docs/app/subagents/) | 把任务委派给在后台运行的子 Agent | -| | `subagent.wait`、`subagent.send`、`subagent.cancel` | 等待结果、给子 Agent 发消息,或停止它 | -| **代码模式** | `run_code` | 在 代码模式 开启时通过 Python 组合多个工具 | - -内置工具的详细参数及默认值见 [工具参考](/zh-cn/docs/reference/tools/)。 - -## 使用工具 {#instructions} - -在 Bub 应用中,工具可以通过两种方式调用: - -1. **模型自主选用**:在会话中正常提问,模型会根据任务意图和工具描述自动选择并调用。 -2. **命令行直接调用**:在终端中使用逗号前缀直接调用工具(不调用模型、不消耗 Token): +| **进程管理** | `bash` | 执行 Shell 命令;支持指定工作目录、超时和后台运行 | +| | `bash.output`、`bash.kill` | 增量读取后台进程输出,或终止后台进程 | +| **文件操作** | `fs.read`、`fs.write`、`fs.edit` | 按行读取文件(或读取图片)、覆盖写入文件、精确替换文本 | +| **网页抓取** | `web.fetch` | 发送 HTTP GET 请求抓取网页(优先请求 Markdown) | +| **能力发现** | `skill` | 列出已发现的技能,或读取指定技能的 `SKILL.md` 正文 | +| | `tool.describe` | 按需加载延迟工具(`deferred=True`)的完整参数定义 | +| **会话管理** | `tape.info`、`tape.search` | 查看会话统计与 Token 用量,或检索会话历史 | +| | `tape.handoff`、`tape.reset` | 前移上下文起点,或备份并重置会话历史 | +| | `spill.read` | 分块读取超出长度阈值的大型工具输出 | +| **子 Agent**| [`subagent`](/zh-cn/docs/app/subagents/) | 将子任务委派给后台运行的子 Agent | +| | `subagent.wait`、`subagent.send`、`subagent.cancel` | 等待子任务结果、追加指令或取消子任务 | +| **代码模式** | `run_code` | 开启代码模式时,通过执行 Python 代码组合调用多个工具 | + +完整参数与返回值说明见 [内置工具参考](/zh-cn/docs/reference/tools/)。 + +## 调用方式 {#instructions} + +在 Bub 应用中,工具有两种调用方式: + +1. **模型自动调用**:在对话中正常提问,模型会根据任务和工具描述自动选择并调用工具。 +2. **命令行直接调用**:使用命令前缀(默认 `,`)直接执行工具,不调用模型、不消耗 Token: ```bash bub run ",fs.read path=README.md" ``` -若要约束或规范模型如何使用工具: -- **全局约定**:在项目根目录的 `AGENTS.md` 中编写通用约束; -- **任务流程**:将多步骤操作封装为 [技能](/zh-cn/docs/app/skills/),指引模型按顺序调用对应工具。 +如需约束模型使用工具的方式: +- **项目级规则**:在工作区根目录的 `AGENTS.md` 中编写通用规范; +- **固定流程**:将多步操作编写为[技能](/zh-cn/docs/app/skills/),指导模型按步骤调用工具。 -## 开启 代码模式 {#code-mode} +## 代码模式 {#code-mode} -当需要处理复杂逻辑或批量处理数据时,模型多次往返调用工具会消耗大量上下文。启用 代码模式 后,模型会直接编写 Python 代码(通过 `run_code` 工具执行)一次性组合多个工具: +处理复杂控制流或批量数据时,让模型多次往返调用工具会消耗大量上下文。开启代码模式后,模型会通过 `run_code` 工具直接编写一段 Python 代码,在一次执行中组合调用多个工具: ```text ,code_mode enable=true ``` -注意: - -- 该设置在下一轮对话生效,并持久化保存在当前会话记录中。 -- 使用 `,code_mode enable=false` 可以关闭并恢复默认模式。 -- 关于在代码模式下调用工具的 Python 语法,见[`run_code` 参考](/zh-cn/docs/reference/tools/#run-code)。 +- 该设置从下一轮对话起生效,并保存在当前会话的 Tape 中。 +- 输入 `,code_mode enable=false` 可关闭代码模式。 +- 代码模式下的 Python 调用语法见 [`run_code` 参考](/zh-cn/docs/reference/tools/#run-code)。 ## 执行环境与安全 {#environment} -内置的 Shell 命令(`bash`)、文件读写(`fs.*`)和代码执行(`run_code`)等均在本地当前用户权限下直接运行,可能会对系统或数据产生不可逆的影响,使用前须知: +内置的 `bash`、`fs.*` 和 `run_code` 默认在本地宿主机上以当前用户权限直接运行: -- **非安全隔离**:默认环境不是隔离沙箱,模型执行的命令会**对本地系统产生真实的读写和进程副作用**。 -- **权限与拦截**:如需在执行高危命令前进行人工审批或条件限制,可使用[工具拦截 Hooks](/zh-cn/docs/app/plugins/#control-a-model-or-tool-call)。 -- **容器与隔离环境**:如需隔离执行,可通过插件提供独立的[执行环境](/zh-cn/docs/reference/hooks/#provide_environment)。 +- **无默认沙箱隔离**:模型执行的命令会对本地文件系统和进程产生真实副作用。 +- **权限审批与拦截**:如需在高危工具执行前进行审批或拦截,请使用[工具拦截 Hooks](/zh-cn/docs/app/plugins/#control-a-model-or-tool-call)。 +- **隔离执行环境**:如需在容器或远程沙箱中执行工具,可通过插件实现 [`provide_environment`](/zh-cn/docs/reference/hooks/#provide_environment)。 -## 集成与扩展工具 {#provide-tools} +## 扩展工具 {#provide-tools} -如果内置工具无法满足需求,可以通过以下方式扩展: +如果内置工具无法满足需求,可以通过以下方式继续扩展: -- **安装社区插件**:浏览 [社区插件](https://hub.bub.build/) 列表搜索插件或第三方 MCP 服务(见 [MCP 集成](/zh-cn/docs/integrations/mcp/)); -- **开发自定义插件**:编写 Python 函数并注册为 Bub 工具,随插件一起分发,详见[插件开发:提供工具](/zh-cn/docs/app/plugins/#provide-tools)。 +- **安装社区插件或 MCP**:从 [社区插件中心](https://hub.bub.build/) 安装工具插件,或[接入 MCP 服务器](/zh-cn/docs/integrations/mcp/); +- **编写自定义工具插件**:用 Python 编写函数并通过 `provide_tools` 注册,见[插件与 Hooks:提供工具](/zh-cn/docs/app/plugins/#provide-tools)。 diff --git a/website/src/content/docs/zh-cn/docs/app/workspace.mdx b/website/src/content/docs/zh-cn/docs/app/workspace.mdx index 771f6433..750d852d 100644 --- a/website/src/content/docs/zh-cn/docs/app/workspace.mdx +++ b/website/src/content/docs/zh-cn/docs/app/workspace.mdx @@ -1,39 +1,39 @@ --- title: 工作区 -description: 介绍如何在一个工作区中使用 Bub。 +description: 在项目工作区目录中运行 Bub CLI,通过 AGENTS.md 配置项目级 Agent 规则,并查看当前可用的会话与快捷命令。 --- -默认情况下,Bub 在一个工作区(Workspace,即目录)中运行并浏览有关于当前工作区的文件信息或指令。 +默认情况下,Bub 会把当前目录作为工作区(Workspace),并在运行时读取其中的文件与指令。 -## 准备工作区(可选) {#prepare-workspace} +## 配置 AGENTS.md(可选) {#prepare-workspace} -假如你还没有对应的项目,才刚开始使用 Bub,那么可以先新建一个目录: +假如你还没有对应的项目,才刚开始使用 Bub,可以先新建一个目录: ```bash mkdir hello-bub cd hello-bub ``` -然后在该目录下创建一个 `AGENTS.md` 文件,并将如下内容写入当中。 +然后在该目录下创建一个 `AGENTS.md` 文件,写入针对当前项目的协作规则: -``` -你是这个工作区的 Bub agent。 -编辑文件前先阅读相关内容。 +```markdown title="AGENTS.md" +你是这个工作区的 Bub Agent。 +编辑文件前先阅读相关代码。 回复保持简短、具体。 ``` -之后每当 Bub 运行时,会从该指令中读取相应的规则,以便模型能够按照规则输出相应内容。在示例之后,你也可以自己不断去修改这个文件中的内容,然后看看不同规则下,模型输出的差异。 +之后每当 Bub 启动对话时,都会自动读取工作区下的 `AGENTS.md` 并注入系统提示词,让模型按照这些规则回复。跑完示例后,你也可以不断去修改这个文件中的内容,看看不同规则下模型输出的差异。 :::tip -`AGENTS.md` 是由 OpenAI 发起的一种用于指导编码代理(Agent)的简单开放格式,就好像很多项目都会有的 `README.md` 文件一样。点击以了解更多有关于 [AGENTS.md](https://agents.md/) 的介绍。 +`AGENTS.md` 是由 OpenAI 发起的一种用于指导编码 Agent 的简单开放格式,就像很多项目都会有的 `README.md` 一样。详见 [AGENTS.md 规范](https://agents.md/)。 ::: -## 检查命令 {#check-commands} +## 查看可用命令 {#check-commands} -现在你可以在一个工作区中试着在终端命令行上试着查看 Bub 有哪些命令: +现在,你可以在工作区终端里运行以下命令,查看当前有哪些可用命令: ```bash bub run ",help" ``` -在后续的运行中,只要以 `,` 逗号开头的前缀会调用相关命令,当然你可以通过[配置项](/zh-cn/docs/reference/settings/#agent-settings)将其修改成你喜欢的字符。 +在后续的运行中,只要以 `,`(逗号)开头就会跳过模型、直接执行对应的内置命令或工具。当然,你也可以通过 [`BUB_COMMAND_PREFIX`](/zh-cn/docs/reference/settings/#command-prefix) 把它修改成你喜欢的字符。 diff --git a/website/src/content/docs/zh-cn/docs/concepts/agent.mdx b/website/src/content/docs/zh-cn/docs/concepts/agent.mdx index 92228776..17772ac4 100644 --- a/website/src/content/docs/zh-cn/docs/concepts/agent.mdx +++ b/website/src/content/docs/zh-cn/docs/concepts/agent.mdx @@ -1,35 +1,51 @@ --- title: Agent 循环 -description: Agent 由什么组装,一次 Run 如何由模型与工具交替的 Step 推进。 +description: 理解 Bub Agent 循环的核心原理:了解 Agent 组件构成、一次 Run 如何交替执行模型推理与工具调用,以及核心层与应用层的划分。 sidebar: label: Agent 循环 --- -Agent 把模型、工具、Tape 与循环组装在一起:模型决定下一步,工具执行动作,Tape 提供历史,循环把这些步骤推进到最终答案。 +单独调用大模型时,它只能接收一段文本、返回一段回答。要让它能自己查文件、调接口、分多步解决实际问题,就需要用循环把**模型**、**工具**和**历史记录**(Tape)串起来:模型根据当前上下文决定下一步动作,工具负责实际执行,Tape 保存整个过程的历史,循环则不断推进直到得出最终答案。 -## Agent 循环 {#loop} +## 循环是如何运转的 {#loop} -一次循环按以下方式推进: +在 Bub 中,一次完整的 Agent 循环按以下三步反复推进: -1. 通过 `TapeContext` 读取历史,加入新的用户消息,调用模型; -2. 如果模型请求工具,就执行工具并把结果交回模型; -3. 如果模型直接作答,本次 Run 结束。 +```mermaid +flowchart LR + A["1. 从 Tape 读取上下文\n并附上新消息"] --> B["2. 调用模型"] + B --> C{"是否请求调用工具?"} + C -->|"是"| D["执行本地工具,结果写回上下文"] + D --> B + C -->|"否"| E["3. 输出最终回复并结束"] +``` -这里有两个执行粒度: +1. **读取上下文并调用模型**:通过 `TapeContext` 从会话历史中提取所需记录,附上本次新消息后发给模型; +2. **按需执行工具**:如果模型决定调用工具,Bub 会校验参数并执行对应的 Python 函数,再把结果带入下一轮模型调用; +3. **给出回答并结束**:当模型认为信息已经充足、不再请求工具而是直接作答时,本次运行结束。 -| 概念 | 定义 | 结束条件 | +为了方便在代码中控制和观测这个循环,Bub 区分了两个执行粒度: + +| 概念 | 含义 | 结束条件 | | --- | --- | --- | -| **Run** | 一次完整的 Agent 执行,向调用方提供 `StreamEvent` 流 | 模型不再请求工具,或调用方关闭流 | -| **Step** | 一次模型推理,以及该响应请求的全部工具调用 | 本次推理请求的 tool calls 处理完毕 | +| **Run** | 一次完整的 Agent 执行(对应一次 `agent.run()` 调用),对外产出 `StreamEvent` 事件流 | 模型直接给出最终回复,或调用方关闭事件流 | +| **Step** | Run 内部的一步:包含一次模型调用,以及该次响应请求的全部工具执行 | 该步请求的所有工具执行完毕 | + +也就是说,**一次 Run 由一个或多个 Step 组成**。如果模型一句话就能直接回答,这次 Run 就只有 1 个 Step;如果它先查了两次工具才回答,这次 Run 就经历了 3 个 Step。 + +在实际使用中,有三个常见的边界需要注意: + +- **Run 是由消费事件流驱动的**:调用 `agent.run()` 只会准备好运行上下文,只有当你用 `async for` 消费事件流时,模型推理与工具调用才会真正往前走。如果中途退出循环并关闭流,当前 Run 也会随之停止。 +- **上下文按步从 Tape 生成,而不是在 Run 里私自攒一个数组**:Run 内部不维护私有的 `messages` 列表。每进入一个新的 Step,它都会通过 `TapeContext` 从 Tape 重新生成当前所需的模型上下文(见 [Tape 与模型上下文](/zh-cn/docs/concepts/tape/))。 +- **Run 不等于 Turn**:Run 是核心层的模型与工具循环;Turn 是应用层处理一条外部消息的完整流程。逗号命令(如 `,help`)甚至可以在 Turn 内直接返回结果,根本不会启动模型 Run(见 [Turn](/zh-cn/docs/concepts/turn/))。 -需要分清三个边界: +## 核心层与应用层的分工 {#layers} -- **Run 由事件流驱动**。只有迭代事件流,模型与工具循环才会推进;这是执行方式,不是另一种事件机制。 -- **模型上下文来自 Tape,不来自 Run**。Run 不另外维护一份消息列表,每次模型调用都通过 `TapeContext` 投影历史,见 [Tape](/zh-cn/docs/concepts/tape/)。 -- **Run 不等于 Turn**。Run 是 Agent 的一次执行;Turn 是应用层对一条消息的处理,直接命令甚至可以不经过 Run,见 [Turn](/zh-cn/docs/concepts/turn/)。 +`bub.core.Agent` 是 Bub 的微内核,只专注于把「模型—工具—事件—Tape」这个循环跑好:**不读取配置文件或 `BUB_*` 环境变量,也不关心消息渠道与插件发现**。 -## 核心层与应用层 {#layers} +而应用层(`BubFramework` 与 `BubAgent`)则是围绕这个内核搭起来的完整运行环境,在循环外围补齐了配置管理、插件 Hooks、技能发现、消息渠道和会话路由。 -`core.Agent` 是 Bub 的微内核:负责模型与工具循环、事件和 Tape,不负责会话路由、配置、插件发现与消息渠道。应用层在同一个循环之外补充这些能力,而不是实现另一套 Agent。 +因此,你可以根据场景自由选择接入方式: -因此,嵌入现有服务时,模型、工具和存储等资源由宿主显式传入;需要完整消息生命周期时,再使用应用层。具体入口见 [SDK](/zh-cn/docs/sdk/) 与[复用 Bub 应用](/zh-cn/docs/integrations/reuse-app/)。 +- **嵌入现有 Python 服务**:使用核心层 [SDK](/zh-cn/docs/sdk/),由宿主代码显式传入模型、工具和存储; +- **需要消息管道、配置或插件**:直接运行 Bub CLI,或在代码中[复用 Bub 应用层能力](/zh-cn/docs/integrations/reuse-app/)。 diff --git a/website/src/content/docs/zh-cn/docs/concepts/events.mdx b/website/src/content/docs/zh-cn/docs/concepts/events.mdx index d6d4f3d4..c7a13347 100644 --- a/website/src/content/docs/zh-cn/docs/concepts/events.mdx +++ b/website/src/content/docs/zh-cn/docs/concepts/events.mdx @@ -1,44 +1,61 @@ --- title: Agent 事件 -description: 分清 AgentEvent、StreamEvent 与 TapeEntry,理解同步分发如何在副作用发生前拦截执行。 +description: 理解 Bub 同步事件总线的设计:区分 AgentEvent、StreamEvent 与 TapeEntry,在副作用发生前观测或拦截调用,并对比 App Hooks。 sidebar: label: 事件 --- -Agent 事件不仅回答「发生了什么」,也能在副作用发生前决定「这件事是否应该发生」。每个 Agent 的 `EventBus` 都支持观察和同步干预。 +在实际开发中,我们经常需要在模型推理或工具调用的前后加上一些通用逻辑:比如打印审计日志、统计 Token 消耗、清理工具入参,或者在执行高危工具(如删除数据、执行命令)前先做权限检查甚至等待人工确认。 -## 三种数据 {#three-kinds} +如果把这些逻辑硬编码进每个工具函数里,业务代码很快就会变得难以维护。为此,每个 `Agent` 实例都自带一条同步事件总线(`agent.events`):它不仅能让你实时观察「刚才发生了什么」,还能在模型或工具真正产生副作用之前,介入并修改参数或拦截调用。 -| 类型 | 用途 | 获取方式 | 能干预吗 | +## 先分清三种数据 {#three-kinds} + +在 Bub 中,你会遇到三种名字里带「事件」或「记录」的对象,它们分别负责运行时控制、流式输出和历史持久化: + +| 类型 | 用途 | 获取方式 | 能否干预当前运行? | | --- | --- | --- | --- | -| `AgentEvent` | 协调与干预当前执行 | `agent.events.on(...)` | 能:修改字段或设置 `decision` | -| `StreamEvent` | 向调用方交付输出 | 迭代 `agent.run()` 的流 | 能:关闭流即结束 Run | -| `TapeEntry` | 保存历史记录 | 查询 [Tape](/zh-cn/docs/concepts/tape/#history-and-context) | 不能:正常记录只追加 | +| `AgentEvent` | 观测循环各阶段,或在调用前修改参数、拦截执行 | `agent.events.on(...)` 注册处理器 | **能**:修改事件属性或设置 `decision` | +| `StreamEvent` | 向调用方实时推送流式输出(思考增量、文本增量、工具进度) | `async for` 迭代 `agent.run()` 返回的流 | **能**:退出循环并关闭流即可取消 Run | +| `TapeEntry` | 持久保存对话历史、工具往返与业务事件 | 查询 [Tape](/zh-cn/docs/concepts/tape/#history-and-context) | **不能**:正常运行时仅追加记录 | + +这三者各司其职,不会自动混同:流式分片不会自动落盘,已写入 Tape 的条目也不会回流到当前正在执行的 Step;只有被 `TapeContext` 选中的条目,才会在下一次请求时作为上下文发给模型。 + +## 为什么事件是同步分发的 {#handlers} -三者不会自动互相转换:流式输出不会自行落盘,Tape 条目不会回灌进正在执行的 Step。只有被 `TapeContext` 选中的条目,才会成为后续模型输入。 +当 Agent 触发事件时,`EventBus.emit()` 会按注册顺序逐个调用匹配的处理器;如果遇到 `async def` 异步处理器,它会**等待该处理器执行完毕**再继续往下走。 -## 同步分发 {#handlers} +之所以采用同步等待而不是扔到后台异步执行,原因很直接:**只有等处理器跑完,Agent 才能在真正调用模型或执行工具之前拿到修改后的参数或拦截决策**(例如在 `ToolCallStarted` 处理器里等待用户在网页上点击「确认删除」)。 -`emit()` 按注册顺序逐个调用匹配的处理器,并等待 async 处理器完成后再继续。需要记住四条规则: +编写事件处理器时,记住以下四条规则即可: -1. 注册到基类的处理器也会收到子类事件。 -2. 返回值会被忽略;干预执行要修改事件字段或设置 `decision`。 -3. 异常会传播给发布方,可能导致整个 Run 失败。 -4. 每次调用处理器前都会检查 `event.stopped`,为 `True` 时停止本次派发。 +1. **支持按基类监听**:监听基类可接收其所有子类事件(如监听 `AgentEvent` 接收全部事件,监听 `TapeEvent` 接收所有带 `event.tape` 的事件)。 +2. **原地修改事件对象**:处理器的返回值会被忽略;如需改写参数或拦截,直接修改事件属性(如 `event.call`)或设置 `event.decision`。 +3. **异常向上传播**:处理器抛出的未捕获异常会直接传回 `emit()` 调用方,并可能中断当前 Run。 +4. **拦截后停止后续分发**:每次调用下一个处理器前都会检查 `event.stopped`;一旦某个处理器设置了拒绝或替换决策(`event.stopped == True`),后续处理器不再执行。 -## 决策先于副作用 {#call-control} +## 在副作用发生前做出裁决 {#call-control} -调用前事件暴露可替换的请求和 `decision`。一次工具调用有四种结果: +像 `ToolCallStarted` 和 `LLMCallStarted` 这类「调用前」事件,都暴露了当前请求内容以及一个 `decision` 属性。以一次工具调用为例,事件处理器可以做出四种选择: -| 操作 | 原工具执行吗 | 交给模型的结果 | +| 处理器操作 | 工具函数是否执行? | 模型收到的结果 | | --- | --- | --- | -| 不设置 `decision` | 是 | 实际结果 | -| 替换 `event.call` | 是,用新调用 | 实际结果 | -| `deny(message)` | 否 | 工具错误 | -| `replace(result)` | 否 | 指定结果 | +| 不设置 `decision`(默认放行) | **是** | 工具函数的返回值 | +| 替换 `event.call` 的参数 | **是**(使用新参数) | 工具函数的返回值 | +| 设置 `ToolCallDecision.deny(message)` | **否** | 包含拒绝原因的工具错误,供模型调整回复 | +| 设置 `ToolCallDecision.replace(result)` | **否** | 你指定的替代结果(适合缓存命中或 Mock) | + +无论工具是正常执行完毕,还是被处理器拒绝(`deny`)或替换(`replace`),结束后都会照常触发 `ToolCallFinished` 事件。这样一来,负责记录日志或统计耗时的后置处理器永远不会漏掉任何一次调用。 + +模型调用也遵循同样的机制:在 `LLMCallStarted` 中,你既可以替换 `event.request`(比如限制 `max_tokens`),也可以通过 `LLMCallDecision.finish(text)` 直接返回回复文本,跳过实际的模型 API 请求。 + +## Agent 事件与 App Hooks 的分工 {#app-hooks} + +如果你同时看过 SDK 文档和应用层插件文档,可能会好奇:`agent.events` 和插件里的 `@hookimpl` 有什么区别? -被拒绝或替换的调用仍会发出 `ToolCallFinished`,完成后的观察逻辑不会漏记。模型调用也遵循同样的调用前干预模型,例如 `LLMCallDecision.finish(text)` 可以跳过供应商直接产生文本。 +- **Agent 事件**(`agent.events`):位于核心层,专门覆盖模型调用、工具执行、Step 和 Run 这几个核心循环节点。 +- **App Hooks**(`@hookimpl`):位于应用层,除支持拦截模型和工具调用外,还覆盖 Turn 的七个阶段、工具与渠道注册、存储替换及 CLI 扩展,支持通过 Python Entry Points 分发。 -## 与 App Hooks 的分工 {#app-hooks} +应用层的 `before_tool_call`、`after_tool_call`、`before_llm_call` 和 `after_llm_call` 底层其实也是通过桥接器挂载到同一组 Agent 事件上的,不过两者在修改参数的方式和异常处理策略上有所不同(例如插件 Hook 抛异常会被记录日志并跳过,而不会直接把整次 Run 搞崩)。详细对比见 [Hooks 参考](/zh-cn/docs/reference/hooks/#event-mapping)。 -Agent 事件介入核心循环中的模型、工具、Step 与 Run;App hooks 面向 Turn 阶段、工具供给、存储和渠道等应用生命周期,并承担插件分发。应用拦截 hooks 可以通过适配器接入同一组 Agent 事件,但两者的参数返回方式与异常策略不同,详见 [Hooks 参考](/zh-cn/docs/reference/hooks/#event-mapping)。具体写法分别见 [SDK:事件](/zh-cn/docs/sdk/events/)与[应用插件:拦截调用](/zh-cn/docs/app/plugins/#control-a-model-or-tool-call)。 +想动手在代码中监听和拦截事件,可以阅读 [SDK:事件](/zh-cn/docs/sdk/events/);想在应用插件中使用拦截 Hook,请阅读[插件与 Hooks:拦截调用](/zh-cn/docs/app/plugins/#control-a-model-or-tool-call)。 diff --git a/website/src/content/docs/zh-cn/docs/concepts/tape.mdx b/website/src/content/docs/zh-cn/docs/concepts/tape.mdx index 30670c56..88e114d6 100644 --- a/website/src/content/docs/zh-cn/docs/concepts/tape.mdx +++ b/website/src/content/docs/zh-cn/docs/concepts/tape.mdx @@ -1,16 +1,25 @@ --- title: Tape 与模型上下文 -description: Tape 保存发生过什么,TapeContext 决定下一次请求能看到什么。 +description: 了解 Bub 的 Tape 记忆模型:Tape 持久保存完整会话历史,通过 TapeContext 与 anchor 精准控制每次模型调用的上下文。 sidebar: label: Tape --- -应用需要完整、可信的历史,模型却只需要有限且相关的输入。Bub 因此把两者分开:**Tape 是持久记录,模型上下文是这份记录的一次投影**。 +在开发长对话或多步骤 Agent 时,我们经常会遇到一个矛盾: + +- **对应用和开发者来说**,我们需要一份完整、不可篡改的历史记录,清楚记下用户说过什么、模型调了哪些工具、传了什么参数、返回了什么结果,以便排查问题、审计行为或恢复会话; +- **对大模型来说**,它的上下文窗口有限,过多陈旧的中间过程会干扰当前推理,因此每次调用只需要一份精简、相关的消息列表。 + +如果把这两件事混在同一个 `messages` 列表里,你就会陷入两难:不裁剪,上下文迟早溢出;一旦裁剪或改写,原本的历史记录就被永久破坏了。 + +Bub 的做法是把「存历史」和「读上下文」彻底分开:**Tape 负责持久化完整的追加式记录,而模型上下文则是每次调用前通过 `TapeContext` 从中筛选并生成的视图**。 ## 一份记录,两种视图 {#history-and-context} -- **Tape(写)**:按顺序追加 `TapeEntry`,包括对话消息、工具调用、工具结果、anchor 和显式记录的业务事件。`tape.query()` 查询原始条目。 -- **`TapeContext`(读)**:选择本次需要的条目并转换成模型消息。`tape.read_messages()` 返回投影,不是原始记录。 +你可以把 Tape 和 `TapeContext` 分别看作同一份会话数据的「写入端」与「读取端」: + +- **Tape**(写):按时间顺序追加 `TapeEntry` 条目,类型包括对话消息(`message`)、工具调用(`tool_call`)、工具结果(`tool_result`)、分界锚点(`anchor`)和自定义事件(`event`)。调用 `tape.query()` 可查询完整原始条目。 +- **`TapeContext`**(读):每次请求模型前,按规则挑选条目并转换为模型消息列表。调用 `tape.read_messages()` 返回转换后的模型上下文。 ```mermaid flowchart LR @@ -18,26 +27,33 @@ flowchart LR E5 ==>|"默认上下文起点"| B["模型上下文
对话 + 工具往返"] ``` -默认投影 `default_tape_context()` 读取最近一个 anchor 之后的条目,重建对话与工具往返。标记为 `context=False` 的条目会在筛选前被排除,不进入模型上下文。 +默认情况下,Agent 使用 `default_tape_context()`:它定位到**最近一个 `anchor`**,只将该锚点之后的条目还原为对话与工具消息。写入时带有 `context=False` 的条目会被自动排除,不进入模型上下文。 -:::note[追加,但不是不可变审计日志] -正常记录只追加;`tape.reset()` 会清空记录并写入新的 `session/start`。 +:::note[只追加,可显式重置] +正常运行时 Tape 只追加新条目、不修改旧记录。调用 `tape.reset()` 会清空当前记录,并写入新的 `session/start` 锚点。 ::: -## anchor 与 handoff {#anchors} +## 用 anchor 与 handoff 切换阶段 {#anchors} -**锚点(anchor)**标记认知阶段的切换,例如信息收集结束或新任务开始。**交接(handoff)**通过追加新的 anchor,把默认上下文的起点前移,同时保留此前的全部记录。 +随着对话不断变长,或者当一个复杂任务从「收集信息」进入「执行修改」阶段时,我们往往希望让模型放下前面的冗长过程、轻装上阵,同时又不想把之前的历史记录删掉。 -handoff 只改变默认读取边界:它不生成摘要、不删除历史,也不会自动把 anchor 的 `state` 注入下一次请求。需要摘要时,应显式生成并写入后续模型输入。具体用法见 [SDK:anchor 和 handoff](/zh-cn/docs/sdk/tape/#anchors-and-handoff)或应用内置的 [`tape.handoff` 命令](/zh-cn/docs/reference/tools/#tape-handoff)。 +Bub 用 **anchor**(锚点)和 **handoff**(阶段交接)来解决这个问题: + +- **anchor** 是插在 Tape 上的一个路标,用来标记会话进入了一个新阶段(例如会话刚开始时的 `session/start`,或代码审查完成后的 `reviewed`)。 +- **handoff** 则是往 Tape 末尾追加一个新 anchor 的操作。因为默认的 `TapeContext` 只从最近一个 anchor 往后读,一旦执行了 handoff,**模型上下文的起点就会立刻前移到这个新路标处**,而此前的所有记录依然完好地保存在 Tape 中,随时可以通过 `tape.query()` 检索。 + +需要注意,handoff 只负责**前移默认读取起点**:它不会自动调用模型生成摘要,不会删除旧记录,也不会自动把 anchor 里的 `state` 注入提示词。如果你需要在切换阶段时保留前情提要,可以先整理出摘要再显式传入。代码用法见 [SDK:anchor 与 handoff](/zh-cn/docs/sdk/tape/#anchors-and-handoff),终端用法见内置的 [`tape.handoff` 工具](/zh-cn/docs/reference/tools/#tape-handoff)。 ## 数据应该放在哪里 {#state} -| 位置 | 生命周期 | 放什么 | +在 Bub 中,不同生命周期的数据有各自对应的存放位置,切勿把所有东西都塞进同一个地方: + +| 位置 | 生命周期 | 用途 | | --- | --- | --- | -| `state` / `TurnState` | 一次 Run 或 Turn | 请求内临时共享的值 | -| `metadata` | 一次 Run | 请求标识等观测信息,不进入模型输入 | -| Tape 条目 | 由存储决定,可跨进程 | 对话、工具往返、显式写入的业务事实 | -| anchor 的 `state` | 随历史保存 | 阶段快照 | -| 应用存储 | 由应用决定 | 需要 `load_state` 恢复的会话配置 | +| `state` / `TurnState` | 单次 Run 或 Turn | 请求内的临时共享变量(如请求 ID、权限标志、确认回调) | +| `metadata` | 单次 Run | 供日志和事件处理器读取的调用元数据,不进入模型上下文 | +| `TapeEntry` | 由存储后端决定,可跨进程持久化 | 对话消息、工具调用往返及显式写入的业务事件 | +| anchor 的 `state` | 随 Tape 持久保存 | 阶段切换时的结构化快照或摘要 | +| 应用外部存储 | 由应用自行管理 | 通过 `load_state` / `save_state` 跨 Turn 读写的业务状态 | -`core.Agent` 默认使用内存存储;持久化、分支与并发等用法见 [SDK:Tape 与记忆](/zh-cn/docs/sdk/tape/),存储后端接入见[存储集成](/zh-cn/docs/integrations/storage/)。 +`core.Agent` 默认使用内存存储(`InMemoryTapeStore`)。想在代码中配置文件持久化、自定义上下文筛选或管理分支,请阅读 [SDK:Tape 与记忆](/zh-cn/docs/sdk/tape/);想接入 SQLite 或 PostgreSQL,请阅读[使用数据库存储会话历史](/zh-cn/docs/integrations/storage/)。 diff --git a/website/src/content/docs/zh-cn/docs/concepts/turn.mdx b/website/src/content/docs/zh-cn/docs/concepts/turn.mdx index 01579a52..06d429c1 100644 --- a/website/src/content/docs/zh-cn/docs/concepts/turn.mdx +++ b/website/src/content/docs/zh-cn/docs/concepts/turn.mdx @@ -1,39 +1,61 @@ --- title: Turn -description: 应用层如何把一条入站消息处理成回复:生命周期阶段、TurnState 与失败边界。 +description: 深入理解 Bub 应用层的 Turn 生命周期:了解入站消息处理的七个阶段、单次 Turn 共享状态 TurnState 与异常失败边界。 sidebar: label: Turn --- -**Turn** 是应用层处理一条入站消息的完整生命周期,由 `BubFramework` 拥有。它固定了会话恢复、输入准备、模型执行、状态保存和回复投递的顺序与错误边界;Agent Run 只是其中的模型执行阶段。 +当你通过终端或聊天平台(如 Telegram、飞书)与 Bub 交互时,应用层收到的不只是一段发给模型的文本。它需要先确认这条消息属于哪个会话、恢复之前的状态、判断用户输入的是普通提问还是命令、运行 Agent、保存最新状态,最后把回复投递回对应的平台。 -## 生命周期 {#stages} +在 Bub 应用层中,处理一条入站消息的这整套生命周期就叫做一个 **Turn**,由 `BubFramework` 统一编排。核心层的 Agent Run 只是其中的模型执行阶段。 -`process_inbound()` 让普通消息经过同一组阶段: +## 七个生命周期阶段 {#stages} + +每次调用 `BubFramework.process_inbound()` 时,入站消息都会依次经过以下七个阶段: + +```mermaid +flowchart LR + A["resolve_session\n解析会话"] --> B["load_state\n加载状态"] + B --> C["build_prompt\n构造输入"] + C --> D["run_model\n执行模型"] + D --> E["save_state\n保存状态"] + E --> F["render_outbound\n生成回复"] + F --> G["dispatch_outbound\n发送消息"] +``` | 阶段 | 职责 | | --- | --- | -| `resolve_session` | 确定消息所属的会话 | -| `load_state` | 恢复会话状态并绑定 Agent | -| `build_prompt` | 识别命令,构造模型输入 | -| `run_model` | 执行 Agent Run,产生模型输出 | -| `save_state` | 保存需要跨 Turn 保留的应用状态 | -| `render_outbound` | 把模型输出渲染为渠道消息 | -| `dispatch_outbound` | 通过对应渠道投递回复 | +| `resolve_session` | 确定消息所属的 `session_id`(默认为 `:`) | +| `load_state` | 从存储中加载当前 Turn 所需的会话状态,并绑定运行时 Agent | +| `build_prompt` | 识别内部命令,或将原始消息构造为模型输入 | +| `run_model` | 运行 Agent Run(或流式的 `run_model_stream`),推进模型推理与工具调用 | +| `save_state` | 在模型阶段结束后保存跨 Turn 的应用状态 | +| `render_outbound` | 将模型输出包装为一条或多条待发送的渠道消息 | +| `dispatch_outbound` | 将待发送消息交给对应渠道投递 | + +每个阶段都对应一个同名 Hook,插件可以在不改动核心代码的情况下扩展或替换任一阶段的行为。函数签名与调用规则见 [Hooks 参考](/zh-cn/docs/reference/hooks/#turn-hooks)。 + +在理解 Turn 时,建议把它和另外两个容易混淆的概念区分开: + +- **Session**:跨多条消息的会话标识。同一聊天窗口连续发送 10 条消息属于 1 个 Session,但会触发 10 个独立的 Turn。`session_id` 仅是标识符,不含互斥锁;同会话并发由渠道准入策略或宿主程序控制。 +- **Turn**:应用层处理一条入站消息的 7 阶段流程。 +- **Run**:核心层 `core.Agent` 的一次模型与工具循环。普通消息在 Turn 的 `run_model` 阶段启动一次 Run;逗号命令(如 `,help`)在 Turn 内直接执行完毕,不启动 Run;通过 SDK 直接调用 `agent.run()` 则只执行 Run,不经过 Turn。 -每个阶段都有同名 hook,可以按契约扩展或替换默认行为,签名见 [Hooks 参考](/zh-cn/docs/reference/hooks/#turn-hooks)。 +## TurnState:单次 Turn 内的共享字典 {#state} -Turn 与 Run 不是同一个粒度:直接命令可以在 Turn 内完成而不启动模型 Run,直接使用 `core.Agent` 创建的 Run 也不属于任何 Turn。**Session** 则是跨多条消息的标识与恢复边界,一个 Session 可以包含多个 Turn;会话标识本身不提供锁,是否允许并发由准入策略或宿主决定。 +在一次 Turn 的推进过程中,不同的 Hook、工具函数和事件处理器往往需要共享一些临时上下文(例如当前请求 ID、用户权限标记或渠道元数据)。Bub 为此提供了 `TurnState`。 -## TurnState {#state} +`TurnState` 本质上是一个普通的 Python 字典(`dict[str, Any]`),**只在当前这一次 Turn 或 Run 内部有效,结束后即销毁,不会自动持久化**。 -`TurnState` 是 hooks、工具和事件处理器在当前执行中共享的临时字典,只在本次 Turn 或 Run 内有效,不会自动持久化。 +- 需要跨 Turn 保留的应用状态,应在 `save_state` 中显式保存,并在 `load_state` 中恢复。 +- 对话历史和工具记录保存在 Tape 中,不要放入 `TurnState`(见[数据应该放在哪里](/zh-cn/docs/concepts/tape/#state))。 +- `_runtime_` 前缀的键由 Bub 内部维护,插件不要修改或覆盖。 -需要留到下一个 Turn 的数据,应在 `save_state` 中保存、在 `load_state` 中恢复;对话与工具往返属于 Tape,不属于 TurnState,见 [数据应该放在哪里](/zh-cn/docs/concepts/tape/#state)。`_runtime_` 前缀的键由运行时写入,插件不应依赖。 +## 异常与失败边界 {#failures} -## 失败边界 {#failures} +在实际运行中,网络抖动、模型超时或工具报错都有可能中断某一次 Turn。Bub 的管道为此划定了明确的失败边界: -- 进入模型阶段后,`save_state` 一定在 `finally` 中执行,模型出错或超时也不会跳过。 -- `resolve_session`、`load_state`、`build_prompt` 的失败发生在该保障范围之前,不触发 `save_state`。 -- 未处理异常交给 `on_error` 观察和上报,然后重新抛出;`on_error` 不会恢复 Turn。 -- Turn 不是事务:工具已经修改的文件、发出的请求等外部副作用不会回滚。 +- **进入模型阶段后必执行 `save_state`**:只要流程进入 `run_model`,框架都会在 `finally` 块中调用 `save_state`。即便模型调用报错或超时,此前写入 `TurnState` 的状态依然会保存。 +- **前置阶段报错不执行 `save_state`**:若异常发生在 `resolve_session`、`load_state` 或 `build_prompt` 阶段,模型尚未启动,`save_state` 不会执行。 +- **`on_error` 仅观测不恢复**:未捕获的异常会先交给 `on_error` Hook 记录日志或告警,随后原样向上抛出。 +- **Turn 不回滚外部副作用**:若工具已修改文件、发起网络请求或写入外部数据库,后续阶段报错不会回滚这些外部操作。 diff --git a/website/src/content/docs/zh-cn/docs/getting-started/index.mdx b/website/src/content/docs/zh-cn/docs/getting-started/index.mdx index 0ef25110..5a7ebb03 100644 --- a/website/src/content/docs/zh-cn/docs/getting-started/index.mdx +++ b/website/src/content/docs/zh-cn/docs/getting-started/index.mdx @@ -1,6 +1,6 @@ --- title: Bub 是什么? -description: 一个由 Python 构建的轻量级 Agent 运行时。可以直接运行,也可以嵌入你自己的程序。 +description: 了解 Bub——基于 Python 的轻量级 AI Agent 运行时,内置开箱即用的 CLI 应用与可组合 SDK,支持 Tape 记忆、工具、技能与插件扩展。 --- import { Card, CardGrid } from '@astrojs/starlight/components'; @@ -8,47 +8,47 @@ Bub 是一个由 Python 构建的轻量级 Agent 运行时。它自带一个开 Agent 的本质是一个循环:模型读取上下文并决定调用哪个工具,工具的结果写回上下文,再交给模型;当模型不再请求工具、直接给出答案时,循环结束。 -构成一个 Agent 的核心有四个:**模型**、**工具**、**上下文**,以及驱动它们的**循环**。所以在这样的共识下 Bub 设计了精简的内核,并围绕内核构建出了一个开箱即用的应用。 +构成一个 Agent 的核心有四个:**模型**、**工具**、**上下文**,以及驱动它们的**循环**。围绕这四个核心部件,Bub 设计了精简的内核,并构建出一套开箱即用的应用: - 提供可自由组合的 Agent 能力,如循环、工具、上下文、事件总线、模型客户端等。 + 可组合的 Agent 内核,包含循环、工具、上下文(Tape)、事件总线和模型客户端。 - 在核心层之上的 Harness,提供配置、插件、hooks、技能、消息渠道、网关等能力。 + 核心层之上的完整应用,提供配置、插件、Hooks、技能、消息渠道和网关。 如何选择? -- 如果你想**把 Bub 与你现有的代码库或服务相结合**,那么请直接使用 Bub 核心层的 [SDK](/zh-cn/docs/sdk/); -- 如果你想**开箱即用 Bub**,那么请直接使用 Bub 应用层的 [App](/zh-cn/docs/app/workspace/)。 +- 如果你想**把 Bub 嵌入现有的代码库或服务**,可以直接使用核心层的 [SDK](/zh-cn/docs/sdk/); +- 如果你想**开箱即用 Bub**,直接使用应用层的 [CLI 应用](/zh-cn/docs/app/workspace/) 即可。 :::tip -二者并不互斥,必要时你甚至可以在 SDK 中[复用 Bub 应用](/zh-cn/docs/integrations/reuse-app/#model-stage)。 +二者并不互斥,必要时你甚至可以在 SDK 中按需[复用 Bub 应用层能力](/zh-cn/docs/integrations/reuse-app/#model-stage)。 ::: ## 特性 {#features} -Bub 秉持着简单、可组合、可扩展的设计理念,意味着你可以自由组合 Bub 的能力,或在 Bub 的基础上构建自己的 Agent,所以 Bub 有以下特性: +Bub 秉持着简单、可组合、可扩展的设计理念——你可以自由组合它的能力,也可以在它之上构建属于自己的 Agent。它有以下几个核心特性: - 会话内容以追加方式(append-only)写入 [tape](/zh-cn/docs/concepts/tape),不修改已有记录。 + 会话记录以追加(append-only)方式写入 [Tape](/zh-cn/docs/concepts/tape/),不修改已有记录。 - 每次一模型与工具调用的发出开始、结束和结果都以事件形式被观测、改写或介入。 + 模型与工具调用的每个阶段都会触发事件,支持观测、改写参数或拦截执行。 - 工具以函数形式存在,直接使用 Python 原生代码驱动,复用社区生态能力。 + 用普通 Python 函数定义工具,直接复用现有 Python 生态。 - - 能力可以通过插件进行扩展。插件可以是一个工具、事件监听器、消息渠道,或完整的技能集合。 + + 通过插件扩展工具、事件处理器、消息渠道和技能。 :::tip -查阅 [Agent 循环](/zh-cn/docs/concepts/agent/)以了解 Bub 的核心执行模型。 +查阅 [Agent 循环](/zh-cn/docs/concepts/agent/),进一步了解 Bub 的核心执行模型。 ::: -现在你可以开始自由探索 Bub 文档,或者跟着下一页,开始你的 Bub 之旅。 +现在你可以自由探索 Bub 文档,或者跟着下一页,开启你的 Bub 之旅。 diff --git a/website/src/content/docs/zh-cn/docs/getting-started/install.mdx b/website/src/content/docs/zh-cn/docs/getting-started/install.mdx index 994b1d76..263080c2 100644 --- a/website/src/content/docs/zh-cn/docs/getting-started/install.mdx +++ b/website/src/content/docs/zh-cn/docs/getting-started/install.mdx @@ -1,11 +1,11 @@ --- title: 安装 Bub -description: 跟着文档一步步安装 Bub,提供了多种安装途径。 +description: 使用 uv 或 pip 安装 Bub:按需选择完整 CLI 应用(bub[app])、轻量级 Python Agent SDK(bub)或从源码运行。 --- import { Tabs, TabItem } from '@astrojs/starlight/components'; -Bub 有 CLI 和 SDK 两种使用方式,因此可以根据你的需要选择对应安装方式。 +Bub 有 CLI 和 SDK 两种使用方式,你可以根据自己的需求选择对应的安装途径。 ## 安装 CLI 应用 {#app-install} @@ -34,17 +34,17 @@ uv tool update-shell -使用安装脚本时,脚本会安装 uv 和 Python 3.12,并把 `bub[app]` 安装到当前环境中。`app` 是 Bub 的可选依赖组,包含 CLI、渠道和插件等应用层能力;只使用 SDK 时不需要它。 +使用安装脚本时,它会自动安装 `uv` 和 Python 3.12,并把 `bub[app]` 安装到当前环境中。`app` 是 Bub 的可选依赖组,包含 CLI、消息渠道和插件等应用层能力;如果只使用 SDK,则不需要它。 -完成后执行 `bub --help`,再运行 `bub onboard` 开始配置。 +安装完成后,先运行 `bub --help` 验证一下,再执行 `bub onboard` 开始初始配置。 :::tip -如果当前环境提示找不到命令,请检查环境变量是否包含了可执行文件所在路径,或者手动把 `~/.local/bin` 加入 PATH。 +如果提示找不到 `bub` 命令,请检查环境变量是否包含了可执行文件所在路径,或手动将 `~/.local/bin` 加入 `PATH`。 ::: ## 安装 SDK {#agent-install} -自 0.6.0 起,Bub 默认只包含核心。可以用包管理工具把 Bub 安装到项目中,这里以 uv 为例: +自 0.6.0 起,`bub` 包默认只包含核心层。用你习惯的包管理器把它添加到项目中即可,这里以 `uv` 为例: ```bash uv add bub @@ -62,3 +62,7 @@ uv sync ``` 之后执行 `uv run bub` 运行即可。 + +--- + +完成安装后,继续阅读[快速上手](/zh-cn/docs/getting-started/quickstart/)。 diff --git a/website/src/content/docs/zh-cn/docs/getting-started/quickstart.mdx b/website/src/content/docs/zh-cn/docs/getting-started/quickstart.mdx index 5e4f4112..6022f015 100644 --- a/website/src/content/docs/zh-cn/docs/getting-started/quickstart.mdx +++ b/website/src/content/docs/zh-cn/docs/getting-started/quickstart.mdx @@ -1,27 +1,27 @@ --- title: 快速上手 -description: 学会如何快速开始在终端或在自己的 Python 项目中使用 Bub。 +description: 几分钟快速上手 Bub:在终端配置大模型并启动 CLI 交互,或在 Python 项目中使用 Bub SDK 跑通首个 Agent。 --- import { CardGrid, LinkCard, Steps } from '@astrojs/starlight/components'; -自 0.6.0 版本起,Bub 本体拆分成了两部分,因此你可以根据需要选择使用哪部分来玩转 Bub。 +自 0.6.0 版本起,Bub 本体拆分成了核心层与应用层两部分,你可以按自己的习惯选择其中一种方式来玩转 Bub。 -这一页假设你已经[安装 Bub](/zh-cn/docs/getting-started/install/)。 +开始前,这一页假设你已经[安装好 Bub](/zh-cn/docs/getting-started/install/)。 ## 从 CLI 启动 {#cli} -打开你系统的终端,然后按如下步骤在命令行中进行操作: +打开你的终端,跟着下面几步在命令行里试试看: -1. 如果你从未配置过 Bub,可以先执行如下命令来完成初始配置: +1. (可选)如果你从未配置过 Bub,可以先运行配置向导完成初始配置: ```bash bub onboard ``` -2. 在任意目录中创建一个工作区(目录)并切换到当中,然后使用 `bub chat` 启动一个交互式会话: +2. 在任意位置创建一个工作区目录并切换进去,然后用 `bub chat` 启动交互式会话: ```bash mkdir hello-bub && cd hello-bub @@ -29,10 +29,10 @@ import { CardGrid, LinkCard, Steps } from '@astrojs/starlight/components'; ``` :::tip - 运行命令前,可输入 `bub --help` 查看命令和选项,或查阅 [CLI 参考](/zh-cn/docs/reference/cli/)。 + 运行 `bub --help` 或查阅 [CLI 参考](/zh-cn/docs/reference/cli/) 了解所有命令选项。 ::: -3. 现在,可以尝试复制粘贴如下文本并与 Bub 进行对话: +3. 现在,试着复制粘贴下面这句话,和 Bub 聊一聊: ```shell Summarize the files in this directory @@ -40,24 +40,24 @@ import { CardGrid, LinkCard, Steps } from '@astrojs/starlight/components'; -在交互式的 CLI 界面中,使用 Ctrl+D 或输入 `,quit` 退出交互式会话。 +在交互式 CLI 界面中,按 Ctrl+D 或输入 `,quit` 即可退出会话。 ## 用 SDK 运行 {#sdk} -如果要把 Agent 嵌入自己的 Python 项目,可以从基础 SDK 开始。 +如果你想把 Agent 嵌入自己的 Python 项目,可以从基础 SDK 开始: -1. 创建新项目并安装 Bub: +1. 创建新项目并安装 `bub`: ```bash uv init --python 3.12 my-agent && cd my-agent uv add bub ``` -2. 把下面这段代码保存为 `main.py` +2. 把下面这段代码保存为 `main.py`: - ```python title="main.py" + ```python title="main.py" {9-11} import asyncio import republic @@ -78,10 +78,10 @@ import { CardGrid, LinkCard, Steps } from '@astrojs/starlight/components'; ``` :::tip - 查阅 [Python API](/zh-cn/docs/reference/python-api/) 以了解更多 API 接口。 + 完整接口说明见 [Python API 参考](/zh-cn/docs/reference/python-api/)。 ::: -3. 用你的 API Key 跑起来 +3. 用你的 API Key 跑起来: ```bash export REPUBLIC_OPENAI_API_KEY=sk-... @@ -90,22 +90,21 @@ import { CardGrid, LinkCard, Steps } from '@astrojs/starlight/components'; - ## 下一步 {#next-steps} -恭喜你,已经掌握 Bub 的基本使用方式了,接下来你可以继续深入探索这两种方式以解锁更多使用场景。 +恭喜你,已经掌握了 Bub 的基本用法!接下来你可以根据使用场景继续深入探索: -当然,如果你愿意的话,也可以继续了解一下 Bub 有哪些设计巧思。 +当然,如果你感兴趣,也可以继续往下读,看看 Bub 背后有哪些设计巧思。 diff --git a/website/src/content/docs/zh-cn/docs/integrations/acp.mdx b/website/src/content/docs/zh-cn/docs/integrations/acp.mdx index 79521005..098081c7 100644 --- a/website/src/content/docs/zh-cn/docs/integrations/acp.mdx +++ b/website/src/content/docs/zh-cn/docs/integrations/acp.mdx @@ -1,31 +1,31 @@ --- title: 通过 ACP 接入 IDE -description: 安装 bub-acp-server,在 Zed 或兼容 ACP 协议的代码编辑器中运行与交互 Bub Agent。 +description: 安装 bub-acp-server 插件,在 Zed 等兼容 ACP 协议的 IDE 中接入 Bub Agent,支持会话同步与远程 HTTP/WebSocket 模式。 sidebar: badge: { text: '应用', variant: 'note' } --- -[Agent Client Protocol](https://agentclientprotocol.com/)(ACP)是一套开放的标准协议,允许代码编辑器(如 Zed)以子进程方式启动 Agent,并通过 JSON-RPC 双向流式交换会话、提示词、工具调用状态和代码编辑操作。 +[Agent Client Protocol](https://agentclientprotocol.com/)(ACP)是让代码编辑器(如 Zed)与 Agent 通过 JSON-RPC 流式交换会话、提示词、工具调用和文件编辑操作的开放协议。 -`bub-acp-server` 插件将 Bub 应用接入 ACP 协议,使你能够在日常使用的 IDE 中直接唤出 Bub 进行代码编写、重构与排障。 +安装 `bub-acp-server` 插件后,就能把 Bub 接入 ACP 协议,在日常使用的 IDE 中直接唤出 Bub 进行代码编写、重构与排障。 ```mermaid flowchart LR - IDE["代码编辑器\n (支持 ACP 协议)"] + IDE["代码编辑器\n(支持 ACP)"] Server["bub-acp-server"] Bub["Bub Agent"] IDE <-->|"JSON-RPC"| Server - Server <-->|"Turn 事件与工具执行"| Bub + Server <-->|"Turn 事件与工具调用"| Bub ``` ## 开始之前 {#before-you-start} -- 已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install),并配置可用模型。 -- 已安装 [Zed](https://zed.dev/) 编辑器(或其他支持 ACP 协议的客户端)。 +- 已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install)并配置好模型。 +- 已安装 [Zed](https://zed.dev/)(或其他兼容 ACP 的编辑器)。 -:::note[环境变量与路径] -Zed 等应用程序在启动时,其继承的 `PATH` 和环境变量通常与终端(如 `~/.zshrc` 或 `~/.bashrc`)不同。请先通过终端确认当前环境的 `bub` 绝对路径: +:::note[查看 `bub` 绝对路径] +桌面应用启动时继承的 `PATH` 通常不包含你在 `~/.zshrc` 或 `~/.bashrc` 中配置的路径。请先在终端获取 `bub` 的绝对路径: ```bash command -v bub @@ -41,23 +41,17 @@ bub install bub-acp-server@main bub acp --help ``` -如果安装成功,终端输出将显示: - -```text -Usage: bub acp [OPTIONS] -``` - -`bub-acp-server` 默认使用标准输入输出(`stdio`)与宿主编辑器通信。 +输出 `Usage: bub acp [OPTIONS]` 即表示安装成功。`bub acp` 默认通过标准输入输出(`stdio`)与编辑器通信。 ## 2. 配置 Zed {#zed} -在 Zed 中使用快捷键 `Cmd+Shift+P`(macOS)或 `Ctrl+Shift+P`(Linux/Windows)打开命令面板,输入并执行 `zed: open settings`,在打开的 `settings.json` 中添加 `agent_servers` 配置。 +在 Zed 中按 `Cmd+Shift+P`(macOS)或 `Ctrl+Shift+P`(Linux/Windows)打开命令面板,执行 `zed: open settings`,在 `settings.json` 中添加 `agent_servers` 配置。 -### 方案 A:全局安装 {#global-install} +### 方式 A:直接调用命令 {#global-install} -如果 `bub` 位于系统全局 `PATH` 中,且不需要额外加载特定项目的 `.env` 文件,可直接配置: +如果不需要加载项目目录下的 `.env` 文件,可直接指向 `bub`(若 Zed 提示找不到命令,请将 `"bub"` 替换为 `command -v bub` 输出的绝对路径): -```json +```json title="~/.config/zed/settings.json" { "agent_servers": { "Bub": { @@ -70,37 +64,35 @@ Usage: bub acp [OPTIONS] } ``` -*如果 Zed 报错找不到 `bub`,请将 `"command"` 替换为前面通过 `command -v bub` 获取到的绝对路径。* - -### 方案 B:使用包装脚本 {#wrapper-script} +### 方式 B:使用启动包装脚本 {#wrapper-script} -如果你的项目依赖特定的 Python 虚拟环境,或者模型 API Key 保存在工作区根目录的 `.env` 中,强烈建议编写一个启动包装脚本(例如 `~/.bub/bub-acp-wrapper`): +如果 API Key 保存在项目根目录的 `.env` 中,或需要激活特定虚拟环境,建议创建包装脚本 `~/.bub/bub-acp-wrapper`: -```bash +```bash title="~/.bub/bub-acp-wrapper" #!/usr/bin/env bash set -euo pipefail -# 1. 激活虚拟环境(若有) +# 1. 可选:激活虚拟环境 # source /path/to/venv/bin/activate -# 2. 加载工作区或用户环境变量 +# 2. 加载当前工作区的 .env if [ -f "$PWD/.env" ]; then set -a source "$PWD/.env" set +a fi -# 3. 使用绝对路径启动 Bub ACP +# 3. 用绝对路径启动 Bub ACP exec /path/to/your/bub acp ``` -赋予执行权限后,在 Zed 设置中直接指向该脚本: +赋予可执行权限并在 Zed 中配置该脚本路径: ```bash chmod +x ~/.bub/bub-acp-wrapper ``` -```json +```json title="~/.config/zed/settings.json" { "agent_servers": { "Bub": { @@ -113,48 +105,42 @@ chmod +x ~/.bub/bub-acp-wrapper } ``` -## 3. 启动会话 {#start} +## 3. 在 Zed 中开始对话 {#start} 保存设置后重启 Zed 或重新加载配置: -1. 按 `Cmd+?`(macOS)或 `Ctrl+?`(Linux/Windows)打开 Zed 的 Agent 侧边面板。 -2. 在模型/后端选择菜单中切换为 **Bub**。 -3. 在输入框中输入消息进行测试: +1. 按 `Cmd+?`(macOS)或 `Ctrl+?`(Linux/Windows)打开 Zed 的 Agent 面板; +2. 将后端切换为 **Bub**; +3. 输入测试消息: ```text 你好!请介绍一下你自己。 ``` -4. Bub 将通过流式传输把响应、思考过程及工具调用步骤逐一投递在面板上。 +4. Bub 会将回复、思考过程与工具调用步骤逐一流式呈现在面板中。 -:::tip[原生工具能力] -Zed 支持让 Agent 借助编辑器的文件系统和终端执行操作。当 Zed 具备相关权限时,Bub 的 `bash`、`fs.read`、`fs.write` 将自动优先由编辑器托管执行;若客户端未声明该能力,则退回到本机运行。 +:::tip[编辑器原生工具托管] +当 Zed 声明了文件系统与终端能力时,Bub 的 `bash`、`fs.read` 和 `fs.write` 会优先交由编辑器执行;若客户端未声明,则自动回退到 Bub 本地执行。 ::: -## 4. 会话与恢复 {#sessions} - -`bub-acp-server` 具备完整的会话生命周期管理能力: +## 4. 会话恢复与参数同步 {#sessions} -- **新建会话**:在 Zed 面板新建 Thread,对应底层开启一条全新的会话 Tape。 -- **历史恢复**:切换回旧 Thread 时,Bub 会从持久化 Tape 存储中提取并重放该会话的历史消息与工具上下文。 -- **持久化绑定**:会话的元数据索引存放在 `$BUB_HOME/acp-sessions.json`。只要你的 `BUB_HOME` 和工作区路径保持稳定,重启编辑器后历史会话列表依然完好无损。 -- **模型与推理参数**:在 Zed 界面中调节的思考深度(Reasoning Effort)或选择的具体模型别名,会自动附加在本次 ACP 会话的后续请求中。 +- **新建与恢复会话**:在 Zed 中新建 Thread 会创建新 Tape;切回历史 Thread 时,Bub 会从 Tape 存储中恢复对应的历史记录。会话索引保存在 `$BUB_HOME/acp-sessions.json`——只要 `BUB_HOME` 和工作区路径不变,重启编辑器后历史会话列表依然完好无损。 +- **模型与推理强度**:在 Zed 面板中切换的模型或推理强度(Reasoning Effort)会自动同步到当前 ACP 会话。 -## 5. 远程服务模式 {#http} +## 5. 远程服务模式(HTTP / WebSocket) {#http} -在大多数本地开发场景中,默认的 `stdio` 是最轻量且低开销的选择。如果你把 Bub 部署在云端开发机(Remote Server)或 Docker 容器内,需要供本地开发机上的编辑器远程调用,可以使用 HTTP/WebSocket 服务模式。 +在大多数本地开发场景中,默认的 `stdio` 是最轻量且低开销的选择。如果你把 Bub 部署在远程开发机或 Docker 容器内,需要本地编辑器远程连接,可以启用 HTTP 或 WebSocket 传输模式。 -### 方式 1:独立启动服务 {#standalone-service} +### 独立启动 {#standalone-service} ```bash -# 启动 HTTP 服务 bub acp --transport http - -# 或启动 WebSocket 服务 +# 或 bub acp --transport websocket ``` -默认监听地址为 `127.0.0.1:28200`(HTTP 端点为 `http://127.0.0.1:28200/acp`,WebSocket 端点为 `ws://127.0.0.1:28200/acp`)。 +默认监听 `127.0.0.1:28200`(端点为 `http://127.0.0.1:28200/acp` 或 `ws://127.0.0.1:28200/acp`)。 -### 方式 2:作为 Bub Gateway 渠道长驻运行 {#gateway-channel} +### 作为网关渠道启动 {#gateway-channel} 通过网关模式可以同时维护会话池与后台连接: @@ -162,23 +148,22 @@ bub acp --transport websocket bub gateway --enable-channel acp-server ``` -| 环境变量 | 默认值 | 作用说明 | +| 环境变量 | 默认值 | 说明 | | --- | --- | --- | -| `BUB_ACP_SERVER_HOST` | `127.0.0.1` | 监听的主机 IP(如需对外开放可设为 `0.0.0.0`,注意网络安全) | -| `BUB_ACP_SERVER_PORT` | `28200` | 服务端口 | -| `BUB_ACP_SERVER_CERTFILE` | 空 | TLS 证书路径(开启 HTTPS/WSS 必须) | +| `BUB_ACP_SERVER_HOST` | `127.0.0.1` | 监听地址(对外监听可设为 `0.0.0.0`) | +| `BUB_ACP_SERVER_PORT` | `28200` | 监听端口 | +| `BUB_ACP_SERVER_CERTFILE` | 空 | TLS 证书路径(启用 HTTPS/WSS 必填) | | `BUB_ACP_SERVER_KEYFILE` | 空 | TLS 私钥路径 | -:::caution[安全边界] -HTTP/WebSocket 端点默认不提供复杂的用户鉴权。若需要跨公网暴露,请务必在前置配置 Nginx 或 Cloudflare Tunnel 增加身份认证,并启用 TLS 加密。 +:::caution[公网安全] +HTTP/WebSocket 端点本身不包含用户鉴权。如需跨网络访问,请通过 SSH 端口转发,或前置 Nginx / Cloudflare Tunnel 配置鉴权与 TLS。 ::: ## 故障排查 {#troubleshooting} -| 常见问题 | 排查切入点 | 解决建议 | -| --- | --- | --- | -| Zed 提示找不到 Agent Server | 检查 `"command"` 路径 | 在终端执行 `command -v bub`,将配置中的 `command` 改为系统绝对路径。 | -| 面板显示启动失败或退回 | 环境变量未生效(如缺少 API Key) | 采用[方案 B](#zed) 编写 wrapper 脚本,在脚本中强制 `source` 所需的 `.env`。 | -| 不清楚协议握手卡在哪里 | 查看 Zed 的 ACP 通信日志 | 在 Zed 中打开命令面板,执行 `dev: open acp logs`,实时观察 JSON-RPC 的交互事件。 | -| 工具调用没有正常触发 | 检查客户端能力协商(Capabilities) | 确认工作区具有读写权限;在同一终端下先用 `bub run` 测试工具是否正常。 | -| 会话历史无法保存 | 检查 `BUB_HOME` 目录权限 | 确保运行 Zed 的用户对 `~/.bub` 目录拥有读写权限。 | +| 现象 | 排查与解决方法 | +| --- | --- | +| Zed 提示找不到 Agent Server | 将 `settings.json` 中的 `command` 改为 `command -v bub` 输出的绝对路径 | +| 启动失败或模型报缺少密钥 | 采用[方式 B](#wrapper-script) 包装脚本,确保 `.env` 被正确 `source` | +| 需要查看 JSON-RPC 通信日志 | 在 Zed 命令面板运行 `dev: open acp logs` | +| 会话历史无法保存 | 检查运行 Zed 的用户对 `$BUB_HOME`(默认 `~/.bub`)是否有读写权限 | diff --git a/website/src/content/docs/zh-cn/docs/integrations/ag-ui.mdx b/website/src/content/docs/zh-cn/docs/integrations/ag-ui.mdx index 882c534b..1a689876 100644 --- a/website/src/content/docs/zh-cn/docs/integrations/ag-ui.mdx +++ b/website/src/content/docs/zh-cn/docs/integrations/ag-ui.mdx @@ -1,6 +1,6 @@ --- -title: 通过 AG-UI 为 Bub 接入 AI 聊天前端 -description: 尝试 Bub 的实验性 AG-UI 集成,按示例接入 AI 聊天前端,处理流式回复、浏览器工具和应用保存的界面历史。 +title: 通过 AG-UI 接入 Web 聊天前端 +description: 安装 bub-ag-ui 插件,通过 AG-UI 协议将 Bub 接入 Web 聊天界面,支持流式输出、浏览器端工具调用与界面历史恢复。 sidebar: label: 通过 AG-UI 接入 Web 前端 badge: { text: '应用', variant: 'note' } @@ -10,18 +10,18 @@ tableOfContents: import { Tabs, TabItem } from '@astrojs/starlight/components'; -`bub-ag-ui` 插件通过 AG-UI 将 Bub 接入 Web 聊天前端,让你接收流式回复,并让 Bub 调用浏览器中的工具。这项集成仍处于实验阶段。 +`bub-ag-ui` 插件(实验性)通过 [AG-UI](https://docs.ag-ui.com/) 协议将 Bub 接入各类 Web 聊天前端,不仅支持流式推送模型回复,还允许 Bub 调用运行在浏览器前端的工具函数。 -本指南接入一个聊天界面,再用天气工具规划在旧金山的下午行程。如果还没有选定前端,可以从 assistant-ui 标签页开始。 +在本指南中,我们将把 Bub 连接到一个 Web 聊天界面,并结合浏览器端的天气查询工具(`get_weather`)来规划旧金山的下午行程。如果你还没有选定具体的前端框架,可以直接从第一个 `assistant-ui` 标签页开始体验。 ## 开始之前 {#before-you-start} -- 已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install),并[配置可用模型](/zh-cn/docs/app/configure/)。 -- 安装 Node.js 和 npm,用于运行前端。 +- 已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install)并[配置好模型](/zh-cn/docs/app/configure/)。 +- 已安装 Node.js 和 npm。 ## 1. 安装并启动插件 {#install} -将插件安装到运行 Bub 的环境中,然后启动服务: +在 Bub 运行环境中安装 `bub-ag-ui` 并启动本地服务: ```bash bub install bub-ag-ui@main @@ -29,16 +29,16 @@ bub ag-ui --help bub ag-ui --host 127.0.0.1 --port 28201 ``` -保持这个终端运行。前端将向 `http://127.0.0.1:28201/agent` 发送请求并接收流式回复。 +保持该终端运行。前端应用会向 `http://127.0.0.1:28201/agent` 发送请求并接收流式回复。 ## 2. 连接前端 {#choose-ui} -选择下方的一个标签页。每个示例都连接同一个 Bub 服务,在浏览器中执行 `get_weather` 工具,并保存界面中的对话以便刷新后恢复。天气数据是固定的旧金山演示预报。 +从下方选择一个你喜欢的前端框架标签页,按步骤创建并启动项目。所有示例都会连接同一个 Bub 后端、在浏览器端注册 `get_weather` 工具(返回演示用的旧金山天气数据),并通过 `sessionStorage` 保存页面消息以便刷新后恢复。 -各标签页用到以下共用文件。创建项目后,复制所选前端需要的文件。 +各个前端示例会用到以下几个共用辅助文件;创建好对应前端项目后,按需把它们复制到项目中即可:
-共用示例文件 +查看共用示例文件(scenario.json / vite 代理配置 / demo-session.ts) CopilotKit、OpenUI 和 AI Elements 将天气工具及数据保存为 `src/scenario.json`。assistant-ui 示例已在 provider 中包含这些内容。 @@ -147,10 +147,7 @@ async rewrites() { 创建 `app/BubRuntimeProvider.tsx`,接入 runtime、恢复界面消息并注册天气工具: -
-app/BubRuntimeProvider.tsx - -```tsx title="app/BubRuntimeProvider.tsx" +```tsx title="app/BubRuntimeProvider.tsx" showLineNumbers collapse={1-14, 19-39, 60-67} "use client"; import { useEffect, useState, type ReactNode } from "react"; @@ -230,8 +227,6 @@ export function BubRuntimeProvider({ children }: { children: ReactNode }) { } ``` -
- 用以下内容替换 `app/assistant.tsx`,保留现有的 `app/page.tsx` 入口: ```tsx title="app/assistant.tsx" @@ -273,10 +268,7 @@ npm install @copilotkit/react-core@1.85.0 @ag-ui/client@1.0.2 @ag-ui/core@1.0.2 将共用文件保存为 `src/demo-session.ts` 和 `src/scenario.json`,添加共用的 Vite 代理。创建 `src/BubHttpAgent.ts`,从浏览器存储恢复界面消息,无需向 Bub 请求历史: -
-src/BubHttpAgent.ts - -```typescript title="src/BubHttpAgent.ts" +```typescript title="src/BubHttpAgent.ts" showLineNumbers collapse={1-6} import { HttpAgent } from "@ag-ui/client"; import { EventType, type BaseEvent, type RunAgentInput } from "@ag-ui/core"; import { Observable } from "rxjs"; @@ -307,11 +299,9 @@ export class BubHttpAgent extends HttpAgent { } ``` -
- 替换 `src/main.tsx`。`useFrontendTool` 注册天气工具,并将执行结果返回给 Bub: -```tsx title="src/main.tsx" +```tsx title="src/main.tsx" showLineNumbers collapse={1-10, 49-52} "useFrontendTool" import { createRoot } from "react-dom/client"; import { BubHttpAgent, storageKey } from "./BubHttpAgent"; import { readDemoSession, persistDemoSession } from "./demo-session"; @@ -392,10 +382,7 @@ npm install @openuidev/react-ui@0.18.5 @openuidev/react-headless@0.18.5 @openuid 将共用文件保存为 `src/demo-session.ts` 和 `src/scenario.json`,添加共用的 Vite 代理,再替换 `src/main.tsx`: -
-src/main.tsx - -```tsx title="src/main.tsx" +```tsx title="src/main.tsx" showLineNumbers collapse={1-28, 41-106} import { createRoot } from "react-dom/client"; import { AgentInterface } from "@openuidev/react-ui"; import { @@ -519,8 +506,6 @@ createRoot(document.getElementById("root")!).render( ); ``` -
- 此示例在侧栏保留一个会话,并禁用删除功能。默认渲染器会将 Markdown 表格显示为纯文本。调整界面时可参考 [OpenUI Agent 示例](https://github.com/thesysdev/openui/tree/main/examples/agent-frameworks/mastra)。 ### 启动前端 {#openui-start} @@ -592,10 +577,7 @@ npx ai-elements@latest add conversation message prompt-input tool suggestion 将共用文件保存为 `src/demo-session.ts` 和 `src/scenario.json`,再替换 `src/main.tsx`。组件用法可参考 [AI Elements 指南](https://docs.langchain.com/oss/python/langchain/frontend/integrations/ai-elements)。 -
-src/main.tsx - -```tsx title="src/main.tsx" +```tsx title="src/main.tsx" showLineNumbers collapse={1-32, 49-180} import { useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import { HttpAgent, type Message as AgMessage } from "@ag-ui/client"; @@ -798,8 +780,6 @@ start().catch((error) => { }); ``` -
- ### 启动前端 {#ai-elements-start} ```bash @@ -809,32 +789,33 @@ npm run dev -## 3. 开始对话 {#verify} +## 3. 验证对话与工具调用 {#verify} -启动一个前端后,打开 `http://localhost:3000`,发送以下请求: +前端启动后,在浏览器打开 `http://localhost:3000` 并发送: ```text Call get_weather for San Francisco, then suggest an afternoon plan using the demo forecast. ``` -Bub 会调用浏览器工具,再根据结果建议下午的行程。预报为 18°C、局部多云,使用的是演示数据,不是实时天气。 +Bub 会调用浏览器端注册的 `get_weather` 工具(返回演示天气:18°C、局部多云),拿到结果后再为你生成一份旧金山下午的行程建议。 -回复结束后,在同一浏览器标签页刷新,消息应仍然可见。OpenUI 需要从侧栏选择保存的会话。继续询问刚才讨论的是哪个城市、多少度,即可接着聊下去。 +等回复生成完毕后,尝试刷新当前浏览器标签页,刚才的聊天记录依然会保留在界面上(OpenUI 可从左侧边栏选择已保存的会话)。你可以继续追问「我们刚才聊的是哪个城市?多少度?」,验证多轮上下文是否正常衔接。 -## 会话与界面历史 {#tools-and-history} +## 会话与界面历史存储机制 {#tools-and-history} -示例将会话 ID、消息和状态保存在 `sessionStorage` 中,刷新后恢复界面中的对话。没有保存消息的新浏览器标签页无法向 Bub 获取旧的界面历史;AG-UI 服务只提供 `POST /agent`。 +在上面的示例中,前端与后端各自分工保存了一部分状态: -Bub 自行管理模型的会话上下文。保留同一个 `threadId` 可以继续对话;后端重启时,需保留 Bub 的默认文件或[数据库存储](/zh-cn/docs/integrations/storage/)。浏览器存储用于恢复界面,无法恢复已删除的 Bub 上下文或未完成的工具调用。回复完成前应保持后端运行。每轮默认超时为 600 秒,包含等待浏览器工具的时间。 +- **前端界面消息**(`sessionStorage`):`demo-session.ts` 将 `threadId`、展示消息和前端状态保存在当前标签页的 `sessionStorage` 中,刷新同一标签页即可恢复界面。由于 `bub-ag-ui` 仅提供 `POST /agent` 接口、不提供历史消息拉取接口,新开的空白标签页无法从后端拉取旧界面记录。 +- **后端模型上下文**(Bub Tape):Bub 通过 Tape 保存模型上下文。只要请求携带相同的 `threadId`,就能继续之前的对话;配置本地文件或[数据库存储](/zh-cn/docs/integrations/storage/)可在后端重启后保留上下文。注意浏览器 `sessionStorage` 仅用于恢复前端界面,无法恢复后端已删除的 Tape 或中断的工具调用;因此在回复和工具调用完成前请保持后端运行(单轮默认超时 600 秒,含等待浏览器工具执行的时间)。 -清除示例的存储键并刷新,即可开始新会话。不支持编辑旧消息或重新生成回复;如果 UI 模板提供这些操作,请禁用相应入口。部署时,将演示存储替换为适合应用的数据存储和用户隔离方案。 +如需开启新会话,清除浏览器 `sessionStorage` 中的对应键并刷新页面即可。当前不支持「编辑历史消息」或「重新生成回复」;若 UI 模板自带这些按钮,建议将其隐藏或禁用。生产部署时请将 `sessionStorage` 替换为你自己的应用存储与多用户隔离方案。 -## 在自己的前端中使用 HttpAgent {#connect} +## 在自定义前端中使用 `HttpAgent` {#connect} -如果自行编写界面,可以用 `@ag-ui/client` 管理连接和消息状态。下方纯 TypeScript 示例展示流式文本,每次刷新都会创建新会话。 +如果你打算从零编写自己的前端界面,可以直接使用官方的 `@ag-ui/client` SDK 管理连接与事件流。以下是不依赖任何 UI 框架的纯 TypeScript 最小示例(每次刷新都会开启新会话):
-最小浏览器聊天示例 +查看最小浏览器聊天示例(Vanilla TypeScript) 创建 Vite 项目: @@ -912,27 +893,27 @@ npm run dev -- --host localhost --port 3000 --strictPort
-此示例直接请求 Bub,默认允许的来源为 `http://localhost:3000`。如果使用其他前端来源,在启动后端前设置 `BUB_AG_UI_ORIGINS`: +这个最小示例没有走本地代理,而是从浏览器直接跨域请求 Bub 后端。`bub-ag-ui` 默认仅放行 `http://localhost:3000`;如果你的前端运行在其他端口(如 Vite 默认的 `5173`),启动后端前请设置 `BUB_AG_UI_ORIGINS`: ```bash export BUB_AG_UI_ORIGINS='["http://localhost:5173"]' ``` -来源中的协议、主机名和端口都需要匹配。`localhost` 和 `127.0.0.1` 属于不同来源。 +注意 Origin 中的协议、域名和端口号必须完全一致(在浏览器跨域规则中,`localhost` 与 `127.0.0.1` 会被视为两个不同的来源)。 -## 部署服务 {#hosting} +## 部署与鉴权 {#hosting} -监听非回环地址时,设置 `BUB_AG_UI_TOKEN`,并在请求中发送 `Authorization: Bearer `。token 保存在应用服务器中。如果浏览器直接连接 Bub,还需配置 `BUB_AG_UI_ORIGINS`。 +监听非本地回环地址(非 `127.0.0.1`)时,请设置 `BUB_AG_UI_TOKEN` 开启鉴权,并在发往 Bub 的请求头中携带 `Authorization: Bearer `。建议由你自己的应用后端保存 Token 并代理转发请求;若由浏览器直连,还需通过 `BUB_AG_UI_ORIGINS` 显式放行前端域名。 -共享 token 对应一个用户身份。多用户认证与网关配置见[插件 README](https://github.com/bubbuild/bub-contrib/blob/main/packages/bub-ag-ui/README.md)。 +单个共享 Token 对应单一用户身份;多用户鉴权与网关挂载方式见 [`bub-ag-ui` 插件文档](https://github.com/bubbuild/bub-contrib/blob/main/packages/bub-ag-ui/README.md)。 -## 排障 {#troubleshooting} +## 故障排查 {#troubleshooting} -| 现象 | 检查方法 | +| 现象 | 排查与解决方法 | | --- | --- | -| 没有 `ag-ui` 命令 | 在安装插件的环境中运行 `bub ag-ui --help`。 | -| 浏览器请求失败 | 检查前端代理;直连时,检查 `BUB_AG_UI_ORIGINS` 是否与完整来源一致。 | -| 请求返回 401 或 403 | 检查 Bearer 请求头和认证配置。 | -| 没有回复 | 用 `bub run "Say hello"` 验证模型配置,并查看后端日志。 | -| 工具调用后没有继续回复 | 检查前端是否返回工具结果并继续对话。 | -| 运行返回 `RUN_ERROR` | 查看事件中的错误信息和后端日志。 | +| 提示找不到 `ag-ui` 子命令 | 确认当前终端的 Python 环境与安装插件的环境一致,再运行 `bub ag-ui --help` | +| 浏览器请求报 CORS 或网络错误 | 使用代理时检查前端代理配置;浏览器直连时检查 `BUB_AG_UI_ORIGINS` 是否与地址栏的协议、域名、端口完全一致 | +| 请求返回 `401` 或 `403` | 检查请求头 `Authorization: Bearer ` 是否与后端 `BUB_AG_UI_TOKEN` 一致 | +| 发送消息后无回复 | 先在终端运行 `bub run "Say hello"` 验证模型配置,并查看 `bub ag-ui` 终端日志 | +| 浏览器工具执行后无后续回复 | 检查前端工具函数是否正常返回结果,并确认前端框架在拿到结果后继续推进了对话 | +| 前端收到 `RUN_ERROR` 事件 | 查看事件的 `message` 字段及后端终端日志 | diff --git a/website/src/content/docs/zh-cn/docs/integrations/agent-plugins.mdx b/website/src/content/docs/zh-cn/docs/integrations/agent-plugins.mdx index 2bae9780..fd15706b 100644 --- a/website/src/content/docs/zh-cn/docs/integrations/agent-plugins.mdx +++ b/website/src/content/docs/zh-cn/docs/integrations/agent-plugins.mdx @@ -1,37 +1,39 @@ --- title: 使用 Agent Plugins -description: 加载与管理遵循开放规范的 Agent Plugins 扩展包,开箱即用打包的技能与 MCP 工具。 +description: 在 Bub 中加载遵循开放规范的便携式 Agent Plugins 扩展包,与原生插件协同复用打包的技能(Skills)与 MCP 服务器。 sidebar: badge: { text: '应用', variant: 'note' } --- import { FileTree, Steps } from '@astrojs/starlight/components'; -[Agent Plugins](https://agent-plugins.org/specification) 是一种跨平台的 Agent 扩展包规范。它采用纯声明式的目录结构,将提示词技能(Skills)和外部工具(MCP 服务器)打包在一起,无需编写或修改任何 Python 代码,即可实现即插即用和跨项目复用。 +[Agent Plugins](https://agent-plugins.org/specification) 是跨平台的声明式 Agent 扩展包规范,支持将提示词技能(`skills/`)和 MCP 服务器(`mcp.json`)打包在同一个目录中,无需编写或修改任何 Python 代码,即可即插即用、跨项目复用。 + +安装 [`bub-agent-plugins`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-agent-plugins) 插件后,Bub 会自动扫描并加载遵循该规范的扩展包。 ```mermaid flowchart TD subgraph Plugin ["Agent Plugin 扩展包"] - PJ["plugin.json (包元数据)"] - SK["skills/ (Prompt 技能集合)"] - MC["mcp.json (专有 MCP 服务器)"] + PJ["plugin.json(清单)"] + SK["skills/(技能集合)"] + MC["mcp.json(MCP 服务器)"] end Bub["Bub Agent"] Bub -->|"自动扫描加载"| Plugin - SK -->|"注册提示词"| Bub + SK -->|"注册技能"| Bub MC -->|"独立渠道挂载"| Bub ``` -[bub-agent-plugins](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-agent-plugins) 插件让 Bub 原生支持这一规范,自动识别并加载插件包中的技能与工具。 +## 快速接入 {#get-started} -## 如何接入 {#get-started} +下面我们会创建一个包含笔记总结技能与时间服务的扩展包。其中的验证命令会直接调用技能和工具,无需提前配置模型 API Key。 -开始前,请先[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install),并确保系统中安装了 [`uvx`](https://docs.astral.sh/uv/)。 +开始前请确认已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install),且系统中已安装 [`uvx`](https://docs.astral.sh/uv/)。 -1. **安装接入插件** +1. **安装插件** ```bash bub install bub-mcp@main bub-agent-plugins@main @@ -39,31 +41,31 @@ flowchart TD ``` :::note - `bub-agent-plugins` 依赖 `bub-mcp` 提供底层工具生命周期支持,即使你当前只打算使用插件包中的技能,也请一并安装。 + `bub-agent-plugins` 依赖 `bub-mcp` 管理 MCP 连接生命周期,即使只使用扩展包中的技能也需一并安装。 ::: - 执行 `bub hooks` 检查输出,确认在 `load_state` 和 `provide_channels` 挂载列表中均出现了 `agent-plugins`。 + 运行 `bub hooks`,确认 `load_state` 和 `provide_channels` 中均包含 `agent-plugins`。 -2. **创建标准插件包** +2. **创建扩展包目录** - 在当前项目工作区根目录下创建如下目录结构: + 在工作区下创建 `.agents/plugins/portable-notes/`: - .agents/ - plugins/ - portable-notes/ - - plugin.json + - **plugin.json** - skills/ - plugin-summary/ - - SKILL.md - - mcp.json + - **SKILL.md** + - **mcp.json** - 编写清单文件 `plugin.json`: + 创建清单文件 `plugin.json`(`$schema` 和 `name` 为必填,`name` 必须与所在目录名一致): - ```json + ```json title=".agents/plugins/portable-notes/plugin.json" { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "portable-notes", @@ -72,22 +74,22 @@ flowchart TD } ``` - 编写技能文件 `skills/plugin-summary/SKILL.md`: + 创建技能文件 `skills/plugin-summary/SKILL.md`: - ```markdown + ```markdown title=".agents/plugins/portable-notes/skills/plugin-summary/SKILL.md" --- name: plugin-summary - description: 快速总结会议或工作笔记,提取决策项和待办动作。 + description: 总结会议或工作笔记,提取决策项和待办动作。 --- 阅读用户提供的笔记内容: - 1. 列出所有已经做出的关键决策; - 2. 列出后续待办动作,并注明具体责任人(若无明确人选,标记为「待指派」)。 + 1. 列出已做出的关键决策; + 2. 列出后续待办动作及负责人(未指定负责人时标为「待指派」)。 ``` - 编写工具文件 `mcp.json`: + 创建 MCP 配置文件 `mcp.json`(必须包含 `$schema`,且每个服务必须显式声明 `type`:`stdio`、`streamable-http` 或 `sse`): - ```json + ```json title=".agents/plugins/portable-notes/mcp.json" { "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", "mcpServers": { @@ -102,58 +104,58 @@ flowchart TD 3. **验证技能加载** - 在当前工作区运行 Bub 内置命令: + 在当前工作区下运行内置命令: ```bash bub --workspace . run ',skill' bub --workspace . run ',skill name=plugin-summary' ``` - - 第一条命令将列出当前工作区可用的全部技能,其中应包含 `plugin-summary`。 - - 第二条命令将打印出该技能的具体提示词内容和来源路径。由于技能本质是静态提示词注入,不需要常驻后台服务,因此可以通过 `bub run` 直接调用。 + 第一条命令应列出 `plugin-summary`,第二条命令会打印技能路径与正文(技能无需后台长连接,可通过 `bub run` 直接查看)。 -4. **验证并调用插件内的 MCP 工具** +4. **验证插件内的 MCP 工具** - 由于插件包内的 MCP 工具需要建立后台通道通信,请启动交互界面: + 由于扩展包内的 MCP 工具需要后台长连接,启动 `bub chat`(会自动开启 `agent-plugins.mcp` 渠道): ```bash bub --workspace . chat ``` - 服务就绪后,直接在聊天窗口中测试插件工具(注意工具名称带插件名作为命名空间): + 服务就绪后,直接调用插件中的时间工具(工具名包含插件名作为前缀): ```text ,mcp.portable-notes.time_get_current_time timezone=UTC ``` - 也可以让配置好的大模型直接基于笔记执行总结或调用时间: + 首次启动时 `uvx` 可能需要短暂下载服务包;若提示工具未找到,可查看启动日志待注册完成后重试。 + + 配置好 [模型](/zh-cn/docs/app/configure/) 后,也可以直接在对话中同时使用技能与工具: ```text - 请使用 $plugin-summary 技能总结今天的任务,并帮我查一下当前的时间。 + 请使用 $plugin-summary 技能总结今天的任务,并查一下当前 UTC 时间。 ``` -## 与全局 MCP 协同 {#with-mcp} +## 与全局 MCP 并存 {#with-mcp} -Agent Plugins 内部声明的 MCP 服务与全局配置 `~/.bub/mcp.json` 是相互隔离的,双方拥有独立的作用域和生命周期通道: +Agent Plugins 内的 MCP 服务与全局 `~/.bub/mcp.json` 相互隔离: -| 配置来源 | 配置文件路径 | 生命周期渠道 | 工具命名格式 | +| 来源 | 配置文件 | 生命周期渠道 | 工具名称格式 | |---|---|---|---| -| 全局独立配置 | `~/.bub/mcp.json` | `mcp.lifecycle` | `mcp._` | -| Agent Plugin 内部 | `/mcp.json` | `agent-plugins.mcp` | `mcp.._` | +| 全局配置 | `~/.bub/mcp.json` | `mcp.lifecycle` | `mcp._` | +| Agent Plugin | `/mcp.json` | `agent-plugins.mcp` | `mcp.._` | -这意味着你可以在两个配置中同时声明名为 `time` 的服务,而绝不会产生命名冲突。 -`bub mcp list` / `add` 仅用于管理全局配置;插件内部的服务会在插件加载时由 `agent-plugins.mcp` 自动维系。 +两边可以同时定义同名服务(如 `time`)而不会冲突。注意 `bub mcp list` / `add` / `remove` 仅管理全局 `~/.bub/mcp.json`。 -## 配置发现路径 {#discovery-paths} +## 配置扫描路径与开关 {#discovery-paths} -Bub 默认会自动扫描以下两处目录的直接子文件夹: -1. **工作区目录**:`/.agents/plugins/`(针对当前项目生效) -2. **用户根目录**:`~/.agents/plugins/`(对本机所有 Bub 任务生效) +Bub 默认自动扫描以下两个目录的直接子目录: +1. **工作区目录**:`/.agents/plugins/` +2. **用户全局目录**:`~/.agents/plugins/` -如果需要加载系统其他目录下的插件,或需要单独开关某些功能,可以在 `~/.bub/config.yml` 中进行配置: +如需自定义扫描路径或单独开关组件,可在 `~/.bub/config.yml` 中配置: -```yaml +```yaml title="~/.bub/config.yml" agent-plugins: paths: - /opt/shared-agent-plugins/dev-tools @@ -163,21 +165,39 @@ agent-plugins: data_root: ~/.bub/agent-plugins ``` -| 配置字段 | 默认值 | 说明 | +| 字段 | 默认值 | 说明 | |---|---|---| -| `paths` | `[]` | 显式指定插件根目录列表(相对路径基于当前工作区)。 | -| `auto_discover` | `true` | 是否自动扫描默认目录;设为 `false` 后仅加载 `paths` 中显式指定的插件。 | -| `skills_enabled` | `true` | 是否加载插件包内的技能(Skills)。 | -| `mcp_enabled` | `true` | 是否启动插件包内的 MCP 服务器。 | -| `data_root` | `~/.bub/agent-plugins` | 插件运行时持久化数据的根存储路径。 | +| `paths` | `[]` | 显式指定的插件目录列表(每个目录直接包含 `plugin.json`;相对路径基于当前工作区) | +| `auto_discover` | `true` | 是否扫描默认的 `.agents/plugins` 目录;设为 `false` 时仅加载 `paths` | +| `skills_enabled` | `true` | 是否加载扩展包内的技能 | +| `mcp_enabled` | `true` | 是否启动扩展包内的 MCP 服务器 | +| `data_root` | `~/.bub/agent-plugins` | 扩展包持久化数据的存储根目录 | + +**优先级**:`paths` 显式路径 > 工作区目录 > 用户全局目录(同名插件以最先扫描到的有效包为准;工作区自身 `.agents/skills/` 下的技能始终优先于扩展包内的同名技能)。 + +环境变量使用 `BUB_AGENT_PLUGINS_` 前缀(列表使用 JSON 字符串): + +```bash +export BUB_AGENT_PLUGINS_PATHS='["/opt/shared-agent-plugins/dev-tools"]' +export BUB_AGENT_PLUGINS_AUTO_DISCOVER=false +``` + +启动 `stdio` 类型的 MCP 子进程时,Bub 会将默认工作目录设为该插件根目录,并注入 `PLUGIN_ROOT`(插件根目录绝对路径)和 `PLUGIN_DATA`(`data_root` 下对应该插件的数据目录)环境变量。`mcp.json` 的 `args`、`env` 值和 `cwd` 中也支持使用 `${PLUGIN_ROOT}` 与 `${PLUGIN_DATA}` 插值: + +```json +{ + "command": "python", + "args": ["${PLUGIN_ROOT}/server.py"] +} +``` -**优先级规则**:`paths` 中显式指定的插件 > 工作区目录插件 > 用户全局目录插件。若遇到同名清单插件,以最先扫描到的为准。 +下载或更新扩展包后,重启 Bub 即可加载最新内容。 ## 故障排查 {#troubleshooting} -| 常见问题 | 排查方法 | 解决办法 | -| --- | --- | --- | -| 无法识别 `plugin-summary` 技能 | 检查 `plugin.json` 中的 `name` 是否与插件目录名一致 | 规范要求目录名与 `name` 严格相同;确认执行命令时携带了 `--workspace .`。 | -| 提示 `mcp....` 工具未找到 | `bub-mcp` 未安装,或运行在 `bub run` 下 | 确认已执行 `bub install bub-mcp@main`,并在长会话模式 `bub chat` 下测试工具。 | -| stdio 工具报路径找不到错误 | 插件依赖环境与系统环境脱节 | 在 `mcp.json` 的 `command` 中使用系统的绝对路径,或确保依赖命令在系统的全局 `PATH` 中。 | -| 同名技能冲突 | 工作区定义了与插件同名的技能 | 工作区自身的技能(`skills/`)始终优先于插件内的同名技能。若想使用插件版本,重命名本地技能。 | +| 现象 | 排查与解决方法 | +| --- | --- | +| `bub hooks` 中无 `agent-plugins` | 确认已在当前环境中执行 `bub install bub-mcp@main bub-agent-plugins@main` | +| 未发现 `plugin-summary` 技能 | 检查 `plugin.json` 中的 `name` 是否与插件目录名一致,以及技能的 `name` 是否与技能子目录名一致 | +| 提示 `mcp....` 工具不存在 | MCP 工具需后台长连接,请使用 `bub chat` 或 `bub gateway`(`bub run` 不启动后台渠道) | +| 同名技能未生效 | 工作区 `.agents/skills/` 下的同名技能优先级更高,请重命名冲突技能 | diff --git a/website/src/content/docs/zh-cn/docs/integrations/local-models.mdx b/website/src/content/docs/zh-cn/docs/integrations/local-models.mdx index 21352cc4..5b4b258d 100644 --- a/website/src/content/docs/zh-cn/docs/integrations/local-models.mdx +++ b/website/src/content/docs/zh-cn/docs/integrations/local-models.mdx @@ -1,60 +1,51 @@ --- title: 接入本地 llama.cpp 模型 -description: 启动本地 llama.cpp 服务,通过标准的 OpenAI 兼容端点由本地 GGUF 大模型驱动 Bub Agent。 +description: 使用 Docker 启动本地 llama.cpp(llama-server)服务,通过 OpenAI 兼容接口驱动 Bub Agent 并进行本地性能调优。 --- -在离线、私有化部署或保护数据隐私的场景中,你可以在本地运行开源大模型来驱动 Bub。 +在离线、私有化部署或数据隐私敏感的场景下,你可以在本地运行开源大模型来驱动 Bub。 -Bub 内置了标准的 OpenAI 兼容提供商(Provider),这意味着只要本地推理引擎提供 `/v1/chat/completions` 接口(例如 `llama.cpp`、`vLLM` 或 `Ollama`),Bub 就能像调用云端模型一样无缝调用本地模型。 +Bub 内置了标准的 OpenAI 兼容提供商,只要本地推理服务提供 `/v1/chat/completions` 接口(例如 `llama.cpp`、`vLLM` 或 `Ollama`),Bub 就能像调用云端模型一样无缝调用本地模型。 ```mermaid flowchart LR Bub["Bub Agent"] OpenAI["OpenAI 兼容层"] - LocalServer["本地推理服务 (如 llama.cpp)"] - Model["GGUF 模型\n(CPU / GPU 推理)"] + LocalServer["本地推理服务(如 llama.cpp)"] + Model["GGUF 模型\n(CPU / GPU)"] Bub --> OpenAI OpenAI -->|"HTTP"| LocalServer LocalServer --> Model ``` -本指南以 `llama.cpp` 结合优秀的开源模型 [`ggml-org/gemma-4-E2B-it-GGUF`](https://huggingface.co/ggml-org/gemma-4-E2B-it-GGUF)(Q8 量化版本)为例进行演示。 +下面以 `llama.cpp` 搭配 [`ggml-org/gemma-4-E2B-it-GGUF`](https://huggingface.co/ggml-org/gemma-4-E2B-it-GGUF)(Q8 量化版)为例。 -:::tip[本地模型的选型] - -Agent 依赖多轮工具调用与长上下文推理: - -- 对于轻量测试,4B 左右的模型可以验证基本的会话连通性。 -- 如果需要稳定可靠的工具调用与代码生成能力,推荐选用 7B/8B 以上并在指令与工具上微调过的模型(例如 `Qwen2.5-Coder-7B-Instruct` 或 `Llama-3.1-8B-Instruct`)。 +:::tip[本地模型选型建议] +- **连通性测试**:4B 左右的小模型可验证基础对话。 +- **多步工具调用与编码**:建议选用 7B/8B 以上且支持 Tool Calling 的指令微调模型(如 `Qwen2.5-Coder-7B-Instruct` 或 `Llama-3.1-8B-Instruct`)。 ::: ## 开始之前 {#before-you-start} -- 已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install)。 -- 已安装 Docker,并确认 Docker 守护进程正常运行。 -- 本机建议预留至少 8 GB 可用内存(Q8 量化模型文件约需 5 GB,还需预留上下文 KV Cache 空间)。 -- 下载 GGUF 模型文件到本地目录 `~/.cache/llama.cpp/`: +- 已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install)与 Docker。 +- 预留至少 8 GB 可用内存(Q8 模型文件约 5 GB,另需 KV Cache 内存)。 +- 将 GGUF 模型文件下载到 `~/.cache/llama.cpp/`: ```text ~/.cache/llama.cpp/ggml-org_gemma-4-E2B-it-GGUF_gemma-4-E2B-it-Q8_0.gguf ~/.cache/llama.cpp/ggml-org_gemma-4-E2B-it-GGUF_mmproj-gemma-4-E2B-it-Q8_0.gguf ``` -*(其中 `mmproj` 为多模态视觉投影模型;如果仅处理纯文本交互,可以不下载该文件。)* +*(`mmproj` 为多模态视觉投影文件;若仅需纯文本对话,可不下载该文件并在启动命令中去掉 `--mmproj` 参数。)* ## 1. 启动 llama-server {#start-server} -为了保证本地服务接口的安全性,建议生成一个随机 API Key: +生成一个本地 API Key 并通过 Docker 启动 `llama.cpp` 服务: ```bash export LLAMA_API_KEY="local-$(openssl rand -hex 8)" -echo "生成的本地密钥: $LLAMA_API_KEY" -``` -使用 Docker 启动 `llama.cpp` 服务容器: - -```bash docker run --rm -it \ -p 127.0.0.1:8080:8080 \ -v "$HOME/.cache/llama.cpp:/models:ro" \ @@ -67,24 +58,18 @@ docker run --rm -it \ --mmproj /models/ggml-org_gemma-4-E2B-it-GGUF_mmproj-gemma-4-E2B-it-Q8_0.gguf ``` -**关键参数说明**: -- `-p 127.0.0.1:8080:8080`:仅绑定宿主机本地回环地址,避免暴露给局域网其他机器。 -- `--alias`:定义在 `/v1/chat/completions` 中请求的模型别名。 -- 当终端打印出 `server is listening on http://0.0.0.0:8080` 时,表明模型已成功载入内存。 +- `-p 127.0.0.1:8080:8080`:仅绑定本机回环地址,防止暴露到局域网; +- `--alias`:指定请求 `/v1/chat/completions` 时使用的模型名称; +- 终端输出 `server is listening on http://0.0.0.0:8080` 即表示就绪。 -## 2. 验证服务端点 {#verify-endpoint} +## 2. 验证本地端点 {#verify-endpoint} -在另一个终端窗口中,使用 `curl` 验证本地服务是否已经就绪: +在另一个终端窗口中,用 `curl` 验证本地服务是否已经就绪: ```bash -# 验证模型列表 curl -sS http://127.0.0.1:8080/v1/models \ -H "Authorization: Bearer $LLAMA_API_KEY" -``` - -测试一次最简单的对话补全请求: -```bash curl -sS http://127.0.0.1:8080/v1/chat/completions \ -H "Authorization: Bearer $LLAMA_API_KEY" \ -H "Content-Type: application/json" \ @@ -95,11 +80,11 @@ curl -sS http://127.0.0.1:8080/v1/chat/completions \ }' ``` -若返回带有 `choices[0].message.content` 的 JSON 数据,说明本地 OpenAI 兼容服务运行完全正常。 +返回包含 `choices[0].message.content` 的 JSON 即说明服务正常。 -## 3. 配置 Bub {#configure-bub} +## 3. 配置并运行 Bub {#configure-bub} -设置 Bub 的环境变量,让它把针对 OpenAI 提供商的请求重定向到本地端点: +将 Bub 的 OpenAI 提供商地址指向本地服务: ```bash export BUB_OPENAI_API_BASE="http://127.0.0.1:8080/v1" @@ -107,9 +92,8 @@ export BUB_OPENAI_API_KEY="$LLAMA_API_KEY" export BUB_MODEL="openai:gemma-4-E2B-it" ``` -:::note[使用其他推理框架(如 Ollama)] - -如果你习惯使用 [Ollama](https://ollama.com/),只需启动 Ollama 后将环境变量指向其兼容接口即可(无需自定义 API Key): +:::note[接入 Ollama] +如果你习惯使用 [Ollama](https://ollama.com/),只需启动 Ollama 并将环境变量指向其默认端口 `11434` 即可(无需自定义 API Key): ```bash export BUB_OPENAI_API_BASE="http://127.0.0.1:11434/v1" export BUB_OPENAI_API_KEY="ollama" @@ -117,46 +101,46 @@ export BUB_MODEL="openai:qwen2.5-coder:7b" ``` ::: -运行一次 Bub 任务进行端到端验证: +运行一次 Bub 任务做端到端验证: ```bash -bub run "用一句话介绍你自己,表明你来自本地模型。" +bub run "用一句话介绍你自己,表明你运行在本地模型上。" ``` -观察终端输出,如果开头显示 `[cli:local]` 且打印出模型回复,说明链路已全线贯通! +查看终端输出:如果看到 `[cli:local]` 开头并正常打印出模型的自我介绍,就说明 Bub 已经成功连上你的本地模型了。 -## 4. 性能调优 {#tune} +## 4. 性能调优参数 {#tune} -Agent 的工作流对上下文窗口和内存有特定要求,可根据你的硬件配置在启动命令中优化以下参数: +Agent 工作流对上下文窗口和内存有特定要求,可根据你的硬件配置在启动命令中调整以下参数: -| 调优目标 | 具体措施 | 原因与效果 | +| 目标 | 参数调整 | 说明 | | --- | --- | --- | -| **扩大上下文窗口** | 增加 `--ctx-size 8192` 或更大 | Agent 的系统提示词、工具定义以及 Tape 历史较长,默认 2048 容易超出上下文。 | -| **减少内存占用** | 改用 `Q4_K_M` 量化版本的 GGUF | 显存/内存占用减半,推理速度显著加快,精度损失极小。 | -| **GPU 硬件加速** | 挂载 GPU 并添加 `--n-gpu-layers 33` | 将计算层卸载到显存中,推理速度提升数倍至数十倍。 | -| **纯文本加速** | 去除 `--mmproj` 参数与对应镜像映射 | 省去图像模态初始化开销,降低系统内存占用。 | +| **扩大上下文窗口** | 添加 `--ctx-size 8192`(或更大) | Agent 的系统提示词、工具 Schema 和历史较长,默认 2048 容易溢出 | +| **降低内存占用** | 换用 `Q4_K_M` 量化模型 | 内存/显存占用约减半,推理更快 | +| **GPU 加速** | 挂载 GPU 并添加 `--n-gpu-layers 33` | 将计算层卸载至显卡显存 | +| **纯文本模式** | 移除 `--mmproj` 参数 | 节省视觉投影模型的内存开销 | :::caution -不要无限制盲目调大 `--ctx-size`。KV Cache 消耗的内存与上下文长度成正比,请确保留出足够的物理内存,防止系统触发 OOM。 +不要盲目调大 `--ctx-size`。KV Cache 消耗的内存与上下文长度成正比,请留出足够的物理内存,避免系统触发 OOM。 ::: ## 故障排查 {#troubleshooting} -| 常见问题 | 可能原因 | 解决办法 | +| 现象 | 可能原因 | 解决方法 | | --- | --- | --- | -| `curl` 返回 `401 Unauthorized` | 请求头中的 API Key 与容器启动时不一致 | 确认 `LLAMA_API_KEY` 变量值,或检查 `docker run` 中的 `--api-key`。 | -| 模型报错找不到或返回 404 | 请求中的模型别名与服务不匹配 | 检查 `BUB_MODEL` 后的名称是否与启动容器时的 `--alias` 完全一致。 | -| 无法调用工具或直接输出乱码 | 模型尺寸过小或未经 Function Calling 微调 | 换用 7B/8B 以上具备工具调用微调的模型(如 Qwen2.5-Coder、Llama-3.1)。 | -| 启动容器或推理时服务崩溃退出 | 物理内存或显存不足导致 OOM | 降低 `--ctx-size`,或换用更小量化等级(如 `Q4_K_M`)的模型文件。 | +| 返回 `401 Unauthorized` | API Key 不一致 | 确认客户端与容器启动终端中的 `LLAMA_API_KEY` 一致 | +| 模型报 404 或找不到 | 模型别名不匹配 | 确认 `BUB_MODEL=openai:` 与 `--alias` 参数一致 | +| 无法调用工具或输出格式错乱 | 模型过小或不支持 Tool Calling | 换用 7B/8B 以上支持工具调用的模型 | +| 推理时容器崩溃退出 | 内存或显存不足(OOM) | 调小 `--ctx-size` 或换用 `Q4_K_M` 量化模型 | -## 清理 {#cleanup} +## 清理环境 {#cleanup} -测试完成后,在运行 Docker 容器的终端按 `Ctrl+C` 停止容器,并清除当前终端的环境变量覆盖: +测试完成后,在运行 Docker 容器的终端按 `Ctrl+C` 停止容器,并清理当前终端的环境变量: ```bash unset BUB_API_BASE BUB_API_KEY BUB_OPENAI_API_BASE BUB_OPENAI_API_KEY BUB_MODEL LLAMA_API_KEY ``` :::note -清除环境变量后,Bub 将恢复使用默认的云端模型配置。之前测试生成的 Tape 会话历史依然保留在 Bub 数据目录中。 +清除环境变量后,Bub 会自动恢复使用默认的云端模型配置。之前测试生成的 Tape 会话历史依然保留在 Bub 数据目录中。 ::: diff --git a/website/src/content/docs/zh-cn/docs/integrations/mcp.mdx b/website/src/content/docs/zh-cn/docs/integrations/mcp.mdx index 5dcedb6f..d00698f1 100644 --- a/website/src/content/docs/zh-cn/docs/integrations/mcp.mdx +++ b/website/src/content/docs/zh-cn/docs/integrations/mcp.mdx @@ -1,38 +1,38 @@ --- title: 接入 MCP 服务器 -description: 安装 bub-mcp 插件,配置 stdio 或 HTTP/SSE 类型的 MCP 服务器,并在 Bub 对话中调用外部工具。 +description: 安装 bub-mcp 插件,配置 stdio 或 HTTP/SSE MCP 服务器,并在 Bub 中调用外部工具。 sidebar: badge: { text: '应用', variant: 'note' } --- import { Steps } from '@astrojs/starlight/components'; -[Model Context Protocol](https://modelcontextprotocol.io/),即 **MCP**,是一种让 Agent 安全、标准化地调用本地或远程的外部工具与数据源的开放协议。 +[Model Context Protocol](https://modelcontextprotocol.io/)(MCP)是让 Agent 安全、标准化地调用本地或远程外部工具与数据源的开放协议。 -通过安装 [bub-mcp](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp) 插件,你可以将整个 MCP 生态中的工具无缝接入 Bub 应用。 +通过安装 [`bub-mcp`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp) 插件,你可以将整个 MCP 生态中的工具无缝接入 Bub 应用。 ```mermaid flowchart LR User["用户 / 客户端"] --> Bub["Bub Agent 运行时"] Bub --> Plugin["bub-mcp 插件"] - Plugin -->|"stdio (子进程)"| LocalServer["本地 MCP Server\n(如: filesystem / time)"] - Plugin -->|"HTTP / SSE (远程)"| RemoteServer["远程 MCP Server\n(如: 企业 API / 数据库)"] + Plugin -->|"stdio(子进程)"| LocalServer["本地 MCP Server\n(如 filesystem / time)"] + Plugin -->|"HTTP / SSE(远程)"| RemoteServer["远程 MCP Server\n(如企业 API / 数据库)"] ``` -## 如何接入 {#get-started} +## 快速接入 {#get-started} -开始前,请确保已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install),且系统中已安装 [`uvx`](https://docs.astral.sh/uv/)(用于免安装启动示例工具)。 +开始前请确认已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install),且系统中已安装 [`uvx`](https://docs.astral.sh/uv/)(用于免安装启动示例工具)。 -1. **安装插件并验证环境** +1. **安装插件并验证** ```bash bub install bub-mcp@main bub hooks ``` - `bub install` 会从 [`bub-contrib`](https://github.com/bubbuild/bub-contrib) 解析安装 `bub-mcp`。执行 `bub hooks` 检查插件是否已正确挂载: + `bub install` 会从 [`bub-contrib`](https://github.com/bubbuild/bub-contrib) 解析并安装 `bub-mcp`。确认 `bub hooks` 输出中包含 `mcp`: ```text load_state: builtin, mcp @@ -41,12 +41,12 @@ flowchart LR ``` :::note - 如果列表中没有出现 `mcp`,说明插件安装到了其他 Python 环境。请确认当前运行的 `bub` 路径(可通过 `command -v bub` 查看)与安装环境一致。 + 若未出现 `mcp`,请运行 `command -v bub` 确认当前 `bub` 所在的 Python 环境与安装插件的环境一致。 ::: 2. **配置 MCP 服务器** - `bub-mcp` 会默认读取 `~/.bub/mcp.json`(若定义了 `BUB_HOME`,则读取 `$BUB_HOME/mcp.json`)。这里以官方时间工具 [`mcp-server-time`](https://pypi.org/project/mcp-server-time/) 为例: + `bub-mcp` 默认读取 `~/.bub/mcp.json`(若设置了 `BUB_HOME`,则读取 `$BUB_HOME/mcp.json`)。以下配置官方时间服务 [`mcp-server-time`](https://pypi.org/project/mcp-server-time/): ```bash mkdir -p ~/.bub @@ -62,12 +62,9 @@ flowchart LR EOF ``` - 填写说明: + 配置中包含 `command` 时自动使用本地 `stdio` 子进程传输,无需显式指定 `transport`。 - - 对于本地命令行服务(stdio),只需填写 `command` 和可选的 `args` / `env`。 - - 带有 `command` 的配置会自动采用 stdio 传输,无需显式声明 `transport`。 - -3. **测试连接与工具发现** +3. **检查连接与工具列表** 运行 `bub mcp list` 检查配置是否生效: @@ -75,7 +72,7 @@ flowchart LR bub mcp list ``` - 正常情况下,输出将显示连接就绪并列出发现的工具: + 连接正常时会列出发现的工具: ```text 🔌 MCP Tools @@ -84,29 +81,27 @@ flowchart LR Tools: mcp.time_get_current_time, mcp.time_convert_time ``` - 注意: - - - 每个 MCP 工具都会以 `mcp._` 命名并注入 Bub。 - - 为了节约提示词 token,Bub 默认采用**延迟加载**策略(模型在需要时通过 `tool.describe` 获取详细模式)。如果希望完整模式直接进入系统提示词,可设置环境变量 `BUB_MCP_DEFERRED_TOOLS=false`。 + - MCP 工具统一以 `mcp._` 命名。 + - 为节省上下文,MCP 工具默认启用**延迟加载**(模型按需调用 `tool.describe` 获取完整参数定义);如需将全部 Schema 直接注入系统提示词,可设置 `BUB_MCP_DEFERRED_TOOLS=false`。 -4. **在会话中调用工具** +4. **在会话中调用** - MCP 工具由后台生命周期渠道 `mcp.lifecycle` 维持长连接。因此,请使用长连接模式运行: + MCP 连接由后台服务 `mcp.lifecycle` 维持,请使用长会话模式启动: ```bash bub chat ``` - 在交互界面中直接提问: + 直接提问: ```text 现在 UTC 时间是多少? ``` - 模型会自动推断并触发 `mcp.time_get_current_time` 工具完成应答。 + 模型会自动推断并调用 `mcp.time_get_current_time` 工具来回答。 - :::tip[无需模型的直接测试] - 如果你想直接测试工具连通性,可以跳过模型推理,在 `bub chat` 中使用前导逗号直接执行工具命令: + :::tip[跳过模型直接测试工具] + 如果你想直接测试工具连通性,可以跳过模型推理,在 `bub chat` 中使用逗号前缀直接调用: ```text ,mcp.time_get_current_time timezone=UTC ``` @@ -114,13 +109,13 @@ flowchart LR -## 添加其他服务器 {#add-servers} +## 配置更多服务器 {#add-servers} -在 `~/.bub/mcp.json` 的 `mcpServers` 字典中可以追加多个服务。 +你可以在 `~/.bub/mcp.json` 的 `mcpServers` 中追加多个服务。 -### 远程服务 (HTTP/SSE) {#remote-http-sse} +### 远程服务(HTTP / SSE) {#remote-http-sse} -如果工具作为微服务运行在远程服务器或本地容器中,使用 `url` 和 `transport` 进行配置: +如果工具作为微服务运行在远程服务器或容器中,使用 `url`、`transport` 和可选的 `headers` 进行配置: ```json title="~/.bub/mcp.json" { @@ -140,9 +135,9 @@ flowchart LR } ``` -### 本地服务 (文件系统) {#local-filesystem} +### 本地文件系统服务 {#local-filesystem} -对于有权限限制的本地工具,可通过 `args` 限制其操作目录范围: +对于有权限限制的本地工具,可通过 `args` 限制其可访问的目录范围: ```json title="~/.bub/mcp.json" { @@ -155,38 +150,38 @@ flowchart LR } ``` -### 命令行管理 {#manage-cli} +### 使用 CLI 管理配置 {#manage-cli} -除了直接编辑 JSON 文件,也可以直接使用 `bub mcp` 命令行工具快速注册或删除: +除了直接编辑 JSON 文件,也可以用 `bub mcp` 命令行工具快速添加或移除服务器: ```bash -# 注册 stdio 本地工具 +# 添加本地 stdio 服务 bub mcp add --transport stdio time -- uvx mcp-server-time bub mcp add --transport stdio --env API_KEY=secret custom -- node ./my-server.js -# 注册远程 HTTP 或 SSE 服务(带认证 Header) +# 添加远程 HTTP 或 SSE 服务 bub mcp add --transport http weather https://weather.example.com/mcp bub mcp add --transport sse --header "Authorization: Bearer token" events https://events.example.com/mcp -# 移除指定服务 +# 移除服务 bub mcp remove time ``` -## 与 Agent Plugins 一起使用 {#with-agent-plugins} +## 与 Agent Plugins 并存 {#with-agent-plugins} -Bub 同样支持标准的 [Agent Plugins](/zh-cn/docs/integrations/agent-plugins/)。两者中的 MCP 服务器分别拥有独立的生命周期渠道与工具命名空间,可以同时无缝运行: +全局 MCP 配置与 [Agent Plugins](/zh-cn/docs/integrations/agent-plugins/) 内的 MCP 配置拥有独立的后台渠道与工具命名前缀,可同时使用: -| 来源 | 配置文件 | 运行渠道 | 工具名称前缀 | +| 来源 | 配置文件 | 生命周期渠道 | 工具名称格式 | |---|---|---|---| | 全局 MCP | `~/.bub/mcp.json` | `mcp.lifecycle` | `mcp._` | | Agent Plugin | `/mcp.json` | `agent-plugins.mcp` | `mcp.._` | ## 故障排查 {#troubleshooting} -| 常见现象 | 可能原因 | 解决办法 | +| 现象 | 可能原因 | 解决方法 | | --- | --- | --- | -| `bub hooks` 中无 `mcp` | 插件未装入当前运行的 Python 环境 | 运行 `command -v bub`,确认当前执行环境后重新执行 `bub install bub-mcp@main`。 | -| `bub mcp list` 显示 `Status: Disconnected` | 外部服务未启动或命令无法执行 | 独立在终端运行 `uvx mcp-server-time` 或用 `curl` 访问 `url`,确认其是否正常响应。 | -| `bub run "..."` 中无法调用 MCP 工具 | `bub run` 是单次执行任务,不启动后台生命周期渠道 | 长期运行请使用 `bub chat` 或 `bub gateway`;如需一次性调用,请在交互中使用 `,mcp.`。 | -| `bub mcp add` 保存时打印 `CancelledError` | 进程提前退出,但配置通常已持久化 | 执行 `bub mcp list` 确认条目是否已写入 `mcp.json`。 | -| 提示 `Permission denied` 无法写入配置 | `~/.bub/` 目录所有者权限不匹配 | 检查 `~/.bub` 目录权限,或设置 `BUB_HOME` 指向当前用户拥有写权限的路径。 | +| `bub hooks` 中无 `mcp` | 插件未安装到当前 Python 环境 | 检查 `command -v bub`,在对应环境中重新执行 `bub install bub-mcp@main` | +| `bub mcp list` 显示 `Disconnected` | 外部命令执行失败或远程地址不可达 | 在终端单独运行 `uvx mcp-server-time` 或 `curl` 目标 URL 排查报错 | +| `bub run "..."` 中无法使用 MCP 工具 | `bub run` 不启动 `mcp.lifecycle` 后台服务 | 改用 `bub chat` 或 `bub gateway` | +| `bub mcp add` 退出时打印 `CancelledError` | 子进程关闭时的清理日志,配置通常已写入 | 运行 `bub mcp list` 确认是否已保存 | +| 写入配置时报 `Permission denied` | `~/.bub/` 目录无写权限 | 修复 `~/.bub` 目录权限,或设置 `BUB_HOME` 指向可写目录 | diff --git a/website/src/content/docs/zh-cn/docs/integrations/observability.mdx b/website/src/content/docs/zh-cn/docs/integrations/observability.mdx index 1cc35a2f..16b75b61 100644 --- a/website/src/content/docs/zh-cn/docs/integrations/observability.mdx +++ b/website/src/content/docs/zh-cn/docs/integrations/observability.mdx @@ -1,39 +1,35 @@ --- title: 可观测性 -description: 检查会话 Tape 上下文,并将模型推理与工具调用 Traces 导出至 Phoenix 或 Logfire。 +description: 查看会话 Tape 统计指标,并通过 OpenTelemetry 将调用链导出至 Arize Phoenix 或 Pydantic Logfire。 --- -Bub 的可观测性遵循「**双轨并行**」原则: -- **状态内省(Tape)**:检查 Agent **记住了什么**、上下文窗口消耗趋势以及提示词缓存命中率(原生支持,无需外部组件)。 -- **运行遥测(Traces)**:追踪每一轮对话 **具体怎么执行**、模型与工具的耗时瓶颈以及错误调用堆栈(通过 OpenTelemetry 导出到外部 APM)。 +Bub 提供了两条互补的途径来观察和排查 Agent 的运行情况: + +- **检查会话 Tape**(内置):查看当前会话记录了多少条目、最近一次模型调用的 Token 消耗与提示词缓存命中率,并检索历史事件——无需安装任何外部组件。 +- **导出 OpenTelemetry 调用链**:追踪每次模型调用与工具执行的细分耗时和异常堆栈,导出到 Arize Phoenix、Pydantic Logfire 等平台。 ```mermaid flowchart LR Turn["Bub Agent"] - Tape["Tape\n(原生上下文持久化)"] - OTEL["OpenTelemetry SDK\n(OTLP 协议导出)"] - Platform["可观测性平台\n(Arize Phoenix / Logfire / 生产 APM)"] + Tape["Tape\n(内置会话记录)"] + OTEL["OpenTelemetry SDK\n(OTLP 导出)"] + Platform["可观测性平台\n(Phoenix / Logfire / APM)"] - Turn -->|"记录会话历史"| Tape - Turn -->|"上报调用 Trace"| OTEL + Turn -->|"记录对话与工具历史"| Tape + Turn -->|"上报 Trace"| OTEL OTEL --> Platform ``` -## 开始之前 {#before-you-start} - -- 已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install),并正确配置模型。 -- 若在本地测试 Phoenix,需确保已安装 Docker 或 Podman。 - -## 检查 Tape {#inspect-tape} +## 检查会话 Tape {#inspect-tape} -Tape 是 Bub 内置的会话记录机制。无需任何配置,你可以直接使用内置指令查看当前会话的健康状况: +Tape 是 Bub 内置的会话记录机制。无需任何配置,直接运行内置命令就能查看当前会话的健康状况: ```bash bub run "你有哪些工具?各自适合做什么?" bub run ",tape.info" ``` -预期终端输出类似: +输出示例: ```text name: becda04eb9f7369c__065943a03cbe6395 @@ -45,111 +41,100 @@ last_token_usage: 7458 last_token_cache_hit_rate: 72.50% ``` -![展示 Bub task run 之后 tape.info 输出的终端截图](/docs/observability/tape-info.png) +![tape.info 终端输出截图](/docs/observability/tape-info.png) -### 核心指标解读 {#core-metrics} +### 指标说明 {#core-metrics} -| 字段 | 含义与排查意义 | +| 字段 | 含义 | |---|---| -| `entries` | 会话中记录的事件总数(含输入、输出、工具调用)。 | -| `anchors` / `last_anchor` | 历史 anchor 数量及最新上下文边界,决定模型调用的上下文起点。 | -| `entries_since_last_anchor` | 自上个 anchor 以来的新条目数;数值过高时建议通过交接(handoff)移动上下文起点。 | -| `last_token_usage` | 最近一次大模型调用的 Token 总消耗量。 | -| `last_token_cache_hit_rate` | 提示词缓存(Prompt Cache)命中率。命中率高代表响应更快且成本更低。 | +| `entries` | 会话记录的条目总数(含对话消息、工具往返与事件) | +| `anchors` / `last_anchor` | 历史 anchor 总数与最近一个 anchor 名称(默认模型上下文的读取起点) | +| `entries_since_last_anchor` | 自最近一个 anchor 以来的新条目数;过高时可执行 `tape.handoff` 前移起点 | +| `last_token_usage` | 最近一次模型调用的 Token 总消耗量 | +| `last_token_cache_hit_rate` | 最近一次模型调用的提示词缓存(Prompt Cache)命中率 | -### 快速检索历史事件 {#search-events} +### 检索历史事件 {#search-events} -当需要排查工具调用是否成功或查找特定步骤时,无需手动翻看完整日志,使用 `,tape.search`: +当需要确认某次工具调用是否成功或定位特定步骤时,无需手动翻看完整日志,直接用 `,tape.search` 按关键词检索即可: ```bash -# 检索包含循环步骤或工具调用的事件 bub run ",tape.search query=loop.step" ``` -## 导出调用链 {#export-traces} +## 导出 OpenTelemetry 调用链 {#export-traces} -当需要分析大模型延迟、工具执行耗时与异常报错时,可通过 OpenTelemetry(OTLP)将调用链导出到专业的分析面板。 +当需要分析模型延迟、工具执行耗时与异常堆栈时,可通过 OpenTelemetry(OTLP)将调用链导出到专业分析面板。 -### Arize Phoenix(本地部署) {#arize-phoenix} +### Arize Phoenix(本地 Docker) {#arize-phoenix} -[Arize Phoenix](https://github.com/Arize-ai/phoenix) 是一款出色的开源 AI 遥测工具,通过 Docker 一键即可启动: +1. 启动本地 [Arize Phoenix](https://github.com/Arize-ai/phoenix) 容器(Web 控制台位于 `http://localhost:6006`): -```bash -docker run --rm --name bub-phoenix \ - -p 6006:6006 \ - arizephoenix/phoenix:latest -``` + ```bash + docker run --rm --name bub-phoenix -p 6006:6006 arizephoenix/phoenix:latest + ``` -启动后可在浏览器打开控制台界面:`http://localhost:6006`。 +2. 在 Bub 环境中安装 `trace` 可选依赖: -在 Bub 所在的环境中安装追踪依赖包: + ```bash + # 项目或虚拟环境安装 + uv add "bub[app,trace]" -```bash -# 源码安装 -uv sync --extra app --extra trace + # 或在 Bub 源码仓库中同步 + uv sync --extra app --extra trace + ``` -# 或发行版安装 -uv add "bub[app,trace]" -``` +3. 设置 OTLP 环境变量并运行任务: -配置标准的 OpenTelemetry 环境变量并运行任务: + ```bash + export OTEL_SERVICE_NAME=bub + export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:6006/v1/traces + export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf -```bash -export OTEL_SERVICE_NAME=bub -export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:6006/v1/traces -export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf + bub run "请使用工具列出当前工作区的文件。" + ``` -bub run "请使用工具列出当前工作区的文件。" -``` +刷新 `http://localhost:6006` 的 Default 项目,即可查看包含模型调用(`chat `)与工具执行(`execute_tool `)的调用瀑布流: -运行完成后,刷新 Phoenix 控制台界面,进入 Default 项目,你将看到完整的调用瀑布流,清晰展现每一次模型调用(`chat `)与工具执行(`execute_tool `)的细分耗时: - -![展示 Bub GenAI 遥测通过 OTLP 导出到 Phoenix 的截图](/docs/observability/phoenix-otel.png) +![Phoenix OTLP 调用链截图](/docs/observability/phoenix-otel.png) ### Pydantic Logfire {#pydantic-logfire} -如果你不想在本地维护 Docker 容器,可以使用 [Pydantic Logfire](https://logfire.pydantic.dev/): +如果你不想在本地维护 Docker 容器,可以直接使用托管的 [Pydantic Logfire](https://logfire.pydantic.dev/): ```bash -# 清除显式 OTLP 端点(让 Logfire 自动接管) +# 清除自定义 OTLP 端点,让 Logfire SDK 接管 unset OTEL_EXPORTER_OTLP_TRACES_ENDPOINT OTEL_EXPORTER_OTLP_ENDPOINT -# 安装 logfire 依赖 uv add "bub[logfire]" - -# 登录并绑定项目 logfire auth logfire projects use -# 运行任务 bub run "检查这个仓库并总结它的目录结构。" ``` 登录 Logfire Web 控制台,在 Agents 页面下即可实时查看 Bub 的运行调用栈与子 Agent 链路。 -### Python 代码配置 {#python-config} +### 在 Python SDK 中启用 {#python-config} -如果你正在通过 Python SDK 复用 Bub,也可以在程序初始化时显式启动遥测: +如果你正在通过 Python SDK 复用 Bub,也可以在程序初始化时调用 `configure_otlp()` 显式开启遥测(自动读取 `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` 等标准环境变量): ```python from bub.tracing import configure_otlp -# 自动读取 OTEL_EXPORTER_OTLP_TRACES_ENDPOINT 等标准环境变量 configure_otlp() ``` ## 故障排查 {#troubleshooting} -| 常见问题 | 可能原因 | 解决办法 | +| 现象 | 可能原因 | 解决方法 | | --- | --- | --- | -| Phoenix 界面中看不到任何 Trace | OTLP 协议或端点配置有误 | 确认 `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` 带有 `/v1/traces`,且协议为 `http/protobuf`。 | -| 终端提示找不到 `opentelemetry` 依赖 | 缺少 `trace` 可选依赖 | 执行 `uv sync --extra app --extra trace` 或 `pip install "bub[app,trace]"`。 | -| Logfire 无法上报数据 | 未登录或未清除 OTLP 变量 | 显式 `unset OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`,并运行 `logfire auth` 重新授权。 | -| `,tape.info` 提示无活跃 Tape | 当前工作区或会话未运行过任务 | 先执行任意一条 `bub run "..."` 命令生成会话记录。 | +| Phoenix 中无 Trace 数据 | 端点路径或协议不匹配 | 确认 `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` 以 `/v1/traces` 结尾,且协议为 `http/protobuf` | +| 报缺少 `opentelemetry` 模块 | 未安装 `trace` 可选依赖 | 运行 `uv add "bub[app,trace]"` 或 `pip install "bub[app,trace]"` | +| Logfire 未收到数据 | 环境变量冲突或未授权 | 执行 `unset OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` 并重新运行 `logfire auth` | -## 清理 {#cleanup} +## 清理测试环境 {#cleanup} -停止并移除本地测试用的 Phoenix 容器: +测试完成后,停止并移除本地 Phoenix 容器并清理环境变量: ```bash docker rm -f bub-phoenix diff --git a/website/src/content/docs/zh-cn/docs/integrations/reuse-app.mdx b/website/src/content/docs/zh-cn/docs/integrations/reuse-app.mdx index 97323c50..fcbdc4af 100644 --- a/website/src/content/docs/zh-cn/docs/integrations/reuse-app.mdx +++ b/website/src/content/docs/zh-cn/docs/integrations/reuse-app.mdx @@ -1,47 +1,49 @@ --- title: 复用 Bub 应用 -description: 按所有权选择复用层级:工具、Agent hooks、BubAgent 模型流或完整 Turn。 +description: 在 Python 服务中按需复用 Bub 应用层能力:从单个插件工具、Agent 循环 Hooks、BubAgent 流,到完整的消息 Turn。 sidebar: - badge: { text: 'SDK', variant: 'note' } + badge: { text: 'SDK', variant: 'tip' } --- -把 Bub 嵌入现有服务时,最重要的不是“哪个入口功能最多”,而是**哪些组装和生命周期仍由宿主负责**。你可以只拿一个工具,也可以让 Bub 处理完整消息 Turn。 +如果你想把 Bub 嵌入自己现有的 Python 服务,除了直接使用微内核 [`bub.core.Agent`](/zh-cn/docs/sdk/) 之外,还可以按需复用 Bub 应用层已经做好的能力——包括配置加载、技能发现、插件 Hooks、内置工具以及完整的 Turn 消息处理流程。 -本页的应用层入口需要 [`app` 可选依赖](/zh-cn/docs/getting-started/install/#app-install),并配置可用模型凭据(例如 `REPUBLIC_OPENAI_API_KEY`): +选择哪个入口,取决于**你希望让 Bub 接管多少流程,以及哪些生命周期仍由你的宿主程序自己掌控**。 + +本页涉及的应用层接口需安装 [`app` 可选依赖](/zh-cn/docs/getting-started/install/#app-install)并配置模型凭据(如 `REPUBLIC_OPENAI_API_KEY`): ```bash uv add "bub[app]" ``` -如果只需要模型循环、工具和 Tape,从[核心 SDK](/zh-cn/docs/sdk/)开始即可。 +如果你只需要纯粹的「模型—工具—Tape」核心循环,不需要应用层的配置、技能或插件,直接从[核心 SDK](/zh-cn/docs/sdk/) 开始即可。 -## 先选择复用层级 {#choose-a-reuse-layer} +## 选择复用层级 {#choose-a-reuse-layer} -| 需要复用的能力 | 入口 | 宿主仍负责 | -| --- | --- | --- | -| 一个工具实现 | 导入公开工具,传给 `core.Agent` | 模型、Tape、Run 与资源生命周期 | -| 插件的 Agent 循环 hooks | `AgentPlugins.attach()` | 驱动 Run、入站与出站消息、同会话并发 | -| 应用配置、技能、工具策略和命令 | `BubAgent.run_stream()` | 消费与关闭流、回复投递、完整 Turn 状态、同会话并发 | -| 从入站消息到出站结果的完整 Turn | `BubFramework.process_inbound()` | 服务生命周期、模型配置、异常、并发,以及未委托渠道的投递 | -| 现成的命令行或网关 | `bub run` / `bub chat` / `bub gateway`,或自定义入口点 | 配置、凭据、部署与扩展,不再编写应用循环 | +Bub 提供了从完整到轻量的五种复用入口。它们是并列关系而非强制升级路径,建议从能满足你需求的最小层级开始: -这些是并列入口,不是必须逐级升级的流程。从能满足需求的最小层级开始。 +| 需要复用的能力 | 推荐入口 | 宿主程序负责的部分 | +| --- | --- | --- | +| **整套 CLI 或常驻网关** | `bub run` / `bub chat` / `bub gateway` 或自定义命令入口 | 提供配置、密钥与部署环境;无需编写 Python 调用循环 | +| **完整的消息 Turn**(从收消息到生成回复) | `BubFramework.process_inbound()` | 服务生命周期、顶层异常捕获、同会话并发锁、自定义回复发送 | +| **应用配置、技能、工具白名单与命令**(自行消费事件流) | `BubAgent.run_stream()` | 消费并关闭流、发送回复、跨 Turn 状态保存、同会话并发锁 | +| **为 `core.Agent` 接入插件的循环 Hooks** | `AgentPlugins.attach()` | 驱动 `agent.run()`、处理入站与出站消息、同会话并发锁 | +| **仅复用单个工具函数** | 直接导入工具并传给 `core.Agent(tools=[...])` | 管理模型连接、Tape 存储、Run 循环与所有资源生命周期 | :::note -安装一个插件包不等于每个入口都会执行它的全部能力。工具和 Agent hooks 可以被较低层级复用;渠道、CLI 和完整消息管道只有在相应运行时中才会执行。插件还可能依赖其他 hooks、状态字段或后台服务,应以其文档为准。 +安装插件包后,不同层级的入口只会激活该层级对应的扩展点。例如,`AgentPlugins` 和 `BubAgent` 可复用插件提供的工具和 Agent 循环 Hooks;但插件注册的消息渠道、CLI 子命令或外围 Turn 阶段 Hooks,只有在 `BubFramework` 或 `bub gateway` 中才会运行。 ::: -## 推荐起点:执行完整 Turn {#run-a-complete-turn} +## 执行完整 Turn:`BubFramework.process_inbound()` {#run-a-complete-turn} -`process_inbound()` 适合希望 Bub 负责会话解析、初始提示词、模型阶段、状态保存和出站消息组装的宿主。 +如果你希望 Bub 替你把「解析会话 ID、构造提示词、调用模型与工具、保存状态、组装出站回复」全套流程都跑完,最省心的入口是 `BubFramework.process_inbound()`。 -创建 `embedded.py`: +将以下代码保存为 `embedded.py`: -```python title="embedded.py" +```python title="embedded.py" {12-17} import asyncio from bub import BubFramework @@ -75,21 +77,22 @@ if __name__ == "__main__": uv run python embedded.py ``` -`load_hooks()` 在启动时调用一次,加载内置实现和已安装插件。`framework.running()` 持有插件生命周期、Tape 存储和 `SteeringInbox` 等资源,应覆盖整个嵌入服务的运行期,而不是每个请求进入一次。 +使用要点: -`process_inbound()` 返回完整的 `TurnResult`,不是事件迭代器。本例不绑定发送渠道,因此宿主读取 `result.outbounds` 并自行投递。如果安装了会发送消息的 `dispatch_outbound` 插件,要避免插件与宿主重复投递。 - -设置 `stream_output=True` 会选择并消费流式模型路径,完成后仍返回 `TurnResult`。绑定 Router 时可以用 `wrap_stream()` 包装事件流;**不绑定 Router 也能使用 `stream_output=True`**。 +- **启动时调用一次 `load_hooks()`**:加载内置实现与当前环境中安装的所有插件。 +- **`framework.running()` 覆盖整个服务周期**:该上下文管理器持有插件生命周期资源、Tape 存储和 `SteeringInbox`。在 Web 服务中,应在服务启动/关闭(如 FastAPI 的 `lifespan`)时进出,不要每次请求重复进出。 +- **从 `result.outbounds` 读取回复**:`process_inbound()` 返回汇总后的 `TurnResult`。若安装了会在 `dispatch_outbound` 阶段主动发消息的渠道插件,请注意避免宿主程序与插件重复发送。 +- **启用流式模型阶段**:传入 `stream_output=True` 会改走流式 `run_model_stream` 并在内部消费完毕后返回 `TurnResult`(绑定了 `ChannelRouter` 时还可通过 `wrap_stream()` 实时转发增量事件;不绑定 Router 也可正常使用 `stream_output=True`)。 -## 只复用模型阶段:BubAgent.run_stream {#model-stage} +## 只复用模型阶段:`BubAgent.run_stream()` {#model-stage} -需要 Bub 的配置、技能、工具策略和命令,但希望自己处理事件流时,使用 `BubAgent.run_stream()`。 +如果你既想使用应用层的配置、技能发现、工具限制和逗号命令,又希望自己用 `async for` 消费流式事件(例如通过 SSE 推给前端),可直接调用 `BubAgent.run_stream()`。 -`run_stream()` 返回 `AsyncStreamEvents`。它没有异步上下文管理器协议,应使用 `contextlib.aclosing()` 保证提前退出和异常时也关闭: +`run_stream()` 返回 `AsyncStreamEvents` 异步迭代器(本身不是上下文管理器),**请务必配合 `contextlib.aclosing()` 使用**,确保提前退出或报错时底层流能正常关闭: -```python +```python collapse={1-7} {14-19,21} import asyncio import contextlib @@ -121,23 +124,25 @@ if __name__ == "__main__": asyncio.run(main()) ``` -在 `framework.running()` 内创建 `BubAgent`,它才能取得该作用域提供的存储。一个 Agent 可以跨会话复用;按 Turn 变化的工具、技能和状态应放在调用参数或 TurnState 中。 +请在 `async with framework.running():` 内部实例化 `BubAgent` 以获取活动存储,并在多个会话间复用同一个 `BubAgent` 实例。 -与完整 Turn 相比,这个直接入口: +与 `process_inbound()` 相比,`BubAgent.run_stream()` 的行为边界: -- 仍会解析会话 Tape、绑定运行时 Agent,并在 `state=None` 时通过 hooks 加载状态; -- 仍可执行直接命令; -- 不执行初始入站 `build_prompt`、`save_state`、出站渲染和分发; -- 不协调同会话并发; -- 不负责替你关闭流,第一个 `final` 也只表示一个 Step 结束。 +- **会执行**:将 `session_id` 解析为会话 Tape、绑定运行时 Agent、在 `state=None` 时自动调用 `load_state` Hooks,并支持执行逗号命令; +- **不执行**:跳过初始 `build_prompt`、结束时不调用 `save_state`、不执行 `render_outbound` 和 `dispatch_outbound`,也不对同 `session_id` 的并发请求加锁; +- **流消费约定**:需用 `aclosing()` 关闭流;`final` 事件仅代表单个 Step 结束,整个 `async for` 循环结束才代表整次运行完成。 -内置系统提示不会要求模型通过 channel skill 回复;`bub gateway` 和 `bub chat` 背后的渠道管理器会注册一个 `system_prompt` Hook,只在它运行的 Turn 中加入这条指令。自己调用 `process_inbound()` 的服务可以注册自己的 Hook,说明回复如何送达。整体替换 `agent.system_prompt` 也会移除插件、技能、延迟工具和 代码模式 的提示片段。 +:::tip[关于系统提示词] +默认系统提示词不会要求模型调用渠道技能(如 `telegram` 技能)回复;该指令仅由 `bub gateway` 和 `bub chat` 的 `ChannelManager` 动态注入。在你自己的服务中调用 `run_stream()` 或 `process_inbound()` 时,模型会直接输出文本。请勿直接覆盖 `agent.system_prompt` 属性,否则会抹掉插件、技能、延迟工具和代码模式注册的提示词片段。 +::: -### 按调用收窄工具和技能 {#narrow-tools-and-skills} +### 按请求限制可用工具与技能 {#narrow-tools-and-skills} + +调用 `BubAgent.run_stream()` 时,可通过 `allowed_tools` 和 `allowed_skills` 限制单次请求允许模型使用的工具与技能: -```python +```python collapse={1-12} ins={27-28} import asyncio import contextlib @@ -177,24 +182,26 @@ if __name__ == "__main__": asyncio.run(main()) ``` -| 参数 | `None` | 空集合 | +| 参数 | 传 `None`(默认) | 传空集合(`[]` 或 `set()`) | | --- | --- | --- | -| `allowed_tools` | 允许实例上的全部工具 | 不允许工具 | -| `allowed_skills` | 使用默认技能发现结果 | 禁用技能发现 | +| `allowed_tools` | 允许使用该 Agent 实例上的全部工具 | 本次请求禁用所有工具 | +| `allowed_skills` | 允许使用发现的全部技能 | 本次请求禁用所有技能 | -未知名称会抛出 `ValueError`。筛选覆盖模型直接调用和 代码模式,但逗号命令直接使用 Agent 实例的工具,不受 `allowed_tools` 限制;需要约束所有执行路径时,在 `before_tool_call` 中执行权限策略。 +传入未注册的工具名会抛出 `ValueError`。注意: -这些限制只有在宿主代码决定参数时才可靠。让模型自己生成子 Agent 的允许列表不构成安全边界。 - -显式传入 `state` 会跳过 `load_state` hooks。需要正常恢复会话又要增加请求元数据时,使用 `framework.build_state()` 构造状态,而不是用一个新字典替换全部状态。完整的 `_runtime_agent` 和状态形式见 [Python API](/zh-cn/docs/reference/python-api/#framework)。 +1. `allowed_tools` 仅限制模型调用和代码模式内的工具,**不限制逗号直接命令**(如 `,fs.read`)。如需拦截所有调用路径,请在 `before_tool_call` Hook 中校验权限。 +2. 只有由**宿主代码**指定 `allowed_tools` 时才构成可靠约束;在对话中由模型生成的 `subagent` 工具白名单不构成强制安全边界。 +3. 显式传入 `run_stream(state=...)` 会跳过 `load_state` Hooks。若需在正常加载状态的基础上添加自定义字段,请先调用 `await framework.build_state(message, session_id)`,再修改返回的字典(见 [Python API](/zh-cn/docs/reference/python-api/#framework))。 -## 只复用工具或 Agent hooks {#reuse-tools-or-hooks} +## 只复用工具或 Agent 循环 Hooks {#reuse-tools-or-hooks} + +### 1. 在 `core.Agent` 中直接复用插件工具 {#tool-implementations} -### 工具实现 {#tool-implementations} +如果你的项目使用的是核心层的 `bub.core.Agent`,但看中了某个 Bub 插件提供的工具函数,你可以直接导入该工具并传给 `Agent(tools=[...])`,完全不需要启动 `BubFramework`。 -已有 `core.Agent` 时,可以直接导入内置工具或插件提供的公开构造函数。下面用 `bub-web-search` 演示只复用搜索工具。先安装依赖并配置搜索与模型凭据: +下面以社区的 `bub-web-search` 插件为例,演示如何只提取它的 `web.search` 工具交给 `core.Agent` 使用。先安装依赖并设置环境变量: ```bash uv add "bub[app]" \ @@ -205,9 +212,9 @@ export BUB_SEARCH_JINA_API_KEY=jina_... export REPUBLIC_OPENAI_API_KEY=sk-... ``` -将下面脚本保存为 `search_agent.py`: +创建 `search_agent.py`: -```python title="search_agent.py" +```python title="search_agent.py" collapse={1-10} {13,19} import asyncio from pathlib import Path @@ -248,17 +255,17 @@ if __name__ == "__main__": asyncio.run(main()) ``` -运行 `uv run python search_agent.py` 会把会话记录到 `sessions/`。这里只复用了选中的搜索工具;模型、Tape、事件流和资源生命周期仍由宿主管理。更多插件说明见 [`bub-web-search`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-web-search)。 +运行 `uv run python search_agent.py` 即可看到搜索结果并把会话写入 `sessions/`。在这种方式下,你只拿走了插件里的工具对象,模型连接、Tape 存储和事件流消费均由宿主代码直接掌控。更多配置说明可参考 [`bub-web-search` 文档](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-web-search)。 -### Agent 循环 hooks {#agent-loop-hooks} +### 2. 用 `AgentPlugins` 将插件 Hooks 挂载到 `core.Agent` {#agent-loop-hooks} -`AgentPlugins` 把插件 hooks 接到核心 Agent 的事件、提示词、工具和运行状态上。这些机制分别建立在哪种数据之上,见 [Agent 事件:事件与其他扩展机制](/zh-cn/docs/concepts/events/#app-hooks)。 +如果你不仅想复用工具,还想在 `core.Agent` 上复用插件里的 `system_prompt`、`provide_tools`、`before_llm_call`、`before_tool_call` 等与 Agent 循环直接相关的 Hooks,可以使用 `AgentPlugins` 桥接器(事件映射关系见 [Hooks 参考](/zh-cn/docs/reference/hooks/#event-mapping))。 -下面的 `PlainTextPlugin` 是一个完整的最小插件示例。将代码保存为 `agent_hooks.py`,并确保已安装 `bub[app]`、配置 `REPUBLIC_OPENAI_API_KEY`: +将以下最小示例保存为 `agent_hooks.py`: -```python title="agent_hooks.py" wrap +```python title="agent_hooks.py" wrap collapse={1-10} {21-25} import asyncio import republic @@ -271,7 +278,7 @@ from bub.turn import TurnState class PlainTextPlugin: - """为 Agent 添加一条系统提示词。""" + """为 Agent 追加系统提示词。""" @hookimpl def system_prompt(self, prompt: str, state: TurnState) -> str: @@ -297,48 +304,43 @@ if __name__ == "__main__": asyncio.run(main()) ``` -示例中的 `PlainTextPlugin` 是最小的自定义插件:它通过 `system_prompt` Hook 为 Agent 增加提示词。`AgentPlugins(plugins=[...])` 只注册列出的插件,不会自动加载 Bub 内置 Hook 或已安装插件;需要它们时,创建 `BubFramework`、调用 `load_hooks()` 并将它传给 `AgentPlugins`。 - 运行示例:`uv run python agent_hooks.py`。 -`components()` 返回普通 kwargs 字典,不会自动解决重复参数。示例用字典合并显式覆盖 `store`;若直接同时传入同名关键字会抛出异常。 - -存储和 `SteeringInbox` 等资源只在 `plugins.running()` 内可用。先 `attach()`,再注册自己的事件处理器,后者才能观察 hooks 对事件的修改。 - -`attach()` 连接的是 Agent 循环,不会自动提供完整 Turn 的初始 `build_prompt`、`run_model` / `run_model_stream`、`save_state`、出站渲染与分发。steering 等特定路径仍可能调用 `build_prompt`,内置错误报告也可能调用 `dispatch_outbound`,所以插件宿主应阅读具体 hook 的执行时机。 - -例如,`bub-context-budget` 通过模型调用 hooks 提醒模型在上下文接近上限时调用 `tape.handoff`。接入时除了 `attach()`,还要把 `tape.handoff` 工具提供给 Agent;这个提醒本身不强制执行压缩。此例说明插件常有 `attach()` 以外的依赖,具体参数见 [`tape.handoff` 参考](/zh-cn/docs/reference/tools/#tape-handoff)。 +使用 `AgentPlugins` 时,请留意以下要点: -MCP 等需要常驻连接的插件还有独立生命周期;`attach()` 不能代替连接、启动和关闭。嵌入方式见 [`bub-mcp`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp#embedding)。 +- **显式插件列表 vs. 自动发现**:`AgentPlugins(plugins=[...])` 仅注册传入的插件,不加载内置 Hooks 或环境中安装的第三方插件。如需加载全部已安装插件,可先创建 `framework = BubFramework()` 并调用 `framework.load_hooks()`,再传入 `AgentPlugins(framework)`。 +- **合并 `components()`**:`plugins.components()` 返回插件提供的 `store`、`context` 和 `sidecars`。如需覆盖其中某项(如 `store`),请用 `{**plugins.components(), "store": ...}` 合并后再传给 `Agent()`。 +- **在 `plugins.running()` 内运行**:先调用 `plugins.attach(agent)`,再注册你自己的 `agent.events.on(...)` 处理器,以便观察到插件修改后的事件状态。 +- **仅覆盖循环阶段**:`attach()` 不会执行外围 Turn 的初始 `build_prompt`、`save_state`、出站渲染或渠道分发。此外,若插件依赖配套工具(如 `bub-context-budget` 需要 `tape.handoff` 工具)或长连接(如 [`bub-mcp`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp#embedding)),需一并提供对应组件。 - +## 绑定 `ChannelRouter` 接管渠道投递 {#bind-a-router} -## 需要渠道投递时绑定 Router {#bind-a-router} +如果你自己的宿主服务已经有了现成的消息返回逻辑(比如直接在 HTTP 响应里返回结果),读取 `TurnResult.outbounds` 就足够了,不需要配置 Router。 -宿主已有发送逻辑时,直接使用 `TurnResult.outbounds` 即可。需要 Bub 渠道负责出站和流包装时,实现并绑定 `ChannelRouter`: +只有在你希望让 Bub 渠道层接管出站投递与流式包装时,才需要实现 `ChannelRouter` 并调用 `framework.bind_channel_router(router)`: -- `dispatch_output()` 执行实际投递;返回 `False` 不会触发自动重试或备用投递,`process_inbound()` 仍返回渲染后的 `outbounds`。 -- `wrap_stream()` 必须返回异步可迭代对象,并保留希望 Bub 继续处理的模型事件;`model_output` 由包装后流中的文本增量聚合。 -- `admit_channel_message()` 属于 `ChannelManager` 的准入路径。直接调用 `process_inbound()` 不会自动执行准入或会话排队。 +- `dispatch_output()`:执行消息投递;返回 `False` 不会触发自动重试,`process_inbound()` 仍会返回 `outbounds`。 +- `wrap_stream()`:返回异步可迭代对象并透传模型事件(最终的 `model_output` 由包装后的流产出的文本增量拼接而成)。 +- `admit_channel_message()`:供 `ChannelManager` 消息准入路径调用;直接调用 `process_inbound()` 不会自动执行准入检查或排队。 -接口签名见 [Python API](/zh-cn/docs/reference/python-api/#framework) 与[渠道概念](/zh-cn/docs/concepts/turn/)。 +相关接口签名详见 [Python API](/zh-cn/docs/reference/python-api/#framework),生命周期概念见 [Turn](/zh-cn/docs/concepts/turn/)。 -## 生命周期、异常与并发清单 {#lifecycle-failure-concurrency} +## 嵌入服务自检清单 {#lifecycle-failure-concurrency} -无论选择哪个应用层入口,都应检查: +无论你选择了上面哪一种应用层入口,在将代码部署上线前,建议对照检查以下七个边界: -1. **启动一次**:`load_hooks()` 在服务组装阶段调用,不在每个请求中重复发现插件。 -2. **一个运行作用域**:同一 Framework 不要重叠进入多个 `running()`;`ChannelManager.listen_and_run()` 已会进入作用域,不要再套一层。 -3. **配置不是隔离沙箱**:不同 Framework 可以隔离插件集合,应用配置仍是进程级缓存。 -4. **异常由宿主接住**:`run_stream()` 的迭代和 `process_inbound()` 都可能抛错;完整 Turn 的错误钩子不会代替宿主异常处理。 -5. **同会话显式协调**:两个直接入口都不会按 `session_id` 自动串行化。使用宿主锁,或通过 ChannelManager 的 `follow_up` 准入策略排队。 -6. **关闭流**:正常消费到结束,提前退出时用 `aclosing()`;`temp/` 前缀会话不合并 Tape,普通会话关闭时默认合并,包括部分记录。 -7. **副作用不是事务**:后续模型失败、取消或丢弃 Tape 都不会回滚工具已经产生的外部副作用。 +1. **启动时只调一次 `load_hooks()`**:不要在每次请求时重复扫描插件。 +2. **共用单一 `running()` 作用域**:不要在同一个 `BubFramework` 上并发或嵌套进入 `running()`(`ChannelManager.listen_and_run()` 内部已包含 `running()`)。 +3. **配置为进程级缓存**:多个 `BubFramework` 实例可隔离插件集,但应用配置(`Settings`)在进程内全局缓存。 +4. **宿主程序捕获异常**:`run_stream()` 和 `process_inbound()` 报错均会向上抛出异常;`on_error` Hook 仅记录日志,不会吞掉异常。 +5. **同会话并发需显式加锁**:按 `session_id` 使用宿主侧互斥锁(如 `asyncio.Lock`),或通过 `ChannelManager` 的 `follow_up` 策略串行化。 +6. **确保关闭事件流**:可能提前退出的路径一律使用 `contextlib.aclosing()`。除 `temp/` 前缀会话外,普通会话在流关闭时默认会将已执行的记录合并回主 Tape。 +7. **外部副作用不自动回滚**:模型报错、取消或丢弃 Tape 分支不会撤销工具对文件、网络或外部数据库的修改。 -## 直接运行或发布命令行 {#run-or-publish-cli} +## 直接运行或封装 CLI {#run-or-publish-cli} -不需要嵌入代码时,直接使用 `bub run`、`bub chat` 或 `bub gateway`。需要自己的命令名时,在发行包中声明 `[project.scripts]` 调用 Bub 入口,并随包分发插件和技能;完整流程见[打包与分发](/zh-cn/docs/app/distribution/)。 +如果你的场景并不需要把 Bub 嵌进另一个 Python 服务,而是直接作为命令行或守护进程使用,直接运行 `bub run`、`bub chat` 或 `bub gateway` 即可。如果你想把它包装成带有自己品牌命令名(如 `my-bub`)的发行包,并把自定义插件和技能一起打包分发给团队,请参考[打包与分发](/zh-cn/docs/app/distribution/)。 diff --git a/website/src/content/docs/zh-cn/docs/integrations/storage.mdx b/website/src/content/docs/zh-cn/docs/integrations/storage.mdx index 0aca26ac..49b2b1ae 100644 --- a/website/src/content/docs/zh-cn/docs/integrations/storage.mdx +++ b/website/src/content/docs/zh-cn/docs/integrations/storage.mdx @@ -1,25 +1,16 @@ --- title: 使用数据库存储会话历史 -description: 通过 SQLAlchemy 存储插件,将 Bub 的 Tape 会话历史保存到 SQLite 或其他关系型数据库。 +description: 通过 bub-tapestore-sqlalchemy 插件将 Bub 的会话 Tape 存储到 SQLite、PostgreSQL 或 MySQL。 --- -Bub 默认采用本地 JSONL 文件持久化会话 Tape。 +Bub 应用默认将会话 Tape 保存为本地 `~/.bub/tapes/` 下的 JSONL 文件。 -通过安装 [`bub-tapestore-sqlalchemy`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-tapestore-sqlalchemy) 插件,可以让应用改用 SQLite、PostgreSQL 或任何支持 SQLAlchemy 的关系型数据库,同时保持 `,tape.info`、`,tape.search`、会话分支及 Sidecar 等行为完全一致。 +通过安装 [`bub-tapestore-sqlalchemy`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-tapestore-sqlalchemy) 插件,你可以将存储后端无缝切换为 SQLite、PostgreSQL 或任何支持 SQLAlchemy 的关系型数据库,同时保持 `,tape.info`、`,tape.search`、分支合并和 Sidecar 行为完全一致。 -:::caution[历史数据] -更换存储后端**不会**自动迁移现有的 JSONL 文件。切换到新数据库后,旧会话不会出现在新库的 `tape.search` 中,原文件依然保留在 Bub 目录的 `tapes/` 下。 +:::caution[旧数据不会自动迁移] +切换数据库后端**不会**自动导入已有的本地 JSONL 文件(原文件仍保留在 `~/.bub/tapes/` 下)。 ::: -## 开始之前 {#before-you-start} - -- 已[安装 Bub 应用](/zh-cn/docs/getting-started/install/#app-install),并正确配置模型。 -- (可选)安装 `sqlite3` 命令行工具,用于直接查询和检验数据表。 -- 确认当前 Bub 主目录路径: - ```bash - printf '%s\n' "${BUB_HOME:-$HOME/.bub}" - ``` - ## 1. 安装插件 {#install} 在运行 Bub 的环境中安装存储插件: @@ -29,44 +20,41 @@ bub install bub-tapestore-sqlalchemy@main bub hooks ``` -执行 `bub hooks` 检查扩展点挂载情况: +确认 `provide_tape_store` 输出中 `tapestore-sqlalchemy` 排在 `builtin` 之前: ```text provide_tape_store: tapestore-sqlalchemy, builtin ``` -列表中高优先级的实现在前。出现 `tapestore-sqlalchemy` 表示插件已生效,并将覆盖内置的文件存储。 +列表中高优先级的实现排在前面,看到 `tapestore-sqlalchemy` 即表示插件已生效并覆盖内置的文件存储。 -## 2. 配置数据库 {#configure} +## 2. 配置数据库连接 {#configure} -插件默认使用 `/tapes.db`。为了便于演示与验证,本指南将其指向当前工作目录: +插件默认使用 `/tapes.db`。可通过 `BUB_TAPESTORE_SQLALCHEMY_URL` 指定标准 SQLAlchemy 连接串(以下以当前目录下的 SQLite 文件为例): ```bash export BUB_TAPESTORE_SQLALCHEMY_URL="sqlite+pysqlite:///$PWD/bub-tapes.db" ``` -- `sqlite+pysqlite` 使用 Python 标准库内置的 SQLite 驱动,无额外依赖。 -- URL 需符合标准 SQLAlchemy 连接串规范;这里使用 `$PWD` 拼接为绝对路径。 - -### 可选配置项 {#optional-settings} +可选环境变量: | 环境变量 | 默认值 | 说明 | | --- | --- | --- | -| `BUB_TAPESTORE_SQLALCHEMY_ECHO` | `false` | 设为 `true` 可打印执行的 SQL 语句,用于开发调试。 | -| `BUB_TAPESTORE_SQLALCHEMY_CONNECT_ARGS` | `{}` | 传给 `create_engine(connect_args=...)` 的 JSON 对象(如超时设置)。 | +| `BUB_TAPESTORE_SQLALCHEMY_ECHO` | `false` | 设为 `true` 时打印执行的 SQL 语句 | +| `BUB_TAPESTORE_SQLALCHEMY_CONNECT_ARGS` | `{}` | 传给 `create_engine(connect_args=...)` 的 JSON 对象(如超时参数) | -如果需要持久生效,可将变量写入工作区根目录的 `.env` 文件。插件在首次连接时会自动初始化所需表结构。 +如果需要持久生效,可将环境变量写入工作区根目录的 `.env` 文件;首次连接时,插件会自动创建所需的数据库表。 -## 3. 验证写入与读取 {#verify} +## 3. 验证读写 {#verify} -运行一次会话,再通过内置指令检查 Tape 是否写入数据库: +运行一次对话并查看 Tape 状态: ```bash -bub run "用一句话打个招呼,表明这是通过数据库存储的一轮会话。" +bub run "用一句话打个招呼,验证数据库存储。" bub run ",tape.info" ``` -输出应包含本次会话的 Tape 名称、条目数量与 anchor 状态: +输出示例: ```text name: 86774b31b96845a4__0b871d5e50e7c192 @@ -76,76 +64,63 @@ last_anchor: session/start entries_since_last_anchor: 8 ``` -使用 `sqlite3` 检查数据库中的物理记录: - -```bash -# 查询 Tape 会话列表 -sqlite3 "$PWD/bub-tapes.db" \ - "SELECT name, last_entry_id FROM tapes ORDER BY name;" -``` +若安装了 `sqlite3` 命令行工具,可直接查询表记录: ```bash -# 查询anchor记录 -sqlite3 "$PWD/bub-tapes.db" \ - "SELECT entry_id, anchor_name, entry_date FROM tape_entries WHERE kind = 'anchor';" +sqlite3 "$PWD/bub-tapes.db" "SELECT name, last_entry_id FROM tapes ORDER BY name;" +sqlite3 "$PWD/bub-tapes.db" "SELECT entry_id, anchor_name, entry_date FROM tape_entries WHERE kind = 'anchor';" ``` -`tapes` 表维护所有会话的元数据;`tape_entries` 表按条目记录每一次 Turn、模型回答与工具调用的具体内容。 +其中 `tapes` 表维护所有会话的元数据,`tape_entries` 表按条目记录每次 Turn、模型回复与工具调用的具体内容。 -## 4. 接入其他数据库 {#other-databases} +## 4. 接入 PostgreSQL 等数据库 {#other-databases} -该插件基于 SQLAlchemy,支持连接 PostgreSQL、MySQL 等关系型数据库: - -1. **安装驱动**(在 `bub` 运行环境中安装对应数据库驱动): +1. **在 Bub 运行环境中安装对应数据库驱动**(以 PostgreSQL 为例): ```bash - # 以 PostgreSQL 为例 uv add "psycopg[binary]" ``` -2. **配置连接串**: +2. **设置连接串**: ```bash export BUB_TAPESTORE_SQLALCHEMY_URL="postgresql+psycopg://user:YOUR_DB_PASSWORD@localhost:5432/bub_db" ``` -生产环境中建议提前测试并发写入与连接池超时配置,保证服务稳定。 +生产环境中建议提前测试并发写入与连接池超时配置,以保证服务稳定。 -## 实现自己的存储后端 {#custom-store} +## 实现自定义存储后端 {#custom-store} -`core.Agent` 与内置应用只依赖存储协议,实现协议即可把它换成任意后端。需要区分「Tape 保存历史」与「TapeContext 投影上下文」时,见 [Tape 与模型上下文](/zh-cn/docs/concepts/tape/#history-and-context)。 +`core.Agent` 与内置应用只依赖存储协议,如需对接 Redis 或自有存储服务,实现协议即可无缝替换(需要区分「Tape 保存历史」与「TapeContext 投影上下文」时,见 [Tape 与模型上下文](/zh-cn/docs/concepts/tape/#history-and-context)): -| 协议 | 使用位置 | +| 协议 / Hook | 用途 | | --- | --- | -| `bub.core.store.TapeStore` | 同步实现,传给 `Agent(store=...)` | -| `bub.core.store.AsyncTapeStore` | 异步实现,推荐用于数据库与远程存储 | -| `provide_tape_store` | 应用层替换,内置应用默认返回 `FuzzyFileTapeStore` | +| `bub.core.store.TapeStore` | 同步存储协议,传给 `Agent(store=...)` | +| `bub.core.store.AsyncTapeStore` | 异步存储协议(推荐用于网络与数据库 I/O) | +| `provide_tape_store` | 应用层插件 Hook,替换内置的 `FuzzyFileTapeStore` | -完整方法签名见 [Python API](/zh-cn/docs/reference/python-api/#tape-store)。实现时至少要保证:按 Tape 名称隔离条目、保持追加顺序、支持 `reset()`,并能让 `TapeQuery` 的 anchor 过滤生效。分支由 `ForkTapeStore` 在现有存储之上构建,后端不需要自行实现。 +方法签名与实现契约见 [Python API:`TapeStore`](/zh-cn/docs/reference/python-api/#tape-store)。分支由 `ForkTapeStore` 在任意存储之上统一构建,后端不需要自行实现。 -## 内置应用的存储 {#app-storage} +## 内置应用的存储解析顺序 {#app-storage} -内置应用通过 `provide_tape_store` 提供 `FuzzyFileTapeStore`,默认目录为 `~/.bub/tapes/`。Tape 名称由工作区路径与会话 ID 共同生成,因此不同工作区中的同名会话不会共享历史。 +内置应用默认通过 `provide_tape_store` 提供 `FuzzyFileTapeStore`(保存在 `~/.bub/tapes/`),并根据「工作区路径 + 会话 ID」生成物理 Tape 名称,使不同工作区的同名会话互不干扰。 `BubAgent` 按以下顺序选择存储: -1. 显式传入的 `tape_store`; -2. 创建 Agent 时 `framework.get_tape_store()` 返回的存储; -3. 两者都没有时,使用内存存储。 - -需要使用 `framework.running()` 提供的存储时,在该作用域内创建 `BubAgent`。替换存储使用 `provide_tape_store`,替换投影策略使用 `build_tape_context`。 +1. 构造函数显式传入的 `tape_store`; +2. 实例化时 `framework.get_tape_store()` 返回的存储(需在 `async with framework.running():` 内实例化); +3. 内存存储 `InMemoryTapeStore`。 -内置应用会从 Tape 恢复模型、推理力度和 代码模式 等会话设置,其他应用状态需要显式持久化。 +内置应用会自动从 Tape 恢复会话级的模型选择、推理强度和代码模式开关;其他自定义应用状态可通过 `load_state` / `save_state` 显式持久化。 ## 故障排查 {#troubleshooting} -| 常见问题 | 可能原因 | 解决办法 | +| 现象 | 可能原因 | 解决方法 | | --- | --- | --- | -| `bub hooks` 中无 `tapestore-sqlalchemy` | 插件装到了其他 Python 环境 | 检查 `command -v bub`,确保在当前使用的虚拟环境中执行 `bub install`。 | -| 提示 SQLite 数据库被锁(Database is locked) | 多进程并发写入超过 SQLite 承受能力 | 配置 busy timeout 参数,或切换到 PostgreSQL 等更适合高并发的关系型数据库。 | -| 连接 PostgreSQL 提示 `ModuleNotFoundError` | 未安装对应数据库驱动 | 在 Bub 环境中执行 `uv add "psycopg[binary]"` 安装驱动。 | -| 无法创建数据表或权限拒绝 | 目标路径或远程数据库用户无建表权限 | 确认文件目录对当前用户可写,或授予数据库用户 `CREATE TABLE` 权限。 | +| `bub hooks` 中无 `tapestore-sqlalchemy` | 插件未装入当前 Python 环境 | 检查 `command -v bub`,在对应虚拟环境中执行 `bub install` | +| SQLite 报 `Database is locked` | 多进程高并发写入超出 SQLite 限制 | 在 `BUB_TAPESTORE_SQLALCHEMY_CONNECT_ARGS` 中调大 timeout,或换用 PostgreSQL | +| 报 `ModuleNotFoundError` | 缺少数据库驱动包 | 在 Bub 环境中安装对应驱动(如 `uv add "psycopg[binary]"`) | -## 清理 {#cleanup} +## 清理测试环境 {#cleanup} -如需还原为 Bub 默认的文件存储模式,清除环境变量并删除测试数据库即可: +如需切回 Bub 默认的本地文件存储,清除环境变量并删除测试数据库即可: ```bash unset BUB_TAPESTORE_SQLALCHEMY_URL BUB_TAPESTORE_SQLALCHEMY_ECHO BUB_TAPESTORE_SQLALCHEMY_CONNECT_ARGS diff --git a/website/src/content/docs/zh-cn/docs/migration/v0-6.mdx b/website/src/content/docs/zh-cn/docs/migration/v0-6.mdx index edebfab0..8056fe20 100644 --- a/website/src/content/docs/zh-cn/docs/migration/v0-6.mdx +++ b/website/src/content/docs/zh-cn/docs/migration/v0-6.mdx @@ -1,20 +1,18 @@ --- title: 升级到 0.6.0 -description: 0.6.0 内核与应用依赖分离的迁移说明。 +description: Bub 0.6.0 升级与迁移指南:了解核心内核(bub)与应用层(bub[app])依赖拆分,获取 pip/uv 更新命令与验证步骤。 --- import { Tabs, TabItem } from '@astrojs/starlight/components'; -0.6.0 之前版本的 `bub` 包含应用和内核两个部分;从 0.6.0 开始,安装 `bub` 时仅包含内核,而应用挪到了 `app` 可选依赖中。如果你需要使用 Bub 应用层的能力(如配置、插件、hooks、技能、消息渠道、网关等),请在安装时加上 `bub[app]`。 +自 0.6.0 起,`bub` 包拆分为核心层与应用层:默认安装 `bub` 仅包含核心层(`bub.core`);CLI、配置、插件、Hooks、技能、渠道和网关等应用层功能移入可选依赖 `bub[app]`。 -## 升级指南 {#upgrade-guide} +如需使用 Bub CLI 或应用层功能,请升级并安装 `bub[app]`。 -根据你当前的安装方式,选择下面的升级方法: +## 升级命令 {#upgrade-guide} - - -用 `uv tool` 安装的: + ```bash uv tool install --upgrade --force "bub[app]" @@ -23,8 +21,6 @@ uv tool install --upgrade --force "bub[app]" -在已经激活的虚拟环境里: - ```bash uv pip install --upgrade "bub[app]" ``` @@ -32,7 +28,7 @@ uv pip install --upgrade "bub[app]" -插件或发行版改 `pyproject.toml` 里的依赖: +插件或发行版请将依赖改为 `bub[app]`: ```toml title="pyproject.toml" ins="bub[app]" dependencies = ["bub[app]>=0.6.0"] @@ -41,6 +37,6 @@ dependencies = ["bub[app]>=0.6.0"] -## 升级验证 {#verify-upgrade} +## 验证升级 {#verify-upgrade} -升级完成后在去[终端](/zh-cn/docs/app/terminal/)命令行中输入 `bub --help`、快速开始一轮对话或再用 `bub hooks` 看插件加载情况。 +升级后运行 `bub --help` 或 `bub hooks` 确认 CLI 与插件加载正常。 diff --git a/website/src/content/docs/zh-cn/docs/reference/cli.mdx b/website/src/content/docs/zh-cn/docs/reference/cli.mdx index 65e8711f..7eec4782 100644 --- a/website/src/content/docs/zh-cn/docs/reference/cli.mdx +++ b/website/src/content/docs/zh-cn/docs/reference/cli.mdx @@ -1,9 +1,9 @@ --- title: CLI -description: bub 命令、参数、默认值、退出码和服务安装行为。 +description: Bub 命令行(CLI)完整参考:查阅 bub chat、bub run、bub gateway 等子命令、全局参数、默认值、退出码与后台服务安装。 --- -`bub` 由应用层提供,需要安装 `app` 可选依赖。本页只列内置命令;插件可以通过 `register_cli_commands` 增加命令。 +`bub` 命令行工具由应用层提供,需[安装](/zh-cn/docs/getting-started/install/#app-install) `bub[app]` 可选依赖。本页列出所有内置命令;第三方插件可通过 `register_cli_commands` Hook 注册额外子命令,实际可用命令以 `bub --help` 输出为准。 ## 全局选项 {#global-options} @@ -13,63 +13,81 @@ bub [OPTIONS] COMMAND [ARGS]... | 选项 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `--workspace`, `-w` | 路径 | 当前工作目录 | 设置工具工作目录、技能发现和相对路径解析的基准 | -| `--version`, `-V` | 开关 | — | 显示 Bub 版本并退出 | -| `--help` | 开关 | — | 显示帮助 | +| `--workspace`, `-w` | 路径 | 当前工作目录 | 设置 `BubFramework.workspace`(影响工具默认工作目录、技能发现与相对路径解析) | +| `--version`, `-V` | 开关 | — | 打印当前安装的 Bub 版本号并退出 | +| `--help` | 开关 | — | 显示帮助信息并退出 | -`--workspace` 不改变 `BUB_HOME` 或配置文件位置。 - -不带命令时执行 `BubFramework.default_command`,内置默认值为 `chat`。缺少 `app` 依赖时,进程打印缺失包和安装命令后以退出码 `1` 结束。 +- `--workspace` 不会改变 `BUB_HOME` 数据目录或 `~/.bub/config.yml` 配置文件的位置。 +- 不带子命令直接运行 `bub`(或 `bub -w PATH`)时,会执行 `BubFramework.default_command`(内置默认为 `chat`,即启动交互式终端会话)。 +- 若当前环境未安装 `app` 可选依赖,运行 `bub` 会打印缺失依赖与安装提示,并以退出码 `1` 退出。 ## `bub run` {#bub-run} -处理一条消息的完整 Turn,并将 `TurnResult.outbounds` 打印到 stdout;不启动渠道管理器。 +处理单条消息的完整 Turn(解析会话、构造提示词、调用模型与工具、保存状态并生成回复),将 `TurnResult.outbounds` 打印到标准输出后退出。不启动 `ChannelManager`。 ```text bub run [OPTIONS] MESSAGE ``` -| 参数与选项 | 类型 | 默认值 | 说明 | +| 参数 / 选项 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `MESSAGE` | 文本 | 必填 | 消息正文;以命令前缀开头时执行命令 | -| `--channel` | 文本 | `cli` | 入站渠道名 | -| `--chat-id` | 文本 | `local` | 入站聊天 ID | +| `MESSAGE` | 文本 | 必填 | 消息正文;以命令前缀(默认 `,`)开头时直接执行内部命令 | +| `--channel` | 文本 | `cli` | 入站消息渠道标识 | +| `--chat-id` | 文本 | `local` | 入站消息聊天 ID | | `--sender-id` | 文本 | `human` | 写入 `context.sender_id` | -| `--session-id` | 文本 | `:` | 覆盖会话 ID | +| `--session-id` | 文本 | `:` | 显式指定会话 ID(用于跨入口共享历史) | 输出格式: ```text [channel:chat_id] -<正文> +<回复正文> +``` + +示例: + +```bash +bub run "Summarize this repository." +bub run --channel web --chat-id demo "Continue the previous topic." +bub run --session-id shared:demo ",tape.info" ``` -- 不启动 `mcp.lifecycle`、`acp-server` 等渠道或后台服务。 -- 不自动发送回复到聊天平台。 -- 仍执行 `provide_tape_store`、`provide_lifespan` 和 `provide_steering_inbox` 的资源作用域。 -- 模型阶段使用非流式 `HookRuntime.run_model`。 +由于 `bub run` 不启动 `ChannelManager`: + +- **不启动常驻后台服务**:`mcp.lifecycle`、`acp-server` 和外部聊天渠道监听器不会启动; +- **不向外部平台发消息**:结果仅打印到终端 stdout; +- **仍初始化核心资源作用域**:`provide_tape_store`、`provide_lifespan` 和 `provide_steering_inbox` 会正常进入并在结束时清理; +- **使用非流式模型调用**:调用 `HookRuntime.run_model`。 + +注意:当模型阶段报错或未返回文本时,`bub run` 会记录错误日志并打印回退文本,进程仍可能以退出码 `0` 结束。在脚本中调用时,请同时检查 `stderr` 和输出内容,不要仅凭退出码判断模型调用是否成功。 ## `bub chat` {#bub-chat} -启动交互式 REPL,启用 `cli` 渠道并附加已启用的 `Lifecycle` 渠道。 +启动交互式终端会话(REPL),启用 `cli` 渠道,并自动启动所有已启用的 `Lifecycle` 后台服务(如 MCP 连接)。 ```text bub chat [OPTIONS] [INITIAL_PROMPT] ``` -| 参数与选项 | 类型 | 默认值 | 说明 | +| 参数 / 选项 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `INITIAL_PROMPT` | 文本 | — | REPL 启动后立即提交 | +| `INITIAL_PROMPT` | 文本 | — | 可选;进入 REPL 后立即自动发送的第一条消息 | | `--chat-id` | 文本 | `local` | CLI 聊天 ID | | `--session-id` | 文本 | `cli_session` | 会话 ID | -`chat` 强制流式输出并忽略 `BUB_STREAM_OUTPUT`。没有 `cli` 渠道时以退出码 `1` 结束。 +- `bub chat` 始终开启流式输出(忽略 `BUB_STREAM_OUTPUT`)。 +- 若插件移除了 `cli` 渠道,命令会报错并以退出码 `1` 退出。 +- 会话内命令前缀由 `BUB_COMMAND_PREFIX` 控制(默认 `,`),输入 `,help` 查看所有命令。 -REPL 命令前缀由 `BUB_COMMAND_PREFIX` 决定,默认为 `,`;`,help` 列出当前命令。 +```bash +bub chat +bub chat "What changed in this repository?" +bub chat --session-id shared:demo +``` ## `bub gateway` {#bub-gateway} -启动渠道管理器并常驻运行已启用的渠道。 +启动渠道管理器并常驻运行所有已启用的外部消息渠道(如 Telegram、飞书、Discord)。 ```text bub gateway [OPTIONS] @@ -77,46 +95,50 @@ bub gateway [OPTIONS] | 选项 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `--enable-channel` | 文本,可重复 | 读取 `BUB_ENABLED_CHANNELS` | 限定或排除渠道 | -| `--install` | 开关 | 关闭 | 安装并启动当前用户的后台服务 | -| `--uninstall` | 开关 | 关闭 | 停止并卸载后台服务 | +| `--enable-channel` | 文本(可重复) | 读取 `BUB_ENABLED_CHANNELS` | 指定要启用的渠道,或用 `!name` 排除某个渠道 | +| `--install` | 开关 | 关闭 | 将网关注册并启动为当前操作系统用户的后台服务 | +| `--uninstall` | 开关 | 关闭 | 停止并卸载已安装的后台网关服务 | -`--install` 与 `--uninstall` 互斥。命令行渠道选择优先于 `BUB_ENABLED_CHANNELS`。 +`--install` 与 `--uninstall` 互斥;命令行 `--enable-channel` 优先级高于 `BUB_ENABLED_CHANNELS`。 -### 渠道选择 {#channel-selection} +### 渠道选择规则 {#channel-selection} -`BUB_ENABLED_CHANNELS` 使用逗号分隔;`--enable-channel` 可以重复。 +`BUB_ENABLED_CHANNELS` 用逗号分隔多个渠道名;`--enable-channel` 可重复传入多次: -| `enabled_channels` | 结果 | +| 配置值 | 实际启动的渠道 | | --- | --- | -| `all` | 所有 `enabled` 且不属于 `Interface` 的渠道,减去 `!name` | -| 显式普通渠道 | 列表中 `enabled` 且未被排除的渠道 | -| 显式普通渠道 + Lifecycle | 先选择普通渠道,再附加所有已启用的 `Lifecycle` | -| 只有 Lifecycle | 只启动这些 Lifecycle | -| 只有 `!name` | 没有包含项,启动失败 | +| `all`(默认) | 所有 `enabled=True` 且不属于 `Interface` 的渠道与 `Lifecycle` 服务,减去 `!name` 排除项 | +| 显式指定普通渠道名 | 列表中 `enabled=True` 且未被排除的普通渠道,并自动附带所有已启用的 `Lifecycle` 服务 | +| 仅指定 `Lifecycle` 名称 | 仅启动指定的 `Lifecycle` 后台服务 | +| 仅有 `!name` 排除项 | 无任何包含项,报错退出(退出码 `1`) | -`Interface` 是需要显式选择的用户界面,例如 `cli`;`Lifecycle` 是后台服务,例如 `mcp.lifecycle`。没有可启用渠道时以退出码 `1` 结束。 +- `Interface` 是交互界面渠道(如 `cli`),需显式指定才会启动,`all` 模式下不启动; +- `Lifecycle` 是伴随网关运行的后台服务(如 `mcp.lifecycle`、`agent-plugins.mcp`); +- 最终无任何可启动渠道时,打印 `No channels are enabled...` 并以退出码 `1` 退出。 -Shell 中排除项应加引号,例如 `'!mcp.lifecycle'`。 +```bash +bub gateway +bub gateway --enable-channel telegram +bub gateway --enable-channel telegram --enable-channel discord +bub gateway --enable-channel telegram --enable-channel '!mcp.lifecycle' +``` -### 后台服务 {#gateway-service} +在 Shell 中使用 `!` 排除渠道时请加单引号(如 `'!mcp.lifecycle'`),防止被 Shell 展开。 -| 平台 | 安装方式 | 位置或行为 | -| --- | --- | --- | -| Linux | systemd 用户单元 | `${XDG_CONFIG_HOME:-~/.config}/systemd/user/bub-gateway.service` | -| Windows | 计划任务 | 任务名 `Bub Gateway`,当前用户登录时启动 | -| macOS | 不支持 `--install` | 使用 launchd、tmux 或[容器部署](/zh-cn/docs/app/deploy/) | +### 后台服务安装 {#gateway-service} -Linux 单元使用 `Restart=on-failure`、`RestartSec=5s` 和 `WantedBy=default.target`;安装时执行 `daemon-reload`、`enable` 和 `restart`。 +| 操作系统 | 安装方式 | 服务位置或行为 | +| --- | --- | --- | +| Linux | systemd 用户服务 | `${XDG_CONFIG_HOME:-~/.config}/systemd/user/bub-gateway.service`(失败自动重启) | +| Windows | Windows 计划任务 | 任务名 `Bub Gateway`,当前用户登录时自启,失败自动重启 | +| macOS | 不支持 `--install` | 请使用 `launchd`、`tmux` 或 [Docker 部署](/zh-cn/docs/app/deploy/) | -- 服务固定当前 Python 解释器、工作区和显式 `--enable-channel` 参数。 -- 重复安装会替换现有单元或任务并重启。 -- `--uninstall` 在服务不存在时也视为成功。 -- Linux 注销后仍需运行时,执行 `loginctl enable-linger "$USER"`。 +- 安装时会记录当前 Python 解释器路径、工作区目录和 `--enable-channel` 参数;更换环境或工作区后需重新运行 `bub gateway --install`。 +- Linux 下如需退出 SSH 后保持服务运行,请执行 `loginctl enable-linger "$USER"`。 ## `bub onboard` {#bub-onboard} -交互式生成配置并写入 `BubFramework.config_file`,默认为 `~/.bub/config.yml`;不启动渠道。 +运行交互式配置向导,生成或更新配置文件(默认 `~/.bub/config.yml`)。 ```text bub onboard [OPTIONS] [PLUGIN_NAME] @@ -124,99 +146,99 @@ bub onboard [OPTIONS] [PLUGIN_NAME] | 参数 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `PLUGIN_NAME` | 文本 | 无 | 只运行指定插件的 `onboard_config` | +| `PLUGIN_NAME` | 文本 | 无 | 可选;仅运行指定插件的 `onboard_config` 向导 | -不带插件名时依次运行内置模型配置和其他已注册插件的配置;指定插件名时跳过网关服务安装询问。 +不传 `PLUGIN_NAME` 时依次运行内置模型向导及所有已注册插件的向导;传入 `PLUGIN_NAME` 时仅运行该插件向导,并跳过末尾的后台服务安装询问。 -| 选择或操作 | 写入行为 | -| --- | --- | -| OpenAI 兼容服务或本地端点 | 写入 `openai:`、`api_base` 和 `client_args.api_format: chat` | -| OpenAI 官方 API 使用非官方地址 | 地址重置为 `https://api.openai.com/v1` | -| Base URL 留空 | 保留提供商默认地址,不写入空值 | -| Base URL 显式输入 | 即使等于默认值也写入 | -| API key 留空 | 保留当前地址的 key,或继续使用环境变量 | -| Base URL 改变 | 清空此前填写的 key | -| 选择 Codex | 跳过模型发现,手动输入模型 ID | +模型向导写入规则: -连接检查只调用模型列表端点,超时 10 秒,不验证工具调用能力。全部配置经过 `configure.validate` 后才写盘。 - -| 退出码 | 含义 | +| 向导操作 | 写入结果 | | --- | --- | -| `0` | 已保存,或用户拒绝安装网关 | -| `1` | 配置校验、写入、插件解析或网关安装失败 | +| 选择 OpenAI 兼容服务或本地端点 | 写入 `openai:`、`api_base`,并设置 `client_args.api_format: chat` | +| 选择 OpenAI 官方 API 但此前填过非官方地址 | 重置为 `https://api.openai.com/v1` | +| Base URL 留空 | 使用提供商默认地址,不向 YAML 写入空值 | +| Base URL 显式输入 | 写入 YAML(修改了 Base URL 时会自动清空旧 API Key) | +| API Key 留空 | 保留当前地址已有 Key,或依赖运行时环境变量 | +| 选择 Codex | 跳过在线模型列表拉取,直接提示输入模型 ID | + +连通性检查仅请求模型列表端点(超时 10 秒),不发起对话生成请求。所有配置合并并通过 `configure.validate` 校验后落盘。成功退出码为 `0`,失败为 `1`。 ## `bub install` {#bub-install} -安装插件到 Bub 管理的 uv 项目;不带参数时同步该项目。 +将插件安装到 Bub 托管的 `uv` 项目目录中;不传参数时同步该项目的现有依赖。 ```text bub install [OPTIONS] [SPECS]... ``` -| 参数与选项 | 类型 | 默认值 | 说明 | +| 参数 / 选项 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `SPECS` | 位置参数 | 空 | 要安装的包或 Git 来源 | -| `--project` | 路径 | `$BUB_HOME/bub-project` 或 `~/.bub/bub-project` | 插件项目目录;也可使用 `BUB_PROJECT` | +| `SPECS` | 位置参数 | 空 | PyPI 包名、官方扩展名或 Git 仓库地址 | +| `--project` | 路径 | `$BUB_HOME/bub-project`(默认 `~/.bub/bub-project`) | 托管插件项目目录(也可通过 `BUB_PROJECT` 设置) | -| 包规格 | 解析为 | +支持的包规格格式: + +| 格式 | 解析目标 | | --- | --- | | `package` | PyPI 包名 | -| `package@ref` | 从配置的 contrib 仓库安装,固定到 `ref` | +| `package@ref` | 官方 [`bub-contrib`](https://github.com/bubbuild/bub-contrib) 仓库的 `packages/package` 子目录,固定到分支或标签 `ref` | | `owner/repo` | `https://github.com/owner/repo.git` | -| `https://github.com/owner/repo.git@ref` | 带前缀的 Git URL,保留 ref | -| `git@...` 或 `https://...` | 加 `git+` 前缀 | +| `https://github.com/owner/repo.git@ref` | 带版本引用的 Git 仓库 URL(注意简写不支持 `owner/repo@ref`,需传完整 URL) | +| `git@...` 或 `https://...` | 自动添加 `git+` 前缀后交给 `uv` | `package@ref` 默认使用官方 `bub-contrib` 仓库。若要使用 fork 或镜像,可设置 `config.yml` 顶层的 `contrib_repo`,或用 `BUB_CONTRIB_REPO` 覆盖。可使用 `uv` 支持的 Git URL,例如 `ssh://git@example.com/org/repo.git#subdirectory=plugins/mcp`。`package@ref` 提供 ref;未设置 `#subdirectory=` 时默认使用 `packages/package`,设为 `.` 则使用仓库根目录。私有仓库请使用 SSH 密钥或 Git 凭据助手,不要在 URL 中嵌入凭据。 `owner/repo@ref` 不受支持;为任意 GitHub 仓库固定版本时使用完整 URL。 -| 命令 | uv 调用 | +```bash +bub install bub-mcp@main +bub install bub-discord +bub install https://github.com/owner/repo.git@v1.2.0 +bub install +``` + +插件管理命令底层执行的 `uv` 命令: + +| Bub 命令 | 底层 `uv` 命令 | | --- | --- | -| `bub install`(无规格) | `uv sync --active --inexact` | +| `bub install`(无参数) | `uv sync --active --inexact` | | `bub install ` | `uv add --active ` | | `bub uninstall ` | `uv remove --active ` | -| `bub update` | `uv sync --active --upgrade --inexact` | +| `bub update`(无参数) | `uv sync --active --upgrade --inexact` | | `bub update ` | `uv sync --active --inexact --upgrade-package ...` | -前置条件: - -- `uv` 位于 `PATH`、当前 Python scripts 目录或 `~/.local/bin`。 -- Bub 运行在虚拟环境中。 -- 显式传入的 `--project` 目录必须存在。 - -前置条件不满足时以退出码 `1` 结束;uv 失败时返回 uv 的退出码。 +前置条件:系统已安装 `uv`、当前 `bub` 运行在虚拟环境中(`sys.prefix != sys.base_prefix`),且显式传入的 `--project` 目录已存在。 ## `bub uninstall` {#bub-uninstall} -从托管项目卸载一个或多个插件,不修改系统 Python 或 Bub 自身所在环境。 +从托管插件项目中卸载插件: ```text bub uninstall [OPTIONS] PACKAGES... ``` -| 参数与选项 | 类型 | 默认值 | 说明 | -| --- | --- | --- | --- | -| `PACKAGES` | 位置参数 | 必填 | 与项目声明一致的包名 | -| `--project` | 路径 | `$BUB_HOME/bub-project` 或 `~/.bub/bub-project` | 插件项目目录;也可使用 `BUB_PROJECT` | +```bash +bub uninstall bub-discord +``` ## `bub update` {#bub-update} -升级托管项目中的插件;不带包名时升级全部依赖。 +升级托管插件项目中的插件(不传包名时升级全部已安装插件): ```text bub update [OPTIONS] [PACKAGES]... ``` -| 参数与选项 | 类型 | 默认值 | 说明 | -| --- | --- | --- | --- | -| `PACKAGES` | 位置参数 | 全部依赖 | 只升级指定包 | -| `--project` | 路径 | `$BUB_HOME/bub-project` 或 `~/.bub/bub-project` | 插件项目目录;也可使用 `BUB_PROJECT` | +```bash +bub update +bub update bub-mcp +``` -升级不会自动迁移插件配置或 Tape 数据。 +升级后请重启正在运行的 `bub chat` 或 `bub gateway` 进程。 ## `bub login codex` {#bub-login-codex} -通过 Codex CLI 配置 ChatGPT 套餐凭据。 +通过 OpenAI Codex CLI 登录并配置 ChatGPT 账号凭据: ```text bub login codex [OPTIONS] @@ -224,70 +246,53 @@ bub login codex [OPTIONS] | 选项 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `--executable` | 文本 | `codex` | Codex CLI 可执行文件 | -| `--device-auth` | 开关 | 关闭 | 使用设备授权流程 | -| `--codex-home` | 路径 | `$CODEX_HOME` 或 `~/.codex` | 凭据目录 | - -成功输出: +| `--executable` | 文本 | `codex` | Codex CLI 可执行文件路径 | +| `--device-auth` | 开关 | 关闭 | 使用设备码(Device Auth)登录 | +| `--codex-home` | 路径 | `$CODEX_HOME` 或 `~/.codex` | 存放 `auth.json` 的目录 | -```text -login: ok -account_id: -Use BUB_MODEL=codex: for ChatGPT plan access. -``` - -使用时设置 `BUB_MODEL=codex:`,不要同时设置 `BUB_API_KEY`。失败时输出 `login: failed: ...` 并以退出码 `1` 结束。 +登录成功后设置 `BUB_MODEL=codex:` 即可使用,**切勿**同时设置 `BUB_API_KEY`。 ## 其他账号登录 {#account-logins} +复用 Grok CLI 或 GitHub CLI 的登录凭据(需先安装对应官方 CLI 工具): + ```bash bub login grok [--executable grok] [--device-auth] bub login github-copilot ``` -Grok 使用官方 Grok CLI;GitHub Copilot 使用 `gh auth login`。请先安装对应 CLI。Republic 复用其凭据并处理令牌刷新或交换,Bub 不增加凭据存储。 - -登录后设置 `BUB_MODEL=grok:` 或 `BUB_MODEL=github-copilot:`,无需配置 API key。登录命令不会修改模型配置。GitHub Copilot 需要账号具有相应订阅及访问权限。 +登录后将模型设为 `BUB_MODEL=grok:` 或 `BUB_MODEL=github-copilot:` 即可(无需设置 API Key)。 ## `bub plugins` {#bub-plugins} -列出已发现的插件及其包和版本号。 +列出已发现的插件及其所属 Python 包名与版本号: ```text bub plugins [OPTIONS] [NAMES]... ``` -| 参数与选项 | 类型 | 默认值 | 说明 | +| 参数 / 选项 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | -| `NAMES` | 文本 | 全部插件 | `bub` entry-point 组中的插件名 | -| `--version-only` | 开关 | 关闭 | 每行只输出一个插件的版本号 | +| `NAMES` | 文本 | 全部插件 | 只查询指定名称的插件 | +| `--version-only` | 开关 | 关闭 | 每行仅输出版本号(无元数据时输出 `-`) | -默认每行输出 `name distribution version`;内置 Hook 显示为 `builtin`,加载失败的插件附带 `(failed: )`。名称不存在时以退出码 `1` 结束。 - -`--version-only` 在插件没有包元数据时输出 `-`。 +默认每行输出 `name distribution version`(加载失败时附带 `(failed: )`)。查询不存在的插件名时退出码为 `1`。 ## `bub hooks` {#bub-hooks} -打印 Hook 实现映射;该命令隐藏且不启动渠道。 +打印所有 Hook 及其绑定的插件列表(用于调试的隐藏命令,不显示在 `bub --help` 中): -```text +```bash bub hooks ``` -```text -: , -``` +输出格式为 `: , ...`,实现名称按 **pluggy 注册顺序**排列。注意注册顺序与运行时执行顺序相反,详见 [Hooks 参考:执行优先级](/zh-cn/docs/reference/hooks/#priority-and-dispatch)。 -实现按 pluggy 注册顺序输出,Hook 名按字母排序;没有实现时输出 `(no hook implementations)`。该顺序不是实际执行顺序。 - -## 退出码 {#exit-codes} +## 退出码汇总 {#exit-codes} | 场景 | 退出码 | | --- | --- | -| 命令成功 | `0` | -| Typer 参数错误 | `2` | -| 缺少 `app` 可选依赖 | `1`,进程在 Typer 前退出 | -| 没有可启用渠道、插件失败、配置失败 | `1` | -| `bub install` / `uninstall` / `update` 的 uv 失败 | uv 的退出码 | - -`bub run` 的模型错误可能只写入日志并返回回退文本,因此脚本还应检查 stderr 和实际输出。 +| 执行成功 | `0` | +| 命令行参数解析错误(Typer) | `2` | +| 缺少 `bub[app]` 依赖、无启用渠道、配置/登录/插件查询失败 | `1` | +| `bub install` / `uninstall` / `update` 中 `uv` 执行失败 | 透传 `uv` 退出码 | diff --git a/website/src/content/docs/zh-cn/docs/reference/hooks.mdx b/website/src/content/docs/zh-cn/docs/reference/hooks.mdx index eb8951ce..c438bc01 100644 --- a/website/src/content/docs/zh-cn/docs/reference/hooks.mdx +++ b/website/src/content/docs/zh-cn/docs/reference/hooks.mdx @@ -1,48 +1,197 @@ --- title: Hooks -description: Turn、App、Agent Hooks 及相关类型的签名。 +description: Bub 扩展 Hooks 完整参考:按 Turn、App 与 Agent 分类查阅 27 个 Hook 的总览、函数签名、返回值、执行优先级与生命周期。 --- +本页列出 Bub 应用层全部 27 个 Hook 的完整接口契约。Hook 是插件介入框架流程的标准扩展点:同一个 Hook 可以由多个插件同时实现,框架会按照下文的规则依次调用它们,并根据返回值决定后续行为。 + +想看如何从零编写一个插件,请阅读[插件与 Hooks](/zh-cn/docs/app/plugins/);想了解一条消息在框架内会经过哪些阶段,请阅读 [Turn](/zh-cn/docs/concepts/turn/#stages)。 + +## 执行方式与基础类型 {#notation} + +下表中的「执行方式」表示**当多个插件实现了同一个 Hook 时,框架如何调用它们并处理返回值**: + +| 执行方式 | 含义 | +| --- | --- | +| **取首个结果** | 按优先级从高到低逐个调用,遇到第一个非 `None` 返回值即采用并停止后续调用(注意 `False`、`""` 和 `[]` 均属于非 `None` 的有效返回值) | +| **全部执行** | 调用所有已注册的实现并收集返回值 | +| **依次处理** | 按优先级逐个调用,后一个实现接收前一个实现修改后的请求对象;若某个实现返回了终止或拦截裁决,则提前结束(用于 Agent 拦截 Hooks) | + +签名中常用的两个基础类型: + +| 类型 | 含义 | +| --- | --- | +| `Envelope` | `Any` 的类型别名。代表一条入站或出站消息(支持字典、dataclass、Pydantic 模型或带属性的对象) | +| `TurnState` | `dict[str, Any]` 的类型别名。单次 Turn 内供 Hook、工具和事件处理器共享的临时字典 | + +下方所有函数签名均取自 `bub.hooks.specs.BubHookSpecs`。用 `@hookimpl` 实现 Hook 时,**只需在函数签名中声明实际用到的参数名**,框架会按参数名自动注入。 + +## 执行优先级 {#priority-and-dispatch} + +Bub 基于 `pluggy` 注册 Hook 实现,并由 `HookRuntime` 统一调度: + +| 规则 | 说明 | +| --- | --- | +| 注册顺序 | 框架启动时先注册内置实现(`builtin`),再按发现顺序注册来自 `bub` 入口点的第三方插件 | +| 显式优先级 | 装饰器标注 `@hookimpl(tryfirst=True)` 的实现最先执行;标注 `@hookimpl(trylast=True)` 的实现最后执行 | +| 同优先级顺序 | 在相同优先级下,**后注册的插件先执行**(LIFO,因此你安装的插件默认优先于 `builtin` 内置实现) | +| 按名传参 | 框架根据你声明的参数名(`argnames`)注入对应变量,未用到的参数可省略 | +| 不支持的选项 | 不支持 pluggy 的 `wrapper=True` 与 `hookwrapper=True` | + +如果你在自定义代码中直接调用 `HookRuntime`,它的两类调用方法区别如下: + +| 方法 | 行为 | +| --- | --- | +| `call_first` / `call_first_sync` | 按优先级调用并返回第一个非 `None` 的结果(空列表 `[]`、空字符串 `""` 和 `False` 均视为非 `None` 结果) | +| `call_many` / `call_many_sync` | 调用所有实现并按执行顺序返回非 `None` 结果组成的列表 | + +:::note +命令行运行 `bub hooks` 打印出的插件顺序是 pluggy 的**注册顺序**,而**不是实际运行时的执行顺序**(运行时会将列表反转后再按 `tryfirst` / `trylast` 排序)。排查执行先后时,请以上述优先级规则和运行日志为准。 +::: + ## Turn Hooks {#turn-hooks} +应用层处理一条入站消息的完整流程称为一个 **Turn**。下面 9 个 Hook 由 `BubFramework.process_inbound()` 按阶段依次触发,覆盖从解析会话到发送回复的全过程。 + +| Hook | 职责 | 执行方式 | +| --- | --- | --- | +| [`resolve_session`](#resolve_session) | 确定入站消息所属的会话 ID | 取首个结果 | +| [`load_state`](#load_state) | 加载并恢复本次 Turn 所需的会话状态 | 全部执行并合并字典 | +| [`build_prompt`](#build_prompt) | 构造发给模型的输入内容(或识别直接命令) | 取首个结果 | +| [`run_model`](#run_model) | 非流式调用模型并返回完整回复文本 | 取首个结果 | +| [`run_model_stream`](#run_model_stream) | 流式调用模型并返回 `AsyncStreamEvents` 事件流 | 取首个结果 | +| [`continue_prompt`](#continue_prompt) | 当 Agent 进入下一个 Step 时,可选地追加一条用户消息 | 取首个结果 | +| [`save_state`](#save_state) | 在模型阶段结束后持久化应用状态 | 全部执行 | +| [`render_outbound`](#render_outbound) | 将模型输出转换为一条或多条待发送的出站消息 | 全部执行并拼接列表 | +| [`dispatch_outbound`](#dispatch_outbound) | 将待发送的出站消息投递至外部渠道 | 每条消息全部执行一次 | + +这组 Hook 在执行期间如果抛出未捕获的异常,会被 `process_inbound()` 捕获:框架会先调用 `on_error(stage="turn", ...)` 进行通知,随后将原异常重新抛出(若模型阶段未找到可用实现或流式输出报错,则 `stage` 为 `"run_model"`)。 + ### `resolve_session` {#resolve_session} +为一条新到达的入站消息确定 `session_id`,让框架知道它归属于哪个会话。 + ```python def resolve_session(self, message: Envelope) -> str: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `message` | `Envelope` | 刚到达的原始入站消息 | +| **返回值** | `str` | 会话 ID;若返回值转成字符串后为空,框架默认回退为 `:` | + +- **执行方式**:取首个结果。 + ### `load_state` {#load_state} +从存储中恢复本次 Turn 所需的应用状态字典。 + ```python def load_state(self, message: Envelope, session_id: str) -> TurnState: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `message` | `Envelope` | 本次入站消息 | +| `session_id` | `str` | 由 `resolve_session` 解析出的会话 ID | +| **返回值** | `TurnState` | 状态字典(非字典返回值会被忽略) | + +- **执行方式**:全部执行;先合并低优先级插件返回的字典,再合并高优先级插件返回的字典(同名键由高优先级覆盖低优先级)。 + ### `build_prompt` {#build_prompt} +根据原始入站消息和已加载的会话状态,构造发给模型的输入内容。 + ```python def build_prompt(self, message: Envelope, session_id: str, state: TurnState) -> list[UserContent] | LegacyPrompt: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `message` | `Envelope` | 本次入站消息 | +| `session_id` | `str` | 当前会话 ID | +| `state` | `TurnState` | 当前 Turn 的共享状态字典(可在发现内部命令时写入 `_command_output` 以跳过模型调用) | +| **返回值** | `list[UserContent] \| LegacyPrompt` | 发给模型的提示词内容;若首个非 `None` 结果为 `""` 或 `[]`,直接回退使用原始消息文本 | + +- **执行方式**:取首个结果。 + +#### 提示词内容格式 {#prompt-content} + +`build_prompt` 推荐返回 `list[UserContent]`,列表中的元素可以是纯文本或 Republic 多模态对象: + +| 内容类型 | 构造方式 | +| --- | --- | +| 纯文本 | `str` | +| 图片 | `republic.image(url, media_type=...)` | +| 音频 | `republic.audio(url, media_type=...)` | +| 视频 | `republic.video(url, media_type=...)` | + +为了兼容旧版插件,`run_model`、`run_model_stream`、`continue_prompt` 和 `system_prompt` 这四个 Hook 的 `prompt` 参数接收的是转换后的兼容格式(`LegacyPrompt`): + +| 情况 | 传入的 `prompt` 格式 | +| --- | --- | +| 只包含纯文本 | `str` | +| 包含图片、音频或视频 | `[{"type", "media_type", "url"}]` 字典列表 | + +你可以使用 `bub.prompt.to_content()` 将兼容格式转回 `list[UserContent]`,或使用 `bub.prompt.to_legacy_prompt()` 转成兼容格式。 + ### `run_model` {#run_model} +执行非流式模型阶段,直接返回完整的模型输出文本。 + ```python def run_model(self, prompt: str | list[dict], session_id: str, state: TurnState) -> str: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `prompt` | `str \| list[dict]` | 兼容格式的模型输入(见[提示词内容格式](#prompt-content)) | +| `session_id` | `str` | 当前会话 ID | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | +| **返回值** | `str` | 模型生成的完整回复文本 | + +- **执行方式**:取首个结果。 + ### `run_model_stream` {#run_model_stream} +执行流式模型阶段,返回可逐条迭代消费的 `AsyncStreamEvents` 事件流。 + ```python def run_model_stream(self, prompt: str | list[dict], session_id: str, state: TurnState) -> AsyncStreamEvents: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `prompt` | `str \| list[dict]` | 兼容格式的模型输入(见[提示词内容格式](#prompt-content)) | +| `session_id` | `str` | 当前会话 ID | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | +| **返回值** | `AsyncStreamEvents` | 产出 `StreamEvent` 的异步迭代器 | + +- **执行方式**:取首个结果。 +- **与 `run_model` 的关系**:自定义模型插件只需实现其中一个即可——框架会自动把普通文本包装成单步流,或者把流中的文本增量聚合成完整字符串。 +- **注意**:如果你用自定义插件替换了内置的模型执行阶段,内置 `BubAgent` 上的 `before_llm_call` / `before_tool_call` 等拦截 Hook 将不会自动触发,除非你的实现自己接入了它们。 + ### `continue_prompt` {#continue_prompt} +当 Agent 完成一个 Step 并准备继续下一个 Step 时,可选地向下一轮模型请求追加一条用户消息。 + ```python def continue_prompt(self, prompt: str | list[dict] | None, tape: Tape, state: StreamState) -> str | None: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `prompt` | `str \| list[dict] \| None` | 当前 Step 的兼容格式输入 | +| `tape` | `Tape` | 当前正在运行的会话 Tape | +| `state` | `StreamState` | 当前流式运行状态(注意类型为 `StreamState` 而非 `TurnState`) | +| **返回值** | `str \| None` | 追加给下一步的用户提示文本;返回 `None` 时直接带着已有工具结果继续推理 | + +- **执行方式**:取首个结果(仅在 `StepFinished.status == "continue"` 时触发)。 + ### `save_state` {#save_state} +在模型阶段结束后保存需要跨 Turn 留存的应用状态。 + ```python def save_state( self, @@ -53,8 +202,20 @@ def save_state( ) -> None: ``` +| 参数 | 类型 | 说明 | +| --- | --- | --- | +| `session_id` | `str` | 当前会话 ID | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | +| `message` | `Envelope` | 本次入站消息 | +| `model_output` | `str` | 模型阶段产出的最终文本(若模型阶段报错则为空字符串) | + +- **执行方式**:全部执行。 +- **调用时机**:在模型阶段的 `finally` 块中调用。只要流程已经进入模型阶段,无论模型正常完成、报错还是被取消,`save_state` 都会执行。仅用于持久化会话状态,运行时资源释放请使用 `provide_lifespan`。 + ### `render_outbound` {#render_outbound} +将模型产出的文本转换为一条或多条待发送的出站消息。 + ```python def render_outbound( self, @@ -65,28 +226,85 @@ def render_outbound( ) -> list[Envelope]: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `message` | `Envelope` | 原始入站消息 | +| `session_id` | `str` | 当前会话 ID | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | +| `model_output` | `str` | 模型阶段或内部命令产出的最终文本 | +| **返回值** | `list[Envelope]` | 待投递的出站消息列表 | + +- **执行方式**:全部执行;将各个实现返回的消息列表按执行顺序展开并拼接。如果所有实现均未返回任何出站消息,内置实现会用 `model_output` 构造一条默认回复并沿用入站消息的 `channel` 和 `chat_id`。 + ### `dispatch_outbound` {#dispatch_outbound} +将渲染好的出站消息投递给外部渠道。 + ```python def dispatch_outbound(self, message: Envelope) -> bool: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `message` | `Envelope` | 单条待投递的出站消息 | +| **返回值** | `bool` | 是否已处理(返回值不会阻止其他插件的 `dispatch_outbound` 继续执行;过滤消息请在 `render_outbound` 阶段完成) | + +- **执行方式**:全部执行;对 `render_outbound` 产出的每条出站消息分别调用一次。 + ## App Hooks {#application-hooks} +以下 14 个 Hook 服务于整个应用运行时,负责管理 CLI 命令、初始化向导、运行时资源、存储后端、消息渠道以及工具集。 + +| Hook | 职责 | 执行方式 | +| --- | --- | --- | +| [`register_cli_commands`](#register_cli_commands) | 向根 CLI 应用注册自定义子命令 | 全部执行 | +| [`onboard_config`](#onboard_config) | 在 `bub onboard` 时收集并补充配置项 | 全部执行 | +| [`provide_model_options`](#provide_model_options) | 提供当前会话可选的模型列表 | 全部执行并合并结果 | +| [`provide_environment`](#provide_environment) | 提供工具执行与文件读写所在的 `Environment` | 取首个结果 | +| [`on_error`](#on_error) | 观察并记录框架各阶段未处理的异常 | 全部执行 | +| [`system_prompt`](#system_prompt) | 追加系统提示词片段 | 全部执行并按优先级拼接 | +| [`provide_tape_store`](#provide_tape_store) | 提供会话 Tape 的存储后端 | 取首个结果 | +| [`provide_lifespan`](#provide_lifespan) | 管理随 `framework.running()` 启动和释放的全局资源 | 全部执行 | +| [`provide_tape_sidecar`](#provide_tape_sidecar) | 为每个会话 Tape 挂载配套的 Sidecar | 全部执行并按名称去重 | +| [`provide_channels`](#provide_channels) | 提供消息收发渠道或后台常驻服务(`Lifecycle`) | 全部执行并按名称去重 | +| [`build_tape_context`](#build_tape_context) | 构造会话的 `TapeContext` 投影策略 | 取首个结果 | +| [`admit_message`](#admit_message) | 决定新到达的渠道消息如何准入(立即处理、排队、引导或丢弃) | 取首个结果 | +| [`provide_steering_inbox`](#provide_steering_inbox) | 提供暂存运行中引导(steering)消息的收件箱 | 取首个结果 | +| [`provide_tools`](#provide_tools) | 向 Agent 提供自定义工具列表 | 全部执行并按名称去重 | + ### `register_cli_commands` {#register_cli_commands} +向 Bub 的根 Typer 应用注册自定义 CLI 子命令。 + ```python def register_cli_commands(self, app: Any) -> None: ``` +| 参数 | 类型 | 说明 | +| --- | --- | --- | +| `app` | `typer.Typer` | Bub 的根 CLI 应用实例,可直接调用 `app.command()` 或 `app.add_typer()` | + +- **执行方式**:全部执行。 + ### `onboard_config` {#onboard_config} +在运行 `bub onboard` 交互式配置向导时,收集或修改插件所需的配置项。 + ```python def onboard_config(self, current_config: dict[str, Any]) -> dict[str, Any] | None: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `current_config` | `dict[str, Any]` | 当前已加载的配置加上前序 Hook 的修改 | +| **返回值** | `dict[str, Any] \| None` | 需要递归合并进总配置的键值字典(返回非 `None` 且非字典的值会抛出 `TypeError`) | + +- **执行方式**:全部执行。 + ### `provide_model_options` {#provide_model_options} +为当前会话提供候选模型列表及当前选中模型。 + ```python def provide_model_options( self, @@ -95,56 +313,137 @@ def provide_model_options( ) -> ModelOptions | None: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `session_id` | `str` | 当前会话 ID | +| `workspace` | `Path \| None` | 当前工作区路径 | +| **返回值** | `ModelOptions \| None` | 包含候选模型列表与 `current_model` 的配置对象 | + +- **执行方式**:全部执行;合并所有实现返回的候选模型列表,并采用优先级最高实现返回的 `current_model`。 + ### `provide_environment` {#provide_environment} +为 `bash`、`fs.*` 和 `run_code` 提供执行环境。 + ```python def provide_environment(self, session_id: str, workspace: Path) -> Environment | None: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `session_id` | `str` | 当前会话 ID | +| `workspace` | `Path` | 当前工作区目录路径 | +| **返回值** | `Environment \| None` | 会话专属的执行环境实例(默认内置实现返回 `LocalEnvironment(workspace)`) | + +- **执行方式**:取首个结果;每个 `session_id` 缓存一个实例,在 `framework.running()` 退出时自动调用 `Environment.close()`。 + ### `on_error` {#on_error} +观察框架各阶段抛出的未捕获异常,适合做错误日志记录或监控告警。 + ```python def on_error(self, stage: str, error: Exception, message: Envelope | None) -> None: ``` +| 参数 | 类型 | 说明 | +| --- | --- | --- | +| `stage` | `str` | 发生异常的阶段标识(如 `"turn"`、`"run_model"`、`"resolve_session"`、`"admit_message"`) | +| `error` | `Exception` | 捕获到的异常实例 | +| `message` | `Envelope \| None` | 触发该流程的入站消息(若在无消息上下文的阶段报错则为 `None`) | + +- **执行方式**:全部执行(若某个 `on_error` 实现自身报错,框架会记录 `hook.on_error_failed` 并继续调用其余实现)。仅用于观察错误,无法吞掉异常或恢复已中断的 Turn。 + ### `system_prompt` {#system_prompt} +向系统提示词追加一段指令文本。 + ```python def system_prompt(self, prompt: str | list[dict], state: TurnState) -> str: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `prompt` | `str \| list[dict]` | 当前 Turn 的兼容格式用户输入 | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | +| **返回值** | `str` | 要追加的系统提示词片段 | + +- **执行方式**:全部执行;所有非空返回值会按优先级**从低到高**用空行拼接在一起(不会被高优先级实现覆盖)。 + ### `provide_tape_store` {#provide_tape_store} +提供用于持久化会话历史的 `TapeStore` 或 `AsyncTapeStore`。 + ```python def provide_tape_store(self) -> TapeStore | AsyncTapeStore | None: ``` +| 返回值 | 类型 | 说明 | +| --- | --- | --- | +| **返回值** | `TapeStore \| AsyncTapeStore \| None` | Tape 存储实例,或产出存储实例的单次 `yield` 生成器(退出时在 `finally` 中释放连接;**不要**添加 `@contextmanager` 装饰器) | + +- **执行方式**:取首个结果(在进入 `framework.running()` 时解析一次;离开该作用域后 `framework.get_tape_store()` 返回 `None`)。 + ### `provide_lifespan` {#provide_lifespan} +在 `framework.running()` 运行期间持有需要随应用启动和清理的全局资源(如数据库连接池、共享 HTTP 客户端)。 + ```python def provide_lifespan(self) -> AsyncIterator[None] | Iterator[None] | None: ``` +| 返回值 | 类型 | 说明 | +| --- | --- | --- | +| **返回值** | `AsyncIterator[None] \| Iterator[None] \| None` | 含单次 `yield` 的同步或异步生成器(**不要**添加 `@contextmanager` / `@asynccontextmanager` 装饰器) | + +- **执行方式**:全部执行;每个返回的生成器都会在 `running()` 启动时进入,并在退出时按相反顺序清理。若任一生成器在启动阶段抛错,整个 `running()` 将中止启动。 + ### `provide_tape_sidecar` {#provide_tape_sidecar} +为每个会话 Tape 挂载一个配套的 `TapeSidecar`(如内置的 `spill` Sidecar)。 + ```python def provide_tape_sidecar(self) -> TapeSidecar: ``` +| 返回值 | 类型 | 说明 | +| --- | --- | --- | +| **返回值** | `TapeSidecar` | 随主 Tape 一起分支、合并、归档和重置的配套 Sidecar(物理名称为 `<主 tape>__sidecar__`) | + +- **执行方式**:全部执行;按 `sidecar.name` 去重,同名时保留优先级最高的实现。 + ### `provide_channels` {#provide_channels} +向网关或交互式会话提供消息渠道或后台常驻服务。 + ```python def provide_channels(self, message_handler: MessageHandler) -> list[Channel]: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `message_handler` | `MessageHandler` | 框架传入的异步回调 `async (message: Envelope) -> None`,渠道收到外部消息时调用 | +| **返回值** | `list[Channel]` | 渠道或后台服务实例列表(必须返回列表) | + +- **执行方式**:全部执行;按 `channel.name` 去重,同名时保留优先级最高的实现。 + ### `build_tape_context` {#build_tape_context} +构造当前应用的 `TapeContext`,决定如何从会话 Tape 投影出模型上下文消息。 + ```python def build_tape_context(self) -> TapeContext: ``` +| 返回值 | 类型 | 说明 | +| --- | --- | --- | +| **返回值** | `TapeContext` | 会话上下文投影规则实例(非 `TapeContext` 返回值会抛出 `TypeError`) | + +- **执行方式**:取首个结果。 + ### `admit_message` {#admit_message} +当渠道收到一条新消息时,决定是立即开启新 Turn、丢弃、排队等待,还是作为 steering 消息注入正在运行的 Turn。 + ```python def admit_message( self, @@ -154,27 +453,158 @@ def admit_message( ) -> AdmitDecision | None: ``` +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `session_id` | `str` | 该消息所属的会话 ID | +| `message` | `Envelope` | 新到达的入站消息 | +| `turn` | `TurnSnapshot` | 当前会话正在运行的 Turn 快照状态 | +| **返回值** | `AdmitDecision \| None` | 准入裁决(返回 `None` 时按该渠道的默认准入规则处理) | + +- **执行方式**:取首个结果。 + +当返回 `AdmitDecision(action=...)` 时,`ChannelManager` 按以下规则调度: + +| `action` | 当该会话已有 Turn 正在运行时 | 当该会话空闲时 | +| --- | --- | --- | +| `process` | 立即并行启动一个新 Turn | 立即启动新 Turn | +| `drop` | 直接丢弃该消息 | 直接丢弃该消息 | +| `follow_up` | 放入待处理队列,等当前 Turn 结束后按顺序处理 | 立即启动新 Turn | +| `steer` | 放入引导收件箱,注入当前 Turn 的下一步模型请求;若来不及被当前 Turn 消费则自动转为待处理队列 | 立即启动新 Turn | + ### `provide_steering_inbox` {#provide_steering_inbox} +提供用于暂存 `steer` 消息的收件箱实现(`SteeringInbox`)。 + ```python def provide_steering_inbox(self) -> SteeringInbox | None: ``` +| 返回值 | 类型 | 说明 | +| --- | --- | --- | +| **返回值** | `SteeringInbox \| None` | 引导消息收件箱实例,或含单次 `yield` 的生成器函数(不要加 `@contextmanager` 装饰器) | + +- **执行方式**:取首个结果。 + ### `provide_tools` {#provide_tools} +向 Agent 注册自定义工具。 + ```python def provide_tools(self) -> list[Tool]: ``` +| 返回值 | 类型 | 说明 | +| --- | --- | --- | +| **返回值** | `list[Tool]` | 自定义工具列表 | + +- **执行方式**:全部执行;按 `tool.name` 去重,当多个插件提供同名工具时,保留优先级最高的实现。 + +### 资源何时创建与释放 {#runtime-resources} + +进入 `async with framework.running():` 时,框架按以下顺序初始化资源: + +1. 启动所有 `provide_lifespan` 返回的生成器; +2. 解析并进入 `provide_tape_store`; +3. 解析并进入 `provide_steering_inbox`。 + +退出 `framework.running()` 时,框架会先关闭所有已缓存的会话执行环境(`Environment.close()`),再按相反顺序释放上述三类资源。 + +| 运行场景 | `framework.running()` 覆盖的生命周期 | +| --- | --- | +| `bub run` | 处理单条消息的整个 Turn 期间 | +| `bub chat` / `bub gateway` | 从命令启动到退出的整个进程运行期 | +| 嵌入自定义 Python 服务 | 由宿主代码决定,应覆盖整个服务生命周期(如 FastAPI 的 `lifespan`) | + +#### 运行期内的异常 {#runtime-errors} + +`on_error` 可以观察运行期间发生的框架异常,但不会吞掉异常或自动重试。在自定义服务中嵌入 Bub 时,宿主代码应自己捕获 `process_inbound()` 抛出的异常。 + ## Agent Hooks {#interception-through-pluginagenthooks} +下面 4 个 Hook 在每次模型调用或工具执行的前后触发。`AgentPlugins` 和内置的 `BubAgent` 会通过订阅 Agent 事件总线自动桥接它们;你也可以通过 [`PluginAgentHooks`](#pluginagenthooks) 手动挂载。 + +| Hook | 职责 | 执行方式 | +| --- | --- | --- | +| [`before_llm_call`](#before_llm_call) | 在请求发往模型前观察、修改参数,或直接返回结果跳过调用 | 依次处理 | +| [`after_llm_call`](#after_llm_call) | 在单次模型调用结束后观察汇总结果与耗时 | 全部执行 | +| [`before_tool_call`](#before_tool_call) | 在工具函数执行前修改入参、返回替代结果或拒绝执行 | 依次处理 | +| [`after_tool_call`](#after_tool_call) | 在工具函数执行后观察或改写返回给模型的结果 | 全部执行 | + +:::caution +当这 4 个拦截 Hook 的实现抛出未捕获异常时,框架会记录 `hook.agent_hook_failed` 日志并**直接跳过该实现**(返回值类型不符时则记录 `hook.agent_hook_bad_return` 并跳过)。这意味着**在 `before_tool_call` 中抛异常并不能阻止工具运行**——要拦截工具,必须显式返回 `ToolCallDecision.deny(...)` 或 `replace(...)`。 +::: + ### `before_llm_call` {#before_llm_call} +在请求发往模型提供商之前观察或修改请求参数,或直接给出回复文本以跳过实际的模型调用。 + ```python def before_llm_call(self, request: LLMCallRequest, state: TurnState) -> LLMCallRequest | LLMCallDecision | None: ``` -### `LLMCallStarted.request` {#llmcallrequest} +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `request` | `LLMCallRequest` | 即将发往模型提供商的不可变请求快照 | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | +| **返回值** | `LLMCallRequest \| LLMCallDecision \| None` | 返回 `dataclasses.replace(request, ...)` 修改请求参数;返回 `LLMCallDecision.finish(text)` 跳过实际模型调用;返回 `None` 原样继续 | + +- **执行方式**:依次处理(若返回 `LLMCallDecision.finish(text)`,不会再触发后续 `before_llm_call` 或 `after_llm_call`)。 + +### `after_llm_call` {#after_llm_call} + +在单次模型调用结束后观察结果、Token 用量、错误或耗时。 + +```python +def after_llm_call(self, request: LLMCallRequest, result: LLMCallResult, state: TurnState) -> None: +``` + +| 参数 | 类型 | 说明 | +| --- | --- | --- | +| `request` | `LLMCallRequest` | 发往模型提供商的最终请求对象 | +| `result` | `LLMCallResult` | 模型调用完成后的汇总结果(含输出文本、工具调用、Token 用量、异常与耗时) | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | + +- **执行方式**:全部执行(模型调用成功或因普通异常失败时都会触发;任务被取消、流被调用方提前关闭或被 `before_llm_call` 提前结束时不触发)。 + +### `before_tool_call` {#before_tool_call} + +在本地工具函数执行前修改参数、返回缓存/Mock 替代结果,或拒绝本次调用。 + +```python +def before_tool_call(self, call: ToolCall, state: TurnState) -> ToolCallDecision | None: +``` + +| 参数 / 返回值 | 类型 | 说明 | +| --- | --- | --- | +| `call` | `ToolCall` | 即将执行的工具调用描述 | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | +| **返回值** | `ToolCallDecision \| None` | 返回 `None` 原样放行;返回 `proceed(arguments)` 改参放行;返回 `replace(result)` 跳过工具并使用替代结果;返回 `deny(message)` 拒绝调用并返回工具错误 | + +- **执行方式**:依次处理。 + +### `after_tool_call` {#after_tool_call} + +在单次工具调用结束后观察结果与耗时,或改写即将交回给模型的结果。 + +```python +def after_tool_call(self, call: ToolCall, result: ToolCallResult, state: TurnState) -> None: +``` + +| 参数 | 类型 | 说明 | +| --- | --- | --- | +| `call` | `ToolCall` | 本次执行的工具调用描述 | +| `result` | `ToolCallResult` | 可变的工具执行结果(原地修改 `result.result` 即可改写模型最终看到的工具输出) | +| `state` | `TurnState` | 当前 Turn 的共享状态字典 | + +- **执行方式**:全部执行(无论工具正常返回、抛错、被 `deny` 还是被 `replace` 都会触发;仅在任务取消或流被提前关闭时不触发)。 + +### 拦截载荷类型定义 {#interception-payloads} + +以下数据类定义在 `bub.core.events`(也可从 `bub.hooks.interception` 导入): + +#### `LLMCallRequest` {#llmcallrequest} + +即将发往模型提供商的请求快照(不可变对象,需通过 `dataclasses.replace()` 修改): ```python @dataclass(frozen=True) @@ -186,7 +616,17 @@ class LLMCallRequest: max_tokens: int | None = None ``` -### `LLMCallStarted.decision` {#llmcalldecision} +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `run_id` | `str` | 当前 Agent 运行 ID | +| `model` | `str` | 目标模型标识符(`provider:model`) | +| `messages` | `list[republic.Message]` | 即将发给模型的上下文消息列表 | +| `tool_names` | `tuple[str, ...]` | 本次模型调用可见的工具名元组(只读观察,不能通过修改它来增删工具) | +| `max_tokens` | `int \| None` | 单次响应的最大输出 Token 数 | + +#### `LLMCallDecision` {#llmcalldecision} + +由 `before_llm_call` 返回的提前结束裁决: ```python @dataclass(frozen=True) @@ -198,13 +638,15 @@ class LLMCallDecision: def finish(cls, text: str) -> LLMCallDecision: ... ``` -### `after_llm_call` {#after_llm_call} +| 字段 / 方法 | 类型 | 说明 | +| --- | --- | --- | +| `action` | `Literal["finish"]` | 裁决动作,固定为 `"finish"` | +| `text` | `str` | 直接作为模型输出的回复文本 | +| `finish(text)` | `LLMCallDecision` | 构造提前结束裁决并跳过实际的模型提供商调用 | -```python -def after_llm_call(self, request: LLMCallRequest, result: LLMCallResult, state: TurnState) -> None: -``` +#### `LLMCallResult` {#llmcallresult} -### `LLMCallFinished.result` {#llmcallresult} +单次模型调用完成后的汇总结果: ```python @dataclass(frozen=True) @@ -217,13 +659,18 @@ class LLMCallResult: duration_ms: int = 0 ``` -### `before_tool_call` {#before_tool_call} +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `run_id` | `str` | 当前 Agent 运行 ID | +| `text` | `str \| None` | 聚合后的助手文本回复 | +| `tool_calls` | `list[dict[str, Any]]` | 模型请求的工具调用列表 | +| `usage` | `dict[str, Any] \| None` | Token 用量统计字典 | +| `error` | `Exception \| None` | 调用失败时的异常对象(成功时为 `None`) | +| `duration_ms` | `int` | 本次模型调用耗时(毫秒) | -```python -def before_tool_call(self, call: ToolCall, state: TurnState) -> ToolCallDecision | None: -``` +#### `ToolCall` {#toolcall} -### `ToolCallStarted.call` {#toolcall} +即将执行的一次工具调用: ```python @dataclass(frozen=True) @@ -234,7 +681,16 @@ class ToolCall: context: ToolContext | None = field(default=None, repr=False, compare=False) ``` -### `ToolCallStarted.decision` {#toolcalldecision} +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `run_id` | `str` | 当前 Agent 运行 ID | +| `tool` | `str` | 工具名称 | +| `arguments` | `dict[str, Any]` | 模型传入的工具关键字参数字典 | +| `context` | `ToolContext \| None` | 当前工具运行上下文(含 `tape`、`run_id`、`state`、`call_id`) | + +#### `ToolCallDecision` {#toolcalldecision} + +由 `before_tool_call` 返回的工具裁决对象: ```python @dataclass(frozen=True) @@ -254,13 +710,19 @@ class ToolCallDecision: def deny(cls, message: str) -> ToolCallDecision: ... ``` -### `after_tool_call` {#after_tool_call} +| 字段 / 方法 | 类型 | 说明 | +| --- | --- | --- | +| `action` | `Literal["proceed", "replace", "deny"]` | 裁决动作:放行、替代结果或拒绝调用 | +| `arguments` | `dict[str, Any] \| None` | `proceed` 时替换后的新参数字典 | +| `result` | `Any` | `replace` 时直接作为工具输出的替代结果 | +| `message` | `str \| None` | `deny` 时返回给模型的拒绝原因说明 | +| `proceed(arguments=None)` | `ToolCallDecision` | 允许工具继续执行(可选替换入参) | +| `replace(result)` | `ToolCallDecision` | 跳过实际工具函数,直接使用 `result` 作为输出 | +| `deny(message)` | `ToolCallDecision` | 拒绝执行工具,并将 `message` 包装为工具错误返回给模型 | -```python -def after_tool_call(self, call: ToolCall, result: ToolCallResult, state: TurnState) -> None: -``` +#### `ToolCallResult` {#toolcallresult} -### `ToolCallFinished.result` {#toolcallresult} +单次工具调用完成后的结果(可变 dataclass,可在 `after_tool_call` 中修改 `result.result`): ```python @dataclass @@ -273,41 +735,50 @@ class ToolCallResult: duration_ms: int = 0 ``` -## App Hooks 与 Agent 事件 {#app-hooks} +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `run_id` | `str` | 当前 Agent 运行 ID | +| `tool` | `str` | 工具名称 | +| `arguments` | `dict[str, Any]` | 实际执行时使用的参数字典 | +| `result` | `Any` | 工具返回结果(可在 `after_tool_call` 中原地重新赋值) | +| `error` | `Exception \| None` | 工具抛出的异常或 `deny()` 产生的错误(成功时为 `None`) | +| `duration_ms` | `int` | 本次工具执行耗时(毫秒) | + +## App Hooks 与 Agent 事件的桥接 {#app-hooks} -概念页只说明「谁在什么方向介入」,这里给出适配细节。三种数据的关系与决策语义见 [Agent 事件](/zh-cn/docs/concepts/events/#three-kinds)。 +概念篇介绍了[Agent 事件与 App Hooks 的职责分工](/zh-cn/docs/concepts/events/#app-hooks),这里列出底层桥接器的映射关系与行为差异。 -### 事件映射 {#event-mapping} +### 事件映射关系 {#event-mapping} -`PluginAgentHooks` 把应用 hooks 接到 Agent 事件上: +`PluginAgentHooks` 与 `AgentPlugins` 将应用层 Hooks 挂载到核心 Agent 的事件总线上: -| 应用 hook | Agent 事件 | 说明 | +| 应用层 Hook | 对应的核心 Agent 事件 | 说明 | | --- | --- | --- | -| `before_llm_call` | `LLMCallStarted` | 每次模型调用前;可返回改写后的 `LLMCallRequest` 或 `LLMCallDecision` | -| `after_llm_call` | `LLMCallFinished` | 调用成功或普通异常失败后各一次 | -| `before_tool_call` | `ToolCallStarted` | 每次工具调用前;可 `proceed(arguments)`、`replace(result)` 或 `deny(message)` | -| `after_tool_call` | `ToolCallFinished` | 成功、失败、拒绝与替代都会触发 | -| `continue_prompt` | `StepFinished` | 仅在 `status == "continue"` 时调用,结果写入 `next_prompt` | -| `provide_steering_inbox` | `MessagesPending` | 排出待注入的 steering 消息,加入当前 Run 的下一步 | +| `before_llm_call` | `LLMCallStarted` | 每次调用模型前触发;可返回新 `LLMCallRequest` 或 `LLMCallDecision` | +| `after_llm_call` | `LLMCallFinished` | 模型调用成功或普通异常失败后触发一次 | +| `before_tool_call` | `ToolCallStarted` | 每次执行工具前触发;可返回 `proceed(arguments)`、`replace(result)` 或 `deny(message)` | +| `after_tool_call` | `ToolCallFinished` | 工具成功、失败、被拒绝或被替代后均会触发 | +| `continue_prompt` | `StepFinished` | 仅当 `status == "continue"` 时调用,返回值写入 `event.next_prompt` | +| `provide_steering_inbox` | `MessagesPending` | 从收件箱取出运行期间到达的 steering 消息,注入当前 Run 的下一步 | -模型可见的工具调用(包括 `.tape.handoff` 这类内置工具)同样经过 `ToolCallStarted` / `ToolCallFinished`。 +所有模型可见的工具调用(包括内置的 `tape.handoff` 等工具)都会经过 `ToolCallStarted` / `ToolCallFinished`。 ### 两种接入方式的差异 {#event-vs-hooks} -| 对比项 | 直接处理 Agent 事件 | 应用拦截 hook | +| 对比维度 | 直接监听 `agent.events` | 实现插件拦截 Hook(`@hookimpl`) | | --- | --- | --- | -| 注册 | `agent.events.on(Type, handler)` | 插件中的 `@hookimpl` | -| 执行顺序 | 注册顺序 | pluggy 优先级 | -| 参数修改 | 原地替换 `event.call` / `event.request` | 返回 `ToolCallDecision.proceed(arguments=...)` 或新的 `LLMCallRequest` | -| 控制 | 设置 `event.decision` | 返回 decision 对象 | -| 异常 | 传播给 `emit()` 调用方,可能使 Run 失败 | 记录日志后跳过,不会中断 Run | -| 返回值类型不符 | 不适用 | 记录警告并跳过该实现 | +| 注册方式 | `agent.events.on(EventType, handler)` | 在插件类或模块中用 `@hookimpl` 声明 | +| 执行顺序 | 按 `on()` 的注册先后顺序 | 按 pluggy 优先级(`tryfirst` / 后注册优先 / `trylast`) | +| 修改调用参数 | 原地替换 `event.call` 或 `event.request` | 返回 `ToolCallDecision.proceed(arguments=...)` 或新 `LLMCallRequest` | +| 拦截或替代 | 给 `event.decision` 赋值 | 直接 `return` 对应的 decision 对象 | +| 未捕获异常 | 直接向上抛给 `emit()` 调用方,可能中断整次 Run | 记录错误日志并跳过该插件,不影响 Run 继续运行 | +| 返回值类型错误 | 返回值被忽略,无影响 | 记录警告日志并跳过该插件 | -因此用 hook 实现的安全策略不能靠抛异常阻止调用,必须返回 `deny(...)`。 +因此,在插件 Hook 中编写权限控制时,**不能靠抛异常来阻断工具调用**,必须显式 `return ToolCallDecision.deny(...)`。 -### 订阅方式 {#subscribe} +### 订阅与挂载 API {#subscribe} -`PluginAgentHooks(runtime).subscribe(events)` 把四个拦截 hook 接到已有或新建的事件总线上;`AgentPlugins.attach(agent)` 会自动订阅,同时接上 `continue_prompt`、steering inbox 与系统提示词。嵌入方式与生命周期要求见[复用 Bub 应用](/zh-cn/docs/integrations/reuse-app/#agent-loop-hooks)。 +`PluginAgentHooks(runtime).subscribe(events)` 负责将四个拦截 Hook 绑定到指定的 `EventBus` 上;而 `AgentPlugins.attach(agent)` 还会在此基础上把 `continue_prompt`、`SteeringInbox`、`system_prompt` 和 `provide_tools` 一并接入核心 `Agent`。在宿主服务中复用它们的完整示例见[复用 Bub 应用](/zh-cn/docs/integrations/reuse-app/#agent-loop-hooks)。 ## PluginAgentHooks {#pluginagenthooks} @@ -344,6 +815,15 @@ class PluginAgentHooks: ) -> None: ... ``` +| 方法 | 说明 | +| --- | --- | +| `__init__(runtime)` | 绑定指定的 `HookRuntime` 实例 | +| `subscribe(events=None)` | 将 4 个拦截 Hook 注册到传入的 `EventBus`(省略时新建一个 `EventBus`)并返回该事件总线 | +| `before_llm_call(request, state)` | 按优先级依次执行 `before_llm_call` 插件并返回更新后的 `(request, decision)` | +| `after_llm_call(request, result, state)` | 执行所有 `after_llm_call` 插件 | +| `before_tool_call(call, state)` | 按优先级依次执行 `before_tool_call` 插件并返回更新后的 `(call, decision)` | +| `after_tool_call(call, result, state)` | 执行所有 `after_tool_call` 插件 | + ## AgentPlugins {#agentplugins} ### `AgentComponents` {#agentcomponents} @@ -355,6 +835,12 @@ class AgentComponents(TypedDict, total=False): sidecars: Sequence[TapeSidecar] ``` +| 键 | 类型 | 说明 | +| --- | --- | --- | +| `store` | `TapeStore \| AsyncTapeStore` | 由 `provide_tape_store` 提供的存储后端(未提供时省略该键) | +| `context` | `TapeContext` | 由 `build_tape_context` 提供的上下文投影策略 | +| `sidecars` | `Sequence[TapeSidecar]` | 由 `provide_tape_sidecar` 提供的 Sidecar 序列 | + ### `AgentPlugins` {#agentplugins-class} ```python @@ -380,3 +866,12 @@ class AgentPlugins: agent: Agent | None = None, ) -> TurnState: ... ``` + +| 参数 / 方法 | 说明 | +| --- | --- | +| `framework` | 复用已有的 `BubFramework` 实例(与 `plugins` 二选一;都不传时默认自动加载已安装的入口点插件) | +| `plugins` | 仅加载指定的插件对象集合,不扫描环境中的其他入口点插件 | +| `running()` | 启动并管理 `provide_lifespan`、`provide_tape_store` 和 `provide_steering_inbox` 生命周期的异步上下文管理器 | +| `components()` | 返回可直接展开传给 `Agent(**plugins.components())` 的存储、上下文和 Sidecar 字典 | +| `attach(agent, *, tools=True)` | 将拦截 Hooks、`continue_prompt`、`SteeringInbox`、`system_prompt` 及插件工具(当 `tools=True` 时)挂载到核心 `Agent` | +| `build_state(session_id, *, message=None, agent=None)` | 调用 `load_state` 组装单轮运行所需的 `TurnState`(包含 `_session_id`、`_runtime_agent` 与 `_steering_inbox`) | diff --git a/website/src/content/docs/zh-cn/docs/reference/python-api.mdx b/website/src/content/docs/zh-cn/docs/reference/python-api.mdx index 10e3dff5..a7365782 100644 --- a/website/src/content/docs/zh-cn/docs/reference/python-api.mdx +++ b/website/src/content/docs/zh-cn/docs/reference/python-api.mdx @@ -1,14 +1,30 @@ --- title: Python API -description: bub.core 与应用层的公开 API 签名。 +description: Bub Python API 完整参考:查阅 bub.core(Agent、Tool、Tape)与应用层的公开类、函数签名、字段与参数说明表。 --- -## `bub.core` +本页按模块列出 Bub 公开的 Python 类与函数签名,并用表格说明其参数、属性与方法。分步使用教程见 [SDK 指南](/zh-cn/docs/sdk/)、[Tape](/zh-cn/docs/concepts/tape/)、[事件](/zh-cn/docs/concepts/events/) 与 [Turn](/zh-cn/docs/concepts/turn/)。 + +- **`bub.core`**:核心层,包含 `Agent` 循环、模型客户端协议、工具、Tape 与事件总线。仅导入 `bub.core` 不会读取 YAML 配置文件、`BUB_*` 环境变量,也不会加载 CLI 或插件。 +- **`bub`**:应用层,包含 `BubFramework`、`BubAgent`、消息渠道与配置加载。需要[安装](/zh-cn/docs/getting-started/install/) `bub[app]` 可选依赖。 + +签名中出现的 `republic.*` 类型来自底层依赖包 Republic,本页不单独展开。 + +--- + +## 核心层 {#core} ### `Agent` {#agent} ```python +from bub.core import Agent + class Agent: + tools: dict[str, Tool] + builtin_tools: list[BuiltinTool] + system_prompt: SystemPrompt + events: EventBus + def __init__( self, *, @@ -92,15 +108,55 @@ class Agent: ) -> list[Tool]: ... ``` -### `Model` {#model} +**构造函数参数**(`Agent.__init__`): + +| 参数 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `model` | `Model \| None` | `None` | 默认模型连接(`republic.ChatModel` 或 `ModelClient`);也可在每次调用 `run()` 时单独传入 | +| `store` | `TapeStore \| AsyncTapeStore \| None` | 新的 `InMemoryTapeStore()` | 会话历史存储后端,支持同步或异步实现 | +| `tools` | `Iterable[Tool \| BuiltinTool]` | `()` | 本地 `Tool` 对象(存入 `agent.tools`)或提供商侧执行的工具如 `republic.tools.WebSearch()`(存入 `agent.builtin_tools`);同名工具后传入的覆盖前面的 | +| `system_prompt` | `SystemPrompt \| PromptSection \| Iterable[PromptSection]` | `()` | 系统提示词;每次 Run 在第一个模型 Step 前渲染一次,并在后续 Step 中复用 | +| `context` | `TapeContext \| None` | `default_tape_context()` | 控制如何从 Tape 历史条目投影出模型上下文消息 | +| `sidecars` | `Sequence[TapeSidecar]` | `()` | 随主 Tape 一起挂载的附属 `TapeSidecar` 列表 | +| `max_steps` | `int` | `sys.maxsize` | 单次 Run 允许的最大 Step 数 | +| `max_tool_concurrency` | `int \| None` | `None` | 单步响应内并发执行本地工具的最大数量(`1` 表示串行执行;不控制不同 Run 之间的并发) | +| `name` | `str` | `"agent"` | OpenTelemetry trace span 中显示的 Agent 名称 | +| `command_prefix` | `str \| None` | `None` | 直接命令前缀(`None` 表示禁用;启用时须为非空且不含空白的字符串,如 `","`) | + +**运行参数**(`Agent.run` / `Agent.start`): + +| 参数 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `prompt` | `str \| list[UserContent]` | 必填 | 本次发送给 Agent 的用户提示词或多模态内容列表 | +| `model` | `Model \| None` | `self.model` | 覆盖本次 Run 使用的模型连接 | +| `options` | `Mapping[str, Any] \| None` | `None` | 传给底层模型生成调用的参数(对应 `republic.ChatOptions`,如 `max_tokens`、`reasoning_effort`) | +| `tape` | `str` | 必填 | 本次 Run 使用的会话 Tape 名称 | +| `state` | `TurnState \| None` | `None` | 本次 Run 内供工具和事件处理器共享的临时字典 | +| `merge_back` | `bool` | `True` | 流关闭时是否将本次 Run 在分支上写入的记录合并回主 Tape(详见[分支合并策略](/zh-cn/docs/sdk/tape/#forks-and-merges)) | +| `metadata` | `dict[str, Any] \| None` | `None` | 随 `RunStarted` 事件发出的调用元数据,不进入模型上下文 | + +**核心方法说明**: + +| 方法 | 说明 | +| --- | --- | +| `run(...)` | 异步上下文管理器:在命名 Tape 的分支上启动一次 Run,退出 `async with` 时自动关闭流并按 `merge_back` 合并记录 | +| `start(...)` | 与 `run(...)` 参数一致,但直接返回 `AsyncStreamEvents`,需由调用方手动调用 `await stream.aclose()` | +| `tape(name, *, state=None)` | 返回指定名称的 `Tape` 读写视图(不会自动写入 `session/start` 初始锚点) | +| `session(name, *, state=None, merge_back=True)` | 异步上下文管理器:打开指定 Tape 的临时分支并在退出时按 `merge_back` 合并 | +| `run_on(tape, prompt, ...)` | 在一个已经打开的 `Tape` 实例上运行一次 Run | +| `run_once(...)` | 仅执行单个模型 Step 及其请求的全部工具调用 | +| `run_command(tape, line)` | 直接执行一条带命令前缀的工具命令,不调用模型 | +| `prepare_tools(tape, prompt)` | 供子类覆写:每次 Run 开始时调用一次以决定可用工具集;若运行中调用了未在初始集合内的延迟工具,则通过 `prepare_tools(tape, None)` 重新解析 | + +--- + +### `Model`、`ModelClient` 与 `ChatModelClient` {#model} ```python -Model = republic.ChatModel | ModelClient -``` +from bub.core import ChatModelClient, Model, ModelClient -### `ModelClient` +type Model = republic.ChatModel | ModelClient -```python class ModelClient(Protocol): max_tokens: int | None @@ -114,11 +170,7 @@ class ModelClient(Protocol): spec: str, options: Mapping[str, Any], ) -> AbstractAsyncContextManager[tuple[str, republic.Stream[Any]]]: ... -``` -### `ChatModelClient` - -```python class ChatModelClient: max_tokens: int | None = None @@ -137,15 +189,23 @@ class ChatModelClient: ) -> AsyncIterator[tuple[str, republic.Stream[Any]]]: ... ``` -### `ToolExposure` +| 成员 / 参数 | 类型 | 说明 | +| --- | --- | --- | +| `spec` | `str` | 模型规格标识符(格式为 `provider:model`) | +| `max_tokens` | `int \| None` | 默认的最大输出 Token 数;单次调用的 `options["max_tokens"]` 优先 | +| `open_stream(messages, *, spec, options)` | 异步上下文管理器 | 打开一次模型流式请求,产出一个 `(resolved_spec, republic_stream)` 元组 | +| `ChatModelClient(model)` | `republic.ChatModel` | 将 `republic.ChatModel` 包装为 `ModelClient` 的内置适配器;底层连接生命周期仍由调用方管理 | -```python -ToolExposure = Literal["auto", "direct", "code", "command"] -``` +--- -### `ToolContext` +### `Tool`、`ToolContext` 与 `@tool` {#tools} ```python +from bub.core import Tool, ToolContext, tool +from bub.core.tools import ToolExposure, content_result, result_content + +type ToolExposure = Literal["auto", "direct", "code", "command"] + @dataclass(frozen=True) class ToolContext: tape: Tape @@ -156,13 +216,7 @@ class ToolContext: events: EventBus | None = field(default=None, repr=False, compare=False) step_messages: list[republic.Message] = field(default_factory=list, repr=False, compare=False) call_id: str | None = None -``` - -`step_messages` 是发起调用的模型步骤发送的用户消息(Tape 要等工具调用结束后才记录它们);`call_id` 是模型给这次调用的 ID,代码模式中的调用沿用 `run_code` 调用的 ID。 -### `Tool` {#tools} - -```python @dataclass(frozen=True) class Tool: name: str @@ -191,36 +245,6 @@ class Tool: renderer: Callable[[Any], str] | None = None, deferred: bool = False, ) -> Tool: ... -``` - -### `tool` - -```python -@overload -def tool( - func: Callable, - *, - name: str | None = ..., - model: type[BaseModel] | None = ..., - description: str | None = ..., - context: bool = ..., - exposure: ToolExposure = ..., - renderer: Callable[[Any], str] | None = ..., - deferred: bool = ..., -) -> Tool: ... - -@overload -def tool( - func: None = ..., - *, - name: str | None = ..., - model: type[BaseModel] | None = ..., - description: str | None = ..., - context: bool = ..., - exposure: ToolExposure = ..., - renderer: Callable[[Any], str] | None = ..., - deferred: bool = ..., -) -> Callable[[Callable], Tool]: ... def tool( func: Callable | None = None, @@ -233,23 +257,48 @@ def tool( renderer: Callable[[Any], str] | None = None, deferred: bool = False, ) -> Tool | Callable[[Callable], Tool]: ... -``` - -### `content_result` -```python def content_result(content: Sequence[UserContent]) -> dict[str, Any]: ... +def result_content(result: Any) -> list[UserContent]: ... ``` -### `result_content` +**`@tool` / `Tool` 参数与字段说明**: -```python -def result_content(result: Any) -> list[UserContent]: ... -``` +| 参数 / 字段 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `func` / `handler` | `Callable[..., Any]` | 必填 | 实际执行工具逻辑的同步或异步 Python 函数 | +| `name` | `str \| None` | 函数名 `func.__name__` | 工具名称(含点号的名称在暴露给模型时会自动转为下划线别名) | +| `model` | `type[BaseModel] \| None` | `None` | 可选的 Pydantic 参数校验模型(仅用于 `@tool(model=...)` 装饰器) | +| `description` | `str \| None` | 函数的 docstring | 工具的功能描述,供模型判断何时调用 | +| `parameters` | `dict[str, Any]` | 自动从类型标注生成 | 工具入参的 JSON Schema 字典 | +| `context` | `bool` | `False` | 设为 `True` 时,运行时会自动向函数注入关键字参数 `context: ToolContext`(该参数不会出现在模型可见的 Schema 中) | +| `exposure` | `ToolExposure` | `"auto"` | 工具暴露方式:`"auto"`(模型直调、代码模式与命令均可用)、`"direct"`(仅模型直调)、`"code"`(仅在 `run_code` 内可调)、`"command"`(仅作为文本命令可调) | +| `renderer` | `Callable[[Any], str] \| None` | `None` | 自定义将工具返回值渲染为字符串的转换函数 | +| `output_schema` | `dict[str, Any] \| None` | 自动从返回类型生成 | 返回值的 JSON Schema(供代码模式生成类型桩文件使用) | +| `deferred` | `bool` | `False` | 是否启用延迟加载:设为 `True` 时初始仅向模型展示名称与简述,模型按需通过 `tool.describe` 加载完整 Schema | + +**`ToolContext` 字段说明**: + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `tape` | `Tape` | 当前会话的 `Tape` 读写对象 | +| `run_id` | `str \| None` | 当前 Run 的唯一标识符 | +| `state` | `dict[str, Any]` | 当前调用共享的 `TurnState` 字典 | +| `code_mode` | `bool` | 本次工具调用是否由代码模式内部发起 | +| `command` | `bool` | 本次工具调用是否由直接命令发起 | +| `events` | `EventBus \| None` | 当前 Agent 的事件总线 | +| `step_messages` | `list[republic.Message]` | 发起本次工具调用的那个模型 Step 所发送的用户消息(这些消息在当前 Step 的工具全部执行完后才写入 Tape) | +| `call_id` | `str \| None` | 模型为本次调用分配的 ID(代码模式内部发起的工具调用会沿用外层 `run_code` 的 `call_id`) | -### `PromptContext` +`content_result(content)` 用于在工具返回值中同时携带文本与图片、音频或视频,投影上下文时由 `result_content(result)` 还原为多模态内容块(详见[媒体内容的存储边界](/zh-cn/docs/sdk/tape/#media))。 + +--- + +### `SystemPrompt`、`PromptSection` 与 `PromptContext` {#system-prompt} ```python +from bub.core import PromptContext, PromptSection, SystemPrompt + @dataclass(frozen=True) class PromptContext: agent: Agent @@ -263,17 +312,9 @@ class PromptContext: @property def available_tools(self) -> list[Tool]: ... -``` - -### `PromptSection` {#system-prompt} - -```python -PromptSection = str | Callable[[PromptContext], str | Awaitable[str | None] | None] -``` -### `SystemPrompt` +type PromptSection = str | Callable[[PromptContext], str | Awaitable[str | None] | None] -```python class SystemPrompt: def __init__(self, sections: Iterable[PromptSection] = ()) -> None: ... @@ -291,60 +332,44 @@ class SystemPrompt: async def render(self, context: PromptContext) -> str: ... ``` -### `TapeEntry` {#tapeentry} - -```python -@dataclass(frozen=True) -class TapeEntry: - id: int - kind: str - payload: dict[str, Any] - meta: dict[str, Any] = field(default_factory=dict) - date: str = field(default_factory=utc_now) - - def copy(self) -> TapeEntry: ... +| 类 / 成员 | 说明 | +| --- | --- | +| `PromptSection` | 一段固定字符串,或接收 `PromptContext` 并返回 `str \| None` 的同步/异步函数 | +| `SystemPrompt.add(section)` / `remove(section)` | 动态追加或移除一段系统提示词片段 | +| `await SystemPrompt.render(context)` | 按顺序执行所有片段,将非空文本用换行拼接为最终系统提示词 | +| `PromptContext` | 渲染时传入的上下文,提供当前 `agent`、`tape`、`prompt`、`tools`、`model`,以及便捷属性 `state` 与 `available_tools` | - @classmethod - def message(cls, message: dict[str, Any], **meta: Any) -> TapeEntry: ... +--- - @classmethod - def system(cls, content: str, **meta: Any) -> TapeEntry: ... +### `bub.prompt` {#prompt} - @classmethod - def anchor( - cls, - name: str, - state: dict[str, Any] | None = None, - **meta: Any, - ) -> TapeEntry: ... +```python +from bub.prompt import LegacyPrompt, UserContent, prompt_text, to_content, to_legacy_prompt - @classmethod - def tool_call( - cls, - calls: list[dict[str, Any]], - *, - content: str = "", - **meta: Any, - ) -> TapeEntry: ... +type UserContent = str | republic.Image | republic.Audio | republic.Video +type LegacyPrompt = str | list[dict[str, Any]] - @classmethod - def tool_result(cls, results: list[Any], **meta: Any) -> TapeEntry: ... +def to_content(prompt: list[UserContent] | LegacyPrompt) -> list[UserContent]: ... +def to_legacy_prompt(content: list[UserContent]) -> LegacyPrompt: ... +def prompt_text(content: list[UserContent]) -> str: ... +``` - @classmethod - def error(cls, error: BubError, **meta: Any) -> TapeEntry: ... +| 类型 / 函数 | 说明 | +| --- | --- | +| `UserContent` | 单块用户输入内容:纯文本或 Republic 多模态媒体对象 | +| `LegacyPrompt` | 旧版 Hook 兼容格式(纯文本为 `str`,含媒体时为字典列表;见[提示词内容格式](/zh-cn/docs/reference/hooks/#prompt-content)) | +| `to_content(prompt)` | 将字符串、字典列表或 `list[UserContent]` 统一标准化为 `list[UserContent]` | +| `to_legacy_prompt(content)` | 将 `list[UserContent]` 转换为 `LegacyPrompt` | +| `prompt_text(content)` | 提取 `list[UserContent]` 中的纯文本部分并拼接为字符串 | - @classmethod - def event( - cls, - name: str, - data: dict[str, Any] | None = None, - **meta: Any, - ) -> TapeEntry: ... -``` +--- -### `TapeContext` +### `Tape`、`TapeContext` 与存储 {#tape} ```python +from bub.core import Tape, TapeContext, default_tape_context, session_tape_name +from bub.core.tape import AnchorSummary, TapeEntry, TapeInfo + @dataclass(frozen=True) class TapeContext: anchor: AnchorSelector = LAST_ANCHOR @@ -352,17 +377,10 @@ class TapeContext: state: dict[str, Any] = field(default_factory=dict) def build_query(self, query: TapeQuery) -> TapeQuery: ... -``` -### `default_tape_context` - -```python def default_tape_context() -> TapeContext: ... -``` - -### `TapeInfo` +def session_tape_name(session_id: str, workspace: Path) -> str: ... -```python @dataclass(frozen=True) class TapeInfo: name: str @@ -372,20 +390,12 @@ class TapeInfo: entries_since_last_anchor: int last_token_usage: int | None last_token_cache_hit_rate: float | None -``` - -### `AnchorSummary` -```python @dataclass(frozen=True) class AnchorSummary: name: str state: dict[str, object] -``` -### `Tape` {#tape} - -```python @dataclass(frozen=True) class Tape: store: AsyncTapeStore @@ -423,46 +433,111 @@ class Tape: async def fork_tape(self, merge_back: bool = True) -> AsyncGenerator[Tape, None]: ... ``` -### `session_tape_name` +**`TapeContext` 字段说明**: -```python -def session_tape_name(session_id: str, workspace: Path) -> str: ... -``` +| 字段 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `anchor` | `AnchorSelector` | `LAST_ANCHOR` | 上下文读取的起始锚点:默认从最近一个 anchor 之后读取;可传具体 anchor 名称字符串,或传 `None` 从头读取全部条目 | +| `select` | `ContextSelector \| None` | `None` | 自定义投影选择器函数 `(Iterable[TapeEntry], TapeContext) -> list[republic.Message]`。建议使用 `default_tape_context()` 工厂函数以支持完整对话与工具往返 | +| `state` | `dict[str, Any]` | `{}` | 绑定在该上下文上的请求级临时状态字典(即 `TurnState`) | + +**`Tape` 属性与方法说明**: -### `TapeSidecar` {#tapesidecar} +| 属性 / 方法 | 说明 | +| --- | --- | +| `name` | 当前 Tape 的名称;若直接构造 `Tape` 而未调用 `scoped(name)`,访问该属性会抛出 `ValueError` | +| `scoped(name, context=None)` | 返回绑定了指定 `name`(及可选新 `context`)的 `Tape` 视图 | +| `with_context(context)` | 返回替换了 `TapeContext` 的新 `Tape` 视图(适合单次临时换一种投影方式读取) | +| `query()` | 返回绑定了当前 Tape 与 `store` 的 `TapeQuery` 查询构建器 | +| `await read_messages()` | 按当前 `TapeContext` 筛选条目并投影为 `list[republic.Message]`(自动排除 `meta["context"] is False` 的条目) | +| `await handoff(*, name, state=None, **meta)` | 追加一条 `anchor` 条目和一条 `handoff` 事件,将默认上下文读取起点前移到此处 | +| `await reset(*, state=None, keep_sidecars=())` | 清空当前 Tape 记录并重新写入 `session/start` 锚点;默认同时重置所有已挂载的 Sidecar | +| `await info()` / `await anchors(limit=20)` | 分别返回 `TapeInfo` 统计信息和 `list[AnchorSummary]` 历史锚点列表 | +| `await search(query)` | 执行传入的 `TapeQuery` 并返回匹配的 `list[TapeEntry]` | +| `await append_event(name, payload, **meta)` | 向 Tape 显式追加一条 `kind="event"` 的业务事件记录 | +| `fork_tape(merge_back=True)` | 异步上下文管理器:在临时分支上读写,退出时默认将新条目合并回主 Tape | + +`session_tape_name(session_id, workspace)` 生成 `__` 格式的物理 Tape 名称,供应用层隔离不同工作区下的会话。 + +#### `TapeSidecar` {#tapesidecar} ```python +from bub.core.sidecars import TapeSidecar, sidecar_tape_name + class TapeSidecar(Protocol): @property def name(self) -> str: ... - def sidecar_tape_name(owner: str, sidecar: str) -> str: ... ``` -Sidecar 由配套 Tape `__sidecar__` 承载:随主 Tape 分支、合并和重置,条目不进入主上下文。挂载方式见 [Sidecar](/zh-cn/docs/sdk/tape/#sidecars),应用层的提供方式见 [`provide_tape_sidecar`](/zh-cn/docs/reference/hooks/#provide_tape_sidecar)。 +Sidecar 由名为 `__sidecar__` 的配套物理 Tape 承载:随主 Tape 一起创建分支、合并和重置,但其中的条目不会进入主对话的模型上下文。挂载方式见 [Sidecar](/zh-cn/docs/sdk/tape/#sidecars),应用层 Hook 见 [`provide_tape_sidecar`](/zh-cn/docs/reference/hooks/#provide_tape_sidecar)。 + +#### `TapeEntry` {#tapeentry} + +```python +@dataclass(frozen=True) +class TapeEntry: + id: int + kind: str + payload: dict[str, Any] + meta: dict[str, Any] = field(default_factory=dict) + date: str = field(default_factory=utc_now) + + def copy(self) -> TapeEntry: ... + + @classmethod + def message(cls, message: dict[str, Any], **meta: Any) -> TapeEntry: ... + @classmethod + def system(cls, content: str, **meta: Any) -> TapeEntry: ... + @classmethod + def anchor(cls, name: str, state: dict[str, Any] | None = None, **meta: Any) -> TapeEntry: ... + @classmethod + def tool_call(cls, calls: list[dict[str, Any]], *, content: str = "", **meta: Any) -> TapeEntry: ... + @classmethod + def tool_result(cls, results: list[Any], **meta: Any) -> TapeEntry: ... + @classmethod + def error(cls, error: BubError, **meta: Any) -> TapeEntry: ... + @classmethod + def event(cls, name: str, data: dict[str, Any] | None = None, **meta: Any) -> TapeEntry: ... +``` + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `id` | `int` | 由存储后端分配的递增序号(新建条目初始为 `0`,在 `store.append` 时改写) | +| `kind` | `str` | 条目类型:`message`、`system`、`anchor`、`tool_call`、`tool_result`、`error`、`event` | +| `payload` | `dict[str, Any]` | 条目的具体内容字典 | +| `meta` | `dict[str, Any]` | 运行时元数据;传入 `context=False` 可让该条目不进入模型上下文 | +| `date` | `str` | ISO 8601 时间戳字符串,默认取当前 UTC 时间 | -### `TapeStore` {#tape-store} +#### `TapeStore` 与 `AsyncTapeStore` {#tape-store} ```python +from bub.core.store import AsyncTapeStore, TapeStore, is_async_tape_store + class TapeStore(Protocol): def list_tapes(self) -> list[str]: ... def reset(self, tape: str) -> None: ... def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ... def append(self, tape: str, entry: TapeEntry) -> None: ... -``` -### `AsyncTapeStore` - -```python class AsyncTapeStore(Protocol): async def list_tapes(self) -> list[str]: ... async def reset(self, tape: str) -> None: ... async def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ... async def append(self, tape: str, entry: TapeEntry) -> None: ... + +def is_async_tape_store(store: TapeStore | AsyncTapeStore) -> TypeIs[AsyncTapeStore]: ... ``` -### `TapeQuery` {#tapequery} +| 方法 | 实现契约 | +| --- | --- | +| `list_tapes()` | 返回已存在的会话 Tape 名称列表(无需列出 sidecar 等内部物理 Tape) | +| `append(tape, entry)` | 追加条目,并在该 Tape 内分配从 `1` 开始单调递增的 `id`(不要依赖调用方传入的 `entry.id`) | +| `fetch_all(query)` | 按写入顺序返回符合 `TapeQuery` 条件的条目集合(异步版本是 `async def` 返回 `Iterable`,而非异步生成器) | +| `reset(tape)` | 清空该 Tape 的所有记录并重置 ID 计数,使下一次 `append` 重新从 `1` 开始 | + +#### `TapeQuery` {#tapequery} ```python @dataclass(frozen=True) @@ -480,44 +555,48 @@ class TapeQuery[T: TapeStore | AsyncTapeStore]: @overload def all(self: TapeQuery[TapeStore]) -> Iterable[TapeEntry]: ... - @overload async def all(self: TapeQuery[AsyncTapeStore]) -> Iterable[TapeEntry]: ... ``` -| 过滤条件 | 语义 | +| 方法 | 过滤语义 | | --- | --- | -| `after_anchor(name)` / `last_anchor()` | 指定 anchor 或最近一个 anchor 之后;Tape 中没有 anchor 时抛 `BubError(kind=NOT_FOUND)` | -| `between_anchors(start, end)` | 两个 anchor 之间,不含边界;任一 anchor 不存在时抛 `NOT_FOUND` | -| `between_dates(start, end)` | ISO 日期或时间范围,含边界;只有日期的上界覆盖整天 | -| `kinds(*kinds)` | 条目类型 | -| `query(value)` | 在 kind、日期、payload 和 meta 的 JSON 文本中做不区分大小写的包含匹配 | -| `limit(value)` | 最多返回的条目数,在其他过滤之后应用 | +| `query(value)` | 在条目的 `kind`、`date`、`payload` 和 `meta` 的 JSON 文本中做不区分大小写的包含匹配 | +| `after_anchor(name)` / `last_anchor()` | 返回指定名称或最近一个 anchor **之后**的条目(不含该边界 anchor 本身);若找不到对应 anchor 则抛出 `BubError(kind=NOT_FOUND)` | +| `between_anchors(start, end)` | 返回两个 anchor 之间的条目(不含两端边界);任一 anchor 不存在时抛出 `BubError(kind=NOT_FOUND)` | +| `between_dates(start, end)` | 按 ISO 日期或时间范围过滤(含边界;只传日期时上界覆盖整天) | +| `kinds(*kinds)` | 只保留指定 `kind` 的条目 | +| `limit(value)` | 最多返回的条目数(在其他过滤条件生效后截断) | +| `all()` | 执行查询(同步 Store 直接返回 `Iterable`,异步 Store 需 `await`) | -`after_anchor` / `last_anchor` 返回指定或最近一个 anchor **之后**的条目,不包含边界 anchor 本身;anchor 不存在时抛出 `BubError(kind=NOT_FOUND)`。因此默认投影不会收到边界 anchor。使用 `anchor=None` 等不过滤 anchor 的读取方式时,选择器可能收到 anchor 条目,默认选择器会把它转换为 `[Anchor created: …]` 助手消息。直接使用 `TapeQuery` 时不叠加 `TapeContext` 的 `context=False` 过滤。 - -### `InMemoryQueryMixin` +#### 内置 Store 实现 {#builtin-stores} ```python +from bub.core.store import ( + AsyncTapeStoreAdapter, + FileTapeStore, + InMemoryQueryMixin, + InMemoryTapeStore, +) + class InMemoryQueryMixin: def read(self, tape: str) -> list[TapeEntry] | None: ... def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ... -``` - -### `InMemoryTapeStore` {#builtin-stores} -```python class InMemoryTapeStore(InMemoryQueryMixin): def __init__(self) -> None: ... def list_tapes(self) -> list[str]: ... def reset(self, tape: str) -> None: ... def read(self, tape: str) -> list[TapeEntry] | None: ... def append(self, tape: str, entry: TapeEntry) -> None: ... -``` -### `AsyncTapeStoreAdapter` +class FileTapeStore(InMemoryQueryMixin): + def __init__(self, directory: Path) -> None: ... + def list_tapes(self) -> list[str]: ... + def reset(self, tape: str) -> None: ... + def append(self, tape: str, entry: TapeEntry) -> None: ... + def read(self, tape: str) -> list[TapeEntry] | None: ... -```python class AsyncTapeStoreAdapter: def __init__(self, store: TapeStore) -> None: ... async def list_tapes(self) -> list[str]: ... @@ -526,118 +605,75 @@ class AsyncTapeStoreAdapter: async def append(self, tape: str, entry: TapeEntry) -> None: ... ``` -### `FileTapeStore` - -```python -class FileTapeStore(InMemoryQueryMixin): - def __init__(self, directory: Path) -> None: ... - def list_tapes(self) -> list[str]: ... - def reset(self, tape: str) -> None: ... - def append(self, tape: str, entry: TapeEntry) -> None: ... - def read(self, tape: str) -> list[TapeEntry] | None: ... -``` +| 类名 | 说明 | +| --- | --- | +| `InMemoryTapeStore` | 进程内内存字典,`read()` 返回条目副本,进程退出即清空 | +| `FileTapeStore(directory)` | 每个 Tape 存为一个 `.jsonl` 文件,单文件配一把线程锁(无跨进程锁);`list_tapes()` 只列出文件名中恰好含有一个 `__` 的主会话文件。由于直接将 Tape 名称用作文件名,Web 服务须校验名称安全性(见 [Tape 与记忆](/zh-cn/docs/sdk/tape/#storage)) | +| `AsyncTapeStoreAdapter(store)` | 将同步 `TapeStore` 包装到 `asyncio.to_thread()` 中,适配为 `AsyncTapeStore` | +| `InMemoryQueryMixin` | 为只实现了 `read(tape)` 的简易存储自动提供内存级的 `fetch_all(query)` 过滤实现 | -### `is_async_tape_store` +--- -```python -def is_async_tape_store( - store: TapeStore | AsyncTapeStore, -) -> TypeIs[AsyncTapeStore]: ... -``` +### `EventBus` 与事件类 {#events} + +```python +from bub.core.events import ( + AgentEvent, + ChatFinished, + CommandFinished, + Event, + EventBus, + LLMCallFinished, + LLMCallStarted, + MessagesPending, + RunFinished, + RunStarted, + StepFinished, + StepStarted, + TapeEvent, + ToolCallFinished, + ToolCallStarted, +) -### `EventBus` {#events} +class Event: + @property + def stopped(self) -> bool: ... -```python class EventBus: @overload def on(self, event_type: type[E]) -> Callable[[EventHandler[E]], EventHandler[E]]: ... - @overload def on(self, event_type: type[E], handler: EventHandler[E]) -> EventHandler[E]: ... def off(self, event_type: type[E], handler: EventHandler[E]) -> None: ... async def emit(self, event: E) -> E: ... -``` - -### `Event` - -```python -class Event: - @property - def stopped(self) -> bool: ... -``` - -### 事件一览 {#event-reference} - -| 事件 | 触发时机 | 处理器可读取或修改的内容 | -| --- | --- | --- | -| `RunStarted` | 模型 Run 开始 | `model`、`prompt`、`metadata` | -| `RunFinished` | Run 的流关闭 | `status`(`ok` / `error` / `cancelled`)、`steps`、耗时和错误 | -| `StepStarted` | Step 开始 | `step`、可选的 `prompt` | -| `StepFinished` | Step 结束 | 进度、用量;继续时设置 `next_prompt` | -| `MessagesPending` | 构建请求时,或 Step 结束且没有工具调用时(`step_ended=True`) | 向 `messages` 追加用户内容;Step 结束时追加的消息会让 Run 继续 | -| `LLMCallStarted` | 调用模型提供商之前 | 替换 `request`;设置 `LLMCallDecision.finish()` | -| `LLMCallFinished` | 提供商调用成功或因普通异常失败 | `request` 和汇总后的 `result` | -| `ToolCallStarted` | 工具执行之前 | 替换 `call`;设置 `deny` 或 `replace` | -| `ToolCallFinished` | 工具成功、普通失败、被拒绝或被替换 | 给 `event.result.result` 赋值,替换面向模型的结果 | -| `ChatFinished` | 当前 Step 的对话和工具往返可以记录时 | 消息、工具往返、用量和错误 | -| `CommandFinished` | 直接命令成功或失败 | 命令、状态和输出 | - -`RunFinished` 在流关闭时发出。尚未迭代就关闭的 Run 以 `cancelled` 结束,Step 数为零。模型和工具的 Finished 事件不保证覆盖取消路径,因此计费和清理不能只依赖它们。 - -`StepFinished.next_prompt` 提供下一个 Step 的用户消息,`MessagesPending.messages` 接收 Run 期间到达的消息。达到 `max_steps`(应用层由 `BUB_MAX_STEPS` 设置)时会抛出 `max_steps_reached` 错误。 -直接命令发出工具事件和 `CommandFinished`,但不发出 `RunStarted` 或 `RunFinished`。所有 Agent 事件都有 `state`,`TapeEvent` 子类还带有当前 `tape`。分发规则与决策语义见 [Agent 事件](/zh-cn/docs/concepts/events/#call-control);应用 hooks 与这些事件的映射见 [Hooks 参考](/zh-cn/docs/reference/hooks/#event-mapping)。 - -### `AgentEvent` - -```python @dataclass(kw_only=True) class AgentEvent(Event): state: TurnState -``` -### `TapeEvent` - -```python @dataclass(kw_only=True) class TapeEvent(AgentEvent): tape: Tape -``` - -### `RunStarted` -```python @dataclass(kw_only=True) class RunStarted(TapeEvent): model: str prompt: list[UserContent] metadata: dict[str, Any] = field(default_factory=dict) -``` -### `RunFinished` - -```python @dataclass(kw_only=True) class RunFinished(TapeEvent): status: str steps: int elapsed_ms: int error: str | None = None -``` - -### `StepStarted` -```python @dataclass(kw_only=True) class StepStarted(TapeEvent): step: int prompt: list[UserContent] | None -``` -### `StepFinished` - -```python @dataclass(kw_only=True) class StepFinished(TapeEvent): step: int @@ -647,20 +683,12 @@ class StepFinished(TapeEvent): prompt: list[UserContent] | None = None stream: StreamState = field(default_factory=StreamState) next_prompt: list[UserContent] | None = None -``` - -### `MessagesPending` -```python @dataclass(kw_only=True) class MessagesPending(TapeEvent): prompt: list[UserContent] | None messages: list[list[UserContent]] = field(default_factory=list) -``` -### `CommandFinished` - -```python @dataclass(kw_only=True) class CommandFinished(TapeEvent): line: str @@ -668,11 +696,7 @@ class CommandFinished(TapeEvent): status: str elapsed_ms: int output: str -``` - -### `LLMCallStarted` -```python @dataclass(kw_only=True) class LLMCallStarted(TapeEvent): request: LLMCallRequest @@ -680,20 +704,12 @@ class LLMCallStarted(TapeEvent): @property def stopped(self) -> bool: ... -``` -### `LLMCallFinished` - -```python @dataclass(kw_only=True) class LLMCallFinished(TapeEvent): request: LLMCallRequest result: LLMCallResult -``` - -### `ToolCallStarted` -```python @dataclass(kw_only=True) class ToolCallStarted(AgentEvent): call: ToolCall @@ -701,20 +717,12 @@ class ToolCallStarted(AgentEvent): @property def stopped(self) -> bool: ... -``` -### `ToolCallFinished` - -```python @dataclass(kw_only=True) class ToolCallFinished(AgentEvent): call: ToolCall result: ToolCallResult -``` - -### `ChatFinished` -```python @dataclass(kw_only=True) class ChatFinished(TapeEvent): run_id: str @@ -731,95 +739,46 @@ class ChatFinished(TapeEvent): context_error: BubError | None = None ``` -### `CodeTools` +#### 事件一览 {#event-reference} -```python -CodeTools = Iterable[Tool] | Callable[[TurnState], Iterable[Tool] | None] -``` +| 事件类 | 触发时机 | 处理器可读取或修改的字段 | +| --- | --- | --- | +| `RunStarted` | 模型 Run 启动时 | `model`、`prompt`、`metadata`、`tape`、`state` | +| `RunFinished` | Run 的事件流关闭时 | `status`(`ok` / `error` / `cancelled`)、`steps`、`elapsed_ms`、`error` | +| `StepStarted` | 单个 Step 开始时 | `step`、可选的 `prompt` | +| `StepFinished` | 单个 Step 结束时 | `step`、`status`、`elapsed_ms`、`stream`;可在继续下一步时设置 `next_prompt` | +| `MessagesPending` | 构建请求前,或某步结束且无工具调用时 | 向 `messages` 追加运行期间到达的用户消息;在步末追加会让 Run 继续下一步 | +| `LLMCallStarted` | 调用模型提供商之前 | 替换 `request`;或设置 `decision = LLMCallDecision.finish(text)` | +| `LLMCallFinished` | 模型调用成功或因普通异常失败后 | `request` 与汇总后的 `result` | +| `ToolCallStarted` | 本地工具执行之前 | 替换 `call`;或设置 `decision`(`proceed` / `deny` / `replace`) | +| `ToolCallFinished` | 工具成功、失败、被拒绝或被替代后 | `call` 与 `result`(可给 `event.result.result` 赋值以替换面向模型的结果) | +| `ChatFinished` | 当前 Step 的对话和工具往返准备写入 Tape 时 | `new_messages`、`response_text`、`tool_calls`、`tool_results`、`usage`、`error` | +| `CommandFinished` | 直接命令执行成功或失败时 | `line`、`name`、`status`、`elapsed_ms`、`output` | + +- `RunFinished` 在事件流关闭时发出;尚未迭代就关闭的 Run 以 `status="cancelled"`、`steps=0` 结束。`LLMCallFinished` 和 `ToolCallFinished` 不保证覆盖外部取消路径。 +- 步数超过 `max_steps`(应用层由 `BUB_MAX_STEPS` 控制)时抛出 `max_steps_reached` 错误。 +- 直接命令触发工具事件和 `CommandFinished`,不触发 `RunStarted` 或 `RunFinished`。 +- 拦截载荷(`LLMCallRequest`、`LLMCallDecision`、`ToolCall`、`ToolCallDecision` 等)的字段定义见 [Hooks 参考](/zh-cn/docs/reference/hooks/#interception-payloads)(事件与 Hook 的映射关系见 [Hooks 事件映射](/zh-cn/docs/reference/hooks/#event-mapping) 与 [Agent 事件](/zh-cn/docs/concepts/events/#call-control))。 + +--- -### `ModelResolver` +### `bub.streaming` {#streams} ```python -ModelResolver = Callable[[str | None, ToolContext], tuple[str, Mapping[str, Any]]] -``` +from bub.streaming import AsyncStreamEvents, StreamEvent, StreamState -### `CodeMode` {#code-mode} +@dataclass +class StreamState: + error: BubError | None = None + usage: dict[str, Any] | None = None + system_prompt: str | None = None + tools: list[Tool] = field(default_factory=list) -```python -class CodeMode: - def __init__( - self, - tools: CodeTools = (), - *, - environment: Environment | Callable[[TurnState], Environment] | None = None, - models: str | ModelResolver | None = None, - stub_dir: Path | Callable[[TurnState], Path] | None = None, - media_tools: bool = True, - name: str = RUN_CODE_TOOL_NAME, - ) -> None: ... - - def code_tools(self, state: TurnState) -> list[Tool] | None: ... - def environment(self, state: TurnState) -> Environment: ... - def prompt(self, context: PromptContext) -> str | None: ... -``` - -## `bub.prompt` {#prompt} - -### `UserContent` - -```python -type UserContent = str | republic.Image | republic.Audio | republic.Video -``` - -### `LegacyPrompt` - -```python -type LegacyPrompt = str | list[dict[str, Any]] -``` - -### `to_content` - -```python -def to_content(prompt: list[UserContent] | LegacyPrompt) -> list[UserContent]: ... -``` - -### `to_legacy_prompt` - -```python -def to_legacy_prompt(content: list[UserContent]) -> LegacyPrompt: ... -``` - -### `prompt_text` - -```python -def prompt_text(content: list[UserContent]) -> str: ... -``` - -## `bub.streaming` {#streams} - -### `StreamState` - -```python -@dataclass -class StreamState: - error: BubError | None = None - usage: dict[str, Any] | None = None - system_prompt: str | None = None - tools: list[Tool] = field(default_factory=list) -``` - -### `StreamEvent` - -```python @dataclass(frozen=True) class StreamEvent: kind: Literal["text", "reasoning", "tool_call", "tool_result", "usage", "error", "final"] data: dict[str, Any] -``` -### `AsyncStreamEvents` - -```python class AsyncStreamEvents: def __init__( self, @@ -836,16 +795,24 @@ class AsyncStreamEvents: @property def error(self) -> BubError | None: ... - @property def usage(self) -> dict[str, Any] | None: ... ``` -## `bub.errors` {#errors} +| 类 / 成员 | 说明 | +| --- | --- | +| `StreamEvent.kind` | 流事件类型:`"text"`、`"reasoning"`、`"tool_call"`、`"tool_result"`、`"usage"`、`"error"`、`"final"`(各类型载荷结构见 [SDK:消费事件流](/zh-cn/docs/sdk/#consume-the-stream)) | +| `StreamEvent.data` | 事件载荷字典;其中 `tool_result` 的 `data["tool_results"]` 与本步工具调用一一对应,失败调用对应项为其 `BubError` | +| `await AsyncStreamEvents.aclose()` | 显式关闭事件流并触发 `on_close` 清理与 Tape 分支合并 | +| `AsyncStreamEvents.error` / `usage` | 读取最近一步记录的 `BubError` 或 Token 用量统计字典 | + +--- -### `ErrorKind` +### `bub.errors` {#errors} ```python +from bub.errors import BubError, ErrorKind + class ErrorKind(StrEnum): INVALID_INPUT = "invalid_input" CONFIG = "config" @@ -854,11 +821,7 @@ class ErrorKind(StrEnum): TEMPORARY = "temporary" NOT_FOUND = "not_found" UNKNOWN = "unknown" -``` -### `BubError` - -```python @dataclass class BubError(Exception): kind: ErrorKind @@ -868,61 +831,72 @@ class BubError(Exception): def as_dict(self) -> dict[str, Any]: ... ``` -## `bub.environment` {#environment} - -### `ENVIRONMENT_STATE_KEY` +| 字段 / 方法 | 类型 | 说明 | +| --- | --- | --- | +| `kind` | `ErrorKind` | 错误分类枚举 | +| `message` | `str` | 错误描述文本 | +| `details` | `dict[str, Any] \| None` | 可选的附加结构化上下文 | +| `as_dict()` | `dict[str, Any]` | 转换为可 JSON 序列化的字典(用于写入 Tape 或通过事件流传输) | -```python -ENVIRONMENT_STATE_KEY = "_runtime_environment" -``` +--- -### `CallTool` +### `CodeMode` {#code-mode} ```python -CallTool = Callable[[str, dict[str, Any]], Awaitable[Any]] -``` +from bub.core.codemode import CodeMode -### `CodeFailed` {#codefailed} +type CodeTools = Iterable[Tool] | Callable[[TurnState], Iterable[Tool] | None] +type ModelResolver = Callable[[str | None, ToolContext], tuple[str, Mapping[str, Any]]] -```python -class CodeFailed(Exception): - def __init__(self, error: str, traceback: str = "") -> None: ... -``` - -### `Process` {#process} - -```python -class Process(abc.ABC): - @property - @abc.abstractmethod - def stdout(self) -> asyncio.StreamReader: ... +class CodeMode: + run_code: Tool - @property - @abc.abstractmethod - def stderr(self) -> asyncio.StreamReader: ... + def __init__( + self, + tools: CodeTools = (), + *, + environment: Environment | Callable[[TurnState], Environment] | None = None, + models: str | ModelResolver | None = None, + stub_dir: Path | Callable[[TurnState], Path] | None = None, + media_tools: bool = True, + name: str = "run_code", + ) -> None: ... - @property - @abc.abstractmethod - def returncode(self) -> int | None: ... + def code_tools(self, state: TurnState) -> list[Tool] | None: ... + def environment(self, state: TurnState) -> Environment: ... + def prompt(self, context: PromptContext) -> str | None: ... +``` - @abc.abstractmethod - async def wait(self) -> int: ... +| 参数 / 成员 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `tools` | `CodeTools` | `()` | 允许在 `run_code` 内通过 `await tools.(...)` 调用的工具列表(或按 `TurnState` 动态返回工具列表的函数) | +| `environment` | `Environment \| Callable \| None` | 当前目录下的 `LocalEnvironment()` | 执行 Python 代码的 `Environment` 实例或工厂函数 | +| `models` | `str \| ModelResolver \| None` | `None` | 允许代码内调用的模型规格或解析器 | +| `stub_dir` | `Path \| Callable \| None` | `None` | 生成工具类型提示桩文件(stubs)的目录 | +| `media_tools` | `bool` | `True` | 是否在代码中暴露 `attach_image` / `attach_audio` / `attach_video` | +| `name` | `str` | `"run_code"` | 暴露给模型的工具名称 | +| `code_mode.run_code` | `Tool` | — | 生成的 `Tool` 实例,可传给 `Agent(tools=[code_mode.run_code])` | +| `code_mode.prompt` | `PromptSection` | — | 描述可用工具签名的系统提示词片段,可传给 `Agent(system_prompt=[..., code_mode.prompt])` | - @abc.abstractmethod - async def write_stdin(self, data: bytes) -> None: ... +用法示例见 [SDK:工具与代码模式](/zh-cn/docs/sdk/tools/#compose-tools-with-codemode)。 - @abc.abstractmethod - def close_stdin(self) -> None: ... +--- - @abc.abstractmethod - def signal(self, *, kill: bool) -> None: ... +### `Environment`、`Process` 与 `LocalEnvironment` {#environment} - def is_running(self) -> bool: ... -``` +```python +from bub.environment import ( + ENVIRONMENT_STATE_KEY, + CallTool, + CodeFailed, + Environment, + LocalEnvironment, + Process, +) -### `Environment` +ENVIRONMENT_STATE_KEY = "_runtime_environment" +type CallTool = Callable[[str, dict[str, Any]], Awaitable[Any]] -```python class Environment(abc.ABC): workspace: str | None = None python: str = "python3" @@ -942,7 +916,6 @@ class Environment(abc.ABC): @abc.abstractmethod async def write_text(self, path: str, content: str) -> None: ... - def resolve_path(self, path: str) -> str: ... @abc.abstractmethod @@ -956,44 +929,98 @@ class Environment(abc.ABC): ) -> None: ... async def close(self) -> None: ... + +class LocalEnvironment(Environment): + def __init__(self, workspace: str | Path | None = None) -> None: ... ``` -### `LocalEnvironment` +#### `Environment` 成员说明 {#environment-members} + +| 成员 | 签名 | 说明 | +| --- | --- | --- | +| `workspace` | `str \| None` | 环境内部的工作目录路径;为 `None` 时拒绝解析相对路径 | +| `python` | `str` | 环境内部的 Python 解释器路径,默认 `"python3"`(`LocalEnvironment` 使用当前 `sys.executable`) | +| `spawn` | `async (command, *, cwd=None, env=None) -> Process` | **抽象方法**。传入字符串时通过 Shell 执行,传入序列时按参数向量启动;`cwd` 默认取 `workspace` | +| `read_text` | `async (path) -> str` | **抽象方法**。按 UTF-8 读取文本文件 | +| `read_bytes` | `async (path) -> bytes` | 读取文件原始字节(默认调用环境内的 `python` 读取;可直接访问文件系统的实现应覆写它) | +| `write_text` | `async (path, content) -> None` | **抽象方法**。按 UTF-8 写入文本文件,并自动创建缺失的父目录 | +| `resolve_path` | `(path) -> str` | 将相对路径基于 `workspace` 解析为环境内绝对路径;无 `workspace` 时抛出 `ValueError` | +| `run_code` | `async (code, *, tools, call_tool, write) -> None` | **抽象方法**。在环境内执行模型编写的 Python 代码 | +| `close` | `async () -> None` | 释放环境资源;在 `framework.running()` 退出时自动调用 | + +#### `Process` {#process} ```python -class LocalEnvironment(Environment): - def __init__(self, workspace: str | Path | None = None) -> None: ... +class Process(abc.ABC): + @property + @abc.abstractmethod + def stdout(self) -> asyncio.StreamReader: ... + @property + @abc.abstractmethod + def stderr(self) -> asyncio.StreamReader: ... + @property + @abc.abstractmethod + def returncode(self) -> int | None: ... - async def spawn( - self, - command: str | Sequence[str], - *, - cwd: str | None = None, - env: Mapping[str, str] | None = None, - ) -> LocalProcess: ... + @abc.abstractmethod + async def wait(self) -> int: ... + @abc.abstractmethod + async def write_stdin(self, data: bytes) -> None: ... + @abc.abstractmethod + def close_stdin(self) -> None: ... + @abc.abstractmethod + def signal(self, *, kill: bool) -> None: ... + def is_running(self) -> bool: ... +``` - async def read_text(self, path: str) -> str: ... - async def read_bytes(self, path: str) -> bytes: ... - async def write_text(self, path: str, content: str) -> None: ... +| 成员 | 说明 | +| --- | --- | +| `stdout` / `stderr` | 标准输出与标准错误的 `asyncio.StreamReader` | +| `returncode` | 进程退出码;运行期间为 `None` | +| `await wait()` | 等待进程结束并返回退出码 | +| `await write_stdin(data)` / `close_stdin()` | 写入并刷新标准输入,或关闭标准输入 | +| `signal(*, kill)` | 请求进程及其子孙进程退出(`kill=True` 时强制终止);进程已退出时调用不得抛异常 | +| `is_running()` | 检查进程或其子孙进程是否仍在运行 | - async def run_code( - self, - code: str, - *, - tools: Sequence[str], - call_tool: CallTool, - write: Callable[[str], None], - ) -> None: ... +#### `run_code` 契约 {#run-code-contract} - def resolve_path(self, path: str) -> str: ... +- `code` 支持顶层 `await`;`tools` 中的工具在代码里通过 `await tools.(**kwargs)` 调用,底层转发给 `await call_tool(name, kwargs)`(代码也可通过 `call_tool` 调用 `republic.` 前缀的媒体与模型辅助方法)。 +- 标准输出必须在产生时立即回调 `write(chunk)`,以确保超时后仍能保留已产生的输出。 +- 代码自身抛错时抛出 `CodeFailed(error, traceback)`;有 Python 解释器的自定义环境可直接复用 `bub.core.codemode.runner.run_code_in_subprocess(self, ...)`。 + +#### `CodeFailed` {#codefailed} + +```python +class CodeFailed(Exception): + def __init__(self, error: str, traceback: str = "") -> None: ... ``` -## `bub` {#application} +`error` 为 `"<异常类型>: <消息>"`,`traceback` 为仅包含模型代码自身栈帧的回溯字符串。 + +#### 环境在应用层中如何提供 {#provide-an-environment} -### `BubFramework` {#framework} +应用层通过 `provide_environment(session_id, workspace)` Hook 为每个会话缓存一个 `Environment`(默认返回 `LocalEnvironment(workspace)`),写入 `TurnState[ENVIRONMENT_STATE_KEY]` 并在 `framework.running()` 退出时调用 `close()`。 + +:::caution +`LocalEnvironment` 直接在宿主机上执行进程与读写文件,**单独的子进程不是安全沙箱**。执行不受信任的代码时,请实现具备文件系统、网络与权限隔离的 `Environment`。 +::: + +--- + +## 应用层 {#application} + +### `BubFramework` 与 `BubAgent` {#framework} ```python +from bub import BubFramework +from bub.builtin.agent import BubAgent + class BubFramework: + workspace: Path + config_file: Path + default_command: str | None + events: EventBus + def __init__(self, config_file: Path = DEFAULT_CONFIG_FILE) -> None: ... @property @@ -1064,13 +1091,7 @@ class BubFramework: def get_system_prompt(self, prompt: list[UserContent], state: dict[str, Any]) -> str: ... def build_tape_context(self) -> TapeContext: ... def collect_onboard_config(self, plugin_name: str | None = None) -> dict[str, Any]: ... -``` -## `bub.builtin.agent` - -### `BubAgent` - -```python class BubAgent(core.Agent): command_prefix: str @@ -1103,49 +1124,50 @@ class BubAgent(core.Agent): ) -> list[Tool]: ... ``` -## `bub.envelope` {#messages} +**`BubFramework` 核心方法说明**: -### `Envelope` +| 方法 | 说明 | +| --- | --- | +| `BubFramework(config_file=...)` | 初始化应用框架并载入配置文件;`workspace` 初始为当前工作目录 | +| `load_hooks()` / `load_builtin_hooks()` | 加载内置 Hook 及环境中已安装的所有 entry-point 插件(或仅加载内置 Hook) | +| `running()` | 异步上下文管理器:启动 `provide_lifespan`、`TapeStore`、会话 `Environment` 与 `SteeringInbox` 作用域 | +| `await process_inbound(inbound, stream_output=False)` | 执行一条入站消息的完整 7 阶段 Turn,返回 `TurnResult` | +| `await build_state(message, session_id)` | 运行 `load_state` Hooks 并注入 `_runtime_*` 键,构造完整的 `TurnState` | +| `get_tools()` / `get_channels(handler)` / `get_tape_store()` | 收集插件注册的工具、渠道或当前活动的 Tape 存储后端 | +| `bind_channel_router(router)` | 绑定渠道路由器,供出站投递、流包装与会话取消使用 | + +**`BubAgent` 构造与 `run_stream()` 参数说明**: + +| 参数 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `framework` | `BubFramework` | 必填 | 关联的 `BubFramework` 实例(应在 `async with framework.running():` 内构造 `BubAgent` 以获取活动存储) | +| `tools` | `Collection[Tool] \| None` | `framework.get_tools()` | 覆盖该实例的基础工具集合 | +| `tape_store` | `TapeStore \| AsyncTapeStore \| None` | `framework.get_tape_store()` | 显式指定存储后端(优先级高于 `framework` 提供的存储) | +| `session_id` | `str` | 必填(`run_stream`) | 会话 ID(以 `temp/` 开头的临时会话在流关闭时不合并回主 Tape) | +| `prompt` | `list[UserContent] \| LegacyPrompt` | 必填(`run_stream`) | 发送给模型的用户输入 | +| `state` | `TurnState \| None` | `None` | 为 `None` 时自动通过 `framework.build_state()` 加载;显式传入字典则会跳过 `load_state` Hooks | +| `model` | `str \| None` | 会话或全局配置的模型 | 临时覆盖本次运行使用的 `provider:model` | +| `allowed_tools` / `allowed_skills` | `Collection[str] \| None` | `None` | 按请求限制允许使用的工具或技能白名单(传 `[]` 表示禁用全部;传未知名称会抛出 `ValueError`) | +| `reasoning_effort` | `str \| None` | 会话或全局配置值 | 临时覆盖本次运行的推理强度 | + +嵌入用法详见[复用 Bub 应用](/zh-cn/docs/integrations/reuse-app/),与完整 Turn 的阶段对比见 [Turn](/zh-cn/docs/concepts/turn/#stages)。 -```python -type Envelope = Any -``` +--- -### `field_of` +### `bub.envelope` 与 `bub.turn` {#messages} ```python -def field_of(message: Envelope, key: str, default: Any = None) -> Any: ... -``` +from bub.envelope import Envelope, content_of, field_of, normalize_envelope, unpack_batch +from bub.turn import TurnResult, TurnState -### `content_of` +type Envelope = Any +type TurnState = dict[str, Any] -```python +def field_of(message: Envelope, key: str, default: Any = None) -> Any: ... def content_of(message: Envelope) -> str: ... -``` - -### `normalize_envelope` - -```python def normalize_envelope(message: Envelope) -> dict[str, Any]: ... -``` - -### `unpack_batch` - -```python def unpack_batch(batch: Any) -> list[Envelope]: ... -``` - -## `bub.turn` - -### `TurnState` - -```python -type TurnState = dict[str, Any] -``` -### `TurnResult` - -```python @dataclass(frozen=True) class TurnResult: session_id: str @@ -1155,45 +1177,56 @@ class TurnResult: state: TurnState = field(default_factory=dict) ``` -## `bub.model_selection` {#model-options} +| 函数 / 字段 | 说明 | +| --- | --- | +| `field_of(message, key, default=None)` | 从字典、dataclass、Pydantic 模型或普通对象上安全读取指定字段值 | +| `content_of(message)` | 读取消息的 `"content"` 文本字段(不存在时返回空字符串 `""`) | +| `normalize_envelope(message)` | 将任意形态的 `Envelope` 统一转换为可变的 Python 字典 | +| `unpack_batch(batch)` | 将 `render_outbound` 返回的单条或列表展开为 `list[Envelope]` | +| `TurnResult` | `process_inbound()` 的返回值,包含解析后的 `session_id`、`prompt`、`model_output`、待发消息列表 `outbounds` 及结束时的 `state` | + +--- -### `ModelChoice` +### `bub.model_selection` {#model-options} ```python +from bub.model_selection import ModelChoice, ModelOptions + @dataclass(frozen=True) class ModelChoice: id: str name: str | None = None description: str | None = None meta: dict[str, Any] | None = None -``` - -### `ModelOptions` -```python @dataclass(frozen=True) class ModelOptions: models: list[ModelChoice] = field(default_factory=list) current_model: str | None = None ``` -## `bub.channels` {#channels} - -### `MediaType` +| 类 / 字段 | 类型 | 说明 | +| --- | --- | --- | +| `ModelChoice.id` | `str` | 必填的模型标识(如 `"openai:gpt-5-mini"`) | +| `ModelChoice.name` / `description` / `meta` | 可选 | 显示名称、描述与附加元数据字典 | +| `ModelOptions.models` | `list[ModelChoice]` | 候选模型列表 | +| `ModelOptions.current_model` | `str \| None` | 当前选中的模型 ID | -```python -type MediaType = Literal["image", "audio", "video", "document"] -``` +--- -### `MessageKind` +### `bub.channels` {#channels} ```python -type MessageKind = Literal["error", "normal", "command"] -``` +from bub.channels import Channel, ChannelManager, ChannelMessage, Interface, Lifecycle +from bub.channels.admission import AdmitDecision, SteeringInbox, TurnAdmissionAction, TurnSnapshot +from bub.channels.contracts import ChannelRouter, MessageHandler +from bub.channels.message import MediaItem, MediaType, MessageKind -### `MediaItem` +type MediaType = Literal["image", "audio", "video", "document"] +type MessageKind = Literal["error", "normal", "command"] +type MessageHandler = Callable[[Envelope], Coroutine[Any, Any, None]] +type TurnAdmissionAction = Literal["process", "drop", "follow_up", "steer"] -```python @dataclass class MediaItem: type: MediaType @@ -1203,11 +1236,7 @@ class MediaItem: data_fetcher: Callable[[], Awaitable[bytes | None]] | None = None async def get_url(self) -> str | None: ... -``` -### `ChannelMessage` - -```python @dataclass class ChannelMessage: session_id: str @@ -1226,23 +1255,17 @@ class ChannelMessage: @classmethod def from_batch(cls, batch: list[ChannelMessage]) -> ChannelMessage: ... -``` -### `Channel` - -```python class Channel(ABC): name: ClassVar[str] = "base" @abstractmethod async def start(self, stop_event: asyncio.Event) -> None: ... - @abstractmethod async def stop(self) -> None: ... @property def needs_debounce(self) -> bool: ... - @property def enabled(self) -> bool: ... @@ -1260,51 +1283,25 @@ class Channel(ABC): message: Envelope, turn: TurnSnapshot, ) -> AdmitDecision | None: ... -``` -### `Interface` - -```python class Interface(Channel): ... -``` - -### `Lifecycle` - -```python class Lifecycle(Channel): ... -``` - -### `MessageHandler` - -```python -type MessageHandler = Callable[[Envelope], Coroutine[Any, Any, None]] -``` -### `ChannelRouter` - -```python class ChannelRouter(Protocol): async def dispatch_output(self, message: Envelope) -> bool: ... - def wrap_stream( self, message: Envelope, stream: AsyncIterable[StreamEvent], ) -> AsyncIterable[StreamEvent]: ... - async def quit(self, session_id: str) -> None: ... - async def admit_channel_message( self, session_id: str, message: Envelope, turn: TurnSnapshot, ) -> AdmitDecision | None: ... -``` -### `ChannelManager` - -```python class ChannelManager: def __init__( self, @@ -1317,44 +1314,27 @@ class ChannelManager: async def on_receive(self, message: ChannelMessage) -> None: ... def get_channel(self, name: str) -> Channel | None: ... async def dispatch_output(self, message: Envelope) -> bool: ... - def wrap_stream( self, message: Envelope, stream: AsyncIterable[StreamEvent], ) -> AsyncIterable[StreamEvent]: ... - async def quit(self, session_id: str) -> None: ... def enabled_channels(self) -> list[Channel]: ... async def listen_and_run(self) -> None: ... async def shutdown(self) -> None: ... - async def admit_channel_message( self, session_id: str, message: Envelope, turn: TurnSnapshot, ) -> AdmitDecision | None: ... -``` - -### `TurnAdmissionAction` - -```python -type TurnAdmissionAction = Literal["process", "drop", "follow_up", "steer"] -``` - -### `AdmitDecision` -```python @dataclass(frozen=True) class AdmitDecision: action: TurnAdmissionAction reason: str | None = None -``` - -### `TurnSnapshot` -```python @dataclass(frozen=True) class TurnSnapshot: session_id: str @@ -1362,77 +1342,86 @@ class TurnSnapshot: running_count: int pending_count: int steering_count: int = 0 -``` - -### `SteeringInbox` -```python class SteeringInbox(Protocol): async def enqueue_message(self, message: Envelope, state: TurnState) -> None: ... async def drain_messages(self, state: TurnState) -> list[Envelope]: ... def message_count(self, state: TurnState) -> int: ... ``` -## `bub.application` {#application-events} +| 类名 | 说明 | +| --- | --- | +| `ChannelMessage` | 渠道入站/出站标准消息对象;`media` 支持 `MediaItem`(通过 `url` 或异步 `data_fetcher` 提供图片、音频、视频字节)。自定义渠道开发见[网关:自定义渠道](/zh-cn/docs/app/gateway/#custom-channels) | +| `Channel` / `Interface` / `Lifecycle` | `Channel` 至少实现 `start(stop_event)` 与 `stop()`;`Interface` 代表需显式开启的用户交互界面(如 `cli`),`Lifecycle` 代表伴随网关运行的后台常驻服务(如 `mcp.lifecycle`) | +| `ChannelManager` | 实现 `ChannelRouter` 协议并管理所有已启用渠道的生命周期、防抖合并、准入排队与出站路由 | +| `AdmitDecision` / `TurnSnapshot` / `SteeringInbox` | 消息准入决策(`process` / `drop` / `follow_up` / `steer`)、当前会话运行快照以及运行中引导消息收件箱协议(详见 [Hooks 参考:`admit_message`](/zh-cn/docs/reference/hooks/#admit_message)) | -### `Outcome` +--- + +### `bub.hooks` {#hooks} ```python -type Outcome = Literal["succeeded", "failed", "cancelled"] +from bub.hooks import BubHookSpecs, hookimpl, hookspec ``` -### `PromptKind` +全部 27 个 Hook 的签名、优先级与返回值规范见 [Hooks 参考](/zh-cn/docs/reference/hooks/)。 -```python -type PromptKind = Literal["question", "permission", "auth"] -``` +--- -### `CommandChanged` +### `bub.application` 与 `bub.program_status` {#application-events} ```python +from bub.application import CommandChanged, Outcome, PromptChanged, PromptKind, WorkChanged +from bub.program_status import ProgramStatus + +type Outcome = Literal["succeeded", "failed", "cancelled"] +type PromptKind = Literal["question", "permission", "auth"] + @dataclass(frozen=True) class CommandChanged(Event): outcome: Outcome | None = None -``` - -### `WorkChanged` -```python @dataclass(frozen=True) class WorkChanged(Event): busy: bool completed: Outcome | None = None -``` - -### `PromptChanged` -```python @dataclass(frozen=True) class PromptChanged(Event): kind: PromptKind | None -``` - -## `bub.program_status` -### `ProgramStatus` - -```python class ProgramStatus: def __init__(self, output: TextIO | None) -> None: ... def __call__(self, event: Event) -> None: ... ``` -## `bub.inquirer` {#inquirer} +这些事件发布在 `framework.events` 总线上(与 `agent.events` 相互独立),用于驱动状态栏和外部界面: -### `CheckboxValidator` +| 类名 | 字段 | 说明 | +| --- | --- | --- | +| `CommandChanged` | `outcome` | CLI 命令启动时为 `None`;结束时为 `"succeeded"` / `"failed"` / `"cancelled"` | +| `WorkChanged` | `busy`, `completed` | 渠道忙碌状态变化,可附带刚完成消息的执行结果 | +| `PromptChanged` | `kind` | 交互式询问打开时为 `"question"` / `"permission"` / `"auth"`;关闭时为 `None` | +| `ProgramStatus` | `output` | 内置终端状态处理器:在 TTY 终端上根据上述事件输出 OSC 7501 状态序列(`idle`、`working`、`blocked`、`done`、`error`),并在命令结束时发送 `state=clear` | -```python -CheckboxValidator = Callable[[list[str]], bool | str] -``` +--- -### `ask_prompt` +### `bub.inquirer` {#inquirer} ```python +from bub.inquirer import ( + CheckboxValidator, + ask_checkbox, + ask_confirm, + ask_fuzzy, + ask_prompt, + ask_secret, + ask_select, + ask_text, +) + +type CheckboxValidator = Callable[[list[str]], bool | str] + def ask_prompt( prompt: Callable[..., InquirerResult[Any]], message: str, @@ -1440,50 +1429,12 @@ def ask_prompt( kind: PromptKind = "question", **kwargs: Any, ) -> Any: ... -``` - -### `ask_text` -```python def ask_text(message: str, default: str = "") -> str: ... -``` - -### `ask_secret` - -```python def ask_secret(message: str) -> str: ... -``` - -### `ask_confirm` - -```python -def ask_confirm( - message: str, - default: bool = False, - *, - kind: PromptKind = "question", -) -> bool: ... -``` - -### `ask_select` - -```python +def ask_confirm(message: str, default: bool = False, *, kind: PromptKind = "question") -> bool: ... def ask_select(message: str, choices: list[str], default: str = "") -> str: ... -``` - -### `ask_fuzzy` - -```python -def ask_fuzzy( - message: str, - choices: list[str], - default: str | None = None, -) -> str: ... -``` - -### `ask_checkbox` - -```python +def ask_fuzzy(message: str, choices: list[str], default: str | None = None) -> str: ... def ask_checkbox( message: str, choices: list[str], @@ -1491,3 +1442,14 @@ def ask_checkbox( validate: CheckboxValidator | None = None, ) -> list[str]: ... ``` + +| 函数 | 参数 | 返回值 | 说明 | +| --- | --- | --- | --- | +| `ask_text` | `message`, `default=""` | `str` | 终端单行文本输入 | +| `ask_secret` | `message` | `str` | 终端密码/密钥隐藏输入 | +| `ask_confirm` | `message`, `default=False`, `*, kind="question"` | `bool` | 是/否交互确认 | +| `ask_select` | `message`, `choices`, `default=""` | `str` | 上下方向键列表单选 | +| `ask_fuzzy` | `message`, `choices`, `default=None` | `str` | 支持关键字模糊过滤的列表单选 | +| `ask_checkbox` | `message`, `choices`, `enabled=None`, `validate=None` | `list[str]` | 多选框输入,支持传入 `validate` 校验函数 | + +在 Bub CLI 中调用这些同步函数时,会自动在 `framework.events` 上发布 `PromptChanged` 事件;当用户按 Ctrl+C 取消输入时抛出 `typer.Abort`。示例见[插件与 Hooks:交互式输入](/zh-cn/docs/app/plugins/#prompt-for-input)。 diff --git a/website/src/content/docs/zh-cn/docs/reference/settings.mdx b/website/src/content/docs/zh-cn/docs/reference/settings.mdx index 6b05056a..e4d8992f 100644 --- a/website/src/content/docs/zh-cn/docs/reference/settings.mdx +++ b/website/src/content/docs/zh-cn/docs/reference/settings.mdx @@ -1,193 +1,275 @@ --- title: 配置项 -description: 应用层环境变量、YAML 字段、默认值和解析顺序。 +description: Bub 应用层配置项完整参考:查阅所有 BUB_* 环境变量、YAML 配置文件字段、默认值、优先级规则及 Telegram 渠道配置。 --- -这些设置属于 Bub 应用;`bub.core.Agent` 不读取 YAML 或 `BUB_*`。插件可以注册自己的配置 section。 +本页列出 **Bub 应用层**的所有内置配置项。核心层 `bub.core.Agent` 不读取 YAML 文件或 `BUB_*` 环境变量(仅接收构造函数参数)。第三方插件也可注册自定义配置段,具体字段见对应插件文档。日常配置流程见[配置](/zh-cn/docs/app/configure/)。 -## 读取顺序 {#precedence} +## 优先级顺序 {#precedence} + +配置类按以下顺序(从高到低)解析字段值: | 优先级 | 来源 | 说明 | | --- | --- | --- | -| 1 | 环境变量 | 设置类实例化时读取 | -| 2 | 当前目录 `.env` | `find_dotenv(usecwd=True)`;不覆盖已有环境变量 | -| 3 | YAML 文件 | 默认 `~/.bub/config.yml`,由 `configure.load` 载入 | -| 4 | 字段默认值 | 代码中的默认值 | - -`--workspace`、`--project`、`--enable-channel` 是命令参数,不属于统一设置层。 +| 1 | 环境变量 | `BUB_*`;在配置类实例化时读取 | +| 2 | 当前目录 `.env` 文件 | `find_dotenv(usecwd=True)`;不会覆盖已存在的系统环境变量 | +| 3 | YAML 配置文件 | 默认为 `~/.bub/config.yml`,由 `configure.load` 读取 | +| 4 | 字段默认值 | 代码中声明的默认值 | -设置实例在进程内缓存;首次 `ensure_config()` 后修改 `os.environ`,通常不会影响已创建的实例。 +- `--workspace`、`--project` 和 `--enable-channel` 是 **CLI 命令行参数**,不属于上述配置层。 +- 配置实例在进程内全局缓存。首次调用 `ensure_config()` 后再修改 `os.environ` 不会影响已缓存的实例;修改配置后请重启进程。 -## 配置文件 {#config-file} +## 配置文件与运行时路径 {#config-file} -| 路径 | 来源 | -| --- | --- | -| `~/.bub/config.yml` | 默认配置文件 | -| `BubFramework(config_file=Path(...))` | 构造参数,解析为绝对路径 | - -`BUB_HOME` 只改变历史、Tape、插件项目和代码模式文件等运行时路径,不移动默认配置文件。 +| 路径 / 变量 | 默认值 | 说明 | +| --- | --- | --- | +| `~/.bub/config.yml` | `DEFAULT_CONFIG_FILE` | 默认 YAML 配置文件路径(也可通过 `BubFramework(config_file=Path(...))` 显式指定) | +| `BUB_HOME` | `~/.bub` | 运行时数据目录(存放会话 Tape、托管插件项目与代码模式临时文件)。**注意:`BUB_HOME` 不会改变默认配置文件 `~/.bub/config.yml` 的位置** | +| `BUB_PROJECT` | `/bub-project` | `bub install` / `uninstall` / `update` 管理的插件项目目录(默认路径不存在时会自动创建;显式指定的其他路径必须预先存在) | -## 运行时路径 {#runtime-paths} +## 环境变量索引 {#env-index} -| 变量 | 默认值 | 说明 | -| --- | --- | --- | -| `BUB_HOME` | `~/.bub` | `bub.home`;也可在 `.env` 中设置 | -| `BUB_PROJECT` | `/bub-project` | `bub install` / `uninstall` / `update` 的项目目录 | +每个 YAML 配置项都有对应的环境变量(均可写入 `.env`): -默认项目目录不存在时会自动创建;显式指定的其他目录必须已存在。 +| 环境变量 | 默认值 | YAML 路径 | 详见 | +| --- | --- | --- | --- | +| `BUB_HOME` | `~/.bub` | — | [运行时路径](#config-file) | +| `BUB_PROJECT` | `/bub-project` | — | [运行时路径](#config-file) | +| `BUB_MODEL` | `openrouter:openrouter/free` | `model` | [AgentSettings](#agent-settings) | +| `BUB_COMMAND_PREFIX` | `,` | `command_prefix` | [命令前缀](#command-prefix) | +| `BUB_FALLBACK_MODELS` | `null` | `fallback_models` | [模型与 fallback](#model-routing) | +| `BUB_API_KEY` | 未设置 | `api_key` | [凭据解析顺序](#credentials) | +| `BUB_API_BASE` | 未设置 | `api_base` | [凭据解析顺序](#credentials) | +| `BUB__API_KEY` | 未设置 | — | [凭据解析顺序](#credentials) | +| `BUB__API_BASE` | 未设置 | — | [凭据解析顺序](#credentials) | +| `BUB_PROVIDERS` | `{}` | `providers` | [自定义提供商](#custom-providers) | +| `BUB_MAX_STEPS` | `sys.maxsize` | `max_steps` | [AgentSettings](#agent-settings) | +| `BUB_MAX_TOKENS` | `16384` | `max_tokens` | [AgentSettings](#agent-settings) | +| `BUB_SUBAGENT_MAX_CONCURRENCY` | `4` | `subagent_max_concurrency` | [AgentSettings](#agent-settings) | +| `BUB_SUBAGENT_TIMEOUT_SECONDS` | `null` | `subagent_timeout_seconds` | [AgentSettings](#agent-settings) | +| `BUB_MODEL_TIMEOUT_SECONDS` | `null` | `model_timeout_seconds` | [AgentSettings](#agent-settings) | +| `BUB_CLIENT_ARGS` | `{}` | `client_args` | [`client_args`](#client-args) | +| `BUB_COMPLETION_ARGS` | `{}` | `completion_args` | [`completion_args`](#completion-args) | +| `BUB_VERBOSE` | `0` | `verbose` | [AgentSettings](#agent-settings) | +| `BUB_ENABLED_CHANNELS` | `all` | `enabled_channels` | [ChannelSettings](#channel-settings) | +| `BUB_DEBOUNCE_SECONDS` | `1.0` | `debounce_seconds` | [ChannelSettings](#channel-settings) | +| `BUB_MAX_WAIT_SECONDS` | `10.0` | `max_wait_seconds` | [ChannelSettings](#channel-settings) | +| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | `active_time_window` | [ChannelSettings](#channel-settings) | +| `BUB_STREAM_OUTPUT` | `false` | `stream_output` | [ChannelSettings](#channel-settings) | +| `BUB_SPILL_THRESHOLD` | `4096` | `spill.threshold` | [SpillSettings](#spill-settings) | +| `BUB_TELEGRAM_TOKEN` | `""` | `telegram.token` | [TelegramSettings](#telegram-settings) | +| `BUB_TELEGRAM_ALLOW_USERS` | 未设置 | `telegram.allow_users` | [TelegramSettings](#telegram-settings) | +| `BUB_TELEGRAM_ALLOW_CHATS` | 未设置 | `telegram.allow_chats` | [TelegramSettings](#telegram-settings) | +| `BUB_TELEGRAM_PROXY` | 未设置 | `telegram.proxy` | [TelegramSettings](#telegram-settings) | +| `CODEX_HOME` | `~/.codex` | — | [第三方登录变量](#login-env) | ## AgentSettings {#agent-settings} -平铺字段写在 YAML 顶层。 - -| 环境变量 | YAML | 类型 | 默认值 | 说明 | -| --- | --- | --- | --- | --- | -| `BUB_MODEL` | `model` | `str` | `openrouter:openrouter/free` | `provider:model` | -| `BUB_COMMAND_PREFIX` | `command_prefix` | `str` | `,` | 非空、无空白,可以多字符 | -| `BUB_FALLBACK_MODELS` | `fallback_models` | `list[str] \| null` | `null` | JSON 数组;只用于配置的默认模型 | -| `BUB_API_KEY` | `api_key` | `str \| dict \| null` | 未设置 | 通用密钥或提供商映射 | -| `BUB_API_BASE` | `api_base` | `str \| dict \| null` | 未设置 | 通用地址或提供商映射 | -| `BUB_PROVIDERS` | `providers` | `dict` | `{}` | JSON 对象,定义自定义提供商 | -| `BUB_MAX_STEPS` | `max_steps` | `int` | `sys.maxsize` | 单次 Run 的模型 Step 上限;须为正整数 | -| `BUB_MAX_TOKENS` | `max_tokens` | `int` | `16384` | 默认输出上限;Codex 调用不传 | -| `BUB_SUBAGENT_MAX_CONCURRENCY` | `subagent_max_concurrency` | `int` | `4` | 进程内同时运行的[子 Agent](/zh-cn/docs/app/subagents/) 上限,超出的排队等待 | -| `BUB_SUBAGENT_TIMEOUT_SECONDS` | `subagent_timeout_seconds` | `int \| null` | `null` | 单个子 Agent 运行的默认时限;`null` 表示不限 | -| `BUB_MODEL_TIMEOUT_SECONDS` | `model_timeout_seconds` | `int \| null` | `null` | 一次模型调用(含流式)的秒数 | -| `BUB_CLIENT_ARGS` | `client_args` | `dict` | `{}` | JSON 对象,传给模型客户端 | -| `BUB_COMPLETION_ARGS` | `completion_args` | `dict` | `{}` | JSON 对象,传给每次生成 | -| `BUB_VERBOSE` | `verbose` | `int` | `0` | `0` 为 INFO,`1` 为 DEBUG,`2` 为 TRACE | - -`client_args` 或 `completion_args` 为 `null` 时按 `{}` 处理。 +定义于 `src/bub/builtin/settings.py`,字段位于 YAML 顶层: + +```python +@config() +class AgentSettings(Settings): + model_config = SettingsConfigDict( + env_prefix="BUB_", + env_parse_none_str="null", + extra="ignore", + ) + model: str = "openrouter:openrouter/free" + command_prefix: str = "," + fallback_models: list[str] | None = None + api_key: str | dict[str, str] | None = None + api_base: str | dict[str, str] | None = None + providers: dict[str, CustomProvider] = {} + max_steps: int = sys.maxsize + max_tokens: int = 16384 + subagent_max_concurrency: int = 4 + subagent_timeout_seconds: int | None = None + model_timeout_seconds: int | None = None + client_args: dict[str, Any] = {} + completion_args: dict[str, Any] = {} + verbose: int = 0 +``` + +| 环境变量 | 默认值 | YAML 键 | 说明 | +| --- | --- | --- | --- | +| `BUB_MODEL` | `openrouter:openrouter/free` | `model` | 模型标识(`provider:model`) | +| `BUB_COMMAND_PREFIX` | `,` | `command_prefix` | 直接命令前缀(非空且不含空白字符) | +| `BUB_FALLBACK_MODELS` | `null` | `fallback_models` | 备用模型列表(环境变量传 JSON 数组);仅对默认主模型生效 | +| `BUB_API_KEY` | 未设置 | `api_key` | 通用 API Key 字符串,或按提供商名称映射的字典 | +| `BUB_API_BASE` | 未设置 | `api_base` | 通用 API 地址字符串,或按提供商名称映射的字典 | +| `BUB__API_KEY` | 未设置 | — | 指定提供商的 API Key(如 `BUB_OPENAI_API_KEY`) | +| `BUB__API_BASE` | 未设置 | — | 指定提供商的 API 地址(如 `BUB_OPENROUTER_API_BASE`) | +| `BUB_PROVIDERS` | `{}` | `providers` | 自定义提供商映射(环境变量传 JSON 对象) | +| `BUB_MAX_STEPS` | `sys.maxsize` | `max_steps` | 单次 Run 允许的最大 Step 数(正整数) | +| `BUB_MAX_TOKENS` | `16384` | `max_tokens` | 单次模型生成的默认最大输出 Token 数(`codex:` 模型不传该项) | +| `BUB_SUBAGENT_MAX_CONCURRENCY` | `4` | `subagent_max_concurrency` | 进程内同时运行的[子 Agent](/zh-cn/docs/app/subagents/) 数量上限 | +| `BUB_SUBAGENT_TIMEOUT_SECONDS` | `null` | `subagent_timeout_seconds` | 单个子 Agent 的默认超时秒数(`null` 表示不限时) | +| `BUB_MODEL_TIMEOUT_SECONDS` | `null` | `model_timeout_seconds` | 单次模型调用(含流式输出全过程)的超时秒数 | +| `BUB_CLIENT_ARGS` | `{}` | `client_args` | 传给底层模型客户端构造函数的额外参数(JSON 对象) | +| `BUB_COMPLETION_ARGS` | `{}` | `completion_args` | 传给每次模型生成请求的额外参数(JSON 对象) | +| `BUB_VERBOSE` | `0` | `verbose` | 日志级别:`0` 为 INFO,`1` 为 DEBUG,`2` 为 TRACE | ### 命令前缀 {#command-prefix} -| 配置 | 命令示例 | +| `command_prefix` | 示例 | | --- | --- | -| `,` | `,help`、`,tape.info` | -| `!` | `!help` | -| `/` | Telegram 中使用 `/bub /help` | +| `,`(默认) | `,help`、`,tape.info` 为直接命令 | +| `!` | `!help` 为直接命令,`,help` 视为普通对话文本 | +| `/` | 在 Telegram 中需通过 `/bub /help` 输入 | -CLI 和 Telegram 的命令解析器不同。 +### 凭据解析顺序 {#credentials} -### 凭据解析 {#credentials} +调用模型时,Bub 按以下顺序查找第一个非空的 `api_key` 与 `api_base`: -调用模型时按顺序取第一个非空值: +1. `providers..api_key` 与 `providers..api_base`(自定义提供商配置); +2. 配置项 `api_key` / `api_base` 中对应提供商的映射值(启动时扫描到的 `BUB__API_KEY` 和 `BUB__API_BASE` 会自动填入该映射,优先级低于显式配置的 `BUB_API_KEY` / `BUB_API_BASE` 和 YAML 键值),或该配置项直接设为单一字符串时的通用值; +3. 不带 `BUB_` 前缀的提供商标准环境变量(如 `OPENAI_API_KEY`、`OPENROUTER_API_KEY`)。 -| 顺序 | 来源 | -| --- | --- | -| 1 | `providers..api_key` / `.api_base` | -| 2 | `api_key` / `api_base` 中对应提供商的映射值,或字段本身的字符串值 | -| 3 | 无 `BUB_` 前缀的 `_API_KEY` / `_API_BASE` | - -`BUB__API_KEY` 和 `BUB__API_BASE` 在启动时写入设置映射,优先级低于 `BUB_API_KEY` / `BUB_API_BASE` 和 YAML。 +:::caution +若将 `BUB_API_KEY` / `BUB_API_BASE`(或 YAML 中的 `api_key` / `api_base`)设为**单一字符串**,它会作为所有提供商的全局通用值,从而覆盖按提供商区分的映射与第 3 步回退。同时使用多个提供商(如主模型与备用模型来自不同提供商)时,请用字典映射或 `BUB__API_KEY` 分别配置。 +::: -通用 `api_key` / `api_base` 为字符串时应用于所有提供商,并阻止映射和第 3 步回退;按提供商分设时使用映射或 `BUB__…`。 +### 模型前缀与 fallback {#model-routing} -### 模型与 fallback {#model-routing} +常用 `BUB_MODEL` 前缀(完整列表见 [Republic providers](https://getrepublic.org/providers/)): -| `model` 前缀 | 提供商或协议 | +| 前缀 | 对应提供商 | | --- | --- | -| `openai:` | OpenAI 或 OpenAI 兼容端点 | -| `codex:` | ChatGPT 套餐登录 | +| `openai:` | OpenAI 官方 API 或任意 OpenAI 兼容端点 | +| `codex:` / `grok:` / `github-copilot:` | 通过 `bub login` 登录的账号凭据 | | `openrouter:` | OpenRouter | -| `anthropic:` / `google:` / `azure-openai:` | 各提供商原生协议 | -| `ollama:` / `magpie:` | 本地服务 | +| `anthropic:` / `google:` / `azure-openai:` | 各提供商原生 API | +| `ollama:` / `magpie:` | 本地模型服务 | -完整提供商列表见 [Republic providers](https://getrepublic.org/providers/)。 +`fallback_models` 仅在当前请求的模型等于默认配置的 `model` 时生效(代码中显式传入 `model=` 或会话内通过 `,model` 切换模型后不生效)。备用模型仅在**建立连接或打开请求流失败时**按序尝试;一旦流已开始产出内容,中途报错不会换模型重放。 -`fallback_models` 只在当前模型与配置的 `model` 相同时生效。fallback 依次尝试打开请求;流开始消费后不再重试。 +### `client_args` 与 `completion_args` {#client-args} -### `client_args` {#client-args} +`client_args` 常用字段: -| 键 | 行为 | +| 键名 | 说明 | | --- | --- | -| `headers` | 与默认 `User-Agent: bub/` 合并;显式值优先 | -| `api_format` | OpenAI 兼容的 Chat Completions 端点通常设为 `chat` | -| `env_prefix` | 默认 `BUB_`,供客户端读取提供商专用环境变量 | -| `timeout` / `max_retries` | 传给底层客户端;总调用超时由 `model_timeout_seconds` 控制 | -| `api_key` / `api_base` | 由 Bub 覆盖,不从 `client_args` 读取 | +| `headers` | 与默认 `User-Agent: bub/` 合并(同名头显式传入优先) | +| `api_format` | 连接 OpenAI 兼容 `/v1/chat/completions` 端点时通常设为 `"chat"` | +| `timeout` / `max_retries` | 底层 HTTP 客户端的单次请求超时与重试次数(整次调用总时限由 `model_timeout_seconds` 控制) | -注入的 HTTP 客户端必须为 `httpx2.AsyncClient`,生命周期由调用方管理。 + -### `completion_args` {#completion-args} +`completion_args` 常用字段(单次调用传入的 `options` 会覆盖同名项): -| 键 | 规则 | +| 键名 | 说明 | | --- | --- | -| `max_tokens` | 由 `BUB_MAX_TOKENS` 或调用级 `max_tokens` 覆盖;Codex 会移除 | -| `reasoning_effort` | 会话或单次 Turn 的值覆盖此配置 | -| `tools` | 由 Agent 根据当前 Step 填入 | -| `extra_body` | 原样交给提供商;Anthropic 默认加入临时 cache control | +| `max_tokens` | 未指定时默认取 `BUB_MAX_TOKENS`(`codex:` 调用自动忽略该项) | +| `reasoning_effort` | 会话级 `,reasoning_effort` 或单次调用 `options` 会覆盖此默认值 | +| `extra_body` | 原样透传给提供商请求体 | -调用级 `options` 覆盖 `completion_args` 中的同名生成项。 +### 自定义提供商(`providers`) {#custom-providers} -### 自定义提供商 {#custom-providers} +需要同时接入多个同协议的不同端点(如多个内部网关或中转站)时,可在 `providers` 下定义自定义前缀: -自定义提供商名称用作 `model` 的提供商前缀。 +```yaml +model: proxy:gpt-5.5 +fallback_models: + - openai:gpt-5.5 + - relay:claude-sonnet-5 +providers: + proxy: + type: openai + api_base: https://llm-proxy.example.com/v1 + api_key: sk-proxy-... + relay: + type: anthropic + api_base: https://relay.example.com + api_key: sk-relay-... +``` | 字段 | 必填 | 说明 | | --- | --- | --- | -| `type` | 是 | 模仿的 Republic 提供商;未注册时配置校验失败 | -| `api_base` | 否 | 缺省时回退到通用 `api_base` 或 `BUB__API_BASE` | -| `api_key` | 否 | 缺省时回退到通用 `api_key` 或 `BUB__API_KEY` | +| `type` | 是 | 遵循的底层 Republic 提供商协议名(如 `openai`、`anthropic`) | +| `api_base` | 否 | 服务 URL;省略时回退读取 `api_base` 映射或 `BUB__API_BASE` | +| `api_key` | 否 | API Key;省略时回退读取 `api_key` 映射或 `BUB__API_KEY` | ## ChannelSettings {#channel-settings} -平铺字段写在 YAML 顶层。 +定义于 `src/bub/channels/manager.py`,字段位于 YAML 顶层: -| 环境变量 | YAML | 类型 | 默认值 | 说明 | -| --- | --- | --- | --- | --- | -| `BUB_ENABLED_CHANNELS` | `enabled_channels` | `str` | `all` | 逗号分隔、`all` 或 `!name` | -| `BUB_DEBOUNCE_SECONDS` | `debounce_seconds` | `float` | `1.0` | 每条活跃消息后重置的批次等待 | -| `BUB_MAX_WAIT_SECONDS` | `max_wait_seconds` | `float` | `10.0` | 非活跃跟进消息的批次等待;不是总上限 | -| `BUB_ACTIVE_TIME_WINDOW` | `active_time_window` | `float` | `60.0` | 最后一条活跃消息后,非活跃消息可加入的秒数 | -| `BUB_STREAM_OUTPUT` | `stream_output` | `bool` | `false` | 网关是否推送流式事件;`bub chat` 强制为 `true` | +| 环境变量 | 默认值 | YAML 键 | 说明 | +| --- | --- | --- | --- | +| `BUB_ENABLED_CHANNELS` | `all` | `enabled_channels` | 启用的渠道列表(逗号分隔、`all` 或 `!name` 排除项;详见 [CLI 渠道选择](/zh-cn/docs/reference/cli/#channel-selection)) | +| `BUB_DEBOUNCE_SECONDS` | `1.0` | `debounce_seconds` | 收到每条活跃消息后重置的防抖等待秒数 | +| `BUB_MAX_WAIT_SECONDS` | `10.0` | `max_wait_seconds` | 群聊中等待未直接 @ 机器人的非活跃跟进消息的最大秒数 | +| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | `active_time_window` | 最后一条活跃消息之后,允许同群非活跃跟进消息并入当前批次的时间窗口(秒) | +| `BUB_STREAM_OUTPUT` | `false` | `stream_output` | 网关是否向渠道推送流式输出事件(`bub chat` 始终强制为 `true`) | -只有 `needs_debounce=True` 的渠道使用缓冲。持续收到活跃消息时,`BUB_MAX_WAIT_SECONDS` 不会强制结束批次。 + -渠道选择规则见 [CLI › 渠道选择](/zh-cn/docs/reference/cli/#channel-selection)。 +防抖缓冲仅对 `needs_debounce=True` 的渠道(如 Telegram)生效。 ## TelegramSettings {#telegram-settings} -字段写在 YAML 的 `telegram:` section 下。 +定义于 `src/bub/channels/telegram.py`,字段位于 YAML 的 `telegram:` 段下: -| 环境变量 | YAML | 类型 | 默认值 | 说明 | -| --- | --- | --- | --- | --- | -| `BUB_TELEGRAM_TOKEN` | `token` | `str` | `""` | 非空时才启用渠道 | -| `BUB_TELEGRAM_ALLOW_USERS` | `allow_users` | `str \| null` | 未设置 | 用户 ID 或用户名,逗号分隔;空表示不限 | -| `BUB_TELEGRAM_ALLOW_CHATS` | `allow_chats` | `str \| null` | 未设置 | 聊天 ID,逗号分隔;空表示不限 | -| `BUB_TELEGRAM_PROXY` | `proxy` | `str \| null` | 未设置 | HTTP 或 SOCKS5 代理 URL | +| 环境变量 | 默认值 | YAML 键 | 说明 | +| --- | --- | --- | --- | +| `BUB_TELEGRAM_TOKEN` | `""` | `token` | Telegram 机器人 Token;非空时自动启用 Telegram 渠道 | +| `BUB_TELEGRAM_ALLOW_USERS` | 未设置 | `allow_users` | 允许访问的用户数字 ID 或用户名(逗号分隔;留空不限制) | +| `BUB_TELEGRAM_ALLOW_CHATS` | 未设置 | `allow_chats` | 允许访问的聊天/群组 ID(逗号分隔;留空不限制) | +| `BUB_TELEGRAM_PROXY` | 未设置 | `proxy` | HTTP 或 SOCKS5 代理地址(如 `http://127.0.0.1:7890` 或 `socks5://host:port`) | -| 条件 | 普通消息 | `/start` | -| --- | --- | --- | -| 聊天 ID 不在 `allow_chats` | 静默忽略 | 回复固定拒绝文本 | -| 用户 ID 和用户名都不在 `allow_users` | 回复 `Access denied.` | 不检查用户 | -| 两者同时配置 | 必须同时满足 | 只检查聊天 | +白名单与群聊触发规则见[网关:配置 Telegram](/zh-cn/docs/app/gateway/#configure-telegram)。 ## SpillSettings {#spill-settings} -字段写在 YAML 的 `spill:` section 下。 +定义于 `src/bub/builtin/spill.py`,字段位于 YAML 的 `spill:` 段下: -| 环境变量 | YAML | 类型 | 默认值 | 说明 | -| --- | --- | --- | --- | --- | -| `BUB_SPILL_THRESHOLD` | `threshold` | `int` | `4096` | 估算 token 上限,按 4 字符/token 计算;`0` 关闭新 spill | - -工具结果超过阈值时写入 `spill` sidecar,模型收到预览和读取句柄。负数无法通过配置校验。 +| 环境变量 | 默认值 | YAML 键 | 说明 | +| --- | --- | --- | --- | +| `BUB_SPILL_THRESHOLD` | `4096` | `threshold` | 触发大输出转存的估算 Token 阈值(按 4 字符 ≈ 1 Token 换算;设为 `0` 时关闭新转存,不能为负数) | -| 情形 | 行为 | -| --- | --- | -| 当前工具集没有 `spill.read` | 不创建新 spill,原样返回结果 | -| 结果已经是 `spill.read` 输出 | 不再 spill | -| 阈值为 `0` | 停止创建新 spill,已有 sidecar 仍可读 | +当工具返回文本超过阈值且当前可用工具包含 `spill.read` 时,完整输出会写入 `spill` Sidecar,主对话仅保留开头预览与读取句柄(`spill.read` 自身的输出不会再次转存)。 ## 第三方登录变量 {#login-env} -| 变量 | 默认值 | 读取方 | 说明 | -| --- | --- | --- | --- | -| `CODEX_HOME` | `~/.codex` | `bub login codex` | `auth.json` 所在目录;`--codex-home` 可覆盖 | +| 环境变量 | 默认值 | 说明 | +| --- | --- | --- | +| `CODEX_HOME` | `~/.codex` | `bub login codex` 存放 `auth.json` 的目录(可通过 `--codex-home` 覆盖) | + +## 会话级持久化设置 {#session-settings} + +以下三个设置项通过会话内的逗号命令动态修改,保存在当前会话的 Tape 中(从**下一次 Turn** 起生效,进程重启后自动恢复): + +| 设置项 | 命令(默认前缀 `,`) | 作用 | +| --- | --- | --- | +| `model` | `,model openai:gpt-5.5` | 切换当前会话的模型(切换为非默认模型后,`fallback_models` 不再生效) | +| `reasoning_effort` | `,reasoning_effort high` | 覆盖当前会话的推理强度 | +| `code_mode` | `,code_mode enable=true` | 为当前会话开启或关闭代码模式 | + +## 插件自定义配置 {#plugin-settings} + +插件可通过 `@config` 装饰器注册配置类: + +```python +from pydantic_settings import SettingsConfigDict +from bub import Settings, config + + +@config(name="orders") +class OrderSettings(Settings): + model_config = SettingsConfigDict( + env_prefix="BUB_ORDERS_", + extra="ignore", + ) + timeout: int = 30 +``` + +- `@config(name="x")` 从 `config.yml` 顶层的 `x:` 段读取字段;`@config()` 直接从顶层读取; +- 调用 `ensure_config(OrderSettings)` 获取进程内缓存的配置实例; +- `bub.configure` 模块提供 `load(path)`、`get_config_data()`、`merge(base, *updates)`、`save(path, data)`、`validate()` 和 `get_value(path, default)` 等管理函数。 -## 完整配置示例 {#example} +## 完整配置文件示例 {#example} -以下示例包含所有内置 YAML 字段;不需要的字段可以省略。 +除 `model` 外,其余字段均可按需省略: ```yaml title="~/.bub/config.yml" model: openrouter:openrouter/free @@ -205,6 +287,8 @@ providers: api_key: "your-provider-api-key" max_steps: 100 max_tokens: 16384 +subagent_max_concurrency: 4 +subagent_timeout_seconds: 600 model_timeout_seconds: 120 client_args: timeout: 60 diff --git a/website/src/content/docs/zh-cn/docs/reference/tools.mdx b/website/src/content/docs/zh-cn/docs/reference/tools.mdx index d8b68713..f6db02c3 100644 --- a/website/src/content/docs/zh-cn/docs/reference/tools.mdx +++ b/website/src/content/docs/zh-cn/docs/reference/tools.mdx @@ -1,15 +1,19 @@ --- title: 内置工具 -description: Bub 应用内置工具与文本命令的参数、默认值和结果。 +description: Bub 应用内置工具与会话命令完整参考:查阅进程、文件、网页、技能发现、Tape 会话管理与子 Agent 工具的参数、默认值及返回值。 --- -模型工具使用下划线别名,例如 `fs.read` 对应 `fs_read`;文本命令保留原名。插件可以增加或覆盖工具,实际集合以 `,help` 和 `,tool.describe` 为准。 +本页列出 Bub 应用层自带的全部内置工具与会话命令。 -文本命令支持位置值和 `key=value`;布尔值使用 `true` / `false`,列表使用 JSON 字符串,含空格的值使用引号。 +- **名称转换**:工具暴露给模型时,名称中的点号会自动转换为下划线别名(如 `fs.read` 在模型侧为 `fs_read`);在终端用命令前缀(如 `,fs.read path=README.md`)直接调用时保留原名。 +- **文本命令传参**:支持位置参数和 `key=value` 键值对;布尔值写 `true` / `false`,列表写 JSON 字符串,含空格的值用引号包裹: + ```text + ,bash command='printf "hello world"' timeout_seconds=10 + ,tool.describe names='["web.fetch", "tape.search"]' + ``` +- **执行环境**:`fs.*`、`bash*` 和 `run_code` 均通过当前会话的 `Environment` 执行,默认直接在宿主机当前用户权限下运行(无安全沙箱)。 -文件、Shell 和 代码模式 操作使用当前会话的 `Environment`,默认直接在宿主机执行,而非安全沙箱中。 - -## 进程 {#processes} +## 进程管理 {#processes} ### `bash` {#bash} @@ -19,12 +23,12 @@ bash(command, cwd=None, timeout_seconds=30, background=False) | 参数 | 类型 | 说明 | | --- | --- | --- | -| `command` | `str` | Shell 命令 | -| `cwd` | `str \| None` | 工作目录;相对路径由当前环境解析 | -| `timeout_seconds` | `float` | 前台等待秒数;超时后转入后台并返回 `shell_id` | -| `background` | `bool` | 是否直接在后台启动;此模式忽略 `timeout_seconds` | +| `command` | `str` | 要执行的 Shell 命令 | +| `cwd` | `str \| None` | 工作目录;相对路径基于当前会话的 `Environment.workspace` 解析 | +| `timeout_seconds` | `float` | 前台等待秒数(默认 30);超时未结束时不会报错,而是自动转为后台继续运行并返回 `shell_id` | +| `background` | `bool` | 是否直接在后台启动;设为 `True` 时立即返回 `shell_id` 并忽略 `timeout_seconds` | -非零退出状态返回工具错误并保留输出;前台无输出时返回 `(no output)`。 +前台命令退出码非零时作为工具错误返回(保留已打印输出);正常退出且无输出时返回 `(no output)`。 ### `bash.output` {#bash-output} @@ -34,11 +38,11 @@ bash.output(shell_id, offset=0, limit=None) | 参数 | 类型 | 说明 | | --- | --- | --- | -| `shell_id` | `str` | 后台 Shell ID | -| `offset` | `int` | 字符偏移;限制在 `0` 到当前输出长度之间 | -| `limit` | `int \| None` | 最多读取的字符数 | +| `shell_id` | `str` | `bash` 返回的后台进程 ID(如 `bsh-12345678`) | +| `offset` | `int` | 起始**字符偏移量**(非行号,自动限制在 `0` 到当前缓冲总长度之间) | +| `limit` | `int \| None` | 本次最多读取的字符数 | -返回 `status`、`exit_code`、`output` 和 `next_offset`;进程运行期间 `exit_code` 为 `null`。 +返回进程状态 `status`、退出码 `exit_code`(运行中为 `null`)、本次输出 `output` 以及供下次读取使用的 `next_offset`。 ### `bash.kill` {#bash-kill} @@ -46,9 +50,9 @@ bash.output(shell_id, offset=0, limit=None) bash.kill(shell_id) ``` -终止后台进程并返回最终状态和退出码;进程已结束时也可调用。 +终止指定的后台 Shell 进程,并返回其最终状态与退出码。 -## 文件 {#files} +## 文件操作 {#files} ### `fs.read` {#fs-read} @@ -58,13 +62,11 @@ fs.read(path, offset=0, limit=None) | 参数 | 类型 | 说明 | | --- | --- | --- | -| `path` | `str` | UTF-8 文本文件路径 | -| `offset` | `int` | 从 `0` 开始的行号 | -| `limit` | `int \| None` | 最多返回的行数 | - -省略分页参数时返回整个文件。 +| `path` | `str` | 文件路径 | +| `offset` | `int` | 起始行号(从 `0` 开始,默认 `0`) | +| `limit` | `int \| None` | 最多读取的行数(省略时读到文件末尾) | -`.png`、`.jpg`、`.jpeg`、`.webp`、`.gif` 文件会作为图片返回给模型查看,上限 10 MiB,此时忽略 `offset` 和 `limit`。 +除读取 UTF-8 文本文件外,当 `path` 指向 `.png`、`.jpg`、`.jpeg`、`.webp` 或 `.gif` 图片(且不超过 10 MiB)时,会作为多模态图片对象返回给模型(此时忽略 `offset` 和 `limit`)。 ### `fs.write` {#fs-write} @@ -72,7 +74,7 @@ fs.read(path, offset=0, limit=None) fs.write(path, content) ``` -写入完整文本并创建缺失的父目录;已有文件会被覆盖,不支持追加或补丁。 +将完整的 UTF-8 文本写入 `path`(自动创建缺失的父目录;已存在的文件会被直接覆盖)。 ### `fs.edit` {#fs-edit} @@ -80,16 +82,9 @@ fs.write(path, content) fs.edit(path, old, new, start=0) ``` -| 参数 | 类型 | 说明 | -| --- | --- | --- | -| `path` | `str` | 文件路径 | -| `old` | `str` | 待替换文本 | -| `new` | `str` | 替换后的文本 | -| `start` | `int` | 从 `0` 开始的查找行号 | - -替换指定范围内的所有字面匹配;找不到匹配时返回错误,不进行语法解析。 +从第 `start` 行(从 `0` 开始)起,将文件中所有与 `old` 完全匹配的字面文本替换为 `new`;未找到匹配项时返回工具错误。 -## 网页 {#web} +## 网页抓取 {#web} ### `web.fetch` {#web-fetch} @@ -99,11 +94,11 @@ web.fetch(url, headers=None, timeout=10) | 参数 | 类型 | 说明 | | --- | --- | --- | -| `url` | `str` | 请求 URL | -| `headers` | `dict \| None` | HTTP 请求头;可覆盖默认的 `Accept: text/markdown` | -| `timeout` | `float` | 整个请求的总秒数 | +| `url` | `str` | 目标 HTTP/HTTPS URL | +| `headers` | `dict \| None` | 自定义请求头(可覆盖默认的 `Accept: text/markdown`) | +| `timeout` | `float` | 请求总超时秒数(默认 10) | -发送 HTTP GET 请求,返回最终 `url`、`status`、`content_type` 和响应正文;非成功状态返回工具错误。 +发送 HTTP GET 请求并返回最终 `url`、状态码 `status`、`content_type` 和响应正文(非 2xx 状态码返回工具错误)。 ## 技能与工具发现 {#discovery} @@ -113,7 +108,7 @@ web.fetch(url, headers=None, timeout=10) skill(name=None) ``` -省略 `name` 时列出当前可用技能;传入名称时返回技能位置和正文。找不到时返回 `(no such skill)`。 +省略 `name` 时列出所有可用技能及简述;传入 `name` 时返回该技能的路径与变量展开后的 `SKILL.md` 正文(不存在时返回 `(no such skill)`)。 ### `tool.describe` {#tool-describe} @@ -121,15 +116,13 @@ skill(name=None) tool.describe(names) ``` -`names` 是运行时名称或模型别名组成的列表。返回工具名称、描述和参数 schema;未知名称列入 `unknown`,已加载名称列入 `already_loaded`。 +加载延迟工具(`deferred=True`)的完整描述与 JSON Schema 参数定义。成功加载的工具从**下一个 Step** 起即可被模型调用,并在当前会话 Tape 重置前保持已加载状态(未知名称列入 `unknown`,已加载名称列入 `already_loaded`)。 -延迟工具从下一个 Step 起可调用,加载记录保存在当前 Tape 中,直到 Tape 重置。 - -## Tape {#tape} +## 会话 Tape 管理 {#tape} ### `tape.info` {#tape-info} -无参数。返回 Tape 名称、条目数、anchor 数、最近 anchor、该 anchor 后的条目数,以及最近的 token 用量和缓存命中率。 +无参数。返回当前会话的物理 Tape 名称、总条目数(`entries`)、锚点总数(`anchors`)、最近一个锚点(`last_anchor`)、自该锚点以来的条目数(`entries_since_last_anchor`),以及最近一次模型调用的 Token 用量与缓存命中率。 ### `tape.search` {#tape-search} @@ -139,18 +132,16 @@ tape.search(query, limit=20, start=None, end=None, kinds=["message", "tool_resul | 参数 | 类型 | 说明 | | --- | --- | --- | -| `query` | `str` | 在 kind、日期、payload 和 meta 的 JSON 文本中进行不区分大小写的包含匹配 | -| `limit` | `int` | 最多返回的条目数 | -| `start` / `end` | `str \| None` | 包含边界的 ISO 日期或时间 | -| `kinds` | `list[str]` | 条目类型列表 | - -返回 `matches` 和 `filtered` 数量,并过滤搜索命令自身产生的输出。 +| `query` | `str` | 搜索关键词(不区分大小写;内置 `FuzzyFileTapeStore` 对 3 字符以上查询支持模糊匹配并按倒序去重) | +| `limit` | `int` | 最多返回条数(默认 20) | +| `start` / `end` | `str \| None` | 可选的起止 ISO 日期或时间范围(含边界) | +| `kinds` | `list[str]` | 要检索的条目类型列表 | -内置 `FuzzyFileTapeStore` 从最新条目向回查找,支持去重和模糊匹配;短于 3 个字符的查询只做包含匹配。其他后端的行为由实现决定。 +返回匹配条目列表 `matches` 和被过滤的重复/自身输出计数 `filtered`。 ### `tape.anchors` {#tape-anchors} -无参数。按记录顺序返回 anchor 名称;没有时返回 `(no anchors)`。 +无参数。按写入顺序列出当前会话 Tape 中的所有 anchor 名称(无 anchor 时返回 `(no anchors)`)。 ### `tape.handoff` {#tape-handoff} @@ -158,12 +149,7 @@ tape.search(query, limit=20, start=None, end=None, kinds=["message", "tool_resul tape.handoff(name="handoff", summary="") ``` -| 参数 | 类型 | 说明 | -| --- | --- | --- | -| `name` | `str` | anchor 名称 | -| `summary` | `str` | 保存到 `state.summary` 的文本 | - -写入 anchor 并移动默认上下文起点,旧记录仍保留。不会自动生成摘要;默认上下文在 anchor 之后读取,边界 anchor 本身不进入模型输入;以 `anchor=None` 读取时,默认选择器会把 anchor 转为 assistant 消息 `[Anchor created: ]: `。 +向当前会话 Tape 追加一个名为 `name` 的新 anchor(`summary` 保存在 `state.summary` 中),将默认模型上下文的读取起点前移到此处。不会自动调用模型生成摘要。 ### `tape.reset` {#tape-reset} @@ -171,7 +157,7 @@ tape.handoff(name="handoff", summary="") tape.reset(archive=False) ``` -清空当前 Tape 并创建新的 `session/start` anchor。`archive=True` 时先将主 Tape 和 sidecar 归档到 `bub.home/tapes/`。 +清空当前会话 Tape 并写入新的 `session/start` 锚点。`archive=True` 时会在清空前将主 Tape 和 Sidecar 备份到 `/tapes/`(带 UTC 时间戳和 `.bak` 后缀)。 ## 子 Agent {#subagent} @@ -182,51 +168,19 @@ subagent(prompt, agent=None, description=None, model=None, reasoning_effort=None session="temp", allowed_tools=None, allowed_skills=None, timeout_seconds=None) ``` -| 参数 | 类型 | 说明 | +| 参数 | 类型与默认值 | 说明 | | --- | --- | --- | -| `prompt` | `str \| list` | 交给子 Agent 的任务 | -| `agent` | `str \| None` | [子 Agent 配置](/zh-cn/docs/app/subagents/#profiles)名;调用中未给出的参数取自配置 | -| `description` | `str \| None` | 任务列表中显示的简短标签;默认取 prompt 第一行 | -| `model` | `str \| None` | 子运行的 `provider:model`;默认取配置中的模型或当前配置 | -| `reasoning_effort` | `str \| None` | 子 Agent 模型的推理强度 | -| `session` | `str` | 子 Agent 的会话策略,默认 `"temp"` | -| `allowed_tools` | `list[str] \| None` | 可用工具;默认为父 Agent 本轮的工具 | -| `allowed_skills` | `list[str] \| None` | 可用技能;默认为父 Agent 本轮的技能,`[]` 禁用技能发现 | -| `timeout_seconds` | `int \| None` | 超时即停止子 Agent;默认取配置中的时限,再取 `BUB_SUBAGENT_TIMEOUT_SECONDS` | - -工具名支持运行时名称和模型别名;技能名不区分大小写。子 Agent 的工具和技能不会超过父 Agent:默认就是父 Agent 本轮允许的范围,指定范围外的工具会报错。子 Agent 不能启动或管理子 Agent,`subagent` 和 `subagent.*` 始终被排除。 - -| `session` | 行为 | -| --- | --- | -| `temp` | 新建空的 `temp/` 会话,结束后丢弃 | -| `fork` | 从当前对话(包括本轮已有内容)的副本开始,结束后丢弃;`inherit` 为其别名 | -| 其他字符串 | 使用指定的会话 ID,会话会被保留,之后可用 `subagent.send` 继续 | - -fork 在调用时复制父 Agent 的 Tape,子 Agent 看不到父 Agent 之后记录的内容。每个子 Agent 拥有自己的轮次状态:父状态的浅拷贝,但去掉了父 Agent 的 steering 键、工具范围和运行中的 Tape,因此发给父 Agent 的 steering 消息仍归父 Agent。 - -返回结构: - -```python -{ - "task_id": "sub-1a2b3c4d", - "session_id": "temp/sub-1a2b3c4d", - "status": "completed", # queued、running、completed、failed 或 cancelled - "output": "...", - "errors": [], -} -``` - -子 Agent 在后台运行:工具立即以 `queued` 或 `running` 状态返回,`output` 为空。任务结束时,父 Agent 会收到一条消息: - -```text - -... - -``` - -`output` 是子 Agent 的最终答案,即它最后一个没有工具调用的步骤的文本。启动了子 Agent 的运行在结果全部送达前不会结束:某一步结束且没有工具调用时,运行会等待下一个任务结束,并带着它的通知继续。如果运行失败、被取消或达到 `max_steps` 后任务才结束,结果会通过会话的 steering 收件箱送达:运行中的轮次在下一步之前读到,否则随下一轮送达。用 `subagent.wait` 读过的结果不再发送通知。 - -进程内同时运行的子 Agent 最多 `BUB_SUBAGENT_MAX_CONCURRENCY` 个,其余以 `queued` 状态排队。运行时退出,或对某个会话执行 `quit` 命令,会取消运行中的子 Agent。`temp` 或 `fork` 子 Agent 结束时,它启动的后台 Shell 会被停止。 +| `prompt` | `str \| list`(必填) | 委派给子 Agent 的任务指令 | +| `agent` | `str \| None`(`None`) | 要使用的[子 Agent Profile](/zh-cn/docs/app/subagents/#profiles) 名称;调用中显式传入的参数优先于 Profile | +| `description` | `str \| None`(`None`) | 任务简短标签;默认取 `prompt` 第一行 | +| `model` | `str \| None`(`None`) | 子 Agent 模型(`provider:model`);默认取 Profile 模型或父 Agent 模型 | +| `reasoning_effort` | `str \| None`(`None`) | 子 Agent 推理强度 | +| `session` | `str`(`"temp"`) | 会话模式:`"temp"`(新建空白临时会话,结束后丢弃)、`"fork"` / `"inherit"`(复制调用时的对话快照,结束后丢弃)或自定义固定会话 ID(结束后保留) | +| `allowed_tools` | `list[str] \| None`(`None`) | 允许使用的工具列表(不能超出父 Agent 本轮可用工具;子 Agent 始终不能再调用 `subagent*`) | +| `allowed_skills` | `list[str] \| None`(`None`) | 允许使用的技能列表(不能超出父 Agent 范围;传 `[]` 禁用技能) | +| `timeout_seconds` | `int \| None`(`None`) | 超时秒数;默认先取 Profile 时限,再取 `BUB_SUBAGENT_TIMEOUT_SECONDS` | + +`subagent` 在后台异步启动子任务,立即返回 `task_id` 与初始状态(`queued` 或 `running`)。当子任务结束时,父 Agent 会在下一步前收到 `` 消息(仅含子 Agent 最后一步的最终回答)。只要父 Agent 启动的子任务尚未全部结束,当前运行就会等待所有子任务完成后再结束。 ### `subagent.wait` {#subagent-wait} @@ -234,7 +188,7 @@ fork 在调用时复制父 Agent 的 Tape,子 Agent 看不到父 Agent 之后 subagent.wait(task_ids=None, timeout_seconds=60) ``` -返回任务结果,最多等待 `timeout_seconds` 让任务结束;`0` 只查看不等待。不传 `task_ids` 时覆盖本会话尚未读取的任务。超时后仍在运行的任务以当前状态返回。 +等待并读取子任务结果(`task_ids` 省略时覆盖当前会话所有未读子任务;`timeout_seconds=0` 时仅查询状态不阻塞)。已被 `subagent.wait` 读取的结果不再发送 ``。 ### `subagent.send` {#subagent-send} @@ -242,7 +196,7 @@ subagent.wait(task_ids=None, timeout_seconds=60) subagent.send(task_id, message) ``` -给任务发消息。运行中的任务在下一步之前读到它。使用命名会话且已结束的任务会作为新的后台任务继续该对话,工具范围受当前运行约束;已结束的 `temp` 或 `fork` 任务无法继续。 +向运行中的子任务追加指令(在下一步前生效),或唤醒已结束的自定义命名会话子任务继续工作(已结束的 `temp` / `fork` 任务不可继续)。 ### `subagent.cancel` {#subagent-cancel} @@ -250,23 +204,19 @@ subagent.send(task_id, message) subagent.cancel(task_id) ``` -停止运行中的任务。状态变为 `cancelled`,已有的部分输出会保留。 +终止运行中的子任务,状态置为 `cancelled` 并保留已产生的部分输出。 -### 事件 {#subagent-events} +### 子 Agent 事件 {#subagent-events} -每个任务都会在 Agent 的事件总线(`agent.events`)上发布事件,`state` 为发起它的那次运行的轮次状态: +子任务在 `agent.events` 上发布以下事件(定义于 `bub.builtin.subagents`,均携带 `event.task: SubagentTask`): -| 事件 | 时机 | +| 事件类 | 触发时机 | | --- | --- | -| `SubagentStarted` | 任务离开队列,子运行即将开始 | -| `SubagentOutput` | 子运行产生一个流事件,见 `event` | -| `SubagentFinished` | 任务以 `completed`、`failed` 或 `cancelled` 结束 | +| `SubagentStarted` | 子任务离开队列、开始执行时 | +| `SubagentOutput` | 子任务每产出一条 `StreamEvent` 时(保存在 `event.event`) | +| `SubagentFinished` | 子任务以 `completed`、`failed` 或 `cancelled` 结束时 | -每个事件都带有 `task`(`SubagentTask`),包含 `task_id`、`session_id`、`parent_session_id`、`parent_call_id`、`description`、`model`、`profile`、`status`、`output`、`errors`、`usage`、步数和工具调用数以及时间戳。它们可从 `bub.builtin.subagents` 导入。处理器抛出的异常只会被记录,不会让子运行失败。 - -子 Agent 与父 Agent 共享 `BubAgent`、插件 Hooks、模型凭据、工作区、`Environment`、文件和外部系统。会话策略只隔离对话记录和模型上下文,不隔离文件、网络或进程副作用。在对话中参数由模型生成,`allowed_tools` 本身不构成安全边界。 - -## 代码模式 与 spill {#code-and-spill} +## 代码模式与大输出转存(Spill) {#code-and-spill} ### `run_code` {#run-code} @@ -274,7 +224,7 @@ subagent.cancel(task_id) run_code(code, timeout_seconds=120) ``` -在 代码模式 中执行 Python。使用 `await tools.(key=value)` 调用工具;只有 `print()` 输出和显式附加的媒体进入结果。 +在代码模式开启时执行 Python 代码。代码内通过 `await tools.(key=value)`(关键字参数)调用其他工具;只有 `print()` 输出和显式附加的媒体会进入返回结果。 ### `attach_image` / `attach_audio` / `attach_video` {#attach-media} @@ -284,9 +234,7 @@ attach_audio(audio) attach_video(video) ``` -将图片、音频或视频附加到当前 `run_code` 调用的结果。对应参数接受 `republic.Image`、`republic.Audio` 或 `republic.Video` 对象,也可传入字符串,指定当前 `Environment` 中的文件路径、`http(s)` / `gs` URL 或 data URL;本地文件通过当前环境解析和读取。 - -这些工具的 `exposure` 为 `"code"`,只能在 `run_code` 内调用。每次调用将媒体追加到结果并返回确认字符串。 +将 Republic 媒体对象、本地文件路径或 URL 附加到当前 `run_code` 的返回结果中(`exposure="code"`,仅可在 `run_code` 内调用)。 ### `spill.read` {#spill-read} @@ -296,27 +244,21 @@ spill.read(handle, cursor=0, count=1, from_end=False) | 参数 | 类型 | 说明 | | --- | --- | --- | -| `handle` | `str` | 原工具输出中的 spill 句柄 | -| `cursor` | `int` | 块位置 | -| `count` | `int` | 读取块数,每次最多 4 块 | -| `from_end` | `bool` | 是否从末尾向前读取 | +| `handle` | `str` | 工具输出预览中给出的 spill 句柄 ID | +| `cursor` | `int` | 起始分块游标 | +| `count` | `int` | 本次连续读取的分块数(单次最多 4 块) | +| `from_end` | `bool` | 是否从末尾倒序读取 | -返回 `next_cursor` 和 `complete`;`complete=True` 表示已到达当前方向的边界。 +返回 `next_cursor` 和 `complete`(是否已读到边界)。转存阈值由 [`BUB_SPILL_THRESHOLD`](/zh-cn/docs/reference/settings/#spill-settings) 控制。 -spill 只在当前工具集包含 `spill.read` 时创建。阈值由 [`BUB_SPILL_THRESHOLD`](/zh-cn/docs/reference/settings/#spill-settings) 控制;设为 `0` 时停止创建新 spill,已有结果仍可读取。 +## 会话控制命令 {#session-commands} -超出阈值的大型工具结果写入 `spill` sidecar,主对话只保留预览和句柄。Sidecar 是与会话 Tape 配套的另一份 Tape:随主 Tape 一起分支、合并和重置,但它的条目不会进入主上下文。概念见 [Sidecar](/zh-cn/docs/sdk/tape/#sidecars)。 - -## 会话命令 {#session-commands} - -这些工具的 `exposure` 为 `command`,只能通过文本命令调用: +以下工具的 `exposure="command"`,仅可通过命令前缀(默认 `,`)直接调用,不暴露给模型: | 命令 | 参数 | 作用 | | --- | --- | --- | -| `,help` | 无 | 列出内部命令和命令前缀 | -| `,model` | `model_id` | 切换当前会话模型 | -| `,reasoning_effort` | `reasoning_effort` | 设置当前会话推理力度 | -| `,code_mode` | `enable=true` / `false` | 开关当前会话的 代码模式 | -| `,quit` | 无 | 清理待处理消息、运行中任务和后台 Shell | - -命令前缀由 `BUB_COMMAND_PREFIX` 决定。会话设置从下一次 Turn 起生效,并持久化在会话 Tape 中。 +| `,help` | 无 | 列出可用内部命令与命令前缀 | +| `,model` | `model_id` | 切换当前会话从下一次 Turn 起使用的模型(保存在 Tape 中) | +| `,reasoning_effort` | `reasoning_effort` | 设置当前会话从下一次 Turn 起的推理强度 | +| `,code_mode` | `enable=true` / `false` | 开启或关闭当前会话的代码模式(从下一次 Turn 起生效) | +| `,quit` | 无 | 清空当前会话的待处理消息队列、取消运行中的子任务并终止后台 Shell 进程 | diff --git a/website/src/content/docs/zh-cn/docs/sdk/events.mdx b/website/src/content/docs/zh-cn/docs/sdk/events.mdx index bae92e7e..d5c1a74b 100644 --- a/website/src/content/docs/zh-cn/docs/sdk/events.mdx +++ b/website/src/content/docs/zh-cn/docs/sdk/events.mdx @@ -1,32 +1,29 @@ --- title: 事件 -description: 注册与注销 Agent 事件处理器,修改参数、拒绝或替代工具调用,并发布自定义事件。 +description: 在 Bub Python SDK 中注册与注销 Agent 事件处理器,实现工具调用拦截、参数修改、拒绝或替换执行,并发布自定义事件。 --- -工具负责具体的业务逻辑(如查询订单或更新状态)。但在实际开发中,我们经常需要在调用前后补充额外逻辑,例如记录日志、清洗输入参数、校验权限或统计耗时。 +工具负责具体的业务逻辑(比如查询订单或更新状态),但在实际开发中,我们经常需要在调用前后补充额外逻辑——记录日志、清洗参数、校验权限或统计耗时。通过 `agent.events` 事件总线,你可以在不修改工具函数本身的前提下,把这些横切逻辑优雅地挂上去。 -Agent 事件提供了这些运行阶段的钩子。通过监听和处理事件,你可以在不修改工具本身的前提下,扩展 Agent 的行为。三类数据如何分工、同步分发有哪些规则,见 [Agent 事件](/zh-cn/docs/concepts/events/#three-kinds)。 +三种数据类型的区分与同步分发规则见 [Agent 事件](/zh-cn/docs/concepts/events/#three-kinds);与 App Hooks(`@hookimpl`)的对比见[Agent 事件与 App Hooks 的区别](/zh-cn/docs/concepts/events/#app-hooks)。 -## Agent 事件与 App Hooks 的区别 {#events-and-app-hooks} +## 注册与注销处理器 {#register} -两者的职责边界见[与 App Hooks 的分工](/zh-cn/docs/concepts/events/#app-hooks)。在 SDK 中,通过 `agent.events` 在模型或工具调用阶段添加逻辑。 +`agent.events.on()` 支持直接调用或作为装饰器使用;`off()` 用于移除处理器: -## 注册与注销 {#register} - -`EventBus.on()` 既可以直接注册,也可以作为装饰器;`off()` 移除处理器: - -```python -from bub.core.events import StepFinished, ToolCallStarted +```python "agent.events.on" "agent.events.off" +from bub.core.events import ToolCallStarted def record_tool_start(event: ToolCallStarted) -> None: print(f"开始调用:{event.call.tool}") -# 注册 +# 直接注册 agent.events.on(ToolCallStarted, record_tool_start) -# 装饰器写法等价 + +# 装饰器注册 @agent.events.on(ToolCallStarted) def log_tool_start(event: ToolCallStarted) -> None: print(f"调用参数:{event.call.arguments}") @@ -36,15 +33,14 @@ def log_tool_start(event: ToolCallStarted) -> None: agent.events.off(ToolCallStarted, record_tool_start) ``` -注册到基类的处理器也会接收子类事件:监听 `AgentEvent` 可以统一处理所有事件,监听 `TapeEvent` 则能拿到 `event.tape`。处理器可以是同步函数,也可以是 `async def`。 +处理器支持同步函数和 `async def` 异步函数。注册到基类的处理器会收到其所有子类事件(如监听 `AgentEvent` 可接收全部事件,监听 `TapeEvent` 可接收所有含 `event.tape` 的事件)。 ## 监听工具调用 {#listen-to-tool-calls} -下面以查询订单工具为例,展示如何记录日志。工具函数只负责业务查询,事件处理器负责记录调用。 +下面以查询订单工具为例,看看怎样把「查订单」和「记日志」解耦:工具函数只管业务查询,事件处理器负责记录调用。先定义工具并初始化 Agent: ```python from bub.core import Agent -from bub.core.events import ToolCallStarted from bub.core.tools import tool @@ -58,57 +54,50 @@ agent = Agent( tools=[get_order], system_prompt="用户询问订单状态时,使用 get_order 工具查询。", ) - ``` -工具执行结束后,`ToolCallFinished` 提供结果、错误信息及耗时: +监听 `ToolCallFinished` 记录工具执行结果与耗时: ```python from bub.core.events import ToolCallFinished + @agent.events.on(ToolCallFinished) def log_tool_finish(event: ToolCallFinished) -> None: status = "error" if event.result.error else "ok" - print( - f"调用结束:{event.result.tool}," - f"{status},耗时 {event.result.duration_ms}ms" - ) - + print(f"调用结束:{event.result.tool},{status},耗时 {event.result.duration_ms}ms") ``` -## 工具调用流程 {#tool-call-order} +## 工具事件执行顺序 {#tool-call-order} -在 Agent 循环中,工具调用的基本流程如下: +在 Agent 循环中,一次工具调用会按以下路径流转: ```mermaid flowchart TD - A[模型请求调用工具] --> B[发出 ToolCallStarted] - B --> C[按注册顺序运行 Started 处理器] - C --> D{处理器的决策} - D -->|继续| E[执行工具函数] - D -->|拒绝| F[跳过工具函数,生成工具错误] - D -->|替代| G[跳过工具函数,使用指定结果] - E --> H[发出 ToolCallFinished] + A[模型请求调用工具] --> B[触发 ToolCallStarted] + B --> C[按注册顺序运行处理器] + C --> D{处理器的 decision} + D -->|继续 proceed| E[执行工具函数] + D -->|拒绝 deny| F[跳过工具函数,生成工具错误] + D -->|替换 replace| G[跳过工具函数,返回替代结果] + E --> H[触发 ToolCallFinished] F --> H G --> H - H --> I[工具结果交回模型循环] + H --> I[结果交回模型循环] I --> J{Run 是否结束?} J -->|否| A - J -->|是| K[关闭流并发出 RunFinished] - + J -->|是| K[关闭流并触发 RunFinished] ``` -`ToolCallStarted` 事件处理器会在工具运行前执行。多个处理器按注册顺序依次运行;如果某处理器设置了拒绝或替代决策,后续处理器和原工具函数将被跳过。 - -无论工具正常执行、被拒绝还是被替代,都会发出 `ToolCallFinished`。注意,一次工具调用结束并不代表整个 Agent 调用的结束;若需判断最终状态,请监听 `RunFinished` 事件。 - -通过 代码模式 的 `tools.()` 和文本命令发起的工具调用同样发出这两个事件。 +- 多个 `ToolCallStarted` 处理器按注册顺序执行;一旦某个处理器设置了 `deny` 或 `replace`,后续处理器和原工具函数都会被跳过。 +- 无论工具正常执行、被拒绝还是被替换,都会触发 `ToolCallFinished`。注意:一次工具调用结束并不代表整个 Agent 运行结束;若需判断最终状态,请监听 `RunFinished`。 +- 代码模式中的 `tools.()` 和直接命令触发的工具调用,同样会发出这两个事件。 -## 在工具执行前修改参数 {#modify-tool-call} +## 在执行前修改工具参数 {#modify-tool-call} -除了观察调用,事件处理器还可以在工具执行前修改参数。例如,清理订单号中的空格并统一为大写: +除了观察调用,事件处理器还可以在工具执行前清洗或改写参数。因为 `ToolCall` 是不可变对象,在 `ToolCallStarted` 处理器中用 `dataclasses.replace()` 替换 `event.call` 即可(例如去除订单号首尾空格并转为大写): -```python +```python {14} from dataclasses import replace from bub.core.events import ToolCallStarted @@ -122,59 +111,44 @@ def normalize_order_id(event: ToolCallStarted) -> None: **event.call.arguments, "order_id": event.call.arguments["order_id"].strip().upper(), } - # ToolCall 是不可变对象,使用 replace 创建新对象并重新赋值 event.call = replace(event.call, arguments=arguments) - ``` -## 检查权限与决策控制 {#control-tool-call} +## 拦截调用与替换结果 {#control-tool-call} -通过设置 `event.decision`,可以在工具执行前继续、拒绝或使用替代结果。四种处理的语义见[决策先于副作用](/zh-cn/docs/concepts/events/#call-control),下面展示具体写法。 +在工具真正执行前,你还可以通过设置 `event.decision` 来做权限校验、直接拦截或返回缓存结果(详细语义见[调用前拦截与控制](/zh-cn/docs/concepts/events/#call-control)): -### 1. 拒绝调用 {#deny-a-call} +### 1. 拒绝工具调用 {#deny-a-call} -如果需要根据参数拦截某些操作(如禁止查询特例订单): - -```python +```python "ToolCallDecision.deny" from bub.core.events import ToolCallDecision, ToolCallStarted @agent.events.on(ToolCallStarted) def check_order_access(event: ToolCallStarted) -> None: - if ( - event.call.tool == "get_order" - and event.call.arguments.get("order_id") == "A123" - ): - event.decision = ToolCallDecision.deny("当前不允许查询这个订单。") - + if event.call.tool == "get_order" and event.call.arguments.get("order_id") == "A123": + event.decision = ToolCallDecision.deny("无权查询该订单。") ``` -设置 `ToolCallDecision.deny(...)` 后,原工具函数不会执行。模型循环会把拒绝作为工具错误交回模型;直接命令没有模型可以接收这个错误,因此向调用方抛出该错误。 +设置 `ToolCallDecision.deny(...)` 后,原工具不会执行。模型循环会将拒绝原因作为工具错误传回模型;若是直接命令调用,则直接向调用方抛出异常。 -### 2. 使用替代结果 {#replacement-result} +### 2. 返回替代结果 {#replacement-result} -如果有直接可用的数据(如命中缓存),可以跳过工具函数并返回替代结果: +命中缓存或 Mock 时,跳过工具函数并直接返回指定结果: -```python +```python "ToolCallDecision.replace" @agent.events.on(ToolCallStarted) def use_cached_order(event: ToolCallStarted) -> None: - if ( - event.call.tool == "get_order" - and event.call.arguments.get("order_id") == "A123" - ): - event.decision = ToolCallDecision.replace( - {"order_id": "A123", "status": "shipped"} - ) - + if event.call.tool == "get_order" and event.call.arguments.get("order_id") == "A123": + event.decision = ToolCallDecision.replace({"order_id": "A123", "status": "shipped"}) ``` -### 3. 修改模型调用 {#control-llm-call} +### 3. 修改或跳过模型调用 {#control-llm-call} -`LLMCallStarted` 上可以替换整个请求,或直接产生输出而跳过供应商: +在 `LLMCallStarted` 中可修改请求参数(如限制 `max_tokens`),或用 `LLMCallDecision.finish(text)` 跳过模型请求直接返回文本: -```python +```python "LLMCallDecision.finish" from dataclasses import replace - from bub.core.events import LLMCallDecision, LLMCallStarted @@ -186,13 +160,12 @@ def guard_llm_call(event: LLMCallStarted) -> None: event.decision = LLMCallDecision.finish("当前处于离线演示模式。") ``` -## 自定义事件 {#custom-events} +## 发布自定义事件 {#custom-events} -事件对象是普通 dataclass,继承 `AgentEvent` 即可发布;需要携带当前 Tape 时继承 `TapeEvent`: +除了监听内置事件,你也可以在业务代码中定义并发布自己的事件。事件对象就是一个普通的 Python `dataclass`,继承 `AgentEvent`(或需要当前会话 Tape 时继承 `TapeEvent`)即可: -```python +```python "class OrderReviewed(TapeEvent):" "await agent.events.emit" from dataclasses import dataclass - from bub.core.events import TapeEvent @@ -213,18 +186,17 @@ async def mark_reviewed() -> None: ) ``` -几点约定: +注意事项: -- `TapeRecorder` 不会自动记录自定义事件,上例显式写入了一条。 -- Tracing 与 Tape 记录相互独立:关闭 tracing 不会停止 `TapeRecorder`,也不会禁用对话和工具往返的 Tape 记录。 -- 自定义事件没有内置的 `decision` 协议。需要返回数据时定义可变字段;需要让决策结束派发时覆写 `stopped` 属性。 -- 工具可以通过 `context.events` 发布事件。 +- **需显式写入 Tape**:内置的 `TapeRecorder` 不会自动记录自定义事件;如需持久化到会话历史,请在处理器中调用 `event.tape.append_event(...)`。 +- **自定义字段与停止分发**:自定义事件不含 `decision` 属性。可在事件类上定义可变字段回传数据,或覆写 `stopped` 属性提前停止分发。 +- **在工具内发事件**:工具函数可通过 `context.events.emit(...)` 发布事件。 -## 监听模型调用、单步与 Run 事件 {#other-events} +## 监听模型、Step 与 Run 事件 {#other-events} -Agent 的执行有三个可观测粒度:模型调用(LLMCall)、Step 和 Run,可以分别监听来做指标、用量统计和日志审计。 +除了工具调用,Agent 的运行还提供了三个层级的生命周期事件:模型调用、Step 和 Run。你可以按需监听它们来收集监控指标、统计 Token 用量或记录审计日志。 -### 1. 模型调用 {#model-calls} +### 1. 模型调用事件 {#model-calls} ```python from bub.core.events import LLMCallFinished, LLMCallStarted @@ -232,7 +204,7 @@ from bub.core.events import LLMCallFinished, LLMCallStarted @agent.events.on(LLMCallStarted) def log_llm_start(event: LLMCallStarted) -> None: - print(f"正在请求大模型,输入消息数:{len(event.request.messages)}") + print(f"请求模型,消息数:{len(event.request.messages)}") @agent.events.on(LLMCallFinished) @@ -240,13 +212,12 @@ def log_llm_finish(event: LLMCallFinished) -> None: if event.result.error: print(f"模型调用失败:{event.result.error}") else: - print(f"模型调用成功,Token 用量:{event.result.usage}") - + print(f"模型调用成功,用量:{event.result.usage}") ``` -### 2. 单步执行事件 {#step-events} +### 2. Step 事件 {#step-events} -`StepFinished` 的 `status` 说明本步之后运行是否继续(`continue`)或结束(`ok`): +每完成一次「模型推理 + 工具执行」触发一次 `StepFinished`。`event.status` 为 `"continue"` 表示还需进入下一步,为 `"ok"` 表示已得出最终回答: ```python from bub.core.events import StepFinished, StepStarted @@ -254,20 +225,19 @@ from bub.core.events import StepFinished, StepStarted @agent.events.on(StepStarted) def log_step_start(event: StepStarted) -> None: - print(f"--- 开始执行第 {event.step} 步 ---") + print(f"--- Step {event.step} 开始 ---") @agent.events.on(StepFinished) def log_step_finish(event: StepFinished) -> None: - print(f"--- 第 {event.step} 步完成:{event.status},{event.elapsed_ms}ms ---") - + print(f"--- Step {event.step} 结束:{event.status},{event.elapsed_ms}ms ---") ``` -设置 `StepFinished.next_prompt` 可以为继续 Run 的下一个 Step 提供一条用户消息;`MessagesPending` 处理器则通过 `event.messages` 补入 Run 期间到达的消息。 +在 `StepFinished`(当 `status == "continue"` 时)设置 `event.next_prompt` 可向下一轮推理追加用户提示;监听 `MessagesPending` 并向 `event.messages` 追加内容,则可注入运行期间到达的外部引导消息。 ### 3. Run 事件 {#run-events} -`RunStarted` 和 `RunFinished` 用于掌控整个任务的起止。特别需要注意的是 `RunFinished`,它在整场运行的事件流关闭时触发(包括正常完成、异常中断或提前取消)。尚未迭代就关闭的 Run 以 `cancelled` 结束,Step 数为零。 +`RunStarted` 和 `RunFinished` 分别在整次 Run 开始和**事件流关闭时**触发。若创建了 `agent.run()` 但未迭代流就直接关闭,`RunFinished` 会以 `status="cancelled"`、`steps=0` 触发: ```python from bub.core.events import RunFinished, RunStarted @@ -275,12 +245,12 @@ from bub.core.events import RunFinished, RunStarted @agent.events.on(RunStarted) def log_run_start(event: RunStarted) -> None: - print("Agent 任务开始运行...") + print("Run 开始...") @agent.events.on(RunFinished) def log_run_result(event: RunFinished) -> None: - print(f"Agent 任务结束:status={event.status},总步数={event.steps}") + print(f"Run 结束:status={event.status},steps={event.steps}") ``` -完整事件列表、字段与触发时机见 [Python API:事件](/zh-cn/docs/reference/python-api/#events)。 +所有事件类的字段定义见 [Python API:事件](/zh-cn/docs/reference/python-api/#events)。 diff --git a/website/src/content/docs/zh-cn/docs/sdk/index.md b/website/src/content/docs/zh-cn/docs/sdk/index.md index d594c043..115b1820 100644 --- a/website/src/content/docs/zh-cn/docs/sdk/index.md +++ b/website/src/content/docs/zh-cn/docs/sdk/index.md @@ -1,25 +1,27 @@ --- -title: Agent 循环 -description: 在自己的代码中驱动 bub.core.Agent:消费运行流、读取流式事件,并管理 Tape 记忆。 +title: 使用 SDK 运行 Agent 循环 +description: 在 Python 应用中嵌入 bub.core.Agent,驱动模型与工具循环、消费异步流式事件并管理会话 Tape 记忆。 +sidebar: + label: Agent 循环 --- -`bub.core.Agent` 是 `bub` 的最小内核,负责驱动大模型与本地工具之间的交互循环。你可以直接将它嵌入任何 Python 服务、后端框架或自定义脚本中。 +`bub.core.Agent` 是 Bub 的最小内核,负责驱动模型与本地工具的交互循环。你可以将它直接嵌入任何 Python 服务、后端框架或脚本。 -在 [快速上手](/zh-cn/docs/getting-started/quickstart/) 中我们已经体验过如何初始化并运行一个 Agent: +在[快速上手](/zh-cn/docs/getting-started/quickstart/)中我们已经体验过如何初始化并运行一个 Agent: -```py +```py title="main.py" {8, 13} import asyncio import republic from bub.core import Agent async def main() -> None: - # 初始化核心 Agent,指定系统提示词 + # 创建 Agent 并设置系统提示词 agent = Agent(system_prompt="Be concise.") - # 使用 republic 获取底层大模型连接 + # 通过 republic 连接大模型 async with republic.get_model("openai:gpt-5-mini") as model: - # 启动一次 Run,指定对话 Tape 名称 + # 启动一次 Run 并指定会话 Tape 名称 async with agent.run("What can you do?", model=model, tape="demo") as stream: async for event in stream: if event.kind == "text": @@ -29,29 +31,29 @@ async def main() -> None: asyncio.run(main()) ``` -本文介绍如何消费运行流、处理流式事件并管理 Tape;Run、Step 与 Turn 的定义见 [Agent 循环](/zh-cn/docs/concepts/agent/#loop)。 +接下来我们重点看看如何消费运行流、处理各类流式事件,以及用 Tape 管理记忆。Run、Step 与 Turn 的概念说明见 [Agent 循环](/zh-cn/docs/concepts/agent/#loop)。 ## 1. 运行流程 {#run-and-step} -下面是一次包含工具调用的多步 Run: +一次包含工具调用的 Run 按以下流程推进: ```mermaid flowchart TD - Start["进入 agent.run(),初始化 Tape 分支"] --> Consume["调用方通过 async for 迭代事件流"] - Start --> RunStarted["发出 RunStarted"] - Consume --> Step["Step 启动:向模型发送上下文"] + Start["进入 agent.run(),创建 Tape 分支"] --> Consume["调用方用 async for 消费事件流"] + Start --> RunStarted["触发 RunStarted"] + Consume --> Step["开始 Step:向模型发送上下文"] Step --> Output["产出 reasoning / text / usage"] - Output --> Decision{"模型是否请求工具?"} - Decision -->|"是"| Call["产出 tool_call,执行本地工具函数"] + Output --> Decision{"是否请求调用工具?"} + Decision -->|"是"| Call["产出 tool_call,执行本地工具"] Call --> Result["产出 tool_result 与单步 final"] Result --> Step - Decision -->|"否"| Final["产出最终文本与 final"] - Final --> Close["关闭流,发出 RunFinished,合并 Tape 分支"] + Decision -->|"否"| Final["产出最终文本与单步 final"] + Final --> Close["关闭流,触发 RunFinished,合并 Tape 分支"] ``` ## 2. 消费事件流 {#consume-the-stream} -进入 `agent.run()` 后,`bub` 会初始化会话并发出 `RunStarted`,但底层的模型与工具循环采用了**惰性求值(Lazy Evaluation)**设计:只有当你通过消费事件流时,Agent 才会真正开始步进和工作。仅仅创建上下文而不消费流,任务将不会执行。下面是一个简单的例子: +进入 `agent.run()` 后,Bub 会初始化会话并触发 `RunStarted`,但底层循环采用了**惰性执行**设计:只有当你用 `async for` 迭代事件流时,模型推理与工具调用才会真正开始——仅仅创建上下文而不消费流,任务并不会运行。 ```python async with agent.run(prompt, model=model, tape="quickstart") as stream: @@ -59,39 +61,36 @@ async with agent.run(prompt, model=model, tape="quickstart") as stream: ... ``` -始终建议将 `agent.run()` 放在 `async with` 上下文管理器中,这样可以确保无论是因为正常跑完、中途异常退出还是被外部取消,底层连接和流都能被安全清理。未正常跑完的 Run 会以 `cancelled` 状态收尾。 - -所有事件你均可以通过 `event.kind` 来获取。 +请始终在 `async with` 块中使用 `agent.run()`,以确保无论正常结束、抛出异常还是被取消,底层流和连接都能安全关闭。未迭代完就被关闭的 Run 状态为 `cancelled`。 :::caution -当出现 `final` 事件时,仅表示**当前 Step 的结束**,而不是整个 Run 的终点。 -如果模型在当前 Step 请求调用了工具,工具执行完毕后,Agent 必然会带着工具结果进入下一个 Step,并产生新的事件。因此,无论你是向客户端返回流式响应,还是统计任务完成状态,都必须**等待整个 `async for event in stream` 循环完整结束**才开始执行。 +`event.kind == "final"` 仅代表**当前 Step 结束**,不代表整次 Run 结束。若模型在当前 Step 调用了工具,Agent 会带着工具结果继续进入下一个 Step 并产出新事件。请以整个 `async for event in stream` 循环自然结束作为 Run 完成的标志。 ::: -## 3. 事件类型与数据 {#stream-events} +## 3. 流事件类型 {#stream-events} -在迭代 `stream` 时,你会收到不同 `kind` 的事件。每个事件的 `event.data` 数据结构如下: +在迭代 `stream` 时,你会按顺序收到不同 `kind` 的事件。通过 `event.kind` 和 `event.data` 读取每条流式事件: -| 事件类型 | `event.data` 示例 | 说明 | +| `event.kind` | `event.data` 结构 | 说明 | | --- | --- | --- | -| `reasoning` | `{"delta": "..."}` | 模型思考过程(Chain of Thought / Reasoning)的文本增量 | -| `text` | `{"delta": "..."}` | 面向用户的正式回复文本增量 | +| `reasoning` | `{"delta": "..."}` | 模型思考过程的文本增量 | +| `text` | `{"delta": "..."}` | 面向用户的回复文本增量 | | `tool_call` | `{"tool_calls": [{"id", "name", "arguments"}, ...]}` | 模型请求调用的工具列表(`arguments` 为 JSON 字符串) | -| `tool_result` | `{"tool_results": [...]}` | 与工具调用顺序对应的执行结果,异常信息也在此回传给模型 | -| `usage` | `{"usage": {...}, "elapsed_seconds": ...}` | 当前 Step 的模型 Token 消耗量与耗时统计 | -| `final` | `{"ok": True, "text": ...}` 或工具汇总 | 当前 Step 的汇总结果 | +| `tool_result` | `{"tool_results": [...]}` | 工具执行结果列表(与 `tool_calls` 顺序对应,含错误结果) | +| `usage` | `{"usage": {...}, "elapsed_seconds": ...}` | 当前 Step 的 Token 用量与耗时 | +| `final` | `{"ok": True, "text": ...}` 或工具汇总 | 当前 Step 的结束汇总 | -因为,在宿主程序中,通常需要根据 `event.kind` 分流处理,这也就是为什么叫 Agent 循环,因为本质上就是在一个循环中不断分流处理事件: +在宿主程序中,通常只需要在循环里按 `event.kind` 分流处理你关心的事件: ```python async for event in stream: if event.kind == "tool_call": for call in event.data["tool_calls"]: - print(f"[{event.step_index}] 模型请求调用工具:{call['name']}") + print(f"调用工具:{call['name']}") elif event.kind == "text": print(event.data["delta"], end="", flush=True) ``` -## 4. Tape 与记忆分支管理 {#tape-management} +## 4. Tape 与会话记忆 {#tape-management} -示例中的 `tape="demo"` 指定本次 Run 使用的历史记录。连续对话、持久化以及分支合并的操作见 [SDK:Tape 与记忆](/zh-cn/docs/sdk/tape/),历史与模型上下文的区别见 [Tape 概念](/zh-cn/docs/concepts/tape/)。 +示例中的 `tape="demo"` 指定了本次 Run 读写的会话记录名称。想要了解多轮对话、持久化存储与分支合并,可以继续阅读 [SDK:Tape 与记忆](/zh-cn/docs/sdk/tape/);历史与模型上下文的区别见 [Tape 概念](/zh-cn/docs/concepts/tape/)。 diff --git a/website/src/content/docs/zh-cn/docs/sdk/tape.mdx b/website/src/content/docs/zh-cn/docs/sdk/tape.mdx index 49b6446c..f47b37de 100644 --- a/website/src/content/docs/zh-cn/docs/sdk/tape.mdx +++ b/website/src/content/docs/zh-cn/docs/sdk/tape.mdx @@ -1,21 +1,17 @@ --- title: Tape 与记忆 -description: 让 Agent 在多轮对话中保留信息,并理解历史记录、模型上下文与 Tape 存储。 +description: 使用 Bub Python SDK 管理多轮记忆:持久化 Tape 历史、自定义 TapeContext 筛选,并使用 Sidecar、anchor 与分支合并。 --- -如果每次请求都只把当前消息交给模型,Agent 就无法接续之前的对话。要让它记得你刚才说过什么,就需要保存对话记录,并在下一轮请求中把相关历史交给模型。 +如果每次请求都只把当前消息交给模型,Agent 就无法接续之前的对话。要让它记得你刚才说过什么,就需要保存对话记录,并在下一轮请求中把相关历史交给模型。Bub 用 Tape 保存对话消息、工具调用往返和运行事件,让 Agent 具备多轮记忆能力。Tape 与模型上下文的分工见 [Tape 与模型上下文](/zh-cn/docs/concepts/tape/#history-and-context)。 -Bub 用 Tape 保存对话、工具调用输入输出和运行记录,让你的 Agent 具备记忆和连续对话的能力。历史与模型上下文为什么分开、`TapeContext` 从哪里开始读取,见 [Tape 与模型上下文](/zh-cn/docs/concepts/tape/#history-and-context)。 +## 保持多轮连续对话 {#remember-previous-turn} -## 连续对话 {#remember-previous-turn} +要让模型能与你连续对话、记住你的偏好,关键在于多次调用 `agent.run()` 时传入同一个 `tape` 名称: -要让模型能与你连续对话或记住你所说的,关键在于调用 `agent.run()` 时要使用同一个 Tape 名称: - -```python +```python 'tape="demo-user"' import asyncio - import republic - from bub.core import Agent @@ -24,12 +20,12 @@ async def run_turn(agent: Agent, model, prompt: str) -> None: async for event in stream: if event.kind == "text": print(event.data["delta"], end="", flush=True) - print("DONE") + print("\nDONE") async def main() -> None: agent = Agent( - system_prompt="你是一个简洁的助手,并记住用户明确提出的回答偏好。", + system_prompt="你是一个简洁的助手,记住用户要求的回答格式。", max_steps=6, ) @@ -40,96 +36,80 @@ async def main() -> None: if __name__ == "__main__": asyncio.run(main()) - ``` -两次调用都使用 `demo-user` 这一 Tape 记忆,所以第二轮可以接续第一轮的对话。Bub 默认使用 `InMemoryTapeStore` 来存储 Tape,但当你进程退出后就会丢失。此外,如果每个请求都重新创建 Agent,即使 Tape 名称相同,也不会共享默认的内存历史。 +`Agent` 默认使用内存存储 `InMemoryTapeStore`:数据仅在当前 `Agent` 实例与当前进程内有效,进程退出或每次请求新建 `Agent` 实例都会丢失历史。 -## 记忆持久化 {#persist-memory} +## 持久化到磁盘或数据库 {#persist-memory} -Bub 内置了一个 `FileTapeStore`,用于帮助你将 Tape 以持久化的方式写入到本地,后续即便退出进程重新进入时也能恢复历史对话,前提是你必须在创建 Agent 时配置: +如果你想让记忆在进程重启后依然保留,可以传入 Bub 内置的 `FileTapeStore`,将每个 Tape 持久化为本地 `.jsonl` 文件: -```python +```python "FileTapeStore" from pathlib import Path - from bub.core import Agent from bub.core.store import FileTapeStore agent = Agent( store=FileTapeStore(Path("sessions")), - system_prompt="你是一个简洁的助手,并记住用户明确提出的回答偏好。", + system_prompt="你是一个简洁的助手,记住用户要求的回答格式。", ) - ``` -于是再次运行程序时,使用同一个存储目录和 Tape 名称即可读取历史记录。于是上面的会话会保存在 `sessions/demo-user.jsonl` 文件中。 +上例中的 `tape="demo-user"` 会保存在 `sessions/demo-user.jsonl`。 -### Tape 名称决定记录延续 {#tape-names} +### Tape 命名与隔离 {#tape-names} -`agent.run(..., tape="customer-42")` 按名称选择 Tape。重复使用同一名称会延续记录,不同名称彼此独立。名称由调用方负责:`core.Agent` 不会替你加工作区、租户或用户前缀。 +`agent.run(..., tape="customer-42")` 按名称隔离会话:同名接续历史,不同名相互独立。`core.Agent` 不会自动添加工作区或用户前缀,命名规则由宿主程序自行管理。 -`FileTapeStore` 直接把 Tape 名称用作文件名。名称由用户输入或来自外部标识时,必须校验字符与长度,或改用随机标识;多租户服务还应把租户与用户身份纳入命名空间。 +### 选择存储后端 {#storage} -### 存储方案怎么选? {#storage} - -| 存储 | 生命周期 | 适用场景 | +| 存储实现 | 生命周期 | 适用场景 | | --- | --- | --- | -| `InMemoryTapeStore`(默认) | 当前 Agent 实例与进程 | 测试、临时脚本 | -| `FileTapeStore` | 每个 Tape 一个 `.jsonl` 文件 | 单机 CLI、开发环境、单节点服务 | -| 自定义 `TapeStore` / `AsyncTapeStore` | 由宿主实现决定 | Redis、SQL、分布式存储 | - -:::note[注意事项] +| `InMemoryTapeStore`(默认) | 当前 `Agent` 实例与进程内 | 测试、一次性脚本 | +| `FileTapeStore` | 每个 Tape 对应一个本地 `.jsonl` 文件 | 本地 CLI、开发环境、单机服务 | +| 自定义 `TapeStore` / `AsyncTapeStore` | 由后端决定 | 生产环境的 SQL 数据库、Redis 或分布式存储 | -* `FileTapeStore` 会把 Tape 名称用于文件名。如 Tape 名称由用户传入,需进行必要安全校验,如严格限制名称字符与长度或使用随机生成的标识;对于多租户服务还应把租户和用户身份纳入会话命名空间。 -* 面向生产时建议自定义并实现 Tape 存储。完整协议见 [Python API](/zh-cn/docs/reference/python-api/#tape)。也可参考数据库接入示例见 [存储集成](/zh-cn/docs/integrations/storage/)。 +:::note[安全与生产建议] +- `FileTapeStore` 直接将 Tape 名称用作文件名。若名称来自用户输入,**必须先校验字符范围与长度**(或映射为随机 UUID);多租户服务应将租户与用户 ID 拼入名称,防止越权访问。 +- 生产环境存储协议见 [Python API:`TapeStore`](/zh-cn/docs/reference/python-api/#tape-store),数据库接入见[使用数据库存储会话历史](/zh-cn/docs/integrations/storage/)。 ::: -### 在 Run 之外查看记录 {#inspect} +### 在 Run 之外查询历史 {#inspect} -不在 Run 中时,通过 `agent.tape(name)` 拿到同一份记录,并分别查看两种视图: +通过 `agent.tape(name)` 可随时读取转换后的模型消息或原始存储条目: ```python async def inspect_history(agent: Agent) -> None: tape = agent.tape("customer-42") - messages = await tape.read_messages() - entries = list(await tape.query().all()) - print(f"模型消息:{len(messages)},存储条目:{len(entries)}") + messages = await tape.read_messages() # 经 TapeContext 筛选后的模型消息 + entries = list(await tape.query().all()) # 存储在 Tape 中的原始条目 + print(f"模型消息:{len(messages)},原始条目:{len(entries)}") ``` -`read_messages()` 应用投影,`query()` 返回原始条目。 +## 自定义 TapeContext {#history-and-context} -## TapeContext {#history-and-context} - -Tape 与模型上下文的区别,以及原始条目和投影消息的读取方式,见[一份记录,两种视图](/zh-cn/docs/concepts/tape/#history-and-context)。下面介绍如何自定义投影。 - -### 默认上下文与自定义 {#default-context} - -每个 Agent 都绑定了一个 `context`(默认是 `default_tape_context()`)。上面的 `agent` 等价于: +每个 `Agent` 都绑定了一个 `context`(默认为 `default_tape_context()`): ```python from bub.core import Agent, default_tape_context agent = Agent( - context=default_tape_context(), # 默认值:每个 agent.tape(name) 都会携带它 - # ... + context=default_tape_context(), ) - ``` -### TapeContext 的构成 {#tape-context-fields} - -`TapeContext` 是一个数据类,控制着上下文的裁剪与转换行为。其核心字段包括: +### TapeContext 字段 {#tape-context-fields} -| 字段 | 默认值 | 作用说明 | +| 字段 | 默认值 | 说明 | | --- | --- | --- | -| `anchor` | `LAST_ANCHOR` | 过滤锚点(anchor):只读取最近一个 anchor 之后的条目;可传具体的 anchor 名称字符串,或传 `None` 表示不按 anchor 过滤。 | -| `select` | `None` | 自定义转换函数:将选中的 Tape 条目转换为模型消息列表。若为 `None`,则使用运行时内置的标准转换规则(支持标准消息、工具往返等)。 | -| `state` | `{}` | 关联的临时状态字典。每次 `agent.run(state=...)` 或 `agent.tape(state=...)` 都会写入这里,工具内部的 `ToolContext.state` 访问的也是同一个字典。 | +| `anchor` | `LAST_ANCHOR` | 读取起点:默认只读最近一个 anchor 之后的条目;可传指定 anchor 名称,或传 `None` 从头读取全部条目 | +| `select` | `None` | 自定义消息选择器函数;为 `None` 时使用内置转换规则 | +| `state` | `{}` | 请求级临时状态字典(与 `agent.run(state=...)` 和 `ToolContext.state` 共享) | -:::tip[关于类与工厂函数] -直接调用 `TapeContext()` 构造的是一个极简的底层基础上下文(通常仅处理基础文本消息);而 `default_tape_context()` 是官方提供的 **全功能工厂函数**,能够完美处理多轮对话、工具调用(`tool_call` / `tool_result`)与 anchor。 +:::tip[`TapeContext()` 与 `default_tape_context()`] +直接调用 `TapeContext()` 构造的是极简的底层上下文,而 `default_tape_context()` 则是全功能工厂函数,预设了完整的多轮对话、工具往返与 anchor 转换规则。 -如果你想保留默认的所有强大特性,只是想更改一下起始的 `anchor`,推荐使用 Python 标准库的 `dataclasses.replace()` 进行微调: +如果你想保留默认的所有强大特性,只是想微调一下起始的 `anchor`,推荐使用 `dataclasses.replace()` 基于 `default_tape_context()` 修改: ```python from dataclasses import replace @@ -137,31 +117,25 @@ from bub.core import Agent, default_tape_context agent = Agent( context=replace(default_tape_context(), anchor="order-reviewed"), - # ... ) - ``` ::: -### 选择其他起点 {#custom-anchors} - -`TapeContext.anchor` 控制查询范围: +### 指定读取起点(`anchor`) {#custom-anchors} -| 值 | 查询范围 | +| `anchor` 取值 | 读取范围 | | --- | --- | -| `LAST_ANCHOR`(默认) | 最近一个 anchor 之后 | -| `"order-reviewed"` | 指定名称的 anchor 之后 | -| `None` | 不按 anchor 过滤 | +| `LAST_ANCHOR`(默认) | 最近一个 anchor 之后的条目 | +| `"order-reviewed"` | 名为 `"order-reviewed"` 的 anchor 之后的条目 | +| `None` | 不按 anchor 截断,从头读取全部条目 | -### 自定义选择器 {#custom-selectors} +### 自定义消息选择器(`select`) {#custom-selectors} -需要不同投影时,向 `TapeContext(select=...)` 传入函数。它接收选中的条目和上下文,返回 Republic 消息或其 awaitable: +如需将自定义业务事件(`kind="event"`)也拼入模型上下文,可向 `TapeContext(select=...)` 传入选择器函数: -```python +```python showLineNumbers {23} from collections.abc import Iterable - import republic - from bub.core import Agent, TapeContext, default_tape_context from bub.core.tape import TapeEntry, build_messages @@ -169,7 +143,7 @@ from bub.core.tape import TapeEntry, build_messages def with_order_notes( entries: Iterable[TapeEntry], _context: TapeContext ) -> list[republic.Message]: - """默认投影之外,把订单备注作为系统提醒交给模型。""" + """在默认对话消息基础上,将订单备注作为系统消息追加给模型。""" entries = list(entries) messages = build_messages(entries, default_tape_context()) notes = [ @@ -185,41 +159,37 @@ def with_order_notes( agent = Agent(context=TapeContext(anchor=None, select=with_order_notes)) ``` -两处容易写错: +编写自定义选择器时,有两个细节容易踩坑: -- 传入的 `entries` 是 `Iterable`,可能是生成器;先 `list()` 物化再遍历,否则第二次遍历会得到空结果。 -- 复用默认投影时要传一个新的 `default_tape_context()`,不要把携带当前 selector 的 `context` 再交给 `build_messages()`,否则会递归调用自己。 +1. **先用 `list(entries)` 转为列表**:传入的 `entries` 可能是单次消费的生成器,多次遍历前必须先转为列表。 +2. **向 `build_messages()` 传入新的 `default_tape_context()`**:不要将当前带有自定义 `select` 的 `_context` 传给 `build_messages()`,否则会导致无限递归。 -自定义选择器会**替换**默认选择器,因此对话、工具往返、anchor 和你关心的业务事件都需要由你有意地组合。此时 `context=False` 的条目仍会在调用选择器前被过滤。 +自定义选择器会整体替换默认选择器;写入时带 `context=False` 的条目会在进入选择器前被自动过滤。 -### 临时切换读取模式 {#read-with-another-context} +### 单次读取时临时切换上下文 {#read-with-another-context} -如果你不想修改 Agent 默认的上下文配置,只是想在某次读取时换一种视角(例如临时跳过 anchor 限制查看全量对话),可以使用 `tape.with_context()`: +如果你不想修改 Agent 默认的上下文配置,只是想在某次读取时换一种视角(例如临时跳过 anchor 限制查看全量对话),可以使用 `tape.with_context(...)`: ```python from dataclasses import replace - from bub.core import default_tape_context tape = agent.tape("demo-user") - -# 临时创建一个不按 anchor 过滤、使用默认转换规则的上下文来读取全部消息 -full_messages = await tape.with_context(replace(default_tape_context(), anchor=None)).read_messages() - +full_messages = await tape.with_context( + replace(default_tape_context(), anchor=None) +).read_messages() ``` -这只改变本次读取的行为,不会修改 Tape 本身的存储,也不会影响 Agent 后续的调用。 - -### anchor 和 handoff {#anchors-and-handoff} +### anchor 与 handoff {#anchors-and-handoff} -anchor 与交接(handoff)的概念和边界见[Tape 与模型上下文](/zh-cn/docs/concepts/tape/#anchors)。这里补充实际使用时需要注意的初始化行为: +anchor 与 handoff 的概念见[用 anchor 与 handoff 切换上下文起点](/zh-cn/docs/concepts/tape/#anchors)。在代码中使用时需注意初始锚点行为: -* 当调用 `agent.run()`、`agent.start()` 或 `agent.session()` 开启会话时,如果 Tape 中尚无 anchor,系统会自动写入一个名为 `session/start` 的初始 anchor。 -* 仅仅调用 `agent.tape(name)` 获取引用不会自动创建 anchor。如果一个手动初始化的空 Tape 没有任何 anchor,直接用默认的 `LAST_ANCHOR` 读取会抛出 `BubError [not_found]`(`No anchors found in tape`)。对于完全空白的 Tape,要么先执行一次 `run()`,要么显式调用 `handoff()`,或者在读取时使用 `TapeContext(anchor=None)`。 +- 调用 `agent.run()`、`agent.start()` 或 `agent.session()` 时,若 Tape 中还没有任何 anchor,会自动写入 `session/start` 初始锚点。 +- 仅调用 `agent.tape(name)` 不会自动写入锚点。对没有任何 anchor 的空 Tape 直接按默认 `LAST_ANCHOR` 调用 `read_messages()` 会抛出 `BubError [not_found]`(`No anchors found in tape`)。此时应先运行一次 `run()`、手动调用 `handoff()`,或用 `anchor=None` 读取。 ### 手动执行 handoff {#manual-handoff} -你可以在业务逻辑的关键节点(如订单确认、步骤切换)手动写入 anchor: +在业务阶段切换时手动写入新 anchor,将默认上下文起点前移: ```python tape = agent.tape("demo-user") @@ -228,56 +198,46 @@ await tape.handoff( name="order-reviewed", state={"summary": "订单 A123 已完成审核并通过。"}, ) - ``` -* `name`:后续可以通过 `TapeContext(anchor="order-reviewed")` 作为起点重新切入。 -* `state`:可以携带该阶段的结构化快照供应用层读取。 - -handoff 之后,默认的 `read_messages()` 只会加载该 anchor 之后的对话,但历史数据依然完好: +handoff 后,`tape.read_messages()` 默认只读取该 anchor 之后的新消息,而历史记录仍可通过 `anchors()` 和 `query()` 完整读取: ```python -# 获取所有历史 anchor 列表及其状态 anchors = await tape.anchors() - -# 依然可以查询到最原始、完整的历史条目 history = list(await tape.query().all()) - ``` -### 该怎么使用它们? {#when-to-use-anchors} +### 常见场景对照 {#when-to-use-anchors} -| 需求场景 | 推荐做法 | +| 场景 | 做法 | | --- | --- | -| 业务阶段推进(如:查完物流后进入售后) | 当前阶段结束时调用 `await tape.handoff(name="after-shipping")` | -| 希望从某个历史存档点恢复上下文 | 配置 `TapeContext(anchor="存档名称")` | -| 需要获取绝对完整的上帝视角历史 | 配置 `TapeContext(anchor=None)` | -| 应对超长上下文溢出 | Agent 在识别到上下文长度错误时会自动写入 `handoff(name="auto_handoff/context_overflow")` 并重试原提示词一次 | -| 按预算主动压缩 | 使用 [`bub-context-budget` 插件](/zh-cn/docs/integrations/reuse-app/#agent-loop-hooks),让模型在接近上限时调用 `tape.handoff` | +| 切换业务阶段(如查完物流进入售后) | 调用 `await tape.handoff(name="after-shipping")` | +| 从指定历史锚点恢复上下文 | 配置 `replace(default_tape_context(), anchor="锚点名")` | +| 读取完整历史消息 | 配置 `replace(default_tape_context(), anchor=None)` | +| 上下文超长溢出自动恢复 | 模型报长度错误时,Agent 会自动写入 `auto_handoff/context_overflow` 并重试一次 | +| 接近上下文上限时主动压缩 | 挂载 [`bub-context-budget` 插件](/zh-cn/docs/integrations/reuse-app/#agent-loop-hooks)并传入 `tape.handoff` 工具 | -## Sidecar:让并行记录留在主上下文之外 {#sidecars} +## Sidecar:隔离大体积附属数据 {#sidecars} -`TapeSidecar` 是挂在会话 Tape 旁边、由配套 Tape 承载的能力。通过 `Agent(sidecars=...)` 挂载后,它随主 Tape 一起分支、合并和重置,但它的条目不会进入主 Tape 的模型上下文。 +有时我们需要跟随当前会话一起保存一些体量较大的附属数据(比如上万行的命令输出或网页抓取结果),但又不希望它们直接占满主对话的模型上下文。Bub 为此提供了 `TapeSidecar`:通过 `Agent(sidecars=...)` 挂载在主会话 Tape 旁,它会**随主 Tape 一起创建分支、合并和重置**,但写入 Sidecar 的条目永远不会进入主对话的模型上下文。 -Bub 应用用 spill sidecar 保存大型工具结果:主对话只保留预览和读取句柄,模型再通过 `spill.read` 分块取回完整内容。阈值由 [`BUB_SPILL_THRESHOLD`](/zh-cn/docs/reference/settings/#spill-settings) 控制,行为说明见 [代码模式 与 spill](/zh-cn/docs/reference/tools/#code-and-spill)。 +例如,Bub 应用层的 `spill` 机制就是通过 Sidecar 实现的:当工具输出超过 [`BUB_SPILL_THRESHOLD`](/zh-cn/docs/reference/settings/#spill-settings) 时,完整文本会转存到 `spill` Sidecar,主对话仅保留预览和句柄,供模型通过 `spill.read` 分块读取(见[内置工具参考](/zh-cn/docs/reference/tools/#code-and-spill))。插件可通过 [`provide_tape_sidecar`](/zh-cn/docs/reference/hooks/#provide_tape_sidecar) 注册自定义 Sidecar。 -自定义 sidecar 需要在插件中实现 `provide_tape_sidecar`,协议见 [Hooks 参考](/zh-cn/docs/reference/hooks/#provide_tape_sidecar)。 +## 多模态媒体存储边界 {#media} -## 媒体有独立的存储边界 {#media} +Tape 定位于轻量文本与事件记录,而非多媒体文件存储: -模型请求可以包含图片、音频和视频,但 Tape 不是媒体文件存储。通过 Agent Run 写入记录时,Bub 会剔除提示词 `content` / `prompt` 中的非文本内容块,只保留文本,避免把内联媒体写进历史。因此,不要假定之后能从 Tape 取回用户上传的原始媒体。 +- **用户输入的媒体不会写入 Tape**:Agent 将用户提示词写入 Tape 时会剔除非文本块、仅保留纯文本,避免大体积 Base64 数据撑爆存储。如需重放或审计用户上传的媒体,请先在宿主程序中将文件存入对象存储或磁盘,再将引用路径写入文本或事件。 +- **工具返回的媒体可传给当前模型**:工具可使用 [`content_result()`](/zh-cn/docs/reference/python-api/#tools) 返回文本与图片、音频或视频(如内置的 `fs.read` 读取图片)。这类结果记录在 `tool_result` 中,并在生成上下文时由 `result_content()` 还原为多模态内容块。 -需要重放或审计媒体时,由宿主把媒体保存到对象存储或文件系统,再在文本中记录可解析的引用。 +## 结合临时 state 与持久化事件 {#state-and-metadata} -工具结果的媒体走另一条路径,不与入站提示词的剔除规则混为一谈:工具需要把媒体连同文本交回当前模型调用时,使用 [`content_result()`](/zh-cn/docs/reference/python-api/#tools),其结果作为工具结果记录,投影时由 `result_content()` 还原成图片、音频或视频。 - -## 调用数据与持久记忆 {#state-and-metadata} - -`state`、`metadata`、Tape 条目和 anchor `state` 的生命周期与用途,统一见[数据应该放在哪里](/zh-cn/docs/concepts/tape/#state)。这里只展示如何把临时数据与持久记录组合使用: +下面通过一个工具示例,看看如何把单次请求内的临时 `state`(如 `request_id`)与持久化的 Tape 业务事件结合起来: ```python from bub.core.tools import ToolContext, tool + @tool(context=True) async def add_order_note(note: str, *, context: ToolContext) -> str: """向当前会话追加一条订单备注。""" @@ -286,34 +246,34 @@ async def add_order_note(note: str, *, context: ToolContext) -> str: {"text": note, "request_id": context.state.get("request_id")}, ) return "备注已记录。" - ``` -普通业务事件写入 Tape 后不会自动成为模型输入。如果希望模型在后续调用中看到这些数据,需要用 TapeContext 以合适的方式选入它们。 +再次提醒:通过 `append_event()` 写入的自定义业务事件会持久保存在 Tape 中,但默认不会自动进入下一次模型调用的上下文;如果希望模型后续看到它们,请配合上面的[自定义消息选择器](#custom-selectors)使用。各类数据的生命周期对比见[数据存放位置](/zh-cn/docs/concepts/tape/#state)。 -## 调用结束时如何处理会话历史 {#forks-and-merges} +## 分支与合并策略(`merge_back`) {#forks-and-merges} -每次 `agent.run()` 都会在 Tape 分支上记录本次 Run 写入的新条目。当调用流关闭时,Bub 默认把已写入的记录合并回主 Tape,见如下时序图: +每次调用 `agent.run()` 时,Bub 并不会直接往主 Tape 上裸写数据,而是先从主 Tape 派生一个临时分支记录本次运行,等事件流关闭时再合并回主 Tape: ```mermaid sequenceDiagram - participant Host as 宿主 + participant Host as 宿主程序 participant Fork as 本次 Run 的 Tape 分支 participant Main as 主 Tape - Host->>Fork: 进入 agent.run(),开始记录 - Host->>Fork: 模型输出、工具输入输出和运行事件 - alt 正常消费完毕 + Host->>Fork: 进入 agent.run(),在分支上记录 + Host->>Fork: 写入模型输出、工具往返与事件 + alt 正常结束 Host->>Fork: 退出 async with,关闭流 else 异常、取消或提前退出 Host->>Fork: 关闭未完成的流 end - Fork->>Main: 默认合并已写入的记录 - + Fork->>Main: 默认将已写入分支的记录合并回主 Tape ``` -默认合并发生在流关闭时,不要求调用成功完成。这意味着网络异常、任务取消或提前退出后,已经写入分支的部分对话和运行记录仍可能保留在主 Tape 中。如果不想保留某次 Run 的记录,可以设置 `merge_back=False` 参数: +这里有一个非常关键的默认行为:**分支合并发生在流关闭的那一刻,而非任务完全成功时**。即使中途报错、取消或提前退出循环,此前已完成并写入分支的步骤默认仍会合并回主 Tape。 -```python +若希望某次运行不修改原有会话历史(如预览或试运行),可设置 `merge_back=False`: + +```python ins={5} async with agent.run( prompt, model=model, @@ -322,19 +282,16 @@ async with agent.run( ) as stream: async for event in stream: ... - ``` -这将丢弃本次调用的 Tape 分支记录,但不会撤销**已经执行的工具操作或其他外部副作用**。也可以自己管理作用域:`agent.session(name, merge_back=...)` 或 `tape.fork_tape(merge_back=...)`。 +也可通过 `agent.session(name, merge_back=...)` 或 `tape.fork_tape(merge_back=...)` 手动控制分支作用域。 :::caution -分支不是针对外部世界的事务。即使设置 `merge_back=False`,工具对文件的修改、已发送的请求和外部写入也不会回滚。 +Tape 分支仅管理会话记录,**不回滚外部系统副作用**。即使设置 `merge_back=False`,工具已修改的文件、发出的网络请求或数据库写入也不会撤销。 ::: -## 会话限制 {#concurrency} - -当两个不同的 Agent 同时使用同一个 Tape 名称时,会各自基于启动时可见的历史创建分支。Bub 不会替你决定这些请求应该排队、覆盖还是交错执行。所以对于同一会话 Tape 被使用时,如同一会话的后续请求如果依赖前一次结果,应由宿主按会话串行处理;如果涉及到并发或者跨 Worker 或实例调用,那么需要考虑会话锁的问题。 +## 同会话并发与加锁 {#concurrency} -`FileTapeStore` 不提供跨 worker 的会话锁;[FastAPI 示例](/zh-cn/docs/sdk/web-service/)演示了单进程内的锁。 +若两个并发请求同时对同一个 Tape 名称调用 `agent.run()`,它们会各自基于启动时的历史创建分支,并在结束时先后合并。`core.Agent` 不会自动对同会话请求排队。 -并发 Run 需要读取彼此已完成的结果时,由应用协调执行顺序。 +在 Web 服务中,若同一会话的请求需要按顺序执行,**宿主程序应按 `session_id` 加锁串行化**。`FileTapeStore` 仅包含单进程文件线程锁,不提供跨进程锁;单进程会话锁示例见 [FastAPI 综合案例](/zh-cn/docs/sdk/web-service/#concurrency)。 diff --git a/website/src/content/docs/zh-cn/docs/sdk/tools.mdx b/website/src/content/docs/zh-cn/docs/sdk/tools.mdx index c0edaeda..7f6dcd7a 100644 --- a/website/src/content/docs/zh-cn/docs/sdk/tools.mdx +++ b/website/src/content/docs/zh-cn/docs/sdk/tools.mdx @@ -1,17 +1,17 @@ --- title: 工具 -description: 为 Agent 添加查询和执行能力,并了解工具参数、结果、错误与运行上下文。 +description: 使用 Bub Python SDK 的 @tool 装饰器定义自定义工具,掌握 Pydantic 参数校验、ToolContext 注入、异步并发控制与代码模式。 --- -Agent 可以理解用户的请求,但要查询真实数据或执行操作,还需要有调用外部能力的途径。而工具(Tool)就是 Agent 的**手脚**:所有的处理逻辑都可以封装成工具,然后 Agent 再根据用户请求决定是否调用。 +大模型能听懂用户的需求,但要真正查数据或改状态,还得靠外部能力。工具(Tool)就是 Agent 的**「手脚」**:你可以把任何数据查询或业务操作写成普通的 Python 函数,交给 Agent 按需调用。 -本节将以一个查询订单的示例开始,逐步说明如何定义工具、模型怎样调用它,以及怎样处理参数、结果和运行时数据。 +本节从一个查询订单的例子出发,带你逐步了解如何定义工具、模型怎样调用它,以及如何处理参数校验、运行上下文与并发控制。 -## 自定义工具 {#add-a-tool} +## 定义自定义工具 {#add-a-tool} -假设我们已经有一个查询订单的 Python 函数。要想 Agent 能调用它,就必须用 Bub SDK 中的 `@tool` 装饰器将其标记,并在初始化 Agent 时传递: +假设我们已经写好了一个查询订单的 Python 函数。要让 Agent 能调用它,只需用 `@tool` 装饰器标记,并在创建 `Agent` 时传入 `tools`: -```python +```python "@tool" "tools=[get_order]" from bub.core import Agent from bub.core.tools import tool @@ -40,21 +40,21 @@ agent = Agent( ) ``` -`@tool` 装饰器会把带类型标注的 Python 函数转换为 Agent 可用的工具。工具函数负责实际业务逻辑,而模型则根据工具名、参数类型和说明来帮助它判断何时以及怎样调用。 +`@tool` 会根据函数的类型标注和 docstring 自动生成供模型阅读的工具描述与参数 Schema。 ## 工具调用流程 {#tool-call-flow} -模型并不会直接执行 Python 代码。而是它先提出工具调用请求,然后 Bub 再校验参数并执行对应函数,最后把结果交回模型: +模型不会直接执行 Python 代码,而是先发起工具调用请求,由 Bub 校验参数并运行函数,再将结果传回模型: ```mermaid flowchart LR - A[用户提出请求] --> B[模型决定调用工具] + A[用户提问] --> B[模型请求调用工具] B --> C[Bub 校验参数并执行函数] - C --> D[工具结果交回模型] - D --> E[模型继续处理并回答] + C --> D[结果传回模型] + D --> E[模型生成最终回答] ``` -所以当我们调用 `agent.run()` 方法时,可以从输出的结果中分别看到模型请求的工具和工具返回的结果: +在事件流中可以观察到完整的调用往返(1 次工具调用 + 1 次最终回答共经历 2 个 Step): ```python async with agent.run(prompt, model=model, tape="tools-demo") as stream: @@ -68,29 +68,23 @@ async with agent.run(prompt, model=model, tape="tools-demo") as stream: print(event.data["delta"], end="", flush=True) ``` -一次工具调用会经过两个步骤: - -1. 模型先请求 `get_order` 工具,Bub 执行函数并把结果交回模型; -2. 模型再根据这个结果生成回答。 - -但是否调用工具仍由模型决定。 +可以看到,一次工具调用会经历两个 Step:模型先请求 `get_order` 并收到工具结果,再结合结果生成最终回答。当然,究竟要不要调用工具,最终决定权仍在模型手里。 -## 工具说明与约束 {#tool-schema} +## 参数描述与 Pydantic 校验 {#tool-schema} -使用 `@tool` 装饰器标记的 Python 函数,其参数类型会被转换为 JSON Schema,而当中的 [docstring](https://peps.python.org/pep-0257/) 则转换为该工具的说明书。因此,参数名和描述都是工具接口的一部分,我们在封装时应确保函数签名和描述的准确性,以确保模型能正确调用。 +用 `@tool` 装饰函数时,参数类型会被转为 JSON Schema,而 [docstring](https://peps.python.org/pep-0257/) 就是给模型看的使用说明书。因此,参数名、类型标注和 docstring 都是工具接口的一部分,写清楚能让模型更准确地传参: ```python @tool def get_order(order_id: str) -> dict[str, str | float]: - """按订单号查询订单。order_id 是用户提供的完整编号,例如 A123。""" + """按订单号查询订单。order_id 是完整订单编号,例如 A123。""" ... ``` -如果输入参数较多或需要如范围、长度等约束时,可以借 [Pydantic](https://pydantic.dev/) 这样的第三方校验库帮助我们,之后将其作为 `@tool` 装饰器的 `model` 参数传入: +当参数较多或需要限制数值范围、字符串长度时,可定义 [Pydantic](https://pydantic.dev/) 模型并传给 `@tool(model=...)`: ```python from pydantic import BaseModel, Field - from bub.core.tools import tool @@ -102,7 +96,7 @@ class RefundInput(BaseModel): @tool(name="refund_order", model=RefundInput) def refund_order(param: RefundInput) -> dict[str, str | float]: - """为已支付订单申请退款;执行前必须完成权限检查。""" + """为已支付订单申请退款。""" return { "order_id": param.order_id, "amount": param.amount, @@ -110,24 +104,20 @@ def refund_order(param: RefundInput) -> dict[str, str | float]: } ``` -在执行中,如因参数类型不匹配或 Pydantic 校验失败时,Bub 会把错误作为工具错误结果交回模型。模型可以据此修正参数后重试(但不保证重试一定成功)。 - -注意,在编写实际的业务逻辑函数时,应区分业务结果和执行错误: +编写实际业务工具时,建议把**「预期的业务结果」**和**「程序执行错误」**区分开——返回结构化字典(如 `{"error": "order_not_found"}`)而非直接抛异常,能让模型和调用方清晰识别已知的业务状态: -| 情况 | 默认行为 | +| 情况 | Bub 的处理行为 | | --- | --- | -| 参数不符合类型或 Pydantic 约束 | 转为参数校验工具错误,交回模型 | -| 工具抛出普通异常 | 转为工具错误,交回模型 | -| 工具返回业务错误对象,例如 `order_not_found` | 作为正常工具结果交回模型 | -| 存储、模型或事件处理器中断调用 | 异常可能从事件迭代抛出,在集成部分处理 | +| 参数类型不匹配或 Pydantic 校验失败 | 包装为工具错误传回模型,模型可修正参数后重试 | +| 工具函数抛出普通异常 | 包装为工具错误传回模型 | +| 工具返回结构化业务状态(如 `{"error": "order_not_found"}`) | 作为正常工具结果传回模型(推荐用于预期的业务错误) | +| 存储、模型连接或事件处理器抛出异常 | 从事件流迭代处直接向上抛出,由宿主代码捕获 | -业务错误对象不是 Python 异常,以稳定的结构化结果返回,可以让模型和调用方识别“订单不存在”这类业务状态。 +## 注入运行上下文(ToolContext) {#tool-context} -## 在工具中传入上下文 {#tool-context} +有时工具内部不只是处理入参,还需要访问当前会话的 Tape、请求级 `state` 或事件总线。这时可以设置 `@tool(context=True)`,让 Bub 自动注入 `ToolContext`: -出于某种需要,有时我们还需要在工具中获取到当前会话、请求级权限或事件总线等信息。可以通过 Bub 注入的 `ToolContext` 对象来获取: - -```python +```python "context=True" "context: ToolContext" from bub.core.tools import ToolContext, tool @@ -141,7 +131,7 @@ async def add_order_note(note: str, *, context: ToolContext) -> str: return f"备注已写入会话 {context.tape.name}" ``` -于是在调用过程中传入 `state` 参数,工具就能读取到 `context.state` 的数据: +调用 `agent.run()` 时传入 `state`,即可在工具内通过 `context.state` 读取: ```python async with agent.run( @@ -154,19 +144,23 @@ async with agent.run( ``` :::tip -`context` 参数由 Bub 注入,不会出现在模型可见的参数 Schema 中。而 `context.state` 只在当前调用内共享,不会自动持久化或恢复。 +`context` 参数由 Bub 自动注入,不会暴露在发给模型的参数 Schema 中。`context.state` 仅在单次调用内有效,不会自动持久化。 ::: -## 异步和批量调用 {#concurrency} +## 异步函数与并发限制 {#concurrency} -`@tool` 装饰器不仅适用于普通函数,还适用于异步函数,通常来说对于可能会阻塞程序运行的逻辑我们都应尽可能将其作为异步函数调用,必要时放到单独的线程中执行: +`@tool` 同时支持同步函数和 `async def` 异步函数。含阻塞 I/O 的逻辑应使用异步函数,或用 `asyncio.to_thread()` 放入线程执行: ```python -import time import asyncio +import time +from bub.core.tools import tool -def build_report_blocking(order_id: str) -> None: + +def build_report_blocking(order_id: str) -> str: time.sleep(3) + return f"https://example.com/reports/{order_id}.pdf" + @tool async def export_order_report(order_id: str) -> str: @@ -174,45 +168,21 @@ async def export_order_report(order_id: str) -> str: return await asyncio.to_thread(build_report_blocking, order_id) ``` -需要说明的是,模型可能在一次响应中可能请求多个工具。所以避免达到系统自身的资源瓶颈,Bub 允许我们传入 `max_tool_concurrency` 参数来限制: +模型在一次响应中可能会同时请求多个工具。为了避免并发过高拖垮下游或触及资源上限,可以通过 `max_tool_concurrency` 限制单步内的最大并发执行数: ```python -from bub.core import Agent -from bub.core.tools import tool - - -ORDERS = { - "A123": { - "order_id": "A123", - "status": "shipped", - "item": "机械键盘", - "amount": 399.0, - } -} - - -@tool -def get_order(order_id: str) -> dict[str, str | float]: - """按订单号查询订单状态、商品和金额。""" - if order := ORDERS.get(order_id): - return order - return {"order_id": order_id, "error": "order_not_found"} - - agent = Agent( tools=[get_order], - system_prompt="用户询问订单时,使用工具查询,不要猜测订单状态。", + system_prompt="用户询问订单时,使用工具查询。", max_tool_concurrency=2, ) - ``` -另外,传给 `Agent(tools=[...])` 的还可以是其他库的工具,比如 `republic.tools.WebSearch()`。但它们将由模型提供商执行,不经过本地 `ToolExecutor`,也不受 `max_tool_concurrency` 的本地并发限制。 - +此外,`Agent(tools=[...])` 也支持传入提供商侧执行的工具(如 `republic.tools.WebSearch()`)。这类工具由模型提供商远端执行,不经过本地执行器,也不受 `max_tool_concurrency` 限制。 -## 直接调用工具 {#call-a-tool-without-a-model} +## 跳过模型直接调用工具 {#call-a-tool-without-a-model} -如果你有自己的想法,明确大概要调什么命令,可以给 Agent 设置 `command_prefix` 命令前缀。命令仍使用同一份工具实现和参数校验,但不调用模型: +如果你已经明确知道要执行哪个工具、不需要走模型推理(也不想消耗模型 Token),可以给 Agent 设置 `command_prefix`。以该前缀开头的输入会跳过模型,直接校验参数并调用同名工具: ```python agent = Agent(tools=[get_order], command_prefix=",") @@ -223,13 +193,14 @@ async with agent.run(",get_order A123", model=model, tape="tools-demo") as strea print(event.data["delta"], end="") ``` -这和普通函数调用的区别在于,直接命令会产生 Bub 定义事件,以便你现有 Agent 流程逻辑可以统一处理。但调用发生错误时,不会像模型工具错误那样交回模型修正。 +直接命令同样通过 `agent.run()` 产出事件流并触发工具事件;但若执行报错,异常会直接抛给调用方,不会交回模型重试。 ## 代码模式 {#compose-tools-with-codemode} -当工具较多或任务需要条件逻辑时,可以让模型通过 `run_code` 工具来编写 Python 代码,以满足更灵活的处理需要或在一次执行中组合多个工具: +当工具数量较多或任务包含循环、条件分支时,可使用 `CodeMode` 让模型通过 `run_code` 工具直接编写 Python 代码组合调用多个工具: ```python +from bub.core import Agent from bub.core.codemode import CodeMode code_mode = CodeMode([get_order]) @@ -237,21 +208,19 @@ code_mode = CodeMode([get_order]) agent = Agent( tools=[code_mode.run_code], system_prompt=[ - "使用可用工具完成任务;可以编写 Python 调用 tools.*。", + "使用可用工具完成任务;可编写 Python 调用 tools.*。", code_mode.prompt, ], ) ``` -模型将生成如下类似可以调用的 Python 代码并执行: +模型在 `run_code` 中生成的 Python 代码示例: ```python order = await tools.get_order(order_id="A123") print(order) ``` -## 安全环境与执行环境 {#choose-an-execution-environment} - -默认情况下,由 Agent 使用的所有工具或代码将在运行 Python 进程的宿主机上被执行,但这并不是独立且安全的沙箱。必要时应进行隔离,并配置具备文件系统、网络和权限等限制。 +## 自定义执行环境 {#choose-an-execution-environment} -Bub 允许你通过自定义 `Environment` 来使用远程或隔离环境作为执行容器。完整协议见 [Environment](/zh-cn/docs/reference/python-api#environment)。 +默认情况下,工具和代码模式直接在运行 Python 进程的宿主机上执行(无安全沙箱)。如需隔离文件系统、网络和进程权限,可实现自定义的 [`Environment`](/zh-cn/docs/reference/python-api/#environment)。 diff --git a/website/src/content/docs/zh-cn/docs/sdk/web-service.mdx b/website/src/content/docs/zh-cn/docs/sdk/web-service.mdx index a52b5b00..49dd6f77 100644 --- a/website/src/content/docs/zh-cn/docs/sdk/web-service.mdx +++ b/website/src/content/docs/zh-cn/docs/sdk/web-service.mdx @@ -1,45 +1,42 @@ --- title: 将 Bub Agent 与 FastAPI 集成 -description: 基于 Bub SDK 构建一个 Todo Agent,并与 FastAPI 集成。 +description: 实战教程:使用 Bub Python SDK 与 FastAPI 构建带工具调用、人工二次确认(Approval)与 SSE 流式输出的 Todo Agent 服务。 sidebar: label: 综合案例 --- -import { FileTree, Steps } from '@astrojs/starlight/components'; +import { Code, FileTree, Steps } from '@astrojs/starlight/components'; +import fullMainPy from '../../../../../../public/examples/bub-todo-agent/main.py?raw'; -经过前面对于 Bub SDK 使用的基本了解后,本节不再引入新概念,而是通过一个综合示例来将所有概念串联起来,最终构建出一个完整的 Agent Demo 应用。 +前面几节我们已经了解了 Bub SDK 的核心组件。本节不再引入新概念,而是把 `Agent`、工具、事件拦截和 Tape 存储串起来,基于 FastAPI 亲手搭一个带 SSE 流式输出和删除二次确认的 Todo Agent 应用。 :::tip[看不懂就问] -本节内容仅对后端逻辑进行展开,前端界面交互部分则不涉及。如遇到不理解的概念、代码或报错,可以直接问 Bub,或让正在使用的 Agent 工具结合本教程和当前代码为你讲解。 +本节只聚焦后端逻辑,前端界面代码不在正文中展开。如果遇到不理解的概念、代码或报错,可以直接问 Bub,或者让你手头的 AI 编程工具结合本文和源码为你解答。 ::: -完整示例代码在 [bub-todo-agent](https://github.com/bubbuild/bub/blob/main/website/public/examples/bub-todo-agent/) 中,你可以下载后自行修改或者跟着教程构建。最终核心文件目录如结构所示: +完整源码位于 [bub-todo-agent](https://github.com/bubbuild/bub/blob/main/website/public/examples/bub-todo-agent/),你可以直接下载试跑,或者跟着下面的步骤一步步搭起来: - bub-todo-agent/ - - main.py # 本文重点 - - index.html # 演示界面,不在本文展开 + - **main.py** # 后端服务代码(本节重点) + - index.html # 前端演示页面 - static/ - uno.global.js - alpine.min.js - - sessions/ # 运行后自动生成 + - sessions/ # 运行时自动生成的 Tape 存储目录 - :::caution -本项目仅用于演示教学,不具备生产能力,请勿将其暴露在任何公网。 +本示例仅用于教学演示,未包含生产级鉴权与持久化数据库,请勿直接暴露在公网。 ::: -## 1. 配置 Agent 并启动 FastAPI 服务 {#lifespan} - -首先,我们把应用骨架搭起来:完成 Bub Agent 相关配置,并在 FastAPI 启动时创建 Agent。所以主要有以下事项: +## 1. 初始化 Agent 与 FastAPI Lifespan {#lifespan} -1. 导入相关依赖,并将配置信息读取作为变量保存; -2. 自定义 FastAPI [生命周期](https://fastapi.tiangolo.com/advanced/events/#lifespan)(lifespan)逻辑,在启动时完成 Bub Agent 配置。 +首先,我们把应用骨架搭起来:在 FastAPI 的 [lifespan](https://fastapi.tiangolo.com/advanced/events/#lifespan) 中初始化模型连接与 `Agent` 实例,并挂载到 `app.state` 上供所有请求复用: -```python title="main.py" +```python title="main.py" showLineNumbers collapse={1-33} {50-58} #!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.12" @@ -79,13 +76,11 @@ BASE_DIR = Path(__file__).resolve().parent load_dotenv() -# ===== 通过环境变量或 .env 覆盖,也可以直接修改这里的默认值 ===== MODEL = os.getenv("BUB_MODEL", "openai:gpt-4o-mini") BASE_URL = os.getenv("BUB_API_BASE", "https://api.openai.com/v1") API_KEY = os.getenv("BUB_API_KEY") or os.getenv("REPUBLIC_OPENAI_API_KEY") HOST = os.getenv("BUB_HOST", "127.0.0.1") PORT = int(os.getenv("BUB_PORT", "8000")) -# ========================================================== @asynccontextmanager @@ -104,7 +99,7 @@ async def lifespan(app: FastAPI): app.state.model = model app.state.agent = agent app.state.session_locks = defaultdict(asyncio.Lock) - # request_id -> future;删除钩子在这里等待答案,由 POST /chat/confirm 唤醒。 + # request_id -> future;删除钩子在此等待用户确认,由 POST /chat/confirm 唤醒 app.state.pending_confirms = {} yield @@ -112,28 +107,19 @@ async def lifespan(app: FastAPI): app = FastAPI(title="Bub Todo Agent", lifespan=lifespan) ``` -注意: +- 将 `Agent` 挂载在 `app.state` 上全局复用,避免每次请求重复初始化; +- `max_steps=6` 限制单次 Run 的最大步数; +- `FileTapeStore` 将会话历史持久化到本地 `sessions/` 目录。 -- 为了避免重复创建 Agent 以及全局使用,这里我们将创建好的 Agent 实例以及多个属性挂载到 FastAPI 的状态对象 `app.state` 上 -- 创建 Bub Agent 时使用 `max_steps` 控制运行一次模型的最大执行步骤数,避免模型陷入死循环 -- 配置 `store` 参数让 Agent 使用 Tape 的能力以确保具备记忆能力可以连续对话 +到这一步还只是一个最基础的骨架——模型目前只能纯聊天,还干不了实事。接下来,我们给它装上真正能操作待办事项的工具。 -但目前这只是一个非常基本的配置,模型只能回答,因此我们接下来为它赋予额外的处理任务能力。 +## 2. 定义业务工具 {#tools} -## 2. 用工具承载业务能力 {#tools} - -Agent 就位之后,接下来让它真正能做事——即我们所有涉及到 Todo 任务的操作以 Python 函数表示并封装成工具,之后交给 Agent 调用。因此我们将有以下事项: - -- 用 Python 的字典对象来存储任务数据 -- 提供常见的增删改查方法来让 Agent 与这个字典对象交互,即查看任务、新增任务、完成任务以及删除任务。 +Agent 就位之后,接下来让它真正能干活——把待办事项的查询、新增、完成和删除操作写成普通 Python 函数,再用 `@tool` 封装成工具交给 Agent: ```python title="main.py" -# ... - from itertools import count - from pydantic import BaseModel, Field - from bub.core.tools import tool TASKS: dict[str, dict[str, object]] = {} @@ -176,23 +162,17 @@ def delete_task(task_id: str) -> dict[str, object]: return {"task_id": task_id, "error": "task_not_found"} ``` -以上代码都是较为基础的 Python 逻辑,这里就不展开,简单来说就是: - -- Python 函数的 docstring 和类型标注会作为工具 schema 使用,后续 Agent 在调用前会阅读后以决定是否调用工具来触发逻辑。 -- 返回值必须能 JSON 序列化;业务失败返回 `{"error": ...}`,不要动辄抛异常中断整个流程。 -- `delete_task` 是不可逆操作,后续我们将会添加拦截事件以便新增二次确认逻辑。 +上面这几个函数都是很基础的 Python 逻辑,这里就不逐行展开了,只需记住三点: -现在让我们修改 Agent 配置: +- 函数的 docstring 和类型标注会自动生成工具 Schema,模型全靠它们决定何时调用以及怎么传参; +- 返回值必须可 JSON 序列化,业务失败(如任务不存在)直接返回 `{"error": ...}`,不要动辄抛异常中断整个流程; +- `delete_task` 是不可逆操作,稍后我们会通过事件处理器给它加上二次确认。 -```python title="main.py" - -# Code snippet.. +现在把这组工具传给 `Agent`,并设置 `max_tool_concurrency=2`: +```python title="main.py" ins={6,13} @asynccontextmanager async def lifespan(app: FastAPI): - - # ... - async with republic.get_model(MODEL, api_base=BASE_URL, api_key=API_KEY) as model: agent = Agent( store=FileTapeStore(BASE_DIR / "sessions"), @@ -207,13 +187,9 @@ async def lifespan(app: FastAPI): ) ``` -这里我们把所有任务作为 `tools` 参数传递,然后设置 `max_tool_concurrency` 限制一次工具调用的最大数量上限。 - -## 3. 包装调用 Agent 操作 {#tape} - -装配了工具的 Bub Agent 有了「手脚」,现在已经具备可以交互的能力了。 +## 3. 封装 Agent 调用参数 {#tape} -在调用前我们可能需要做一些简单的参数处理或封装,真正调用 Agent 时参数是正确的,所以我们这里的逻辑很简单: +装上工具之后,我们的 Agent 就有了「手脚」。在接入 HTTP 路由前,先写一个轻量的包装函数 `run_agent`,把请求参数 `ChatRequest`、会话 `session_id` 和删除确认回调 `confirm_delete` 传给 `agent.run()`: ```python ConfirmDelete = Callable[[dict[str, object]], Awaitable[bool]] @@ -236,38 +212,17 @@ def run_agent(agent: Agent, model, req: ChatRequest, confirm_delete: ConfirmDele ) ``` -注意: - -- `tape=req.session_id` 让同一会话共享历史;换一个 `session_id` 则是开启新会话。 -- `state` 属于临时状态的数据存储,为后续事件 hook 共用 - -## 4. 注册事件 hooks {#events} - -由于 Bub 提供了多种 Hook 入口,因此我们可以利用 Hook 来自定义某些阶段的业务流程,比如输出工具调用日志或拦截没有确认的删除指令等。 - -核心业务逻辑如下: - -1. 当收到 `ToolCallFinished` 事件时,则记录工具名、状态和耗时。 -2. 当收到 `ToolCallStarted` 事件时先截 `delete_task` 操作。 -3. 从 `state` 取出确认回调;没有就拒绝。 -4. 用户拒绝时设置 `deny`,并告诉模型替代方案。 - -所以在 Agent 创建后,我们再在 FastAPI 的 `lifespan` 中新增如下逻辑: - -```python title="main.py" -# ... - -from bub.core.events import ToolCallDecision, ToolCallFinished, ToolCallStarted - - -@asynccontextmanager -async def lifespan(app: FastAPI): - async with republic.get_model(MODEL, api_base=BASE_URL, api_key=API_KEY) as model: +- `tape=req.session_id` 让同一 `session_id` 的请求共享多轮对话历史(通过正则限制字符范围,确保作为文件名安全); +- `state` 将当前请求的确认回调传递给接下来的事件处理器。 +## 4. 注册事件处理器(日志与删除审批) {#events} - # ... +有了工具之后,我们还可以利用事件总线在关键节点「插一手」——比如记录工具调用日志,或者在执行删除前拦下来等用户点头。在 `lifespan` 中注册两个事件处理器: +1. `ToolCallFinished`:记录每次工具调用的名称、状态和耗时; +2. `ToolCallStarted`:在执行 `delete_task` 前暂停并等待前端用户确认;若用户拒绝或超时,通过 `ToolCallDecision.deny(...)` 拦截删除。 +```python title="main.py" "@agent.events.on(ToolCallFinished)" "@agent.events.on(ToolCallStarted)" "ToolCallDecision.deny" @agent.events.on(ToolCallFinished) def audit_tool(event: ToolCallFinished) -> None: logger.info( @@ -277,11 +232,8 @@ async def lifespan(app: FastAPI): event.result.duration_ms, ) - @agent.events.on(ToolCallStarted) async def authorize_tool(event: ToolCallStarted) -> None: - # 异步处理器会被等待,因此这里可以暂停 Run,直到用户在界面上作答。 - # 没人作答时默认拒绝,是更安全的失败方式。 if event.call.tool != "delete_task": return confirm: ConfirmDelete | None = event.state.get("confirm_delete") @@ -292,33 +244,19 @@ async def lifespan(app: FastAPI): ) ``` -注意: - -- 异步处理器会暂停当前 Agent 调用流程,直到用户回答。 -- `deny` 操作只跳过这次工具调用,不会终止整个流程;模型会收到拒绝原因并调整回答。 +由于 `EventBus` 会同步 `await` 异步处理器,当前 Run 会在 `await confirm(...)` 处暂停,直到用户在前端点击确认或取消。同时注意,`deny` 只会跳过这一次工具调用,不会终止整次 Run;模型会收到拒绝原因并顺势调整回复。 -## 5. 会话锁与确认操作 {#concurrency} +## 5. 会话锁与确认接口 {#concurrency} -上一节中提到会在删除任务前暂停流程,但要让「暂停」真正成立,还缺两样东西: - -1. 同一会话的请求需要排队,避免等待处理期间又有请求进来导致 Tape 会话被占用 -2. 用户对删除的回答也要送回那个暂停中 Hook 逻辑 - -因此我们可能需要「锁」,确保同一个 Tape 存储记录只能有一次请求持有,这两项状态都在 `lifespan` 中初始化: +上一节我们在删除前暂停了事件处理器,但要让「暂停等待确认」在并发 Web 服务中可靠跑起来,还需要解决两件事:同一会话的请求得排队,以及前端的确认结果得准确送回那个等待中的处理器。为此,我们在 `lifespan` 中维护了两个字典: ```python app.state.session_locks = defaultdict(asyncio.Lock) -# request_id -> future;删除钩子在这里等待答案,由 POST /chat/confirm 唤醒。 app.state.pending_confirms = {} ``` -后续在请求入口中我们按 `session_id` 取锁,让同一会话的请求就会依次执行即可: - -```python -lock: asyncio.Lock = state.session_locks[req.session_id] -``` - -对于确认的交互,我们使用一个单独的接口逻辑处理: +- `session_locks`:按 `session_id` 加锁,确保同一会话不会并发读写同一个 Tape; +- `pending_confirms`:保存 `request_id -> asyncio.Future`,当用户在前端点击确认按钮并调用 `POST /chat/confirm` 时,唤醒正在等待的事件处理器: ```python class Confirmation(BaseModel): @@ -335,20 +273,13 @@ async def confirm_tool_call(req: Confirmation, request: Request): return {"approved": req.approved} ``` -现在让我们来做最后一步构建。 +好,基础设施全部就位,现在来做最后一块拼图。 -## 6. 构建 API 接口并使用 SSE 传输 {#sse} +## 6. 通过 SSE 流式推送响应 {#sse} -锁和确认操作就位后,就可以把它们也一同接入与 Agent 的对话中来: +锁和确认接口就位后,最后把它们串进 `/chat/stream` 接口:后台任务驱动 Agent 运行,并通过 `asyncio.Queue` 将文本增量、工具调用、确认请求和完成信号统一作为 [SSE](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/)(Server-Sent Events)帧推给前端: -1. 前端通过向 `/chat/stream` 路径进行 HTTP 请求 -2. 接收请求后由 FastAPI 调用对应接口逻辑,即使用 Agent 生成内容 -3. Agent 生成的输出内容被 FastAPI 用 [SSE](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/) 协议序列化成对应事件后返回给前端 -4. 前端根据事件类型处理和展示 - -这里直接给出完整代码: - -```python title="main.py" +```python title="main.py" collapse={1-8} import asyncio from collections.abc import AsyncIterable from contextlib import suppress @@ -362,8 +293,6 @@ from fastapi.sse import EventSourceResponse, ServerSentEvent async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[ServerSentEvent]: state = request.app.state lock: asyncio.Lock = state.session_locks[req.session_id] - # Run 放在后台任务里推进,这样钩子也能往队列里推帧; - # 钩子运行在 Agent 事件流内部,响应生成器此时无法直接 yield。 queue: asyncio.Queue[ServerSentEvent | None] = asyncio.Queue() async def confirm_delete(arguments: dict[str, object]) -> bool: @@ -382,7 +311,7 @@ async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[Serve ) ) try: - # 失败即关闭:两分钟内没有回答,或客户端断开,都不执行删除。 + # 120 秒超时或客户端断开时默认拒绝删除 return await asyncio.wait_for(future, timeout=120) except TimeoutError: return False @@ -401,7 +330,7 @@ async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[Serve names = [call["name"] for call in event.data["tool_calls"]] queue.put_nowait(ServerSentEvent(data={"names": names}, event="tool")) - # 整个 Run 结束后才发送 done;final 只代表一个 Step 结束。 + # 整个 Run 结束后发送 done(final 事件仅代表单个 Step 结束) queue.put_nowait( ServerSentEvent(data={"last_step_usage": stream.usage}, event="done") ) @@ -423,16 +352,26 @@ async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[Serve await task ``` -## 完整回顾与一次交互 {#wiring} +你也可以直接在下方查看完整的 `bub-todo-agent/main.py` 源码(辅助函数与常规路由已默认折叠,点击即可展开): -我们快速回顾一下本章内容,在本 Demo 中一次完整的交互路径示意如下: + + +## 交互时序总览 {#wiring} + +我们快速回顾一下本章内容,整个 Demo 中一次完整的交互路径如下: ```mermaid sequenceDiagram participant C as 客户端 participant S as /chat/stream participant A as Agent - participant H as 事件钩子 + participant H as 事件处理器 participant K as /chat/confirm C->>S: POST {session_id, prompt} @@ -442,62 +381,59 @@ sequenceDiagram A-->>S: text / tool_call 事件 S-->>C: SSE message / tool 帧 - opt delete_task 需要确认 + opt delete_task 触发二次确认 A->>H: ToolCallStarted H->>S: 请求用户确认 S-->>C: SSE confirm 帧(request_id) C->>K: POST {request_id, approved} - K->>H: 返回确认结果 - H-->>A: 放行或拒绝 + K->>H: 唤醒 Future 返回结果 + H-->>A: 放行或 deny end A-->>S: 事件流结束 S-->>C: SSE done 帧 ``` -总的来说,整个 Demo 可以分为三部分: +总的来说,这个应用可以清晰地分成三部分: -- **配置与集成**:配置 Bub Agent,并与 FastAPI 集成在一起; -- **基于工具与事件机制自定义逻辑**:将实际的交互逻辑封装成可供 Agent 调用的工具,并对工具调用时的一些事件阶段流程进行自定义; -- **通过 HTTP 接口交互**:对外交互的入口为 HTTP 接口,在接口内组合多个部分、逻辑最终完成交互流程。 +- **配置与集成**:在 FastAPI `lifespan` 中初始化 Bub Agent 与 Tape 存储; +- **工具与事件定制**:把待办操作封装成工具,再通过事件处理器加上审计日志与删除二次确认; +- **HTTP 与流式交互**:用会话锁、确认接口和 SSE 流把所有环节串成完整的前后端闭环。 -## 运行与体验 {#run} +## 运行示例 {#run} -到这里,我们完整的 Demo 示例就算完成了。现在你可以直接通过 [bub-todo-agent](https://github.com/bubbuild/bub/blob/main/website/public/examples/bub-todo-agent/) 来运行整个服务然后在前端界面进行体验: +到这里,我们的完整 Demo 就算大功告成了!现在你可以直接下载 [bub-todo-agent](https://github.com/bubbuild/bub/blob/main/website/public/examples/bub-todo-agent/) 在本地启动,打开浏览器体验一下: -1. 将 `.env.example` 重命名为 `.env`,并填写模型相关参数或端口: - - ```bash title=".env" - BUB_MODEL=openai:gpt-4o-mini - BUB_API_BASE=https://api.openai.com/v1 +1. 将 `.env.example` 复制为 `.env` 并填入模型配置: - BUB_API_KEY=sk-... + ```bash title=".env" + BUB_MODEL=openai:gpt-4o-mini + BUB_API_BASE=https://api.openai.com/v1 + BUB_API_KEY=sk-... + BUB_HOST=127.0.0.1 + BUB_PORT=8000 + ``` - BUB_HOST=127.0.0.1 - BUB_PORT=8000 - ``` +2. 使用 `uv` 启动服务: -2. 使用 uv 运行 `main.py`: + ```shell + uv run main.py + ``` - ```shell - uv run main.py - ``` +3. 在浏览器中访问 `http://127.0.0.1:8000`: -3. 看到日志有输出时点击或复制 URL 地址通过浏览器进入页面即可: + ```text + $ uv run main.py + INFO: Started server process [85377] + INFO: Waiting for application startup. + INFO: Application startup complete. + INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) + ``` - ``` - $ uv run main.py - INFO: Started server process [85377] - INFO: Waiting for application startup. - INFO: Application startup complete. - INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) - ``` - - ![Bub Todo Agent Screenshot](/docs/sdk/bub-todo-agent-screenshot.png) + ![Bub Todo Agent Screenshot](/docs/sdk/bub-todo-agent-screenshot.png) - 祝你玩得愉快!