Compare commits

...
Author SHA1 Message Date
Xubin Ren aead911004 feat(whatsapp): add neonize activity cues and mentions 2026-06-27 11:46:25 +08:00
axelray-devandXubin Ren 2bf111f456 fix(exec): remove ad-hoc shell comment stripping from _guard_command
- Removes match_text regex that stripped # comments before pattern matching
(broke on quoted # inside strings)
- allow_patterns now run re.fullmatch against the full lowercased command
- deny_patterns search the original lowercased command
- Replaces comment-stripping test with comment-tail bypass regression
(touch canary # echo allowlisted must be blocked)
- Adds Re-bin regression for quoted hash + blocked command
(echo "#" followed by blocked command must be caught)
- All 10 tests pass

Signed-off-by: axelray-dev <110029405+axelray-dev@users.noreply.github.com>
2026-06-27 11:11:46 +08:00
axelray-devandXubin Ren aa6c1bf300 fix(exec): prevent allowPatterns bypass via chained commands and shell comments 2026-06-27 11:11:46 +08:00
chengyongruandXubin Ren 5281e67222 fix(docker): repair whatsapp image build 2026-06-27 11:05:03 +08:00
chengyongruandXubin Ren dbb53109f4 build(docker): remove node from runtime image 2026-06-27 11:05:03 +08:00
chengyongruandXubin Ren b015515f30 docs(security): remove whatsapp bridge wording 2026-06-27 11:05:03 +08:00
chengyongruandXubin Ren be88e14424 docs(security): trim whatsapp migration note 2026-06-27 11:05:03 +08:00
chengyongruandXubin Ren 9e490ef473 docs(readme): restore changelog wording 2026-06-27 11:05:03 +08:00
chengyongruandXubin Ren bfb4246659 fix(docker): limit whatsapp bridge removal 2026-06-27 11:05:03 +08:00
chengyongruandXubin Ren fbf96a3502 fix(whatsapp): add bridge migration compatibility 2026-06-27 11:05:03 +08:00
chengyongruandXubin Ren 2a9e288dfe refactor(whatsapp): replace bridge with neonize 2026-06-27 11:05:03 +08:00
chengyongruandXubin Ren 3460ca3cb9 fix(agent): gate microcompaction on context pressure
Extract model-facing context governance from AgentRunner.

Only compact in-flight tool results when the model request is over budget, keep compacted IDs stable within a turn, and allow the newest result to be compacted as a last resort when it is the remaining source of overflow.
2026-06-27 11:04:41 +08:00
chengyongruandXubin Ren 9b45fc1172 fix(session): remove message time replay prefixes 2026-06-27 11:04:36 +08:00
chengyongruandXubin Ren 8656549129 test: cover exec login default public path
maintainer edit: add a regression test for the public ExecTool.execute path so omitted login stays non-login by default, and update the Unix environment docstring to match the new explicit login behavior.
2026-06-27 11:04:31 +08:00
axelray-devandXubin Ren 4c1f127549 test: update login-shell assertion for new default=False 2026-06-27 11:04:31 +08:00
axelray-devandXubin Ren 13c951aa41 fix: change exec login-shell default from true to false (#4518)
The exec tool defaults login=True for bash/zsh, which causes the shell
to source ~/.bash_profile and similar startup files. This reintroduces
secrets from shell startup files into the exec environment, even though
_build_env() intentionally starts with a curated environment.

Change the default to login=False in both _prepare_command() and _spawn(),
and update the schema default accordingly.
2026-06-27 11:04:31 +08:00
chengyongruandXubin Ren cd1fb61eb5 ci: relax webui install lock check 2026-06-27 11:04:11 +08:00
chengyongruandXubin Ren e79cb816e3 ci: pin bun for webui job 2026-06-27 11:04:11 +08:00
chengyongruandXubin Ren 64901be67f test: harden webui and gateway checks 2026-06-27 11:04:11 +08:00
chengyongruandXubin Ren 9ce9d2235a docs: clarify heartbeat versus cron delivery 2026-06-27 11:04:08 +08:00
Xubin Ren 06d5495b60 docs: document subagent tool error behavior 2026-06-25 22:53:36 +08:00
axelray-devandXubin Ren 851a0ff50c fix: make subagent fail_on_tool_error configurable (#4198)
Add fail_on_tool_error to AgentDefaults and wire it through
AgentLoop -> SubagentManager -> AgentRunSpec.

Previously hardcoded to True in SubagentManager._run_subagent.
Now configurable via config.json with default True for backward
compatibility. When set to False, subagents can retry on minor
tool errors instead of immediately failing.

Changes:
- nanobot/config/schema.py: add fail_on_tool_error field (default True)
- nanobot/agent/subagent.py: accept and forward fail_on_tool_error
- nanobot/agent/loop.py: pass config through to SubagentManager
- tests/agent/test_subagent.py: add regression test

Signed-off-by: axelray-dev <110029405+axelray-dev@users.noreply.github.com>
2026-06-25 22:53:36 +08:00
Xubin Ren 3596ccf828 docs: explain custom provider thinking style 2026-06-25 22:53:15 +08:00
axelray-devandXubin Ren d1ae73a8a8 fix: add clear error message for invalid thinking_style values
Widen thinking_style from Literal to str | None and add a
@field_validator that produces a helpful error message listing
valid options when an invalid value is provided.

Addresses the review feedback on #4482.
2026-06-25 22:53:15 +08:00
axelray-devandXubin Ren c661012754 fix: coalesce None thinking_style to empty string in provider creation
ProviderConfig.thinking_style defaults to None (Optional field), but
create_dynamic_spec expects a string. Coalesce None to "" at all call
sites (factory.py, settings_api.py) and fix the test assertion to
expect None from the config default.
2026-06-25 22:53:15 +08:00
axelray-devandXubin Ren 0e19ea3062 fix: validate thinking_style against known values at config load time 2026-06-25 22:53:15 +08:00
axelray-devandXubin Ren ceae6d7b61 fix: allow custom provider to configure thinking style (#4429) 2026-06-25 22:53:15 +08:00
Xubin Ren 34f776b48b test(cli): lock disabled dream cursor advancement 2026-06-25 22:53:10 +08:00
axelray-devandXubin Ren f7b027a295 fix: only advance dream cursor when behind latest (#4242)
Address review: avoid overwriting cursor on every restart when Dream
is disabled. Now only advances if current cursor is behind the latest
position, so repeated restarts don't permanently skip entries.
2026-06-25 22:53:10 +08:00
axelray-devandXubin Ren 6c880a6691 fix: advance dream cursor when Dream is disabled to prevent prompt bloat (#4242)
When dream.enabled is false, the Dream cron job never runs, so the
dream cursor (.dream_cursor) stays at its initial value (0). This
causes read_recent_history_for_prompt() to treat every history entry
as unprocessed, injecting the full chat history into every system
prompt and growing without bound.

Fix: fast-forward the dream cursor to the latest history entry at
gateway startup when Dream is disabled.
2026-06-25 22:53:10 +08:00
Xubin Ren 4636c78100 test(webui): cover xiaomi mimo wav recording path 2026-06-25 22:52:55 +08:00
zpljd258andXubin Ren 28c8c89a42 fix(webui): convert WebM to WAV for Xiaomi MiMo ASR transcription
MiMo ASR (mimo-v2.5-asr) only accepts audio/wav, audio/mp3, and
audio/mpeg formats. Web browsers record in WebM/Opus by default,
causing the API to reject the payload with a transcription error.

This change adds a frontend WebM→WAV converter using the Web Audio API
(DecodeAudioData + PCM encoding) that activates only when the
configured transcription provider is 'xiaomi_mimo'. Other providers
are unaffected — they continue to receive the original browser format.

Tested and confirmed working on WebUI.
2026-06-25 22:52:55 +08:00
7899857201 refactor(cli): simplify onboard search-provider dispatch
- Extract _set_field_from_choices for the shared pick-and-set tail used by
  both the LLM and search provider handlers.
- Replace the single-entry _TYPED_FIELD_HANDLERS registry with a direct
  isinstance check in _resolve_field_handler (robust to renames, no
  class-name strings).
- Drop a redundant str() in the search default computation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 22:52:50 +08:00
9354b80a6e fix(cli): show search engines (incl. Keenable) in onboard wizard
The onboard wizard dispatched field handlers by bare field name, so
WebSearchConfig.provider was hijacked by the LLM-provider handler and
showed LLM providers instead of search engines. Keenable was also never
wired into the CLI wizard when it landed in the WebUI.

- Add a single source of truth for selectable search providers
  (SEARCH_PROVIDER_OPTIONS in web.py); WebUI settings now import it.
- Add a WebSearchConfig-aware search-provider picker to the wizard and
  resolve handlers by (model type, field name) so the LLM and search
  provider fields no longer collide.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 22:52:50 +08:00
Max HsuandXubin Ren 638af123ba fix(dingtalk): preserve richText formatting and set HTTP client timeout
richText messages only kept rich_text_list items whose type was
"text", so bold/italic/inlineCode/pre segments were silently dropped;
a message made entirely of formatted segments produced empty content
and fell through to the "unsupported message type: richText" warning.
Now any item carrying text is kept (matching the SDK's own
get_text_list, which keys off the "text" field) and its type is mapped
to Markdown so the formatting survives into the agent's context.

Text and downloadCode within a rich-text item are handled
independently (the SDK treats them as separate via get_text_list /
get_image_list), so an item carrying both a caption and an attachment
no longer drops the file.

The shared httpx.AsyncClient was created without a timeout, so all
requests (including large file/image downloads) used httpx's 5s
default and hit ConnectTimeout/ReadTimeout on uploads. Set an explicit
httpx.Timeout (connect=10s, read/write=30s).

Adds regression tests for formatted-segment preservation, the
all-formatted no-drop case, the text+downloadCode item, and the client
timeout configuration.

Closes #4497
2026-06-25 22:52:45 +08:00
michaelxerandXubin Ren 42aa37cfc0 docs: update enabledTools docs and schema comment to reflect resource/prompt gating
The enabledTools gate now also controls MCP resource and prompt
registration (not just tools). Update the configuration docs and
schema field comment to document this behavioral change.

Refs: #4435, #4436
2026-06-25 16:10:37 +08:00
michaelxerandXubin Ren 03302c751f log info when resources/prompts skipped due to enabledTools gate
Address chengyongru review: bump skip message from silent to logger.info
so operators get a visible trace when resources/prompts are not registered.
2026-06-25 16:10:37 +08:00
michaelxerandXubin Ren 246ea8ef61 fix(tools): gate MCP resource and prompt registration behind enabledTools
The enabledTools allowlist was only enforced for MCP tools returned by
session.list_tools(). Resources and prompts from session.list_resources()
and session.list_prompts() were registered unconditionally, allowing a
deny-all or restrictive enabledTools config to leak resource and prompt
capabilities to the model.

Now resources and prompts are only registered when allow_all_tools is
true (default ["*"] wildcard). Any explicit tool restriction — including
enabledTools: [] (deny-all) or a list of specific tool names — also
blocks resource and prompt registration from that server.

Fixes #4435
2026-06-25 16:10:37 +08:00
chengyongruandXubin Ren f60b3c7920 docs: explain Telegram rich messages opt-in
maintainer edit: document that richMessages defaults to false, when to enable it, and why Telegram Web users should leave it disabled.
2026-06-25 16:10:33 +08:00
chengyongruandXubin Ren e92899607a fix: make Telegram rich messages opt in
maintainer edit: Telegram Web cannot render sendRichMessage payloads, so keep the rich path available only for explicit opt-in instead of enabling it by default.
2026-06-25 16:10:33 +08:00
axelray-devandXubin Ren c930aa3713 fix: add rich_messages config to disable sendRichMessage for Telegram Web (#4488) 2026-06-25 16:10:33 +08:00
chengyongruandXubin Ren 4378944459 test: speed up test suite 2026-06-25 16:10:28 +08:00
chengyongruandXubin Ren 123384975e fix(webui): restore code block copy fallback 2026-06-25 16:10:23 +08:00
76 changed files with 3437 additions and 2091 deletions
+30 -2
View File
@@ -44,10 +44,38 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y libolm-dev build-essential
- name: Install dependencies
run: uv sync --all-extras
run: uv sync --all-extras --dev
- name: Lint with ruff
run: uv run ruff check nanobot --select F
- name: Run tests
run: uv run pytest tests/
run: uv run python -m pytest tests/ --cov=nanobot --cov-report=term-missing:skip-covered
webui:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- name: Set up Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.6
- name: Install WebUI dependencies
working-directory: webui
run: bun install
- name: Lint WebUI
working-directory: webui
run: bun run lint
- name: Test WebUI
working-directory: webui
run: bun run test
- name: Build WebUI
working-directory: webui
run: bun run build
-1
View File
@@ -41,7 +41,6 @@ Messages flow through an async `MessageBus` (`nanobot/bus/queue.py`) that decoup
- **Memory** (`nanobot/agent/memory.py`): Session history persistence with Dream two-phase memory consolidation. Uses atomic writes with fsync for durability.
- **Session Management** (`nanobot/session/`): Per-session history, context compaction, TTL-based auto-compaction (`manager.py`), and sustained goal state tracking (`goal_state.py`).
- **Config** (`nanobot/config/schema.py`, `loader.py`): Pydantic-based configuration loaded from `~/.nanobot/config.json`. Supports camelCase aliases for JSON compatibility.
- **Bridge** (`bridge/`): TypeScript services (e.g. WhatsApp bridge) bundled into the wheel via `pyproject.toml` `force-include`.
- **WebUI** (`webui/`): Vite-based React SPA that talks to the gateway over a WebSocket multiplex protocol. The dev server proxies `/api`, `/webui`, `/auth`, and WebSocket traffic to the gateway.
- **API Server** (`nanobot/api/server.py`): OpenAI-compatible HTTP API (`/v1/chat/completions`, `/v1/models`) for programmatic access.
- **Command Router** (`nanobot/command/`): Slash command routing and built-in command handlers.
+15 -22
View File
@@ -1,15 +1,16 @@
FROM node:24-bookworm-slim AS webui-builder
WORKDIR /app
COPY webui/package.json webui/package-lock.json ./webui/
WORKDIR /app/webui
RUN npm ci
COPY webui/ ./
RUN mkdir -p /app/nanobot/web && npm run build
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim
# Install Node.js for the WhatsApp bridge
RUN apt-get update && \
apt-get install -y --no-install-recommends curl ca-certificates gnupg git bubblewrap openssh-client && \
mkdir -p /etc/apt/keyrings && \
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg && \
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_24.x nodistro main" > /etc/apt/sources.list.d/nodesource.list && \
apt-get update && \
apt-get install -y --no-install-recommends nodejs && \
apt-get purge -y gnupg && \
apt-get autoremove -y && \
apt-get install -y --no-install-recommends ca-certificates git bubblewrap openssh-client libmagic1 && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
@@ -17,22 +18,14 @@ WORKDIR /app
# Install Python dependencies first (cached layer). Hatch reads the custom build
# hook from hatch_build.py even for this metadata-only install.
COPY pyproject.toml README.md LICENSE THIRD_PARTY_NOTICES.md hatch_build.py ./
RUN mkdir -p nanobot bridge && touch nanobot/__init__.py && \
uv pip install --system --no-cache . && \
rm -rf nanobot bridge
RUN mkdir -p nanobot && touch nanobot/__init__.py && \
NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[whatsapp]" && \
rm -rf nanobot
# Copy the full source and install
COPY nanobot/ nanobot/
COPY bridge/ bridge/
COPY webui/ webui/
RUN NANOBOT_FORCE_WEBUI_BUILD=1 uv pip install --system --no-cache .
# Build the WhatsApp bridge
WORKDIR /app/bridge
RUN git config --global --add url."https://github.com/".insteadOf ssh://git@github.com/ && \
git config --global --add url."https://github.com/".insteadOf git@github.com: && \
npm install && npm run build
WORKDIR /app
COPY --from=webui-builder /app/nanobot/web/dist/ nanobot/web/dist/
RUN NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[whatsapp]"
# Create non-root user and config directory
RUN useradd -m -u 1000 -s /bin/bash nanobot && \
+7 -16
View File
@@ -48,7 +48,7 @@ chmod 600 ~/.nanobot/config.json
},
"whatsapp": {
"enabled": true,
"allowFrom": ["+1234567890"]
"allowFrom": ["1234567890"]
}
}
}
@@ -57,7 +57,7 @@ chmod 600 ~/.nanobot/config.json
**Security Notes:**
- In `v0.1.4.post3` and earlier, an empty `allowFrom` allowed all users. Since `v0.1.4.post4`, empty `allowFrom` denies all access by default — set `["*"]` to explicitly allow everyone.
- Get your Telegram user ID from `@userinfobot`
- Use full phone numbers with country code for WhatsApp
- Use WhatsApp sender IDs as full phone numbers with country code and no leading `+`
- Review access logs regularly for unauthorized access attempts
### 3. Shell Command Execution
@@ -109,10 +109,9 @@ File operations have path traversal protection, but:
- Timeouts are configured to prevent hanging requests
- Consider using a firewall to restrict outbound connections if needed
**WhatsApp Bridge:**
- The bridge binds to `127.0.0.1:3001` (localhost only, not accessible from external network)
- Set `bridgeToken` in config to enable shared-secret authentication between Python and Node.js
- Keep authentication data in `~/.nanobot/whatsapp-auth` secure (mode 0700)
**WhatsApp:**
- Keep the neonize session database under `~/.nanobot/whatsapp-auth` secure (mode 0700).
- Use `nanobot channels login whatsapp --force` to remove and recreate the local session database when rotating linked devices.
### 6. Dependency Security
@@ -127,17 +126,9 @@ pip-audit
pip install --upgrade nanobot-ai
```
For Node.js dependencies (WhatsApp bridge):
```bash
cd bridge
npm audit
npm audit fix
```
**Important Notes:**
- Keep `litellm` updated to the latest version for security fixes
- We've updated `ws` to `>=8.17.1` to fix DoS vulnerability
- Run `pip-audit` or `npm audit` regularly
- Run `pip-audit` regularly, including optional channel dependencies such as `nanobot-ai[whatsapp]`
- Subscribe to security advisories for nanobot and its dependencies
### 7. Production Deployment
@@ -238,7 +229,7 @@ If you suspect a security breach:
✅ **Secure Communication**
- HTTPS for all external API calls
- TLS for Telegram API
- WhatsApp bridge: localhost-only binding + optional token auth
- WhatsApp session secrets stay in the local session database
## Known Limitations
-26
View File
@@ -1,26 +0,0 @@
{
"name": "nanobot-whatsapp-bridge",
"version": "0.1.0",
"description": "WhatsApp bridge for nanobot using Baileys",
"type": "module",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsc && node dist/index.js"
},
"dependencies": {
"@whiskeysockets/baileys": "7.0.0-rc.9",
"ws": "^8.17.1",
"qrcode-terminal": "^0.12.0",
"pino": "^9.0.0"
},
"devDependencies": {
"@types/node": "^24.0.0",
"@types/ws": "^8.5.10",
"typescript": "^5.4.0"
},
"engines": {
"node": ">=20.0.0"
}
}
-56
View File
@@ -1,56 +0,0 @@
#!/usr/bin/env node
/**
* nanobot WhatsApp Bridge
*
* This bridge connects WhatsApp Web to nanobot's Python backend
* via WebSocket. It handles authentication, message forwarding,
* and reconnection logic.
*
* Usage:
* npm run build && npm start
*
* Or with custom settings:
* BRIDGE_PORT=3001 AUTH_DIR=~/.nanobot/whatsapp npm start
*/
// Polyfill crypto for Baileys in ESM
import { webcrypto } from 'crypto';
if (!globalThis.crypto) {
(globalThis as any).crypto = webcrypto;
}
import { BridgeServer } from './server.js';
import { homedir } from 'os';
import { join } from 'path';
const PORT = parseInt(process.env.BRIDGE_PORT || '3001', 10);
const AUTH_DIR = process.env.AUTH_DIR || join(homedir(), '.nanobot', 'whatsapp-auth');
const TOKEN = process.env.BRIDGE_TOKEN?.trim();
if (!TOKEN) {
console.error('BRIDGE_TOKEN is required. Start the bridge via nanobot so it can provision a local secret automatically.');
process.exit(1);
}
console.log('🐈 nanobot WhatsApp Bridge');
console.log('========================\n');
const server = new BridgeServer(PORT, AUTH_DIR, TOKEN);
// Handle graceful shutdown
process.on('SIGINT', async () => {
console.log('\n\nShutting down...');
await server.stop();
process.exit(0);
});
process.on('SIGTERM', async () => {
await server.stop();
process.exit(0);
});
// Start the server
server.start().catch((error) => {
console.error('Failed to start bridge:', error);
process.exit(1);
});
-155
View File
@@ -1,155 +0,0 @@
/**
* WebSocket server for Python-Node.js bridge communication.
* Security: binds to 127.0.0.1 only; requires BRIDGE_TOKEN auth; rejects browser Origin headers.
*/
import { WebSocketServer, WebSocket } from 'ws';
import { WhatsAppClient, InboundMessage } from './whatsapp.js';
interface SendCommand {
type: 'send';
to: string;
text: string;
}
interface SendMediaCommand {
type: 'send_media';
to: string;
filePath: string;
mimetype: string;
caption?: string;
fileName?: string;
}
type BridgeCommand = SendCommand | SendMediaCommand;
interface BridgeMessage {
type: 'message' | 'status' | 'qr' | 'error';
[key: string]: unknown;
}
export class BridgeServer {
private wss: WebSocketServer | null = null;
private wa: WhatsAppClient | null = null;
private clients: Set<WebSocket> = new Set();
constructor(private port: number, private authDir: string, private token: string) {}
async start(): Promise<void> {
if (!this.token.trim()) {
throw new Error('BRIDGE_TOKEN is required');
}
// Bind to localhost only — never expose to external network
this.wss = new WebSocketServer({
host: '127.0.0.1',
port: this.port,
verifyClient: (info, done) => {
const origin = info.origin || info.req.headers.origin;
if (origin) {
console.warn(`Rejected WebSocket connection with Origin header: ${origin}`);
done(false, 403, 'Browser-originated WebSocket connections are not allowed');
return;
}
done(true);
},
});
console.log(`🌉 Bridge server listening on ws://127.0.0.1:${this.port}`);
console.log('🔒 Token authentication enabled');
// Initialize WhatsApp client
this.wa = new WhatsAppClient({
authDir: this.authDir,
onMessage: (msg) => this.broadcast({ type: 'message', ...msg }),
onQR: (qr) => this.broadcast({ type: 'qr', qr }),
onStatus: (status) => this.broadcast({ type: 'status', status }),
});
// Handle WebSocket connections
this.wss.on('connection', (ws) => {
// Require auth handshake as first message
const timeout = setTimeout(() => ws.close(4001, 'Auth timeout'), 5000);
ws.once('message', (data) => {
clearTimeout(timeout);
try {
const msg = JSON.parse(data.toString());
if (msg.type === 'auth' && msg.token === this.token) {
console.log('🔗 Python client authenticated');
this.setupClient(ws);
} else {
ws.close(4003, 'Invalid token');
}
} catch {
ws.close(4003, 'Invalid auth message');
}
});
});
// Connect to WhatsApp
await this.wa.connect();
}
private setupClient(ws: WebSocket): void {
this.clients.add(ws);
ws.on('message', async (data) => {
try {
const cmd = JSON.parse(data.toString()) as BridgeCommand;
await this.handleCommand(cmd);
ws.send(JSON.stringify({ type: 'sent', to: cmd.to }));
} catch (error) {
console.error('Error handling command:', error);
ws.send(JSON.stringify({ type: 'error', error: String(error) }));
}
});
ws.on('close', () => {
console.log('🔌 Python client disconnected');
this.clients.delete(ws);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
this.clients.delete(ws);
});
}
private async handleCommand(cmd: BridgeCommand): Promise<void> {
if (!this.wa) return;
if (cmd.type === 'send') {
await this.wa.sendMessage(cmd.to, cmd.text);
} else if (cmd.type === 'send_media') {
await this.wa.sendMedia(cmd.to, cmd.filePath, cmd.mimetype, cmd.caption, cmd.fileName);
}
}
private broadcast(msg: BridgeMessage): void {
const data = JSON.stringify(msg);
for (const client of this.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
}
}
async stop(): Promise<void> {
// Close all client connections
for (const client of this.clients) {
client.close();
}
this.clients.clear();
// Close WebSocket server
if (this.wss) {
this.wss.close();
this.wss = null;
}
// Disconnect WhatsApp
if (this.wa) {
await this.wa.disconnect();
this.wa = null;
}
}
}
-3
View File
@@ -1,3 +0,0 @@
declare module 'qrcode-terminal' {
export function generate(text: string, options?: { small?: boolean }): void;
}
-360
View File
@@ -1,360 +0,0 @@
/**
* WhatsApp client wrapper using Baileys.
* Based on OpenClaw's working implementation.
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import makeWASocket, {
DisconnectReason,
useMultiFileAuthState,
fetchLatestBaileysVersion,
makeCacheableSignalKeyStore,
downloadMediaMessage,
extractMessageContent as baileysExtractMessageContent,
} from '@whiskeysockets/baileys';
import { Boom } from '@hapi/boom';
import qrcode from 'qrcode-terminal';
import pino from 'pino';
import { readFile, writeFile, mkdir } from 'fs/promises';
import { join, basename, resolve, sep } from 'path';
import { randomBytes } from 'crypto';
const VERSION = '0.1.0';
export interface InboundMessage {
id: string;
sender: string;
pn: string;
participant?: string;
content: string;
timestamp: number;
isGroup: boolean;
isForwarded?: boolean;
wasMentioned?: boolean;
isReplyToBot?: boolean;
media?: string[];
}
export interface WhatsAppClientOptions {
authDir: string;
onMessage: (msg: InboundMessage) => void;
onQR: (qr: string) => void;
onStatus: (status: string) => void;
}
export class WhatsAppClient {
private sock: any = null;
private options: WhatsAppClientOptions;
private reconnecting = false;
constructor(options: WhatsAppClientOptions) {
this.options = options;
}
private normalizeJid(jid: string | undefined | null): string {
return (jid || '').trim().toLowerCase().replace(/:\d+(?=@)/g, '');
}
private selfJids(): Set<string> {
return new Set(
[this.sock?.user?.id, this.sock?.user?.lid, this.sock?.user?.jid]
.map((jid) => this.normalizeJid(jid))
.filter(Boolean),
);
}
private messageContextInfos(msg: any): any[] {
const unwrapped = baileysExtractMessageContent(msg?.message);
const containers = [msg?.message, unwrapped];
const infos = containers.flatMap((message) => [
message?.extendedTextMessage?.contextInfo,
message?.imageMessage?.contextInfo,
message?.videoMessage?.contextInfo,
message?.documentMessage?.contextInfo,
message?.audioMessage?.contextInfo,
]);
return infos.filter(Boolean);
}
private botAddressing(msg: any): { wasMentioned: boolean; isReplyToBot: boolean } {
if (!msg?.key?.remoteJid?.endsWith('@g.us')) {
return { wasMentioned: false, isReplyToBot: false };
}
const selfIds = this.selfJids();
const contextInfos = this.messageContextInfos(msg);
const mentioned = contextInfos.flatMap((info) => (
Array.isArray(info?.mentionedJid) ? info.mentionedJid : []
));
const wasMentioned = mentioned.some((jid: string) => selfIds.has(this.normalizeJid(jid)));
const isReplyToBot = contextInfos.some((info) => {
const quotedParticipant = this.normalizeJid(info?.participant);
return Boolean(info?.stanzaId && quotedParticipant && selfIds.has(quotedParticipant));
});
return { wasMentioned, isReplyToBot };
}
private isForwarded(msg: any): boolean {
return this.messageContextInfos(msg).some((info) => Boolean(info?.isForwarded));
}
async connect(): Promise<void> {
const logger = pino({ level: 'silent' });
const { state, saveCreds } = await useMultiFileAuthState(this.options.authDir);
const { version } = await fetchLatestBaileysVersion();
console.log(`Using Baileys version: ${version.join('.')}`);
// Record startup time — messages older than this will be ignored
// to avoid replaying history on reconnect
const startupTimestamp = Math.floor(Date.now() / 1000);
// Create socket following OpenClaw's pattern
this.sock = makeWASocket({
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, logger),
},
version,
logger,
printQRInTerminal: false,
browser: ['nanobot', 'cli', VERSION],
syncFullHistory: false,
markOnlineOnConnect: false,
});
// Handle WebSocket errors
if (this.sock.ws && typeof this.sock.ws.on === 'function') {
this.sock.ws.on('error', (err: Error) => {
console.error('WebSocket error:', err.message);
});
}
// Handle connection updates
this.sock.ev.on('connection.update', async (update: any) => {
const { connection, lastDisconnect, qr } = update;
if (qr) {
// Display QR code in terminal
console.log('\n📱 Scan this QR code with WhatsApp (Linked Devices):\n');
qrcode.generate(qr, { small: true });
this.options.onQR(qr);
}
if (connection === 'close') {
const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode;
const shouldReconnect = statusCode !== DisconnectReason.loggedOut;
console.log(`Connection closed. Status: ${statusCode}, Will reconnect: ${shouldReconnect}`);
this.options.onStatus('disconnected');
if (shouldReconnect && !this.reconnecting) {
this.reconnecting = true;
console.log('Reconnecting in 5 seconds...');
setTimeout(() => {
this.reconnecting = false;
this.connect();
}, 5000);
}
} else if (connection === 'open') {
console.log('✅ Connected to WhatsApp');
this.options.onStatus('connected');
}
});
// Save credentials on update
this.sock.ev.on('creds.update', saveCreds);
// Handle incoming messages
this.sock.ev.on('messages.upsert', async ({ messages, type }: { messages: any[]; type: string }) => {
if (type !== 'notify') return;
for (const msg of messages) {
if (msg.key.fromMe) continue;
if (msg.key.remoteJid === 'status@broadcast') continue;
// Drop messages older than startup time (avoid replaying history on reconnect)
const msgTimestamp = msg.messageTimestamp as number;
if (msgTimestamp && msgTimestamp < startupTimestamp) continue;
// Send read receipt (blue check) immediately
try {
await this.sock!.readMessages([msg.key]);
} catch (e) {
// Non-fatal: log but don't block message processing
console.error('Failed to send read receipt:', (e as Error).message);
}
const unwrapped = baileysExtractMessageContent(msg.message);
if (!unwrapped) continue;
const content = this.getTextContent(unwrapped);
let fallbackContent: string | null = null;
const mediaPaths: string[] = [];
if (unwrapped.imageMessage) {
fallbackContent = '[Image]';
const path = await this.downloadMedia(msg, unwrapped.imageMessage.mimetype ?? undefined);
if (path) mediaPaths.push(path);
} else if (unwrapped.documentMessage) {
fallbackContent = '[Document]';
const path = await this.downloadMedia(msg, unwrapped.documentMessage.mimetype ?? undefined,
unwrapped.documentMessage.fileName ?? undefined);
if (path) mediaPaths.push(path);
} else if (unwrapped.videoMessage) {
fallbackContent = '[Video]';
const path = await this.downloadMedia(msg, unwrapped.videoMessage.mimetype ?? undefined);
if (path) mediaPaths.push(path);
} else if (unwrapped.audioMessage) {
fallbackContent = '[Voice Message]';
const path = await this.downloadMedia(msg, unwrapped.audioMessage.mimetype ?? undefined);
if (path) mediaPaths.push(path);
} else if (unwrapped.contactMessage) {
// Single shared contact
const displayName = unwrapped.contactMessage.displayName || '';
const vcard = unwrapped.contactMessage.vcard || '';
fallbackContent = `[Contact: ${displayName}]\n${vcard}`;
} else if (unwrapped.contactsArrayMessage) {
// Multiple shared contacts
const vcards = unwrapped.contactsArrayMessage.contacts || [];
const parts = vcards.map((c: any) => {
const name = c.displayName || '';
const vc = c.vcard || '';
return `[Contact: ${name}]\n${vc}`;
});
fallbackContent = parts.join('\n\n');
}
const isForwarded = this.isForwarded(msg);
const finalContent = content || (mediaPaths.length === 0 ? fallbackContent : '') || '';
if (!finalContent && mediaPaths.length === 0) continue;
const isGroup = msg.key.remoteJid?.endsWith('@g.us') || false;
const { wasMentioned, isReplyToBot } = this.botAddressing(msg);
this.options.onMessage({
id: msg.key.id || '',
sender: msg.key.remoteJid || '',
pn: msg.key.remoteJidAlt || '',
...(isGroup && msg.key.participant ? { participant: msg.key.participant } : {}),
content: finalContent,
timestamp: msg.messageTimestamp as number,
isGroup,
...(isForwarded ? { isForwarded } : {}),
...(isGroup ? { wasMentioned: wasMentioned || isReplyToBot, isReplyToBot } : {}),
...(mediaPaths.length > 0 ? { media: mediaPaths } : {}),
});
}
});
}
private async downloadMedia(msg: any, mimetype?: string, fileName?: string): Promise<string | null> {
try {
const mediaDir = join(this.options.authDir, '..', 'media');
await mkdir(mediaDir, { recursive: true });
const buffer = await downloadMediaMessage(msg, 'buffer', {}) as Buffer;
let outFilename: string;
if (fileName) {
const safeName = basename(fileName).replace(/[^a-zA-Z0-9._-]/g, '_');
outFilename = `wa_${Date.now()}_${randomBytes(4).toString('hex')}_${safeName}`;
} else {
const mime = mimetype || 'application/octet-stream';
const ext = '.' + (mime.split('/').pop()?.split(';')[0] || 'bin');
outFilename = `wa_${Date.now()}_${randomBytes(4).toString('hex')}${ext}`;
}
const filepath = resolve(mediaDir, outFilename);
if (!filepath.startsWith(resolve(mediaDir) + sep)) {
throw new Error(`Path traversal blocked: ${outFilename}`);
}
await writeFile(filepath, buffer);
return filepath;
} catch (err) {
console.error('Failed to download media:', err);
return null;
}
}
private getTextContent(message: any): string | null {
// Text message
if (message.conversation) {
return message.conversation;
}
// Extended text (reply, link preview)
if (message.extendedTextMessage?.text) {
return message.extendedTextMessage.text;
}
// Image with optional caption
if (message.imageMessage) {
return message.imageMessage.caption || '';
}
// Video with optional caption
if (message.videoMessage) {
return message.videoMessage.caption || '';
}
// Document with optional caption
if (message.documentMessage) {
return message.documentMessage.caption || '';
}
// Voice/Audio message
if (message.audioMessage) {
return `[Voice Message]`;
}
return null;
}
async sendMessage(to: string, text: string): Promise<void> {
if (!this.sock) {
throw new Error('Not connected');
}
await this.sock.sendMessage(to, { text });
}
async sendMedia(
to: string,
filePath: string,
mimetype: string,
caption?: string,
fileName?: string,
): Promise<void> {
if (!this.sock) {
throw new Error('Not connected');
}
const buffer = await readFile(filePath);
const category = mimetype.split('/')[0];
if (category === 'image') {
await this.sock.sendMessage(to, { image: buffer, caption: caption || undefined, mimetype });
} else if (category === 'video') {
await this.sock.sendMessage(to, { video: buffer, caption: caption || undefined, mimetype });
} else if (category === 'audio') {
await this.sock.sendMessage(to, { audio: buffer, mimetype });
} else {
const name = fileName || basename(filePath);
await this.sock.sendMessage(to, { document: buffer, mimetype, fileName: name });
}
}
async disconnect(): Promise<void> {
if (this.sock) {
this.sock.end(undefined);
this.sock = null;
}
}
}
-16
View File
@@ -1,16 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+52 -15
View File
@@ -79,6 +79,8 @@ If `nanobot channels status` does not show the channel as enabled, the config sn
```
> You can find your **User ID** in Telegram settings. It is shown as `@yourUserId`. Copy this value **without the `@` symbol** and paste it into the config file.
>
> `richMessages` defaults to `false`. Set it to `true` only if your Telegram client supports Bot API 10.1 rich messages and you want richer markdown rendering; keep it disabled for Telegram Web, which may show unsupported-message errors for rich messages.
**3. Run**
@@ -301,9 +303,15 @@ nanobot gateway
<details>
<summary><b>WhatsApp</b></summary>
Requires **Node.js ≥18**.
Requires the WhatsApp optional dependencies:
**1. Link device**
```bash
pip install "nanobot-ai[whatsapp]"
# Source checkout:
python -m pip install -e ".[whatsapp]"
```
**1. Link device with QR**
```bash
nanobot channels login whatsapp
@@ -317,30 +325,59 @@ nanobot channels login whatsapp
"channels": {
"whatsapp": {
"enabled": true,
"allowFrom": ["+1234567890"]
"allowFrom": ["1234567890"]
}
}
}
```
**3. Run** (two terminals)
Optional session database path:
```bash
# Terminal 1
nanobot channels login whatsapp
# Terminal 2
nanobot gateway
```json
{
"channels": {
"whatsapp": {
"databasePath": "~/.nanobot/whatsapp-auth/neonize.db"
}
}
}
```
> WhatsApp bridge updates are not applied automatically for existing installations. After upgrading nanobot, rebuild the local bridge with:
> `rm -rf ~/.nanobot/bridge && nanobot channels login whatsapp`
Optional activity cues:
```json
{
"channels": {
"whatsapp": {
"typingPresence": true,
"reactEmoji": "👀"
}
}
}
```
Set `typingPresence` to `false` to stop sending composing indicators. Set
`reactEmoji` to `""` to disable the temporary reaction while nanobot works.
Outbound WhatsApp messages preserve explicit mention metadata when a tool or
channel sends native WhatsApp mentions.
**Migrating from the old bridge**
- Remove `bridgeUrl` and `bridgeToken`; WhatsApp no longer runs a local Node.js bridge.
- Re-run `nanobot channels login whatsapp`; old Baileys bridge auth data is not reused by neonize.
- Update `allowFrom` entries to the WhatsApp sender ID without a leading `+`.
**3. Run**
```bash
nanobot gateway
```
**Optional: static LID mappings**
Modern WhatsApp can deliver a sender's LID instead of their phone number. nanobot
learns the LID→phone mapping at runtime (and reuses the ones the bridge persists on
disk), but you can also seed mappings up front so the phone number resolves from the
learns LID to phone mappings at runtime when both identifiers are present, but you
can also seed mappings up front so the phone number resolves from the
very first message:
```json
@@ -348,7 +385,7 @@ very first message:
"channels": {
"whatsapp": {
"enabled": true,
"allowFrom": ["+1234567890"],
"allowFrom": ["1234567890"],
"lidMappings": { "123456789012345": "1234567890" }
}
}
+6 -4
View File
@@ -57,18 +57,20 @@ Preset names come from the top-level `modelPresets` config. Switching is runtime
## Periodic Tasks
Periodic tasks are driven by `HEARTBEAT.md` in your workspace (`~/.nanobot/workspace/HEARTBEAT.md`). When `nanobot gateway` starts, it registers a protected heartbeat cron job by default. Every 30 minutes, that job checks the file; if it finds tasks under `## Active Tasks`, the agent executes them and delivers results to your most recently active chat channel. If there are no active tasks, the heartbeat is skipped silently.
Periodic background checks are driven by `HEARTBEAT.md` in your workspace (`~/.nanobot/workspace/HEARTBEAT.md`). When `nanobot gateway` starts, it registers a protected heartbeat cron job by default. Every 30 minutes, that job checks the file; if it finds tasks under `## Active Tasks`, the agent executes them and delivers only results that pass the notification gate to your most recently active chat channel. If there are no active tasks, or the result is routine with nothing useful to report, the heartbeat is skipped silently.
Use heartbeat for recurring checks that should usually stay quiet. User-created cron jobs are different: they run as scheduled turns in the chat/session where they were created and normally deliver the result back to that channel.
**Setup:** edit `~/.nanobot/workspace/HEARTBEAT.md` (created automatically by `nanobot onboard`):
```markdown
## Active Tasks
- Check weather forecast and send a summary
- Scan inbox for urgent emails
- Check weather forecast and notify me only if storms are expected
- Scan inbox for urgent emails and notify me if any are found
```
The agent can also manage this file itself ask it to "add a periodic task" and it will update `HEARTBEAT.md` for you. Completed tasks should be deleted from the file, not moved to another section.
The agent can also manage this file itself - ask it to "add a periodic background check" or "check this periodically but only notify me if something changes" and it will update `HEARTBEAT.md` for you. Completed tasks should be deleted from the file, not moved to another section.
You can change the interval or disable the built-in heartbeat in `~/.nanobot/config.json`:
+2 -2
View File
@@ -136,9 +136,9 @@ When `nanobot gateway` starts, it creates workspace-scoped cron storage at `<wor
- `dream`, when `agents.defaults.dream.enabled` is true;
- `heartbeat`, when `gateway.heartbeat.enabled` is true.
Heartbeat reads `<workspace>/HEARTBEAT.md`. If the file has tasks under `## Active Tasks`, nanobot executes them and sends useful results to the most recently active chat target.
Heartbeat reads `<workspace>/HEARTBEAT.md`. If the file has tasks under `## Active Tasks`, nanobot executes them and sends only useful/actionable results to the most recently active chat target. Routine "nothing changed" results are suppressed.
User-created reminders use the same cron service but are not the same as the protected heartbeat system job.
User-created reminders use the same cron service but are not the same as the protected heartbeat system job. They run as scheduled turns in their origin chat/session and normally deliver the result back to that channel.
## Where to Go Next
+44 -4
View File
@@ -985,6 +985,29 @@ Some OpenAI-compatible gateways expose request-body extensions such as vLLM guid
}
```
If a custom OpenAI-compatible endpoint exposes a provider-specific thinking toggle, set `thinkingStyle` so nanobot can translate `reasoningEffort` into the right request body. Supported styles are `thinking_type` (`{"thinking":{"type":"enabled"}}`), `enable_thinking` (`{"enable_thinking": true}`), and `reasoning_split` (`{"reasoning_split": true}`):
```json
{
"providers": {
"companyProxy": {
"apiKey": "${COMPANY_PROXY_API_KEY}",
"apiBase": "https://api.your-provider.com/v1",
"thinkingStyle": "enable_thinking"
}
},
"modelPresets": {
"company": {
"provider": "companyProxy",
"model": "served-model-name",
"reasoningEffort": "high"
}
}
}
```
Leave `thinkingStyle` unset unless the endpoint explicitly documents one of those wire formats. `extraBody` is still applied last, so advanced users can override the generated value.
</details>
<a id="local-providers"></a>
@@ -1482,6 +1505,8 @@ Global settings that apply to all channels. Configure under the `channels` secti
}
```
Telegram `richMessages` defaults to `false`. Enable it only to opt in to Bot API 10.1 `sendRichMessage` rendering; leave it disabled for Telegram Web clients that show unsupported-message errors for rich messages.
### Retry Behavior
Retry is intentionally simple.
@@ -1827,9 +1852,9 @@ Use `enabledTools` to register only a subset of tools from an MCP server:
`enabledTools` accepts either the raw MCP tool name (for example `read_file`) or the wrapped nanobot tool name (for example `mcp_filesystem_write_file`).
- Omit `enabledTools`, or set it to `["*"]`, to register all tools.
- Set `enabledTools` to `[]` to register no tools from that server.
- Set `enabledTools` to a non-empty list of names to register only that subset.
- Omit `enabledTools`, or set it to `["*"]`, to register all capabilities (tools, resources, and prompts).
- Set `enabledTools` to `[]` to register no tools from that server. Resources and prompts are also skipped, since they have no per-name filter.
- Set `enabledTools` to a non-empty list of names to register only those tools — resources and prompts are not registered.
MCP tools are automatically discovered and registered on startup. The LLM can use them alongside built-in tools — no extra configuration needed.
@@ -1938,7 +1963,9 @@ The gateway can run a protected heartbeat cron job that periodically checks `HEA
}
```
If `HEARTBEAT.md` has tasks under `## Active Tasks`, the agent executes them and delivers useful results to the most recently active chat target. If the file has no active tasks, the heartbeat is skipped silently.
If `HEARTBEAT.md` has tasks under `## Active Tasks`, the agent executes them and sends only useful/actionable results to the most recently active chat target. If the file has no active tasks, or the result is routine with nothing useful to report, the heartbeat is skipped silently.
This is intentionally different from user-created cron jobs. A cron job created with the `cron` tool runs as a scheduled turn in its origin chat/session and normally delivers the result back to that channel. Use `HEARTBEAT.md` for recurring background checks that should not notify the user on every run.
The heartbeat job is backed by the same cron service as user-created reminders. It is stored under the active workspace (`<workspace>/cron/jobs.json`) and shows up in `cron(action="list")` as `heartbeat`, but it is system-managed and cannot be removed with the `cron` tool. Disable it through config and restart the gateway if you do not want periodic heartbeat checks.
@@ -1963,9 +1990,22 @@ By default, nanobot only allows one spawned subagent at a time. When the limit i
}
```
Subagents also stop immediately when one of their tools returns an execution error. That default keeps failures visible to the parent agent. If your subagent workflows use tools that can fail transiently and should be retried or worked around by the model, disable hard-stop behavior:
```json
{
"agents": {
"defaults": {
"failOnToolError": false
}
}
}
```
| Option | Default | Description |
|--------|---------|-------------|
| `agents.defaults.maxConcurrentSubagents` | `1` | Maximum number of spawned subagents that may run at the same time. Attempts to spawn beyond this limit return an error. |
| `agents.defaults.failOnToolError` | `true` | Stop a spawned subagent when a tool execution fails. Set to `false` to return tool errors to the subagent model so it can recover within the same run. |
## Auto Compact
+2
View File
@@ -293,6 +293,8 @@ If you have more than one custom OpenAI-compatible endpoint, give each endpoint
Custom provider keys are treated as direct OpenAI-compatible providers. `apiBase` is required because nanobot cannot know the endpoint URL. `apiKey` is optional for local servers or private proxies that do not require one. Choose a name that does not conflict with a built-in provider name or alias, such as `openai`, `openai-codex`, `github-copilot`, or `lm-studio`. Do not set `apiType` on custom provider keys; `apiType` is only for `providers.openai`.
If your custom endpoint documents a nonstandard thinking toggle, set `providers.<name>.thinkingStyle` to `thinking_type`, `enable_thinking`, or `reasoning_split`; nanobot then maps `reasoningEffort` onto that provider-specific request body. Leave it unset for ordinary OpenAI-compatible endpoints.
This named custom provider path is not for Anthropic-compatible endpoints. For Anthropic-compatible proxies, use `providers.anthropic.apiBase` and set the preset provider to `anthropic`.
### Ollama
+2 -3
View File
@@ -326,11 +326,10 @@ python -m pip install -e .
nanobot --version
```
If you use WhatsApp, rebuild the local bridge after upgrading:
If you use WhatsApp from a source checkout, keep the optional dependencies installed:
```bash
rm -rf ~/.nanobot/bridge
nanobot channels login whatsapp
python -m pip install -e ".[whatsapp]"
```
## First-Run Troubleshooting
+6 -1
View File
@@ -118,7 +118,12 @@ to perform that task.
Automations are scheduled agent turns. They should be created from the chat,
channel, or session where they are supposed to run so nanobot keeps the correct
target context.
target context. When an automation runs, it normally delivers the result back to
that linked chat.
For recurring background checks that should stay quiet unless there is something
useful to report, use the protected heartbeat job by editing `HEARTBEAT.md`
instead of creating a chat automation.
Use the Automations view to:
+391
View File
@@ -0,0 +1,391 @@
"""Model-message governance for agent runner requests.
This module owns model-facing message shaping and tool-result content normalization.
It may return copied messages or persisted-result placeholders, but it must not
mutate an existing session history list in place.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any
from loguru import logger
from nanobot.utils.helpers import (
estimate_message_tokens,
estimate_prompt_tokens_chain,
find_legal_message_start,
maybe_persist_tool_result,
truncate_text,
)
from nanobot.utils.runtime import ensure_nonempty_tool_result
if TYPE_CHECKING:
from nanobot.providers.base import LLMProvider
SNIP_SAFETY_BUFFER = 1024
MICROCOMPACT_KEEP_RECENT = 10
MICROCOMPACT_MIN_CHARS = 500
INFLIGHT_COMPACT_TARGET_RATIO = 0.85
COMPACTABLE_TOOLS = frozenset({
"read_file", "exec", "grep", "find_files",
"web_search", "web_fetch", "list_dir", "list_exec_sessions",
})
# read_file is the recovery path for persisted results; exempting it prevents persist->read->persist loops.
TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS = frozenset({"read_file"})
BACKFILL_CONTENT = "[Tool result unavailable — call was interrupted or lost]"
@dataclass(slots=True)
class ContextGovernanceConfig:
provider: LLMProvider
model: str
tools: Any
workspace: Path | None
session_key: str | None
max_tool_result_chars: int
context_window_tokens: int | None = None
context_block_limit: int | None = None
max_tokens: int | None = None
inflight_start_index: int = 0
class ContextGovernor:
"""Prepare model-copy messages while preserving persisted history."""
def prepare_for_model(
self,
config: ContextGovernanceConfig,
messages: list[dict[str, Any]],
compacted_tool_call_ids: set[str],
) -> list[dict[str, Any]]:
updated = self.drop_orphan_tool_results(messages)
updated = self.backfill_missing_tool_results(updated)
updated = self.apply_tool_result_budget(config, updated)
updated = self.compact_inflight_overflow(config, updated, compacted_tool_call_ids)
updated = self.snip_history(config, updated)
updated = self.drop_orphan_tool_results(updated)
return self.backfill_missing_tool_results(updated)
@staticmethod
def input_budget(config: ContextGovernanceConfig) -> int:
if not config.context_window_tokens:
return 0
provider_max_tokens = getattr(
getattr(config.provider, "generation", None),
"max_tokens",
4096,
)
max_output = config.max_tokens if isinstance(config.max_tokens, int) else (
provider_max_tokens if isinstance(provider_max_tokens, int) else 4096
)
budget = config.context_block_limit or (
config.context_window_tokens - max_output - SNIP_SAFETY_BUFFER
)
return budget if budget > 0 else 0
@staticmethod
def normalize_tool_result(
config: ContextGovernanceConfig,
tool_call_id: str,
tool_name: str,
result: Any,
) -> Any:
result = ensure_nonempty_tool_result(tool_name, result)
if tool_name in TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS:
return result
try:
content = maybe_persist_tool_result(
config.workspace,
config.session_key,
tool_call_id,
result,
max_chars=config.max_tool_result_chars,
)
except Exception:
logger.exception(
"Tool result persist failed for {} in {}; using raw result",
tool_call_id,
config.session_key or "default",
)
content = result
if isinstance(content, str) and len(content) > config.max_tool_result_chars:
return truncate_text(content, config.max_tool_result_chars)
return content
@staticmethod
def drop_orphan_tool_results(
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Drop tool results that have no matching assistant tool_call earlier in history."""
declared: set[str] = set()
updated: list[dict[str, Any]] | None = None
for idx, msg in enumerate(messages):
role = msg.get("role")
if role == "assistant":
for tc in msg.get("tool_calls") or []:
if isinstance(tc, dict) and tc.get("id"):
declared.add(str(tc["id"]))
if role == "tool":
tid = msg.get("tool_call_id")
if tid and str(tid) not in declared:
if updated is None:
updated = [dict(m) for m in messages[:idx]]
continue
if updated is not None:
updated.append(dict(msg))
if updated is None:
return messages
return updated
@staticmethod
def backfill_missing_tool_results(
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Insert synthetic error results for assistant tool_calls with missing tool outputs."""
declared: list[tuple[int, str, str]] = []
fulfilled: set[str] = set()
for idx, msg in enumerate(messages):
role = msg.get("role")
if role == "assistant":
for tc in msg.get("tool_calls") or []:
if isinstance(tc, dict) and tc.get("id"):
name = ""
func = tc.get("function")
if isinstance(func, dict):
name = func.get("name", "")
declared.append((idx, str(tc["id"]), name))
elif role == "tool":
tid = msg.get("tool_call_id")
if tid:
fulfilled.add(str(tid))
missing = [(ai, cid, name) for ai, cid, name in declared if cid not in fulfilled]
if not missing:
return messages
updated = list(messages)
offset = 0
for assistant_idx, call_id, name in missing:
insert_at = assistant_idx + 1 + offset
while insert_at < len(updated) and updated[insert_at].get("role") == "tool":
insert_at += 1
updated.insert(insert_at, {
"role": "tool",
"tool_call_id": call_id,
"name": name,
"content": BACKFILL_CONTENT,
})
offset += 1
return updated
def apply_tool_result_budget(
self,
config: ContextGovernanceConfig,
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
updated = messages
for idx, message in enumerate(messages):
if message.get("role") != "tool":
continue
normalized = self.normalize_tool_result(
config,
str(message.get("tool_call_id") or f"tool_{idx}"),
str(message.get("name") or "tool"),
message.get("content"),
)
if normalized != message.get("content"):
if updated is messages:
updated = [dict(m) for m in messages]
updated[idx]["content"] = normalized
return updated
def compact_inflight_overflow(
self,
config: ContextGovernanceConfig,
messages: list[dict[str, Any]],
compacted_tool_call_ids: set[str],
) -> list[dict[str, Any]]:
"""Compact in-flight tool results only when the request would overflow."""
budget = self.input_budget(config)
if budget <= 0:
return messages
tools = config.tools.get_definitions()
updated = self._apply_recorded_compactions(messages, compacted_tool_call_ids)
estimate, source = estimate_prompt_tokens_chain(
config.provider,
config.model,
updated,
tools,
)
if estimate <= budget:
return updated
target = int(budget * INFLIGHT_COMPACT_TARGET_RATIO)
candidates = self._inflight_compaction_candidates(
config,
updated,
compacted_tool_call_ids,
)
if not candidates:
return updated
for candidate_idx, (idx, tool_call_id) in enumerate(candidates):
is_newest_candidate = candidate_idx == len(candidates) - 1
if is_newest_candidate and estimate <= budget:
break
if tool_call_id in compacted_tool_call_ids:
continue
if updated is messages:
updated = [dict(m) for m in messages]
compacted_tool_call_ids.add(tool_call_id)
self._compact_tool_result_at(updated, idx)
estimate, source = estimate_prompt_tokens_chain(
config.provider,
config.model,
updated,
tools,
)
if estimate <= target:
break
logger.debug(
"In-flight context compaction for {}: prompt={} budget={} target={} via {}, ids={}",
config.session_key or "default",
estimate,
budget,
target,
source,
len(compacted_tool_call_ids),
)
return updated
def snip_history(
self,
config: ContextGovernanceConfig,
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
if not messages or not config.context_window_tokens:
return messages
budget = self.input_budget(config)
if budget <= 0:
return messages
tools = config.tools.get_definitions()
estimate, _ = estimate_prompt_tokens_chain(
config.provider,
config.model,
messages,
tools,
)
if estimate <= budget:
return messages
system_messages = [dict(msg) for msg in messages if msg.get("role") == "system"]
non_system = [dict(msg) for msg in messages if msg.get("role") != "system"]
if not non_system:
return messages
system_tokens = sum(estimate_message_tokens(msg) for msg in system_messages)
fixed_tokens, _ = estimate_prompt_tokens_chain(
config.provider,
config.model,
system_messages,
tools,
)
remaining_budget = max(0, budget - max(system_tokens, fixed_tokens))
kept: list[dict[str, Any]] = []
kept_tokens = 0
for message in reversed(non_system):
msg_tokens = estimate_message_tokens(message)
if kept and kept_tokens + msg_tokens > remaining_budget:
break
kept.append(message)
kept_tokens += msg_tokens
kept.reverse()
return system_messages + self._legal_history_tail(kept, non_system)
@staticmethod
def _summary_for(message: dict[str, Any]) -> str:
name = message.get("name", "tool")
return f"[{name} result omitted from context]"
def _legal_history_tail(
self,
kept: list[dict[str, Any]],
non_system: list[dict[str, Any]],
) -> list[dict[str, Any]]:
fallback = kept if kept else (non_system[-1:] if non_system else [])
kept = self._user_tail(kept) or self._user_tail(non_system, last=True) or fallback
start = find_legal_message_start(kept)
return kept[start:] if start else kept
@staticmethod
def _user_tail(messages: list[dict[str, Any]], *, last: bool = False) -> list[dict[str, Any]]:
indexes = range(len(messages) - 1, -1, -1) if last else range(len(messages))
for idx in indexes:
if messages[idx].get("role") == "user":
return messages[idx:]
return []
def _apply_recorded_compactions(
self,
messages: list[dict[str, Any]],
compacted_tool_call_ids: set[str],
) -> list[dict[str, Any]]:
if not compacted_tool_call_ids:
return messages
updated = messages
for idx, msg in enumerate(messages):
if msg.get("role") != "tool":
continue
tool_call_id = msg.get("tool_call_id")
if not tool_call_id or str(tool_call_id) not in compacted_tool_call_ids:
continue
summary = self._summary_for(msg)
if msg.get("content") == summary:
continue
if updated is messages:
updated = [dict(m) for m in messages]
updated[idx]["content"] = summary
return updated
def _inflight_compaction_candidates(
self,
config: ContextGovernanceConfig,
messages: list[dict[str, Any]],
compacted_tool_call_ids: set[str],
) -> list[tuple[int, str]]:
compactable: list[tuple[int, str]] = []
for idx, msg in enumerate(messages):
if idx < config.inflight_start_index:
continue
if msg.get("role") != "tool" or msg.get("name") not in COMPACTABLE_TOOLS:
continue
tool_call_id = msg.get("tool_call_id")
if not tool_call_id or str(tool_call_id) in compacted_tool_call_ids:
continue
content = msg.get("content")
if not isinstance(content, str) or len(content) < MICROCOMPACT_MIN_CHARS:
continue
compactable.append((idx, str(tool_call_id)))
if not compactable:
return []
primary_count = max(0, len(compactable) - MICROCOMPACT_KEEP_RECENT)
primary = compactable[:primary_count]
# Hard overflow beats the keep-recent preference. Return recent results
# after stale ones so the newest result is naturally last.
fallback = compactable[primary_count:]
return primary + fallback
def _compact_tool_result_at(self, messages: list[dict[str, Any]], idx: int) -> None:
messages[idx]["content"] = self._summary_for(messages[idx])
+3 -2
View File
@@ -190,6 +190,7 @@ class AgentLoop:
context_window_tokens: int | None = None,
context_block_limit: int | None = None,
max_tool_result_chars: int | None = None,
fail_on_tool_error: bool | None = None,
provider_retry_mode: str = "standard",
tool_hint_max_length: int | None = None,
cron_service: CronService | None = None,
@@ -287,6 +288,7 @@ class AgentLoop:
disabled_skills=disabled_skills,
max_iterations=self.max_iterations,
max_concurrent_subagents=max_concurrent_subagents,
fail_on_tool_error=fail_on_tool_error,
llm_wall_timeout_for_session=lambda sk: runner_wall_llm_timeout_s(self.sessions, sk),
)
self._unified_session = unified_session
@@ -377,6 +379,7 @@ class AgentLoop:
context_window_tokens=context_window_tokens,
context_block_limit=defaults.context_block_limit,
max_tool_result_chars=defaults.max_tool_result_chars,
fail_on_tool_error=defaults.fail_on_tool_error,
provider_retry_mode=defaults.provider_retry_mode,
tool_hint_max_length=defaults.tool_hint_max_length,
restrict_to_workspace=config.tools.restrict_to_workspace,
@@ -1180,7 +1183,6 @@ class AgentLoop:
_hist_kwargs: dict[str, Any] = {
"max_messages": self._max_messages,
"max_tokens": self._replay_token_budget(),
"include_timestamps": True,
"extend_to_user": is_subagent,
}
history = session.get_history(**_hist_kwargs)
@@ -1459,7 +1461,6 @@ class AgentLoop:
_hist_kwargs: dict[str, Any] = {
"max_messages": self._max_messages,
"max_tokens": self._replay_token_budget(),
"include_timestamps": True,
"extend_to_user": False,
}
ctx.history = ctx.session.get_history(**_hist_kwargs)
+5 -7
View File
@@ -479,6 +479,9 @@ class MemoryStore:
def set_last_dream_cursor(self, cursor: int) -> None:
self._dream_cursor_file.write_text(str(cursor), encoding="utf-8")
def get_latest_cursor(self) -> int:
return max(self._next_cursor() - 1, 0)
def build_dream_prompt(self, *, max_entries: int = 20) -> tuple[str, int] | None:
"""Build the Dream prompt with unprocessed history context.
@@ -709,17 +712,12 @@ class Consolidator:
@staticmethod
def _full_unconsolidated_history(
session: Session,
*,
include_timestamps: bool = False,
) -> list[dict[str, Any]]:
"""Return the whole unconsolidated tail for consolidation decisions."""
unconsolidated_count = len(session.messages) - session.last_consolidated
if unconsolidated_count <= 0:
return []
return session.get_history(
max_messages=unconsolidated_count,
include_timestamps=include_timestamps,
)
return session.get_history(max_messages=unconsolidated_count)
@staticmethod
def _replay_overflow_boundary(
@@ -794,7 +792,7 @@ class Consolidator:
session: Session,
) -> tuple[int, str]:
"""Estimate prompt size from the full unconsolidated session tail."""
history = self._full_unconsolidated_history(session, include_timestamps=True)
history = self._full_unconsolidated_history(session)
channel, chat_id = (session.key.split(":", 1) if ":" in session.key else (None, None))
# Include archived summary in estimation so the budget accounts for it.
meta = session.metadata.get("_last_summary")
+29 -246
View File
@@ -13,6 +13,10 @@ from typing import Any, Callable
from loguru import logger
from nanobot.agent.context_governance import (
ContextGovernanceConfig,
ContextGovernor,
)
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
@@ -32,11 +36,8 @@ from nanobot.utils.helpers import (
estimate_message_tokens,
estimate_prompt_tokens_chain,
extract_reasoning,
find_legal_message_start,
maybe_persist_tool_result,
strip_reasoning_tags,
strip_think,
truncate_text,
)
from nanobot.utils.progress_events import (
invoke_file_edit_progress,
@@ -49,7 +50,6 @@ from nanobot.utils.runtime import (
build_finalization_retry_message,
build_goal_continue_message,
build_length_recovery_message,
ensure_nonempty_tool_result,
is_blank_text,
repeated_external_lookup_error,
repeated_workspace_violation_error,
@@ -67,17 +67,6 @@ _MAX_EMPTY_RETRIES = 2
_MAX_LENGTH_RECOVERIES = 3
_MAX_INJECTIONS_PER_TURN = 3
_MAX_INJECTION_CYCLES = 5
_SNIP_SAFETY_BUFFER = 1024
_MICROCOMPACT_KEEP_RECENT = 10
_MICROCOMPACT_MIN_CHARS = 500
_COMPACTABLE_TOOLS = frozenset({
"read_file", "exec", "grep", "find_files",
"web_search", "web_fetch", "list_dir", "list_exec_sessions",
})
# read_file is the recovery path for persisted results; exempting it prevents persist->read->persist loops.
_TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS = frozenset({"read_file"})
_BACKFILL_CONTENT = "[Tool result unavailable — call was interrupted or lost]"
# Backward-compatible module attribute for tests/extensions that monkeypatch
# the former single-file tracker hook. Runtime uses prepare_file_edit_trackers.
prepare_file_edit_tracker = _prepare_file_edit_tracker
@@ -135,6 +124,7 @@ class AgentRunner:
def __init__(self, provider: LLMProvider):
self.provider = provider
self.context_governor = ContextGovernor()
@staticmethod
def _merge_message_content(left: Any, right: Any) -> str | list[dict[str, Any]]:
@@ -367,6 +357,19 @@ class AgentRunner:
length_recovery_count = 0
had_injections = False
injection_cycles = 0
compacted_tool_call_ids: set[str] = set()
governance_config = ContextGovernanceConfig(
provider=self.provider,
model=spec.model,
tools=spec.tools,
workspace=spec.workspace,
session_key=spec.session_key,
max_tool_result_chars=spec.max_tool_result_chars,
context_window_tokens=spec.context_window_tokens,
context_block_limit=spec.context_block_limit,
max_tokens=spec.max_tokens,
inflight_start_index=len(spec.initial_messages),
)
for iteration in range(spec.max_iterations):
try:
@@ -374,14 +377,11 @@ class AgentRunner:
# may repair or compact historical messages for the model, but
# those synthetic edits must not shift the append boundary used
# later when the caller saves only the new turn.
messages_for_model = self._drop_orphan_tool_results(messages)
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
messages_for_model = self._microcompact(messages_for_model)
messages_for_model = self._apply_tool_result_budget(spec, messages_for_model)
messages_for_model = self._snip_history(spec, messages_for_model)
# Snipping may have created new orphans; clean them up.
messages_for_model = self._drop_orphan_tool_results(messages_for_model)
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
messages_for_model = self.context_governor.prepare_for_model(
governance_config,
messages,
compacted_tool_call_ids,
)
except Exception:
logger.exception(
"Context governance failed on turn {} for {}; applying minimal repair",
@@ -389,8 +389,10 @@ class AgentRunner:
spec.session_key or "default",
)
try:
messages_for_model = self._drop_orphan_tool_results(messages)
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
messages_for_model = ContextGovernor.drop_orphan_tool_results(messages)
messages_for_model = ContextGovernor.backfill_missing_tool_results(
messages_for_model
)
except Exception:
messages_for_model = messages
context = AgentHookContext(
@@ -463,8 +465,8 @@ class AgentRunner:
"role": "tool",
"tool_call_id": tool_call.id,
"name": tool_call.name,
"content": self._normalize_tool_result(
spec,
"content": self.context_governor.normalize_tool_result(
governance_config,
tool_call.id,
tool_call.name,
result,
@@ -1334,225 +1336,6 @@ class AgentRunner:
return
messages.append(build_assistant_message(_PERSISTED_MODEL_ERROR_PLACEHOLDER))
def _normalize_tool_result(
self,
spec: AgentRunSpec,
tool_call_id: str,
tool_name: str,
result: Any,
) -> Any:
result = ensure_nonempty_tool_result(tool_name, result)
if tool_name in _TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS:
# Exempt tools bound their own output; skip generic offload and truncation.
return result
try:
content = maybe_persist_tool_result(
spec.workspace,
spec.session_key,
tool_call_id,
result,
max_chars=spec.max_tool_result_chars,
)
except Exception:
logger.exception(
"Tool result persist failed for {} in {}; using raw result",
tool_call_id,
spec.session_key or "default",
)
content = result
if isinstance(content, str) and len(content) > spec.max_tool_result_chars:
return truncate_text(content, spec.max_tool_result_chars)
return content
@staticmethod
def _drop_orphan_tool_results(
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Drop tool results that have no matching assistant tool_call earlier in the history."""
declared: set[str] = set()
updated: list[dict[str, Any]] | None = None
for idx, msg in enumerate(messages):
role = msg.get("role")
if role == "assistant":
for tc in msg.get("tool_calls") or []:
if isinstance(tc, dict) and tc.get("id"):
declared.add(str(tc["id"]))
if role == "tool":
tid = msg.get("tool_call_id")
if tid and str(tid) not in declared:
if updated is None:
updated = [dict(m) for m in messages[:idx]]
continue
if updated is not None:
updated.append(dict(msg))
if updated is None:
return messages
return updated
@staticmethod
def _backfill_missing_tool_results(
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Insert synthetic error results for orphaned tool_use blocks."""
declared: list[tuple[int, str, str]] = [] # (assistant_idx, call_id, name)
fulfilled: set[str] = set()
for idx, msg in enumerate(messages):
role = msg.get("role")
if role == "assistant":
for tc in msg.get("tool_calls") or []:
if isinstance(tc, dict) and tc.get("id"):
name = ""
func = tc.get("function")
if isinstance(func, dict):
name = func.get("name", "")
declared.append((idx, str(tc["id"]), name))
elif role == "tool":
tid = msg.get("tool_call_id")
if tid:
fulfilled.add(str(tid))
missing = [(ai, cid, name) for ai, cid, name in declared if cid not in fulfilled]
if not missing:
return messages
updated = list(messages)
offset = 0
for assistant_idx, call_id, name in missing:
insert_at = assistant_idx + 1 + offset
while insert_at < len(updated) and updated[insert_at].get("role") == "tool":
insert_at += 1
updated.insert(insert_at, {
"role": "tool",
"tool_call_id": call_id,
"name": name,
"content": _BACKFILL_CONTENT,
})
offset += 1
return updated
@staticmethod
def _microcompact(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Replace old compactable tool results with one-line summaries."""
compactable_indices: list[int] = []
for idx, msg in enumerate(messages):
if msg.get("role") == "tool" and msg.get("name") in _COMPACTABLE_TOOLS:
compactable_indices.append(idx)
if len(compactable_indices) <= _MICROCOMPACT_KEEP_RECENT:
return messages
stale = compactable_indices[: len(compactable_indices) - _MICROCOMPACT_KEEP_RECENT]
updated: list[dict[str, Any]] | None = None
for idx in stale:
msg = messages[idx]
content = msg.get("content")
if not isinstance(content, str) or len(content) < _MICROCOMPACT_MIN_CHARS:
continue
name = msg.get("name", "tool")
summary = f"[{name} result omitted from context]"
if updated is None:
updated = [dict(m) for m in messages]
updated[idx]["content"] = summary
return updated if updated is not None else messages
def _apply_tool_result_budget(
self,
spec: AgentRunSpec,
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
updated = messages
for idx, message in enumerate(messages):
if message.get("role") != "tool":
continue
normalized = self._normalize_tool_result(
spec,
str(message.get("tool_call_id") or f"tool_{idx}"),
str(message.get("name") or "tool"),
message.get("content"),
)
if normalized != message.get("content"):
if updated is messages:
updated = [dict(m) for m in messages]
updated[idx]["content"] = normalized
return updated
def _snip_history(
self,
spec: AgentRunSpec,
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
if not messages or not spec.context_window_tokens:
return messages
provider_max_tokens = getattr(getattr(self.provider, "generation", None), "max_tokens", 4096)
max_output = spec.max_tokens if isinstance(spec.max_tokens, int) else (
provider_max_tokens if isinstance(provider_max_tokens, int) else 4096
)
budget = spec.context_block_limit or (
spec.context_window_tokens - max_output - _SNIP_SAFETY_BUFFER
)
if budget <= 0:
return messages
estimate, _ = estimate_prompt_tokens_chain(
self.provider,
spec.model,
messages,
spec.tools.get_definitions(),
)
if estimate <= budget:
return messages
system_messages = [dict(msg) for msg in messages if msg.get("role") == "system"]
non_system = [dict(msg) for msg in messages if msg.get("role") != "system"]
if not non_system:
return messages
system_tokens = sum(estimate_message_tokens(msg) for msg in system_messages)
fixed_tokens, _ = estimate_prompt_tokens_chain(
self.provider,
spec.model,
system_messages,
spec.tools.get_definitions(),
)
remaining_budget = max(0, budget - max(system_tokens, fixed_tokens))
kept: list[dict[str, Any]] = []
kept_tokens = 0
for message in reversed(non_system):
msg_tokens = estimate_message_tokens(message)
if kept and kept_tokens + msg_tokens > remaining_budget:
break
kept.append(message)
kept_tokens += msg_tokens
kept.reverse()
if kept:
for i, message in enumerate(kept):
if message.get("role") == "user":
kept = kept[i:]
break
else:
# Recover nearest user message from outside the kept window;
# GLM rejects system→assistant (error 1214). Budget is
# intentionally exceeded — oversized beats invalid.
for idx in range(len(non_system) - 1, -1, -1):
if non_system[idx].get("role") == "user":
kept = non_system[idx:]
break
# If no user exists at all, _enforce_role_alternation
# will insert a synthetic one as a safety net.
start = find_legal_message_start(kept)
if start:
kept = kept[start:]
if not kept:
kept = non_system[-min(len(non_system), 4) :]
start = find_legal_message_start(kept)
if start:
kept = kept[start:]
return system_messages + kept
def _partition_tool_batches(
self,
spec: AgentRunSpec,
+7 -1
View File
@@ -86,6 +86,7 @@ class SubagentManager:
disabled_skills: list[str] | None = None,
max_iterations: int | None = None,
max_concurrent_subagents: int | None = None,
fail_on_tool_error: bool | None = None,
llm_wall_timeout_for_session: Callable[[str | None], float | None] | None = None,
):
defaults = AgentDefaults()
@@ -107,6 +108,11 @@ class SubagentManager:
if max_concurrent_subagents is not None
else defaults.max_concurrent_subagents
)
self.fail_on_tool_error = (
fail_on_tool_error
if fail_on_tool_error is not None
else defaults.fail_on_tool_error
)
self.runner = AgentRunner(provider)
self._llm_wall_timeout_for_session = llm_wall_timeout_for_session
self._running_tasks: dict[str, asyncio.Task[None]] = {}
@@ -251,7 +257,7 @@ class SubagentManager:
max_iterations_message="Task completed but no final response was generated.",
finalize_on_max_iterations=False,
error_message=None,
fail_on_tool_error=True,
fail_on_tool_error=self.fail_on_tool_error,
checkpoint_callback=_on_checkpoint,
session_key=sess_key,
workspace=root,
+47 -21
View File
@@ -797,31 +797,57 @@ async def connect_mcp_servers(
", ".join(available_wrapped_names) or "(none)",
)
try:
resources_result = await session.list_resources()
for resource in resources_result.resources:
wrapper = MCPResourceWrapper(
session, name, resource, resource_timeout=cfg.tool_timeout
)
registry.register(wrapper)
registered_count += 1
# Only register resources and prompts when no tool restriction is
# active. enabledTools is a per-*tool* allowlist; resources and
# prompts have no equivalent name filter, so they must be skipped
# whenever the operator specified a tool subset. An empty list
# (deny-all) or a list of specific tool names both indicate that
# the operator intended to restrict capabilities — registering
# unrestricted resource/prompt wrappers would violate that intent.
# The default ["*"] (allow-all) means no restriction was intended.
register_extras = allow_all_tools
if register_extras:
try:
resources_result = await session.list_resources()
for resource in resources_result.resources:
wrapper = MCPResourceWrapper(
session, name, resource, resource_timeout=cfg.tool_timeout
)
registry.register(wrapper)
registered_count += 1
logger.debug(
"MCP: registered resource '{}' from server '{}'",
wrapper.name,
name,
)
except Exception as e:
logger.debug(
"MCP: registered resource '{}' from server '{}'", wrapper.name, name
"MCP server '{}': resources not supported or failed: {}", name, e
)
except Exception as e:
logger.debug("MCP server '{}': resources not supported or failed: {}", name, e)
try:
prompts_result = await session.list_prompts()
for prompt in prompts_result.prompts:
wrapper = MCPPromptWrapper(
session, name, prompt, prompt_timeout=cfg.tool_timeout
try:
prompts_result = await session.list_prompts()
for prompt in prompts_result.prompts:
wrapper = MCPPromptWrapper(
session, name, prompt, prompt_timeout=cfg.tool_timeout
)
registry.register(wrapper)
registered_count += 1
logger.debug(
"MCP: registered prompt '{}' from server '{}'",
wrapper.name,
name,
)
except Exception as e:
logger.debug(
"MCP server '{}': prompts not supported or failed: {}", name, e
)
registry.register(wrapper)
registered_count += 1
logger.debug("MCP: registered prompt '{}' from server '{}'", wrapper.name, name)
except Exception as e:
logger.debug("MCP server '{}': prompts not supported or failed: {}", name, e)
else:
logger.info(
"MCP server '{}': skipping resource/prompt registration "
"(enabledTools does not include '*' — only tools allowed)",
name,
)
logger.info(
"MCP server '{}': connected, {} capabilities registered", name, registered_count
+8 -7
View File
@@ -93,8 +93,8 @@ class _PreparedCommand:
nullable=True,
),
login=BooleanSchema(
description="Whether to run bash/zsh with login shell semantics (default true).",
default=True,
description="Whether to run bash/zsh with login shell semantics (default false).",
default=False,
nullable=True,
),
yield_time_ms=IntegerSchema(
@@ -432,7 +432,7 @@ class ExecTool(Tool):
env=env,
timeout=effective_timeout,
shell_program=shell_program,
login=True if login is None else login,
login=False if login is None else login,
)
def _compose_path(self, current_path: str) -> str:
@@ -461,7 +461,7 @@ class ExecTool(Tool):
async def _spawn(
command: str, cwd: str, env: dict[str, str],
shell_program: str | None = None,
login: bool = True,
login: bool = False,
*,
stdin: int = asyncio.subprocess.DEVNULL,
) -> asyncio.subprocess.Process:
@@ -541,8 +541,9 @@ class ExecTool(Tool):
def _build_env(self) -> dict[str, str]:
"""Build a minimal environment for subprocess execution.
On Unix, only HOME/LANG/TERM are passed; ``bash -l`` sources the
user's profile which sets PATH and other essentials.
On Unix, only HOME/LANG/TERM are passed by default. If callers request
``login=True``, bash/zsh may source the user's profile and add PATH or
other variables.
On Windows, ``cmd.exe`` has no login-profile mechanism, so a curated
set of system variables (including PATH) is forwarded. API keys and
@@ -602,7 +603,7 @@ class ExecTool(Tool):
# exempt specific commands (e.g. "rm -rf" inside a build directory)
# from the hardcoded deny list via configuration.
explicitly_allowed = bool(self.allow_patterns) and any(
re.search(p, lower) for p in self.allow_patterns
re.fullmatch(p, lower) for p in self.allow_patterns
)
if not explicitly_allowed:
for pattern in self.deny_patterns:
+18
View File
@@ -36,6 +36,24 @@ _VOLCENGINE_TIME_RANGES = {"OneDay", "OneWeek", "OneMonth", "OneYear"}
_VOLCENGINE_DATE_RANGE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}\.\.\d{4}-\d{2}-\d{2}$")
# Single source of truth for selectable search providers (CLI wizard + WebUI).
# "credential" describes what each provider needs: none / api_key / base_url /
# optional_api_key.
SEARCH_PROVIDER_OPTIONS: tuple[dict[str, str], ...] = (
{"name": "duckduckgo", "label": "DuckDuckGo", "credential": "none"},
{"name": "brave", "label": "Brave Search", "credential": "api_key"},
{"name": "tavily", "label": "Tavily", "credential": "api_key"},
{"name": "searxng", "label": "SearXNG", "credential": "base_url"},
{"name": "jina", "label": "Jina", "credential": "api_key"},
{"name": "kagi", "label": "Kagi", "credential": "api_key"},
{"name": "exa", "label": "Exa", "credential": "api_key"},
{"name": "olostep", "label": "Olostep", "credential": "api_key"},
{"name": "bocha", "label": "Bocha", "credential": "api_key"},
{"name": "volcengine", "label": "Volcengine Search", "credential": "api_key"},
{"name": "keenable", "label": "Keenable", "credential": "optional_api_key"},
)
class WebSearchConfig(Base):
"""Web search configuration."""
provider: str = "duckduckgo"
+20 -6
View File
@@ -94,11 +94,23 @@ class NanobotDingTalkHandler(CallbackHandler):
for item in rich_list:
if not isinstance(item, dict):
continue
if item.get("type") == "text":
t = item.get("text", "").strip()
if t:
content = (content + " " + t).strip() if content else t
elif item.get("downloadCode"):
# A rich-text item may carry text and/or a downloadCode; the
# DingTalk SDK treats them independently, so handle both.
t = item.get("text", "").strip()
if t:
fmt = item.get("type", "")
if fmt == "bold":
formatted = f"**{t}**"
elif fmt == "italic":
formatted = f"*{t}*"
elif fmt == "inlineCode":
formatted = f"`{t}`"
elif fmt == "pre":
formatted = f"```\n{t}\n```"
else:
formatted = t
content = (content + " " + formatted).strip() if content else formatted
if item.get("downloadCode"):
dc = item["downloadCode"]
fname = item.get("fileName") or "file"
sender_uid = chatbot_msg.sender_staff_id or chatbot_msg.sender_id or "unknown"
@@ -214,7 +226,9 @@ class DingTalkChannel(BaseChannel):
return
self._running = True
self._http = httpx.AsyncClient()
self._http = httpx.AsyncClient(
timeout=httpx.Timeout(10.0, connect=10.0, read=30.0, write=30.0, pool=10.0)
)
self.logger.info(
"Initializing Stream Client with Client ID: {}...",
+2
View File
@@ -199,6 +199,8 @@ class EmailChannel(BaseChannel):
except Exception:
self.logger.exception("Polling error")
if not self._running:
break
await asyncio.sleep(poll_seconds)
async def stop(self) -> None:
+4 -1
View File
@@ -351,6 +351,8 @@ class TelegramConfig(Base):
streaming: bool = True
# Enable inline keyboard buttons in Telegram messages.
inline_keyboards: bool = False
# Opt in to Bot API 10.1 sendRichMessage for richer markdown rendering.
rich_messages: bool = False
stream_edit_interval: float = Field(default=_STREAM_EDIT_INTERVAL_DEFAULT, ge=0.1)
webhook_url: str = ""
webhook_listen_host: str = "127.0.0.1"
@@ -803,6 +805,7 @@ class TelegramChannel(BaseChannel):
# latches off permanently if the server doesn't support it.
if (
not render_as_blockquote
and self.config.rich_messages
and not getattr(self, "_rich_send_disabled", False)
):
rich_ok = await self._try_send_rich(
@@ -911,7 +914,7 @@ class TelegramChannel(BaseChannel):
# Skip when a streaming preview already exists to avoid the
# delete-and-resend pattern that causes flickering and drops
# line breaks (issue #4470).
if not buf.message_id and not getattr(self, "_rich_send_disabled", False):
if not buf.message_id and self.config.rich_messages and not getattr(self, "_rich_send_disabled", False):
reply_params = None
if reply_to_message_id := meta.get("message_id"):
reply_params = {"message_id": int(reply_to_message_id), "allow_sending_without_reply": True}
File diff suppressed because it is too large Load Diff
+7
View File
@@ -154,6 +154,12 @@ def _install_gateway_shutdown_handlers(
return restore
def _advance_dream_cursor_if_behind(memory: Any) -> None:
latest = memory.get_latest_cursor()
if memory.get_last_dream_cursor() < latest:
memory.set_last_dream_cursor(latest)
class SafeFileHistory(FileHistory):
"""FileHistory subclass that sanitizes surrogate characters on write.
@@ -1165,6 +1171,7 @@ def _run_gateway(
console.print(f"[green]✓[/green] Dream: {dream_cfg.describe_schedule()}")
else:
console.print("[yellow]○[/yellow] Dream: disabled")
_advance_dream_cursor_if_behind(agent.context.memory)
# Register Heartbeat system job (idempotent on restart)
if hb_cfg.enabled:
+35 -7
View File
@@ -762,13 +762,11 @@ def _handle_model_preset_field(
setattr(working_model, field_name, new_value)
def _handle_provider_field(
working_model: BaseModel, field_name: str, field_display: str, current_value: Any
def _set_field_from_choices(
working_model: BaseModel, field_name: str, field_display: str,
choices: list[str], default_choice: str
) -> None:
"""Handle the 'provider' field with a list of registered providers."""
provider_names = sorted(_get_provider_names().keys())
choices = ["auto"] + provider_names
default_choice = str(current_value) if current_value else "auto"
"""Prompt to pick one of ``choices`` and set the field (no-op on back/cancel)."""
new_value = _select_with_back(field_display, choices, default=default_choice)
if new_value is _BACK_PRESSED:
return
@@ -776,6 +774,15 @@ def _handle_provider_field(
setattr(working_model, field_name, new_value)
def _handle_provider_field(
working_model: BaseModel, field_name: str, field_display: str, current_value: Any
) -> None:
"""Handle the 'provider' field with a list of registered LLM providers."""
choices = ["auto"] + sorted(_get_provider_names().keys())
default_choice = str(current_value) if current_value else "auto"
_set_field_from_choices(working_model, field_name, field_display, choices, default_choice)
def _handle_fallback_models_field(
working_model: BaseModel, field_name: str, field_display: str, current_value: Any
) -> None:
@@ -836,6 +843,17 @@ def _handle_fallback_models_field(
items.clear()
def _handle_search_provider_field(
working_model: BaseModel, field_name: str, field_display: str, current_value: Any
) -> None:
"""Handle the web-search 'provider' field with the search-engine list."""
from nanobot.agent.tools.web import SEARCH_PROVIDER_OPTIONS
choices = [opt["name"] for opt in SEARCH_PROVIDER_OPTIONS]
default_choice = current_value if current_value in choices else choices[0]
_set_field_from_choices(working_model, field_name, field_display, choices, default_choice)
_FIELD_HANDLERS: dict[str, Any] = {
"model": _handle_model_field,
"context_window_tokens": _handle_context_window_field,
@@ -845,6 +863,16 @@ _FIELD_HANDLERS: dict[str, Any] = {
}
def _resolve_field_handler(model: BaseModel, field_name: str) -> Any:
"""Resolve the handler for a field. WebSearchConfig shares the bare "provider"
name with LLM configs but needs the search-engine picker, not the LLM list."""
if field_name == "provider":
from nanobot.agent.tools.web import WebSearchConfig
if isinstance(model, WebSearchConfig):
return _handle_search_provider_field
return _FIELD_HANDLERS.get(field_name)
def _is_str_or_none(annotation: Any) -> bool:
"""Check whether a field annotation is ``str | None`` (or ``Optional[str]``)."""
origin = get_origin(annotation)
@@ -934,7 +962,7 @@ def _configure_pydantic_model(
continue
# Registered special-field handlers
handler = _FIELD_HANDLERS.get(field_name)
handler = _resolve_field_handler(working_model, field_name)
if handler:
handler(working_model, field_name, field_display, current_value)
continue
-2
View File
@@ -2,7 +2,6 @@
from nanobot.config.loader import get_config_path, load_config
from nanobot.config.paths import (
get_bridge_install_dir,
get_cli_history_path,
get_cron_dir,
get_data_dir,
@@ -29,6 +28,5 @@ __all__ = [
"get_workspace_path",
"is_default_workspace",
"get_cli_history_path",
"get_bridge_install_dir",
"get_legacy_sessions_dir",
]
-5
View File
@@ -66,11 +66,6 @@ def get_cli_history_path() -> Path:
return Path.home() / ".nanobot" / "history" / "cli_history"
def get_bridge_install_dir() -> Path:
"""Return the shared WhatsApp bridge installation directory."""
return Path.home() / ".nanobot" / "bridge"
def get_legacy_sessions_dir() -> Path:
"""Return the legacy global session directory used for migration fallback."""
return Path.home() / ".nanobot" / "sessions"
+27 -3
View File
@@ -2,9 +2,9 @@
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
from typing import TYPE_CHECKING, Any, ClassVar, Literal
from pydantic import AliasChoices, ConfigDict, Field, model_validator
from pydantic import AliasChoices, ConfigDict, Field, field_validator, model_validator
from pydantic_settings import BaseSettings
from nanobot.config_base import Base
@@ -132,6 +132,7 @@ class AgentDefaults(Base):
fallback_models: list[FallbackCandidate] = Field(default_factory=list)
max_tool_iterations: int = 200
max_concurrent_subagents: int = Field(default=1, ge=1)
fail_on_tool_error: bool = True
max_tool_result_chars: int = 16_000
provider_retry_mode: Literal["standard", "persistent"] = "standard"
tool_hint_max_length: int = Field(
@@ -182,6 +183,29 @@ class ProviderConfig(Base):
extra_headers: dict[str, str] | None = None # Custom headers (e.g. APP-Code for AiHubMix)
extra_body: dict[str, Any] | None = None # Extra provider request fields; shape depends on provider/API surface
extra_query: dict[str, str] | None = None # Extra query params (e.g. api-version for Azure-style gateways)
thinking_style: str | None = None # Thinking/reasoning style for custom providers
# Valid values mirror the keys of _THINKING_STYLE_MAP in
# nanobot/providers/openai_compat_provider.py. Kept duplicated here to
# avoid an import cycle (schema.py must not import from providers/).
_VALID_THINKING_STYLES: ClassVar[tuple[str, ...]] = (
"thinking_type",
"enable_thinking",
"reasoning_split",
)
@field_validator("thinking_style")
@classmethod
def _validate_thinking_style(cls, v: str | None) -> str | None:
if not v: # None or "" -> no injection, valid (backwards compatible)
return v
if v not in cls._VALID_THINKING_STYLES:
raise ValueError(
f"Invalid thinking_style {v!r}. "
f"Must be one of: {', '.join(repr(s) for s in cls._VALID_THINKING_STYLES)} "
f"(or empty/omitted)."
)
return v
class BedrockProviderConfig(ProviderConfig):
@@ -307,7 +331,7 @@ class MCPServerConfig(Base):
url: str = "" # HTTP/SSE: endpoint URL
headers: dict[str, str] = Field(default_factory=dict) # HTTP/SSE: custom headers
tool_timeout: int = 30 # seconds before a tool call is cancelled
enabled_tools: list[str] = Field(default_factory=lambda: ["*"]) # Only register these tools; accepts raw MCP names or wrapped mcp_<server>_<tool> names; ["*"] = all tools; [] = no tools
enabled_tools: list[str] = Field(default_factory=lambda: ["*"]) # Only register these tools; accepts raw MCP names or wrapped mcp_<server>_<tool> names; ["*"] = all capabilities (tools, resources, prompts); any restriction = only listed tools, no resources/prompts
def _lazy_default(module_path: str, class_name: str) -> Any:
+1 -1
View File
@@ -54,7 +54,7 @@ def _make_provider_core(
if provider_name and not spec and p:
if not p.api_base:
raise ValueError(f"Provider '{provider_name}' requires api_base in config.")
spec = create_dynamic_spec(provider_name)
spec = create_dynamic_spec(provider_name, thinking_style=(p.thinking_style or "") if p else "")
if spec and spec.is_transcription_only:
raise ValueError(f"Provider '{provider_name}' only supports transcription.")
backend = spec.backend if spec else "openai_compat"
+2 -1
View File
@@ -628,7 +628,7 @@ def find_by_name(name: str) -> ProviderSpec | None:
return None
def create_dynamic_spec(name: str) -> ProviderSpec:
def create_dynamic_spec(name: str, *, thinking_style: str = "") -> ProviderSpec:
"""Create a dynamic ProviderSpec for custom user-defined providers."""
normalized = to_snake(name.replace("-", "_"))
strip_prefixes = tuple(dict.fromkeys((name, normalized)))
@@ -640,4 +640,5 @@ def create_dynamic_spec(name: str) -> ProviderSpec:
backend="openai_compat",
is_direct=True,
strip_model_prefixes=strip_prefixes,
thinking_style=thinking_style,
)
-22
View File
@@ -118,25 +118,6 @@ class Session:
):
self.last_consolidated = 0
@staticmethod
def _annotate_message_time(message: dict[str, Any], content: Any) -> Any:
"""Expose persisted turn timestamps to the model for relative-date reasoning.
Annotating *every* assistant turn trains the model (via in-context
demonstrations) to start its own replies with the same
``[Message Time: ...]`` prefix, which leaks metadata back to the user.
We therefore only annotate user turns. User-side stamps are enough to
pin adjacent assistant replies for relative-time reasoning, including
proactive messages the user replies to later.
"""
timestamp = message.get("timestamp")
if not timestamp or not isinstance(content, str):
return content
role = message.get("role")
if role != "user":
return content
return f"[Message Time: {timestamp}]\n{content}"
def add_message(self, role: str, content: str, **kwargs: Any) -> None:
"""Add a message to the session."""
msg = {
@@ -153,7 +134,6 @@ class Session:
max_messages: int = 120,
*,
max_tokens: int = 0,
include_timestamps: bool = False,
extend_to_user: bool = False,
) -> list[dict[str, Any]]:
"""Return unconsolidated messages for LLM input.
@@ -243,8 +223,6 @@ class Session:
if mcp_lines:
breadcrumbs = "\n".join(mcp_lines)
content = f"{content}\n{breadcrumbs}" if content else breadcrumbs
if include_timestamps:
content = self._annotate_message_time(message, content)
if role == "assistant" and isinstance(content, str) and not content.strip():
if not any(key in message for key in ("tool_calls", "reasoning_content", "thinking_blocks")):
continue
+3 -1
View File
@@ -5,7 +5,9 @@ description: Schedule reminders and recurring tasks.
# Cron
Use the `cron` tool to schedule reminders or recurring tasks.
Use the `cron` tool to schedule reminders or recurring tasks that should report back to the originating chat/session when they run.
Do not use `cron` for periodic background checks that should stay quiet when there is nothing useful to report. For those, update `HEARTBEAT.md`; the protected heartbeat job runs those checks and only delivers results that pass the notification gate.
## Three Modes
+2 -1
View File
@@ -9,6 +9,7 @@ Use this file for project-specific preferences, recurring workflow conventions,
- Before scheduling reminders, check available skills and follow skill guidance first.
- Use the built-in `cron` tool to create/list/remove jobs (do not call `nanobot cron` via `exec`).
- Get USER_ID and CHANNEL from the current session (e.g., `8281248569` and `telegram` from `telegram:8281248569`).
- Cron jobs run as scheduled turns in the origin chat/session and normally deliver the result back to that channel. Do not use cron for background checks that should stay silent when there is nothing useful to report; use `HEARTBEAT.md` instead.
**Do NOT just write reminders to MEMORY.md** — that won't trigger actual notifications.
@@ -20,4 +21,4 @@ Use this file for project-specific preferences, recurring workflow conventions,
- Use `edit_file` only for small exact replacements copied from the current `HEARTBEAT.md`.
- Use `write_file` for first creation or intentional full-file rewrites.
When the user asks for a recurring/periodic heartbeat task, update `HEARTBEAT.md` instead of creating a one-time reminder. Use the built-in `cron` tool for separate reminders or custom schedules that should not be part of the heartbeat task list.
When the user asks for a recurring/periodic heartbeat task, or for a periodic background check that should only notify on actionable changes, update `HEARTBEAT.md` instead of creating a one-time reminder. Use the built-in `cron` tool for explicit reminders, scheduled tasks that should report every run, or custom schedules that should not be part of the heartbeat task list.
+3 -1
View File
@@ -3,7 +3,9 @@
<!--
This file is checked periodically by your nanobot agent. When nanobot gateway starts with gateway.heartbeat.enabled=true, it automatically registers a protected heartbeat cron job that reads this file.
If this file has no tasks (only headers and comments), the agent will skip it. Completed tasks should be deleted, not kept — heartbeat only reads "Active Tasks".
Use this file for recurring background checks that should stay quiet unless there is something useful to report. Regular cron jobs are different: they normally deliver each run's result back to the chat/session where they were created.
If this file has no tasks (only headers and comments), the agent will skip it. Completed tasks should be deleted, not kept - heartbeat only reads "Active Tasks".
-->
## Active Tasks
+4 -15
View File
@@ -16,6 +16,7 @@ from zoneinfo import ZoneInfo
import httpx
from nanobot import __version__
from nanobot.agent.tools.web import SEARCH_PROVIDER_OPTIONS
from nanobot.audio.transcription import resolve_transcription_config
from nanobot.audio.transcription_registry import (
resolve_transcription_provider,
@@ -79,19 +80,7 @@ _NATIVE_RESTART_BEHAVIOR_BY_SECTION = {
"apps": "engineRestart",
}
_WEB_SEARCH_PROVIDER_OPTIONS: tuple[dict[str, str], ...] = (
{"name": "duckduckgo", "label": "DuckDuckGo", "credential": "none"},
{"name": "brave", "label": "Brave Search", "credential": "api_key"},
{"name": "tavily", "label": "Tavily", "credential": "api_key"},
{"name": "searxng", "label": "SearXNG", "credential": "base_url"},
{"name": "jina", "label": "Jina", "credential": "api_key"},
{"name": "kagi", "label": "Kagi", "credential": "api_key"},
{"name": "exa", "label": "Exa", "credential": "api_key"},
{"name": "olostep", "label": "Olostep", "credential": "api_key"},
{"name": "bocha", "label": "Bocha", "credential": "api_key"},
{"name": "volcengine", "label": "Volcengine Search", "credential": "api_key"},
{"name": "keenable", "label": "Keenable", "credential": "optional_api_key"},
)
_WEB_SEARCH_PROVIDER_OPTIONS = SEARCH_PROVIDER_OPTIONS
_WEB_SEARCH_PROVIDER_BY_NAME = {
provider["name"]: provider for provider in _WEB_SEARCH_PROVIDER_OPTIONS
}
@@ -370,7 +359,7 @@ def _resolve_settings_provider(
normalized = provider_name.replace("-", "_")
for extra_name, provider_config in _dynamic_provider_items(config):
if provider_name == extra_name or normalized == extra_name.replace("-", "_"):
return create_dynamic_spec(extra_name), extra_name, provider_config
return create_dynamic_spec(extra_name, thinking_style=(provider_config.thinking_style or "")), extra_name, provider_config
return None
@@ -750,7 +739,7 @@ def settings_payload(
providers.append(
_provider_settings_row(
provider_key,
create_dynamic_spec(provider_key),
create_dynamic_spec(provider_key, thinking_style=(provider_config.thinking_style or "")),
provider_config,
)
)
+5 -4
View File
@@ -93,6 +93,10 @@ matrix = [
discord = [
"discord.py>=2.5.2,<3.0.0",
]
whatsapp = [
"neonize>=0.3.18.post0,<0.4.0",
"segno>=1.6.1,<2.0.0",
]
langsmith = [
"langsmith>=0.1.0",
]
@@ -150,14 +154,10 @@ packages = ["nanobot"]
[tool.hatch.build.targets.wheel.sources]
"nanobot" = "nanobot"
[tool.hatch.build.targets.wheel.force-include]
"bridge" = "nanobot/bridge"
[tool.hatch.build.targets.sdist]
include = [
"nanobot/",
"nanobot/web/dist/",
"bridge/",
"hatch_build.py",
"README.md",
"LICENSE",
@@ -182,6 +182,7 @@ source = ["nanobot"]
omit = ["tests/*", "**/tests/*"]
[tool.coverage.report]
fail_under = 75
exclude_lines = [
"pragma: no cover",
"def __repr__",
+1 -1
View File
@@ -223,7 +223,7 @@ class TestAgentLoopTTLParam:
kwargs = session.get_history.call_args.kwargs
assert isinstance(kwargs.get("max_tokens"), int)
assert kwargs["max_tokens"] > 0
assert kwargs["include_timestamps"] is True
assert set(kwargs) == {"max_messages", "max_tokens", "extend_to_user"}
@pytest.mark.asyncio
async def test_session_file_cap_archives_and_trims_old_messages(self, tmp_path):
+3 -5
View File
@@ -1222,11 +1222,9 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
non_system = [m for m in seen["initial_messages"] if m.get("role") != "system"]
assert "question" in non_system[0]["content"]
assert "working" in non_system[1]["content"]
# User turns carry the timestamp prefix so the model can reason about
# relative time. Assistant turns do NOT, otherwise the model treats those
# past replies as in-context examples and starts its own outputs with
# ``[Message Time: ...]`` (which then leaks back to the user).
assert "[Message Time:" in non_system[0]["content"]
# Persisted timestamps stay in session records, but replay content is not
# rewritten with volatile ``[Message Time: ...]`` prefixes.
assert "[Message Time:" not in non_system[0]["content"]
assert "[Message Time:" not in non_system[1]["content"]
assert non_system[2]["content"].count("subagent result") == 1
assert "Current Time:" in non_system[2]["content"]
+21
View File
@@ -330,6 +330,27 @@ class TestDreamCursor:
def test_initial_cursor_is_zero(self, store):
assert store.get_last_dream_cursor() == 0
def test_returns_zero_when_empty(self, store):
assert store.get_latest_cursor() == 0
def test_returns_cursor_of_last_entry(self, store):
store.append_history("event 1")
store.append_history("event 2")
store.append_history("event 3")
assert store.get_latest_cursor() == 3
def test_returns_zero_when_no_entries(self, store):
store.history_file.write_text("", encoding="utf-8")
assert store.get_latest_cursor() == 0
def test_matches_next_cursor_minus_one(self, store):
store.append_history("event 1")
store.append_history("event 2")
assert store.get_latest_cursor() == max(store._next_cursor() - 1, 0)
def test_set_and_get_cursor(self, store):
store.set_last_dream_cursor(5)
assert store.get_last_dream_cursor() == 5
+24
View File
@@ -1998,3 +1998,27 @@ class TestModelPresetWizard:
defaults = AgentDefaults()
_handle_provider_field(defaults, "provider", "Provider", "auto")
assert defaults.provider == "anthropic"
def test_search_provider_field_handler(self, monkeypatch):
"""_handle_search_provider_field should set the search engine from choices."""
from nanobot.agent.tools.web import WebSearchConfig
from nanobot.cli.onboard import _handle_search_provider_field
monkeypatch.setattr(onboard_wizard, "_select_with_back", lambda *a, **kw: "keenable")
cfg = WebSearchConfig()
_handle_search_provider_field(cfg, "provider", "Provider", "duckduckgo")
assert cfg.provider == "keenable"
def test_provider_field_dispatch_is_model_type_aware(self):
"""WebSearchConfig.provider must not be hijacked by the LLM provider handler."""
from nanobot.agent.tools.web import WebSearchConfig
from nanobot.cli.onboard import (
_handle_provider_field,
_handle_search_provider_field,
_resolve_field_handler,
)
from nanobot.config.schema import AgentDefaults
assert _resolve_field_handler(WebSearchConfig(), "provider") is _handle_search_provider_field
assert _resolve_field_handler(AgentDefaults(), "provider") is _handle_provider_field
+295 -113
View File
@@ -2,16 +2,45 @@
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from nanobot.agent.context_governance import (
BACKFILL_CONTENT,
MICROCOMPACT_KEEP_RECENT,
ContextGovernanceConfig,
ContextGovernor,
)
from nanobot.agent.runner import AgentRunSpec
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMResponse, ToolCallRequest
from nanobot.providers.base import LLMResponse
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
def _governance_config(
provider,
tools,
spec: AgentRunSpec,
*,
inflight_start_index: int = 0,
) -> ContextGovernanceConfig:
return ContextGovernanceConfig(
provider=provider,
model=spec.model,
tools=tools,
workspace=spec.workspace,
session_key=spec.session_key,
max_tool_result_chars=spec.max_tool_result_chars,
context_window_tokens=spec.context_window_tokens,
context_block_limit=spec.context_block_limit,
max_tokens=spec.max_tokens,
inflight_start_index=inflight_start_index,
)
def _make_loop(tmp_path):
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
@@ -22,13 +51,14 @@ def _make_loop(tmp_path):
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SubagentManager") as MockSubMgr:
MockSubMgr.return_value.cancel_by_session = AsyncMock(return_value=0)
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path)
return loop
async def test_runner_uses_raw_messages_when_context_governance_fails():
from nanobot.agent.runner import AgentRunSpec, AgentRunner
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
captured_messages: list[dict] = []
@@ -46,7 +76,9 @@ async def test_runner_uses_raw_messages_when_context_governance_fails():
]
runner = AgentRunner(provider)
runner._snip_history = MagicMock(side_effect=RuntimeError("boom")) # type: ignore[method-assign]
runner.context_governor.prepare_for_model = MagicMock( # type: ignore[method-assign]
side_effect=RuntimeError("boom")
)
result = await runner.run(AgentRunSpec(
initial_messages=initial_messages,
tools=tools,
@@ -57,13 +89,12 @@ async def test_runner_uses_raw_messages_when_context_governance_fails():
assert result.final_content == "done"
assert captured_messages == initial_messages
def test_snip_history_drops_orphaned_tool_results_from_trimmed_slice(monkeypatch):
from nanobot.agent.runner import AgentRunSpec, AgentRunner
def test_snip_history_drops_orphaned_tool_results_from_trimmed_slice(monkeypatch):
provider = MagicMock()
tools = MagicMock()
tools.get_definitions.return_value = []
runner = AgentRunner(provider)
messages = [
{"role": "system", "content": "system"},
{"role": "user", "content": "old user"},
@@ -85,7 +116,10 @@ def test_snip_history_drops_orphaned_tool_results_from_trimmed_slice(monkeypatch
context_block_limit=100,
)
monkeypatch.setattr("nanobot.agent.runner.estimate_prompt_tokens_chain", lambda *_args, **_kwargs: (500, None))
monkeypatch.setattr(
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
lambda *_args, **_kwargs: (500, None),
)
token_sizes = {
"old user": 120,
"tool call": 120,
@@ -94,11 +128,11 @@ def test_snip_history_drops_orphaned_tool_results_from_trimmed_slice(monkeypatch
"system": 0,
}
monkeypatch.setattr(
"nanobot.agent.runner.estimate_message_tokens",
"nanobot.agent.context_governance.estimate_message_tokens",
lambda msg: token_sizes.get(str(msg.get("content")), 40),
)
trimmed = runner._snip_history(spec, messages)
trimmed = ContextGovernor().snip_history(_governance_config(provider, tools, spec), messages)
# After the fix, the user message is recovered so the sequence is valid
# for providers that require system → user (e.g. GLM error 1214).
@@ -108,12 +142,9 @@ def test_snip_history_drops_orphaned_tool_results_from_trimmed_slice(monkeypatch
def test_snip_history_reserves_budget_for_tool_definitions(monkeypatch):
from nanobot.agent.runner import AgentRunSpec, AgentRunner
provider = MagicMock()
tools = MagicMock()
tools.get_definitions.return_value = [{"type": "function", "function": {"name": "large_tool"}}]
runner = AgentRunner(provider)
messages = [
{"role": "system", "content": "system"},
{"role": "user", "content": "old user"},
@@ -139,7 +170,7 @@ def test_snip_history_reserves_budget_for_tool_definitions(monkeypatch):
assert estimate_tools == tools.get_definitions.return_value
return 350, None
monkeypatch.setattr("nanobot.agent.runner.estimate_prompt_tokens_chain", _estimate)
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", _estimate)
token_sizes = {
"system": 50,
"old user": 200,
@@ -149,11 +180,11 @@ def test_snip_history_reserves_budget_for_tool_definitions(monkeypatch):
"recent two": 200,
}
monkeypatch.setattr(
"nanobot.agent.runner.estimate_message_tokens",
"nanobot.agent.context_governance.estimate_message_tokens",
lambda msg: token_sizes.get(str(msg.get("content")), 40),
)
trimmed = runner._snip_history(spec, messages)
trimmed = ContextGovernor().snip_history(_governance_config(provider, tools, spec), messages)
contents = [message.get("content") for message in trimmed]
assert contents == ["system", "recent two"]
@@ -161,7 +192,6 @@ def test_snip_history_reserves_budget_for_tool_definitions(monkeypatch):
async def test_backfill_missing_tool_results_inserts_error():
"""Orphaned tool_use (no matching tool_result) should get a synthetic error."""
from nanobot.agent.runner import AgentRunner, _BACKFILL_CONTENT
messages = [
{"role": "user", "content": "hi"},
@@ -175,18 +205,16 @@ async def test_backfill_missing_tool_results_inserts_error():
},
{"role": "tool", "tool_call_id": "call_a", "name": "exec", "content": "ok"},
]
result = AgentRunner._backfill_missing_tool_results(messages)
result = ContextGovernor.backfill_missing_tool_results(messages)
tool_msgs = [m for m in result if m.get("role") == "tool"]
assert len(tool_msgs) == 2
backfilled = [m for m in tool_msgs if m.get("tool_call_id") == "call_b"]
assert len(backfilled) == 1
assert backfilled[0]["content"] == _BACKFILL_CONTENT
assert backfilled[0]["content"] == BACKFILL_CONTENT
assert backfilled[0]["name"] == "read_file"
def test_drop_orphan_tool_results_removes_unmatched_tool_messages():
from nanobot.agent.runner import AgentRunner
messages = [
{"role": "system", "content": "system"},
{"role": "user", "content": "old user"},
@@ -202,7 +230,7 @@ def test_drop_orphan_tool_results_removes_unmatched_tool_messages():
{"role": "assistant", "content": "after tool"},
]
cleaned = AgentRunner._drop_orphan_tool_results(messages)
cleaned = ContextGovernor.drop_orphan_tool_results(messages)
assert cleaned == [
{"role": "system", "content": "system"},
@@ -222,8 +250,6 @@ def test_drop_orphan_tool_results_removes_unmatched_tool_messages():
@pytest.mark.asyncio
async def test_backfill_noop_when_complete():
"""Complete message chains should not be modified."""
from nanobot.agent.runner import AgentRunner
messages = [
{"role": "user", "content": "hi"},
{
@@ -236,13 +262,13 @@ async def test_backfill_noop_when_complete():
{"role": "tool", "tool_call_id": "call_x", "name": "exec", "content": "done"},
{"role": "assistant", "content": "all good"},
]
result = AgentRunner._backfill_missing_tool_results(messages)
result = ContextGovernor.backfill_missing_tool_results(messages)
assert result is messages # same object — no copy
@pytest.mark.asyncio
async def test_runner_drops_orphan_tool_results_before_model_request():
from nanobot.agent.runner import AgentRunSpec, AgentRunner
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
captured_messages: list[dict] = []
@@ -283,7 +309,6 @@ async def test_runner_drops_orphan_tool_results_before_model_request():
async def test_backfill_repairs_model_context_without_shifting_save_turn_boundary(tmp_path):
"""Historical backfill should not duplicate old tail messages on persist."""
from nanobot.agent.loop import AgentLoop
from nanobot.agent.runner import _BACKFILL_CONTENT
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
@@ -335,7 +360,7 @@ async def test_backfill_repairs_model_context_without_shifting_save_turn_boundar
if message.get("role") == "tool" and message.get("tool_call_id") == "call_missing"
]
assert len(synthetic) == 1
assert synthetic[0]["content"] == _BACKFILL_CONTENT
assert synthetic[0]["content"] == BACKFILL_CONTENT
session_after = loop.sessions.get_or_create("cli:test")
assert [
@@ -367,7 +392,7 @@ async def test_backfill_repairs_model_context_without_shifting_save_turn_boundar
@pytest.mark.asyncio
async def test_runner_backfill_only_mutates_model_context_not_returned_messages():
"""Runner should repair orphaned tool calls for the model without rewriting result.messages."""
from nanobot.agent.runner import AgentRunSpec, AgentRunner, _BACKFILL_CONTENT
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
captured_messages: list[dict] = []
@@ -413,7 +438,7 @@ async def test_runner_backfill_only_mutates_model_context_not_returned_messages(
if message.get("role") == "tool" and message.get("tool_call_id") == "call_missing"
]
assert len(synthetic) == 1
assert synthetic[0]["content"] == _BACKFILL_CONTENT
assert synthetic[0]["content"] == BACKFILL_CONTENT
assert [
{
@@ -447,96 +472,254 @@ async def test_runner_backfill_only_mutates_model_context_not_returned_messages(
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_microcompact_replaces_old_tool_results():
"""Tool results beyond _MICROCOMPACT_KEEP_RECENT should be summarized."""
from nanobot.agent.runner import AgentRunner, _MICROCOMPACT_KEEP_RECENT
total = _MICROCOMPACT_KEEP_RECENT + 5
long_content = "x" * 600
def _microcompact_messages(*, total: int, tool_name: str, content: str) -> list[dict]:
messages: list[dict] = [{"role": "system", "content": "sys"}]
for i in range(total):
messages.append({
"role": "assistant",
"content": "",
"tool_calls": [{"id": f"c{i}", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}],
"tool_calls": [{
"id": f"c{i}",
"type": "function",
"function": {"name": tool_name, "arguments": "{}"},
}],
})
messages.append({
"role": "tool", "tool_call_id": f"c{i}", "name": "read_file",
"content": long_content,
"role": "tool",
"tool_call_id": f"c{i}",
"name": tool_name,
"content": content,
})
return messages
result = AgentRunner._microcompact(messages)
def test_microcompact_skips_when_prompt_under_hard_budget(monkeypatch):
"""Cache-friendly path: in-flight tool results stay stable while prompt fits."""
provider = MagicMock()
provider.generation = SimpleNamespace(max_tokens=0)
tools = MagicMock()
tools.get_definitions.return_value = []
total = MICROCOMPACT_KEEP_RECENT + 5
long_content = "x" * 600
messages = _microcompact_messages(total=total, tool_name="read_file", content=long_content)
spec = AgentRunSpec(
initial_messages=messages,
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
max_tokens=0,
context_window_tokens=20_000,
)
monkeypatch.setattr(
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
lambda *_args, **_kwargs: (1000, "test"),
)
result = ContextGovernor().compact_inflight_overflow(
_governance_config(provider, tools, spec),
messages,
set(),
)
assert result is messages
def test_microcompact_overflow_compacts_to_low_watermark(monkeypatch):
"""Overflow path: compact in-flight stale results with headroom for later calls."""
provider = MagicMock()
provider.generation = SimpleNamespace(max_tokens=0)
tools = MagicMock()
tools.get_definitions.return_value = []
total = MICROCOMPACT_KEEP_RECENT + 8
long_content = "x" * 600
messages = _microcompact_messages(total=total, tool_name="read_file", content=long_content)
spec = AgentRunSpec(
initial_messages=messages,
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
max_tokens=0,
context_window_tokens=2224, # input budget 1200, low target 1020
)
def estimate(_provider, _model, msgs, _tools):
return sum(
100 if (content := msg.get("content")) == long_content
else 1 if isinstance(content, str) and "omitted from context" in content
else 0
for msg in msgs
if msg.get("role") == "tool"
), "test"
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate)
result = ContextGovernor().compact_inflight_overflow(
_governance_config(provider, tools, spec),
messages,
set(),
)
tool_msgs = [m for m in result if m.get("role") == "tool"]
stale_count = total - _MICROCOMPACT_KEEP_RECENT
compacted = [m for m in tool_msgs if "omitted from context" in str(m.get("content", ""))]
preserved = [m for m in tool_msgs if m.get("content") == long_content]
assert len(compacted) == stale_count
assert len(preserved) == _MICROCOMPACT_KEEP_RECENT
assert len(compacted) == 8
assert len(preserved) == total - 8
assert [m["tool_call_id"] for m in compacted] == [f"c{i}" for i in range(8)]
@pytest.mark.asyncio
async def test_microcompact_preserves_short_results():
"""Short tool results (< _MICROCOMPACT_MIN_CHARS) should not be replaced."""
from nanobot.agent.runner import AgentRunner, _MICROCOMPACT_KEEP_RECENT
def test_microcompact_compacts_newest_when_it_alone_overflows(monkeypatch):
"""The newest result is preserved only while the request can still fit."""
provider = MagicMock()
provider.generation = SimpleNamespace(max_tokens=0)
tools = MagicMock()
tools.get_definitions.return_value = []
total = _MICROCOMPACT_KEEP_RECENT + 5
messages: list[dict] = []
for i in range(total):
messages.append({
"role": "assistant",
"content": "",
"tool_calls": [{"id": f"c{i}", "type": "function", "function": {"name": "exec", "arguments": "{}"}}],
})
messages.append({
"role": "tool", "tool_call_id": f"c{i}", "name": "exec",
"content": "short",
})
long_content = "x" * 600
messages = _microcompact_messages(total=1, tool_name="read_file", content=long_content)
spec = AgentRunSpec(
initial_messages=messages,
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
max_tokens=0,
context_window_tokens=2000,
context_block_limit=500,
)
result = AgentRunner._microcompact(messages)
def estimate(_provider, _model, msgs, _tools):
return sum(
1000 if msg.get("content") == long_content else 1
for msg in msgs
if msg.get("role") == "tool"
), "test"
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate)
compacted_tool_call_ids: set[str] = set()
result = ContextGovernor().compact_inflight_overflow(
_governance_config(provider, tools, spec),
messages,
compacted_tool_call_ids,
)
tool_msg = next(m for m in result if m.get("role") == "tool")
assert "omitted from context" in tool_msg["content"]
assert compacted_tool_call_ids == {"c0"}
def test_context_governor_keeps_compaction_boundary_stable(monkeypatch):
provider = MagicMock()
provider.generation = SimpleNamespace(max_tokens=0)
tools = MagicMock()
tools.get_definitions.return_value = []
total = MICROCOMPACT_KEEP_RECENT + 8
long_content = "x" * 600
messages = _microcompact_messages(total=total, tool_name="read_file", content=long_content)
spec = AgentRunSpec(
initial_messages=messages,
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
max_tokens=0,
context_window_tokens=2224,
)
def estimate(_provider, _model, msgs, _tools):
return sum(
100 if msg.get("content") == long_content else 1
for msg in msgs
if msg.get("role") == "tool"
), "test"
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate)
governor = ContextGovernor()
compacted_tool_call_ids: set[str] = set()
config = _governance_config(provider, tools, spec, inflight_start_index=0)
first = governor.compact_inflight_overflow(config, messages, compacted_tool_call_ids)
first_ids = set(compacted_tool_call_ids)
second = governor.compact_inflight_overflow(config, messages, compacted_tool_call_ids)
assert compacted_tool_call_ids == first_ids
assert [m.get("content") for m in second] == [m.get("content") for m in first]
def test_microcompact_preserves_short_results(monkeypatch):
"""Short tool results below the compaction threshold should not be replaced."""
provider = MagicMock()
provider.generation = SimpleNamespace(max_tokens=0)
tools = MagicMock()
tools.get_definitions.return_value = []
total = MICROCOMPACT_KEEP_RECENT + 5
messages = _microcompact_messages(total=total, tool_name="exec", content="short")
spec = AgentRunSpec(
initial_messages=messages,
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
max_tokens=0,
context_window_tokens=2024,
)
monkeypatch.setattr(
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
lambda *_args, **_kwargs: (2000, "test"),
)
result = ContextGovernor().compact_inflight_overflow(
_governance_config(provider, tools, spec),
messages,
set(),
)
assert result is messages # no copy needed — all stale results are short
@pytest.mark.asyncio
async def test_microcompact_skips_non_compactable_tools():
def test_microcompact_skips_non_compactable_tools(monkeypatch):
"""Non-compactable tools (e.g. 'message') should never be replaced."""
from nanobot.agent.runner import AgentRunner, _MICROCOMPACT_KEEP_RECENT
provider = MagicMock()
provider.generation = SimpleNamespace(max_tokens=0)
tools = MagicMock()
tools.get_definitions.return_value = []
total = _MICROCOMPACT_KEEP_RECENT + 5
total = MICROCOMPACT_KEEP_RECENT + 5
long_content = "y" * 1000
messages: list[dict] = []
for i in range(total):
messages.append({
"role": "assistant",
"content": "",
"tool_calls": [{"id": f"c{i}", "type": "function", "function": {"name": "message", "arguments": "{}"}}],
})
messages.append({
"role": "tool", "tool_call_id": f"c{i}", "name": "message",
"content": long_content,
})
messages = _microcompact_messages(total=total, tool_name="message", content=long_content)
spec = AgentRunSpec(
initial_messages=messages,
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
max_tokens=0,
context_window_tokens=2024,
)
result = AgentRunner._microcompact(messages)
monkeypatch.setattr(
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
lambda *_args, **_kwargs: (2000, "test"),
)
result = ContextGovernor().compact_inflight_overflow(
_governance_config(provider, tools, spec),
messages,
set(),
)
assert result is messages # no compactable tools found
def test_governance_repairs_orphans_after_snip():
"""After _snip_history clips an assistant+tool_calls, the second
_drop_orphan_tool_results pass must clean up the resulting orphans."""
from nanobot.agent.runner import AgentRunner
messages = [
{"role": "system", "content": "system"},
{"role": "user", "content": "old msg"},
{"role": "assistant", "content": None,
"tool_calls": [{"id": "tc_old", "type": "function",
"function": {"name": "search", "arguments": "{}"}}]},
{"role": "tool", "tool_call_id": "tc_old", "name": "search",
"content": "old result"},
{"role": "assistant", "content": "old answer"},
{"role": "user", "content": "new msg"},
]
"""After snipping clips an assistant+tool_calls, orphan repair cleans up the tail."""
# Simulate snipping that keeps only the tail: drop the assistant with
# tool_calls but keep its tool result (orphan).
snipped = [
@@ -547,7 +730,7 @@ def test_governance_repairs_orphans_after_snip():
{"role": "user", "content": "new msg"},
]
cleaned = AgentRunner._drop_orphan_tool_results(snipped)
cleaned = ContextGovernor.drop_orphan_tool_results(snipped)
# The orphan tool result should be removed.
assert not any(
m.get("role") == "tool" and m.get("tool_call_id") == "tc_old"
@@ -556,10 +739,7 @@ def test_governance_repairs_orphans_after_snip():
def test_governance_fallback_still_repairs_orphans():
"""When full governance fails, the fallback must still run
_drop_orphan_tool_results and _backfill_missing_tool_results."""
from nanobot.agent.runner import AgentRunner
"""When full governance fails, the fallback must still repair orphans."""
# Messages with an orphan tool result (no matching assistant tool_call).
messages = [
{"role": "user", "content": "hello"},
@@ -568,10 +748,12 @@ def test_governance_fallback_still_repairs_orphans():
{"role": "assistant", "content": "hi"},
]
repaired = AgentRunner._drop_orphan_tool_results(messages)
repaired = AgentRunner._backfill_missing_tool_results(repaired)
repaired = ContextGovernor.drop_orphan_tool_results(messages)
repaired = ContextGovernor.backfill_missing_tool_results(repaired)
# Orphan tool result should be gone.
assert not any(m.get("tool_call_id") == "orphan_tc" for m in repaired)
def test_snip_history_preserves_user_message_after_truncation(monkeypatch):
"""When _snip_history truncates messages and the only user message ends up
outside the kept window, the method must recover the nearest user message
@@ -585,12 +767,9 @@ def test_snip_history_preserves_user_message_after_truncation(monkeypatch):
- _snip_history activates, keeping only recent assistant/tool pairs.
- The injected user message is in the truncated prefix and gets lost.
"""
from nanobot.agent.runner import AgentRunSpec, AgentRunner
provider = MagicMock()
tools = MagicMock()
tools.get_definitions.return_value = []
runner = AgentRunner(provider)
messages = [
{"role": "system", "content": "system"},
@@ -621,7 +800,10 @@ def test_snip_history_preserves_user_message_after_truncation(monkeypatch):
)
# Make estimate_prompt_tokens_chain report above budget so _snip_history activates.
monkeypatch.setattr("nanobot.agent.runner.estimate_prompt_tokens_chain", lambda *_a, **_kw: (500, None))
monkeypatch.setattr(
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
lambda *_a, **_kw: (500, None),
)
# Make kept window small: only the last 2 messages fit the budget.
token_sizes = {
"system": 0,
@@ -631,11 +813,11 @@ def test_snip_history_preserves_user_message_after_truncation(monkeypatch):
"tool output 2": 80,
}
monkeypatch.setattr(
"nanobot.agent.runner.estimate_message_tokens",
"nanobot.agent.context_governance.estimate_message_tokens",
lambda msg: token_sizes.get(str(msg.get("content")), 100),
)
trimmed = runner._snip_history(spec, messages)
trimmed = ContextGovernor().snip_history(_governance_config(provider, tools, spec), messages)
# The first non-system message MUST be user (not assistant).
non_system = [m for m in trimmed if m.get("role") != "system"]
@@ -649,12 +831,9 @@ def test_snip_history_preserves_user_message_after_truncation(monkeypatch):
def test_snip_history_no_user_at_all_falls_back_gracefully(monkeypatch):
"""Edge case: if non_system has zero user messages, _snip_history should
still return a valid sequence (not crash or produce systemassistant)."""
from nanobot.agent.runner import AgentRunSpec, AgentRunner
provider = MagicMock()
tools = MagicMock()
tools.get_definitions.return_value = []
runner = AgentRunner(provider)
messages = [
{"role": "system", "content": "system"},
@@ -674,13 +853,16 @@ def test_snip_history_no_user_at_all_falls_back_gracefully(monkeypatch):
context_block_limit=100,
)
monkeypatch.setattr("nanobot.agent.runner.estimate_prompt_tokens_chain", lambda *_a, **_kw: (500, None))
monkeypatch.setattr(
"nanobot.agent.runner.estimate_message_tokens",
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
lambda *_a, **_kw: (500, None),
)
monkeypatch.setattr(
"nanobot.agent.context_governance.estimate_message_tokens",
lambda msg: 100,
)
trimmed = runner._snip_history(spec, messages)
trimmed = ContextGovernor().snip_history(_governance_config(provider, tools, spec), messages)
# Should not crash. The result should still be a valid list.
assert isinstance(trimmed, list)
+6 -5
View File
@@ -6,15 +6,13 @@ import os
import time
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMResponse, ToolCallRequest
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
async def test_runner_persists_large_tool_results_for_follow_up_calls(tmp_path):
from nanobot.agent.runner import AgentRunSpec, AgentRunner
from nanobot.agent.runner import AgentRunner, AgentRunSpec
provider = MagicMock()
captured_second_call: list[dict] = []
@@ -172,7 +170,7 @@ async def test_read_file_result_is_not_offloaded(tmp_path):
async def test_runner_keeps_going_when_tool_result_persistence_fails():
from nanobot.agent.runner import AgentRunSpec, AgentRunner
from nanobot.agent.runner import AgentRunner, AgentRunSpec
provider = MagicMock()
captured_second_call: list[dict] = []
@@ -195,7 +193,10 @@ async def test_runner_keeps_going_when_tool_result_persistence_fails():
tools.execute = AsyncMock(return_value="tool result")
runner = AgentRunner(provider)
with patch("nanobot.agent.runner.maybe_persist_tool_result", side_effect=RuntimeError("disk full")):
with patch(
"nanobot.agent.context_governance.maybe_persist_tool_result",
side_effect=RuntimeError("disk full"),
):
result = await runner.run(AgentRunSpec(
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
+15 -16
View File
@@ -266,13 +266,8 @@ def test_get_history_preserves_reasoning_content():
]
def test_get_history_annotates_user_turns_but_not_assistant_turns():
"""Only user turns carry the timestamp prefix.
Annotating assistant turns trains the model (via in-context examples) to
start its own replies with ``[Message Time: ...]``. User-side stamps are
enough to pin adjacent assistant replies for relative-time reasoning.
"""
def test_get_history_does_not_inject_persisted_timestamps_into_replay_content():
"""Persisted timestamps are session metadata, not prompt content."""
session = Session(key="test:timestamps")
session.messages.append({
"role": "user",
@@ -285,12 +280,14 @@ def test_get_history_annotates_user_turns_but_not_assistant_turns():
"timestamp": "2026-04-26T22:00:05",
})
history = session.get_history(max_messages=500, include_timestamps=True)
history = session.get_history(max_messages=500)
assert session.messages[0]["timestamp"] == "2026-04-26T22:00:00"
assert session.messages[1]["timestamp"] == "2026-04-26T22:00:05"
assert history == [
{
"role": "user",
"content": "[Message Time: 2026-04-26T22:00:00]\n10 点提醒是昨天发生的",
"content": "10 点提醒是昨天发生的",
},
{
"role": "assistant",
@@ -299,8 +296,8 @@ def test_get_history_annotates_user_turns_but_not_assistant_turns():
]
def test_get_history_does_not_annotate_proactive_assistant_deliveries_with_timestamps():
"""Assistant-side timestamp examples can leak back into future replies."""
def test_get_history_keeps_proactive_delivery_timestamps_out_of_replay_content():
"""Timestamp metadata remains persisted without becoming prompt text."""
session = Session(key="test:proactive-timestamps")
session.messages.append({
"role": "assistant",
@@ -314,8 +311,10 @@ def test_get_history_does_not_annotate_proactive_assistant_deliveries_with_times
"timestamp": "2026-04-26T18:00:00",
})
history = session.get_history(max_messages=500, include_timestamps=True)
history = session.get_history(max_messages=500)
assert session.messages[0]["timestamp"] == "2026-04-26T15:00:00"
assert session.messages[1]["timestamp"] == "2026-04-26T18:00:00"
assert history == [
{
"role": "assistant",
@@ -323,18 +322,18 @@ def test_get_history_does_not_annotate_proactive_assistant_deliveries_with_times
},
{
"role": "user",
"content": "[Message Time: 2026-04-26T18:00:00]\n",
"content": "",
},
]
def test_get_history_does_not_annotate_tool_results_with_timestamps():
def test_get_history_does_not_inject_tool_result_timestamps():
session = Session(key="test:tool-timestamps")
session.messages.append({"role": "user", "content": "run tool"})
session.messages.extend(_tool_turn("ts", 0))
session.messages[-1]["timestamp"] = "2026-04-26T22:00:10"
history = session.get_history(max_messages=500, include_timestamps=True)
history = session.get_history(max_messages=500)
tool_result = history[-1]
assert tool_result["role"] == "tool"
@@ -555,7 +554,7 @@ def test_get_history_sanitizes_existing_assistant_replay_artifacts():
}
)
history = session.get_history(max_messages=500, include_timestamps=True)
history = session.get_history(max_messages=500)
assert history == [{"role": "assistant", "content": "来了 🎨"}]
+33 -2
View File
@@ -1,11 +1,12 @@
"""Tests for SubagentManager."""
from pathlib import Path
from unittest.mock import MagicMock
from unittest.mock import AsyncMock, MagicMock
import pytest
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.runner import AgentRunResult
from nanobot.agent.subagent import SubagentManager, SubagentStatus
from nanobot.agent.tools.filesystem import FileToolsConfig
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import ToolsConfig
@@ -79,3 +80,33 @@ def test_subagent_respects_file_tool_toggle(tmp_path):
"write_file",
}
assert file_tools.isdisjoint(tools.tool_names)
@pytest.mark.asyncio
async def test_subagent_forwards_fail_on_tool_error_to_runner(tmp_path):
provider = MagicMock(spec=LLMProvider)
provider.get_default_model.return_value = "test"
sm = SubagentManager(
provider=provider,
workspace=tmp_path,
bus=MessageBus(),
model="test",
max_tool_result_chars=16_000,
fail_on_tool_error=False,
)
sm.runner.run = AsyncMock(
return_value=AgentRunResult(final_content="ok", messages=[], stop_reason="completed")
)
sm._announce_result = AsyncMock()
status = SubagentStatus(
task_id="t1",
label="label",
task_description="task",
started_at=0.0,
)
await sm._run_subagent("t1", "task", "label", {"channel": "cli", "chat_id": "direct"}, status)
spec = sm.runner.run.call_args.args[0]
assert spec.fail_on_tool_error is False
+144
View File
@@ -259,6 +259,150 @@ async def test_handler_processes_file_message(monkeypatch) -> None:
assert "/tmp/nanobot_dingtalk/user1/report.xlsx" in msg.content
def _rich_text_message(rich_text_list):
class _FakeRichTextChatbotMessage:
text = None
extensions = {}
image_content = None
rich_text_content = SimpleNamespace(rich_text_list=rich_text_list)
sender_staff_id = "user1"
sender_id = "fallback-user"
sender_nick = "Alice"
message_type = "richText"
@staticmethod
def from_dict(_data):
return _FakeRichTextChatbotMessage()
return _FakeRichTextChatbotMessage
@pytest.mark.asyncio
async def test_handler_richtext_keeps_formatted_segments(monkeypatch) -> None:
"""richText segments with non-'text' types (bold/italic/code/pre) must be kept
and mapped to Markdown, not dropped (issue #4497)."""
bus = MessageBus()
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
bus,
)
handler = NanobotDingTalkHandler(channel)
fake_msg = _rich_text_message([
{"type": "bold", "text": "Title"},
{"type": "text", "text": "plain"},
{"type": "italic", "text": "em"},
{"type": "inlineCode", "text": "x = 1"},
{"type": "pre", "text": "block"},
])
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", fake_msg)
monkeypatch.setattr(dingtalk_module, "AckMessage", SimpleNamespace(STATUS_OK="OK"))
status, body = await handler.process(
SimpleNamespace(data={"conversationType": "1", "text": {"content": ""}})
)
msg = await asyncio.wait_for(bus.consume_inbound(), timeout=2.0)
assert (status, body) == ("OK", "OK")
assert msg.content == "**Title** plain *em* `x = 1` ```\nblock\n```"
@pytest.mark.asyncio
async def test_handler_richtext_all_formatted_not_dropped(monkeypatch) -> None:
"""A richText message made only of formatted segments must not end up with empty
content and fall through to the 'unsupported message type' path (issue #4497)."""
bus = MessageBus()
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
bus,
)
handler = NanobotDingTalkHandler(channel)
fake_msg = _rich_text_message([{"type": "bold", "text": "Important"}])
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", fake_msg)
monkeypatch.setattr(dingtalk_module, "AckMessage", SimpleNamespace(STATUS_OK="OK"))
status, body = await handler.process(
SimpleNamespace(data={"conversationType": "1", "text": {"content": ""}})
)
# Before the fix this message produced empty content and never reached the bus,
# so consume_inbound would block here.
msg = await asyncio.wait_for(bus.consume_inbound(), timeout=2.0)
assert (status, body) == ("OK", "OK")
assert msg.content == "**Important**"
@pytest.mark.asyncio
async def test_handler_richtext_item_with_text_and_download(monkeypatch) -> None:
"""A rich-text item carrying both text and a downloadCode must yield both the
text and the downloaded file, not drop the attachment (issue #4497)."""
bus = MessageBus()
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
bus,
)
handler = NanobotDingTalkHandler(channel)
fake_msg = _rich_text_message([
{"text": "see attached", "downloadCode": "abc123", "fileName": "report.xlsx"},
])
async def fake_download(download_code, filename, sender_id):
return f"/tmp/nanobot_dingtalk/{sender_id}/{filename}"
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", fake_msg)
monkeypatch.setattr(dingtalk_module, "AckMessage", SimpleNamespace(STATUS_OK="OK"))
monkeypatch.setattr(channel, "_download_dingtalk_file", fake_download)
status, body = await handler.process(
SimpleNamespace(data={"conversationType": "1", "text": {"content": ""}})
)
await asyncio.gather(*list(channel._background_tasks))
msg = await asyncio.wait_for(bus.consume_inbound(), timeout=2.0)
assert (status, body) == ("OK", "OK")
assert "see attached" in msg.content
assert "/tmp/nanobot_dingtalk/user1/report.xlsx" in msg.content
@pytest.mark.asyncio
async def test_start_configures_http_timeout(monkeypatch) -> None:
"""The shared httpx client must be created with an explicit timeout so file/image
downloads don't hit httpx's 5s default and ConnectTimeout (issue #4497)."""
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
class _FakeStreamClient:
def __init__(self, _credential):
pass
def register_callback_handler(self, _topic, _handler):
pass
async def start(self):
# Exit the reconnect loop after one iteration.
channel._running = False
monkeypatch.setattr(dingtalk_module, "DINGTALK_AVAILABLE", True)
monkeypatch.setattr(dingtalk_module, "Credential", lambda *a, **k: object())
monkeypatch.setattr(dingtalk_module, "DingTalkStreamClient", _FakeStreamClient)
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", SimpleNamespace(TOPIC="topic"))
await channel.start()
assert channel._http is not None
timeout = channel._http.timeout
assert timeout.connect == 10.0
assert timeout.read == 30.0
assert timeout.write == 30.0
assert timeout.pool == 10.0
await channel.stop()
@pytest.mark.asyncio
async def test_download_dingtalk_file(tmp_path, monkeypatch) -> None:
"""Test the two-step file download flow (get URL then download content)."""
+13
View File
@@ -35,7 +35,20 @@ def test_feishu_channel_constructor_does_not_import_lark_oapi():
def test_lark_runtime_thread_import_clears_sdk_import_loop():
out = _run_import_probe(
"import asyncio\n"
"import sys\n"
"import tempfile\n"
"from pathlib import Path\n"
"from nanobot.channels.feishu import _load_lark_runtime\n"
"root = Path(tempfile.mkdtemp())\n"
"pkg = root / 'lark_oapi'\n"
"(pkg / 'ws').mkdir(parents=True)\n"
"(pkg / 'core').mkdir(parents=True)\n"
"(pkg / '__init__.py').write_text('class LogLevel:\\n INFO = 20\\n')\n"
"(pkg / 'ws' / '__init__.py').write_text('')\n"
"(pkg / 'ws' / 'client.py').write_text('import asyncio\\nloop = asyncio.new_event_loop()\\n')\n"
"(pkg / 'core' / '__init__.py').write_text('')\n"
"(pkg / 'core' / 'const.py').write_text(\"FEISHU_DOMAIN = 'feishu'\\nLARK_DOMAIN = 'lark'\\n\")\n"
"sys.path.insert(0, str(root))\n"
"async def main():\n"
" await asyncio.to_thread(_load_lark_runtime)\n"
" import lark_oapi.ws.client as ws\n"
+19 -2
View File
@@ -471,7 +471,7 @@ async def test_send_rich_capability_error_latches_and_falls_back() -> None:
from telegram.error import BadRequest
channel = TelegramChannel(
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], rich_messages=True),
MessageBus(),
)
channel._app = _FakeApp(lambda: None)
@@ -490,7 +490,7 @@ async def test_send_rich_bad_request_does_not_latch_capability() -> None:
from telegram.error import BadRequest
channel = TelegramChannel(
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], rich_messages=True),
MessageBus(),
)
channel._app = _FakeApp(lambda: None)
@@ -505,6 +505,23 @@ async def test_send_rich_bad_request_does_not_latch_capability() -> None:
assert len(channel._app.bot.sent_messages) == 1
@pytest.mark.asyncio
async def test_rich_messages_default_skips_send_rich_message() -> None:
"""By default, sendRichMessage should not be called."""
channel = TelegramChannel(
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),
MessageBus(),
)
channel._app = _FakeApp(lambda: None)
channel._app.bot.do_api_request = AsyncMock()
await channel.send(OutboundMessage(channel="telegram", chat_id="123", content="**hello**"))
channel._app.bot.do_api_request.assert_not_called()
assert len(channel._app.bot.sent_messages) == 1
assert channel._app.bot.sent_messages[0]["text"]
@pytest.mark.asyncio
async def test_on_error_logs_network_issues_as_warning(monkeypatch) -> None:
from telegram.error import NetworkError
+1 -1
View File
@@ -136,7 +136,7 @@ def isolate_webui_workspace_state(tmp_path, monkeypatch) -> None:
async def _http_get(url: str, headers: dict[str, str] | None = None) -> httpx.Response:
"""Run GET in a thread to avoid blocking the asyncio loop shared with websockets."""
return await asyncio.to_thread(
functools.partial(httpx.get, url, headers=headers or {}, timeout=5.0)
functools.partial(httpx.get, url, headers=headers or {}, timeout=5.0, trust_env=False)
)
+2 -3
View File
@@ -109,7 +109,7 @@ async def _http_get(
url: str, headers: dict[str, str] | None = None
) -> httpx.Response:
return await asyncio.to_thread(
functools.partial(httpx.get, url, headers=headers or {}, timeout=5.0)
functools.partial(httpx.get, url, headers=headers or {}, timeout=5.0, trust_env=False)
)
@@ -506,12 +506,11 @@ async def test_cli_apps_catalog_does_not_block_other_webui_http_routes(
token = boot.json()["token"]
auth = {"Authorization": f"Bearer {token}"}
started = time.perf_counter()
catalog_task = asyncio.create_task(
_http_get("http://127.0.0.1:29935/api/settings/cli-apps", headers=auth)
)
assert await asyncio.wait_for(entered.wait(), 2.0)
assert time.perf_counter() - started < 1.0
assert not catalog_task.done()
workspaces_started = time.perf_counter()
workspaces = await _http_get("http://127.0.0.1:29935/api/workspaces", headers=auth)
+1 -1
View File
@@ -90,7 +90,7 @@ async def _http_get(
url: str, headers: dict[str, str] | None = None
) -> httpx.Response:
return await asyncio.to_thread(
functools.partial(httpx.get, url, headers=headers or {}, timeout=5.0)
functools.partial(httpx.get, url, headers=headers or {}, timeout=5.0, trust_env=False)
)
@@ -0,0 +1,77 @@
"""Boundary tests for pure WebSocket protocol helpers."""
from __future__ import annotations
import pytest
from nanobot.channels.websocket import (
_extract_data_url_mime,
_is_valid_chat_id,
_parse_envelope,
)
def test_chat_id_validator_accepts_only_compact_capability_keys() -> None:
valid = [
"a",
"A-Z_09:chat-id",
"x" * 64,
]
invalid = [
"",
"x" * 65,
"../escape",
"chat/id",
"chat id",
"chat\nid",
None,
123,
]
for value in valid:
assert _is_valid_chat_id(value), value
for value in invalid:
assert not _is_valid_chat_id(value), repr(value)
@pytest.mark.parametrize(
("raw", "expected_type"),
[
("plain text", None),
("{not json", None),
("[]", None),
("{}", None),
('{"type": 42}', None),
('{"type": "message", "content": "hi"}', "message"),
(' {"type": "new_chat"} ', "new_chat"),
],
)
def test_parse_envelope_only_accepts_typed_json_objects(
raw: str,
expected_type: str | None,
) -> None:
parsed = _parse_envelope(raw)
if expected_type is None:
assert parsed is None
else:
assert parsed is not None
assert parsed["type"] == expected_type
@pytest.mark.parametrize(
("url", "expected"),
[
("data:image/png;base64,AAAA", "image/png"),
("data:IMAGE/JPEG;charset=utf-8;base64,AAAA", "image/jpeg"),
("data:video/webm;codecs=vp9;base64,AAAA", "video/webm"),
("data:image/svg+xml;base64,AAAA", "image/svg+xml"),
("data:image/png,AAAA", None),
("data:;base64,AAAA", None),
("https://example.invalid/image.png", None),
],
)
def test_extract_data_url_mime_normalizes_only_base64_data_urls(
url: str,
expected: str | None,
) -> None:
assert _extract_data_url_mime(url) == expected
File diff suppressed because it is too large Load Diff
+14
View File
@@ -10,6 +10,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from typer.testing import CliRunner
from nanobot.agent.memory import MemoryStore
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.cli import commands as cli_commands
from nanobot.cli.commands import app
@@ -140,6 +141,19 @@ def test_gateway_tty_signal_mode_restores_ctrl_c(monkeypatch) -> None:
os.close(slave_fd)
def test_disabled_dream_cursor_only_advances_when_behind(tmp_path) -> None:
store = MemoryStore(tmp_path)
store.append_history("first")
store.append_history("second")
cli_commands._advance_dream_cursor_if_behind(store)
assert store.get_last_dream_cursor() == 2
store.set_last_dream_cursor(10)
cli_commands._advance_dream_cursor_if_behind(store)
assert store.get_last_dream_cursor() == 10
@pytest.fixture
def mock_paths():
"""Mock config/workspace paths for test isolation."""
-2
View File
@@ -1,7 +1,6 @@
from pathlib import Path
from nanobot.config.paths import (
get_bridge_install_dir,
get_cli_history_path,
get_cron_dir,
get_data_dir,
@@ -34,7 +33,6 @@ def test_media_dir_supports_channel_namespace(monkeypatch, tmp_path: Path) -> No
def test_shared_and_legacy_paths_remain_global() -> None:
assert get_cli_history_path() == Path.home() / ".nanobot" / "history" / "cli_history"
assert get_bridge_install_dir() == Path.home() / ".nanobot" / "bridge"
assert get_legacy_sessions_dir() == Path.home() / ".nanobot" / "sessions"
@@ -0,0 +1,62 @@
"""Tests for custom provider thinking_style config passthrough."""
from __future__ import annotations
from nanobot.config.schema import ProviderConfig, ProvidersConfig
from nanobot.providers.registry import create_dynamic_spec
class TestCustomProviderThinkingStyle:
"""Verify that thinking_style flows from config to ProviderSpec."""
def test_default_thinking_style_is_empty(self) -> None:
cfg = ProviderConfig()
assert cfg.thinking_style is None
def test_create_dynamic_spec_default(self) -> None:
spec = create_dynamic_spec("custom")
assert spec.thinking_style == ""
def test_create_dynamic_spec_with_thinking_type(self) -> None:
spec = create_dynamic_spec("custom", thinking_style="thinking_type")
assert spec.thinking_style == "thinking_type"
def test_create_dynamic_spec_with_enable_thinking(self) -> None:
spec = create_dynamic_spec("custom", thinking_style="enable_thinking")
assert spec.thinking_style == "enable_thinking"
def test_create_dynamic_spec_with_reasoning_split(self) -> None:
spec = create_dynamic_spec("custom", thinking_style="reasoning_split")
assert spec.thinking_style == "reasoning_split"
def test_provider_config_accepts_camel_case(self) -> None:
"""Config JSON uses camelCase: thinkingStyle."""
cfg = ProviderConfig.model_validate({"thinkingStyle": "thinking_type"})
assert cfg.thinking_style == "thinking_type"
def test_providers_config_custom_has_thinking_style(self) -> None:
"""Full providers config round-trip."""
data = {
"custom": {
"apiKey": "sk-test",
"apiBase": "https://example.com/v1",
"thinkingStyle": "enable_thinking",
}
}
pc = ProvidersConfig.model_validate(data)
assert pc.custom.thinking_style == "enable_thinking"
def test_invalid_thinking_style_raises_with_clear_message(self) -> None:
"""An invalid thinking_style must raise a ValidationError whose message
lists the valid options (not just Pydantic's generic Literal error)."""
import pytest
from pydantic import ValidationError
with pytest.raises(ValidationError) as exc_info:
ProviderConfig.model_validate({"thinkingStyle": "thinking_typ"})
message = str(exc_info.value)
assert "Invalid thinking_style" in message
assert "thinking_type" in message
assert "enable_thinking" in message
assert "reasoning_split" in message
+1 -1
View File
@@ -1228,7 +1228,7 @@ def test_openai_compat_defaults_missing_tool_arguments_to_empty_object() -> None
@pytest.mark.asyncio
async def test_openai_compat_stream_watchdog_returns_error_on_stall(monkeypatch) -> None:
monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "0")
monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "0.01")
mock_create = AsyncMock(return_value=_StalledStream())
spec = find_by_name("openai")
+33
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import ipaddress
import socket
from unittest.mock import patch
@@ -107,6 +108,38 @@ def test_blocks_ipv6_mapped_rfc1918():
assert not ok
def test_blocks_sampled_addresses_from_internal_networks():
"""Property-style guard: sampled blocked CIDRs must all fail closed."""
configure_ssrf_whitelist([])
blocked_networks = [
"0.0.0.0/8",
"10.0.0.0/8",
"100.64.0.0/10",
"127.0.0.0/8",
"169.254.0.0/16",
"172.16.0.0/12",
"192.168.0.0/16",
"::1/128",
"fc00::/7",
"fe80::/10",
]
samples: list[str] = []
for cidr in blocked_networks:
network = ipaddress.ip_network(cidr)
samples.append(str(network.network_address))
if network.num_addresses > 2:
samples.append(str(network.network_address + 1))
samples.append(str(network[-2]))
for idx, ip in enumerate(samples):
host = f"internal-{idx}.example"
resolver = _fake_resolve_v6 if ":" in ip else _fake_resolve
with patch("nanobot.security.network.socket.getaddrinfo", resolver(host, [ip])):
ok, err = validate_url_target(f"http://{host}/")
assert not ok, f"expected {ip} to be blocked"
assert "blocked" in err.lower() or "private" in err.lower()
def test_allows_public_ipv6():
"""Public IPv6 addresses must still be allowed."""
with patch("nanobot.security.network.socket.getaddrinfo", _fake_resolve_v6("example.com", ["2606:4700::6810:84e5"])):
+32
View File
@@ -53,6 +53,38 @@ def test_resolve_allowed_path_blocks_parent_traversal(tmp_path: Path) -> None:
resolve_allowed_path("../secret.txt", workspace=workspace, allowed_root=workspace)
def test_resolve_allowed_path_blocks_traversal_shapes(tmp_path: Path) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir()
outside = tmp_path / "secret.txt"
outside.write_text("secret", encoding="utf-8")
traversal_shapes: list[str | Path] = [
"../secret.txt",
"src/../../secret.txt",
Path("..") / "secret.txt",
workspace / "src" / ".." / ".." / "secret.txt",
]
if os.name == "nt":
traversal_shapes.append("src\\..\\..\\secret.txt")
for candidate in traversal_shapes:
with pytest.raises(WorkspaceBoundaryError, match="outside allowed directory"):
resolve_allowed_path(candidate, workspace=workspace, allowed_root=workspace)
def test_resolve_allowed_path_blocks_prefix_sibling(tmp_path: Path) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir()
sibling = tmp_path / "workspace-other"
sibling.mkdir()
secret = sibling / "secret.txt"
secret.write_text("secret", encoding="utf-8")
with pytest.raises(WorkspaceBoundaryError, match="outside allowed directory"):
resolve_allowed_path(secret, workspace=workspace, allowed_root=workspace)
def test_resolve_allowed_path_blocks_symlink_escape(tmp_path: Path) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir()
+33 -2
View File
@@ -15,7 +15,7 @@ def test_deny_patterns_block_rm_rf():
def test_allow_patterns_bypass_deny():
"""allow_patterns take priority: matching command skips deny check."""
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/tmp/"])
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/tmp/.*"])
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
assert result is None
@@ -49,10 +49,41 @@ def test_allow_patterns_bypass_extra_deny():
def test_allow_patterns_is_whitelist_only():
"""When allow_patterns is set, non-matching non-denied commands are blocked."""
tool = ExecTool(allow_patterns=[r"\becho\b"])
tool = ExecTool(allow_patterns=[r"echo\s+hello"])
# echo matches allow → ok
assert tool._guard_command("echo hello", "/tmp") is None
# ls does not match allow and is not in deny → blocked by allowlist
result = tool._guard_command("ls /tmp", "/tmp")
assert result is not None
assert "allowlist" in result.lower()
def test_allow_patterns_do_not_allow_chained_command_bypass():
"""A partial allowlist match must not bypass deny patterns in chained commands."""
tool = ExecTool(allow_patterns=[r"\becho\b"])
result = tool._guard_command("echo hello; rm -rf /", "/tmp")
assert result is not None
assert "deny pattern filter" in result.lower()
def test_allow_patterns_do_not_allow_comment_tail_bypass():
"""Comment tails must not make a non-allowlisted command match."""
tool = ExecTool(allow_patterns=[r"echo allowlisted"])
result = tool._guard_command("touch canary # echo allowlisted", "/tmp")
assert result is not None
assert "allowlist" in result.lower()
def test_deny_patterns_search_original_command_with_quoted_hash():
"""Deny checks must still inspect text after a quoted hash."""
tool = ExecTool(deny_patterns=[r"\brm\s+-rf\s+/"])
result = tool._guard_command('echo "#"; rm -rf /', "/tmp")
assert result is not None
assert "deny pattern filter" in result.lower()
def test_allow_patterns_fullmatch_allows_exact_command():
"""A full-command allow pattern can still exempt an exact denied command."""
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/tmp/build"])
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
assert result is None
+24 -1
View File
@@ -105,7 +105,7 @@ class TestSpawnUnix:
args = mock_exec.call_args[0]
assert "bash" in args[0]
assert "-l" in args
assert "-l" not in args
assert "-c" in args
assert "echo hi" in args
@@ -400,6 +400,29 @@ class TestExecuteEndToEnd:
assert "hello world" in result
assert "Exit code: 0" in result
@pytest.mark.asyncio
async def test_execute_defaults_to_non_login_shell(self):
"""The public execute path must not silently request a login shell."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok\n", b"")
mock_proc.returncode = 0
captured_login = []
async def capture_spawn(cmd, cwd, env, shell_program=None, login=None, *, stdin=None):
captured_login.append(login)
return mock_proc
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch.object(ExecTool, "_spawn", side_effect=capture_spawn),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool()
await tool.execute(command="echo ok")
await tool.execute(command="echo ok", login=True)
assert captured_login == [False, True]
# ---------------------------------------------------------------------------
# _extract_absolute_paths - UNC path support
+73
View File
@@ -433,6 +433,79 @@ async def test_connect_mcp_servers_enabled_tools_empty_list_registers_none(
assert registry.tool_names == []
@pytest.mark.asyncio
async def test_connect_mcp_servers_enabled_tools_empty_list_blocks_resources_and_prompts(
fake_mcp_runtime: dict[str, object | None],
) -> None:
"""enabledTools: [] (deny-all) must also block resource and prompt registration."""
fake_mcp_runtime["session"] = _make_fake_session_with_capabilities(
tool_names=["demo"],
resource_names=["secret_data"],
prompt_names=["admin_prompt"],
)
registry = ToolRegistry()
stacks = await connect_mcp_servers(
{"test": MCPServerConfig(command="fake", enabled_tools=[])},
registry,
)
for stack in stacks.values():
await stack.aclose()
assert registry.tool_names == []
# Resources and prompts must also be blocked
assert not any("secret_data" in name for name in registry.tool_names)
assert not any("admin_prompt" in name for name in registry.tool_names)
@pytest.mark.asyncio
async def test_connect_mcp_servers_enabled_tools_specific_list_blocks_resources_and_prompts(
fake_mcp_runtime: dict[str, object | None],
) -> None:
"""enabledTools with specific tool names must not leak resources or prompts."""
fake_mcp_runtime["session"] = _make_fake_session_with_capabilities(
tool_names=["demo", "other"],
resource_names=["secret_data"],
prompt_names=["admin_prompt"],
)
registry = ToolRegistry()
stacks = await connect_mcp_servers(
{"test": MCPServerConfig(command="fake", enabled_tools=["demo"])},
registry,
)
for stack in stacks.values():
await stack.aclose()
# Only the allowed tool should be registered
assert "mcp_test_demo" in registry.tool_names
assert "mcp_test_other" not in registry.tool_names
# Resources and prompts must not leak
assert not any("secret_data" in name for name in registry.tool_names)
assert not any("admin_prompt" in name for name in registry.tool_names)
@pytest.mark.asyncio
async def test_connect_mcp_servers_enabled_tools_wildcard_allows_resources_and_prompts(
fake_mcp_runtime: dict[str, object | None],
) -> None:
"""enabledTools: ['*'] should allow all tools, resources, and prompts."""
fake_mcp_runtime["session"] = _make_fake_session_with_capabilities(
tool_names=["demo"],
resource_names=["public_data"],
prompt_names=["help_prompt"],
)
registry = ToolRegistry()
stacks = await connect_mcp_servers(
{"test": MCPServerConfig(command="fake", enabled_tools=["*"])},
registry,
)
for stack in stacks.values():
await stack.aclose()
assert "mcp_test_demo" in registry.tool_names
assert any("public_data" in name for name in registry.tool_names)
assert any("help_prompt" in name for name in registry.tool_names)
@pytest.mark.asyncio
async def test_connect_mcp_servers_enabled_tools_warns_on_unknown_entries(
fake_mcp_runtime: dict[str, object | None], monkeypatch: pytest.MonkeyPatch
+179
View File
@@ -0,0 +1,179 @@
"""Black-box smoke test for the real gateway WebUI transport."""
from __future__ import annotations
import asyncio
import json
import socket
import subprocess
import sys
import time
from pathlib import Path
from urllib.parse import quote
import httpx
import pytest
import websockets
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return int(sock.getsockname()[1])
def _write_smoke_config(path: Path, *, workspace: Path, ws_port: int, gateway_port: int) -> None:
config = {
"agents": {
"defaults": {
"workspace": str(workspace),
"provider": "custom",
"model": "custom/smoke-model",
"maxToolIterations": 1,
"dream": {"enabled": False},
}
},
"providers": {
"custom": {
"apiKey": "smoke-no-external-call",
"apiBase": "http://127.0.0.1:9/v1",
}
},
"channels": {
"websocket": {
"enabled": True,
"host": "127.0.0.1",
"port": ws_port,
"allowFrom": ["*"],
}
},
"gateway": {
"host": "127.0.0.1",
"port": gateway_port,
"heartbeat": {"enabled": False},
},
}
path.write_text(json.dumps(config), encoding="utf-8")
def _start_gateway(config_path: Path, log_path: Path) -> subprocess.Popen[bytes]:
log_file = log_path.open("wb")
try:
process = subprocess.Popen(
[
sys.executable,
"-m",
"nanobot",
"gateway",
"--config",
str(config_path),
],
cwd=Path(__file__).resolve().parents[2],
stdout=log_file,
stderr=subprocess.STDOUT,
)
finally:
log_file.close()
return process
def _stop_gateway(process: subprocess.Popen[bytes]) -> None:
if process.poll() is not None:
return
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=10)
def _get_json(url: str, *, token: str | None = None) -> dict:
headers = {"Authorization": f"Bearer {token}"} if token else {}
response = httpx.get(url, headers=headers, timeout=5.0, trust_env=False)
response.raise_for_status()
return response.json()
def _wait_for_bootstrap(base_url: str, process: subprocess.Popen[bytes], log_path: Path) -> dict:
deadline = time.monotonic() + 20
last_error: Exception | None = None
while time.monotonic() < deadline:
if process.poll() is not None:
break
try:
return _get_json(f"{base_url}/webui/bootstrap")
except (httpx.HTTPError, OSError) as exc:
last_error = exc
time.sleep(0.2)
logs = log_path.read_text(encoding="utf-8", errors="replace")
raise AssertionError(f"gateway did not start; last_error={last_error!r}\n{logs}")
async def _recv_until(ws: websockets.WebSocketClientProtocol, event: str) -> dict:
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
raw = await asyncio.wait_for(ws.recv(), timeout=5)
payload = json.loads(raw)
if payload.get("event") == event:
return payload
raise AssertionError(f"websocket event {event!r} was not received")
@pytest.mark.asyncio
async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Path) -> None:
ws_port = _free_port()
gateway_port = _free_port()
workspace = tmp_path / "workspace"
workspace.mkdir()
config_path = tmp_path / "config.json"
log_path = tmp_path / "gateway.log"
_write_smoke_config(
config_path,
workspace=workspace,
ws_port=ws_port,
gateway_port=gateway_port,
)
process = _start_gateway(config_path, log_path)
base_url = f"http://127.0.0.1:{ws_port}"
try:
bootstrap = _wait_for_bootstrap(base_url, process, log_path)
assert bootstrap["model_name"] == "custom/smoke-model"
ws_url = f'{bootstrap["ws_url"]}?token={bootstrap["token"]}&client_id=smoke'
async with websockets.connect(ws_url) as ws:
ready = await _recv_until(ws, "ready")
assert ready["client_id"] == "smoke"
await ws.send(json.dumps({"type": "new_chat"}))
attached = await _recv_until(ws, "attached")
chat_id = attached["chat_id"]
await _recv_until(ws, "session_updated")
await ws.send(json.dumps({
"type": "message",
"chat_id": chat_id,
"content": "/model",
"webui": True,
"turn_id": "smoke-turn",
}))
answer = await _recv_until(ws, "message")
assert "Current model: `custom/smoke-model`" in answer["text"]
await _recv_until(ws, "turn_end")
api_token = _wait_for_bootstrap(base_url, process, log_path)["token"]
sessions = _get_json(f"{base_url}/api/sessions", token=api_token)
key = f"websocket:{chat_id}"
assert key in {row["key"] for row in sessions["sessions"]}
encoded_key = quote(key, safe="")
thread = _get_json(
f"{base_url}/api/sessions/{encoded_key}/webui-thread",
token=api_token,
)
contents = [str(message.get("content") or "") for message in thread["messages"]]
assert "/model" in contents
assert any("Current model: `custom/smoke-model`" in text for text in contents)
finally:
_stop_gateway(process)
+8 -147
View File
@@ -9,10 +9,8 @@
"version": "0.1.0",
"dependencies": {
"@radix-ui/react-alert-dialog": "^1.1.4",
"@radix-ui/react-avatar": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.4",
"@radix-ui/react-dropdown-menu": "^2.1.4",
"@radix-ui/react-scroll-area": "^1.2.2",
"@radix-ui/react-separator": "^1.1.1",
"@radix-ui/react-slot": "^1.1.1",
"@radix-ui/react-tooltip": "^1.1.6",
@@ -37,7 +35,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.2",
"@types/node": "^22.10.5",
"@types/node": "^24.0.0",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@types/react-syntax-highlighter": "^15.5.13",
@@ -1009,10 +1007,6 @@
"node": ">= 8"
}
},
"node_modules/@radix-ui/number": {
"version": "1.1.1",
"license": "MIT"
},
"node_modules/@radix-ui/primitive": {
"version": "1.1.3",
"license": "MIT"
@@ -1080,65 +1074,6 @@
}
}
},
"node_modules/@radix-ui/react-avatar": {
"version": "1.1.11",
"license": "MIT",
"dependencies": {
"@radix-ui/react-context": "1.1.3",
"@radix-ui/react-primitive": "2.1.4",
"@radix-ui/react-use-callback-ref": "1.1.1",
"@radix-ui/react-use-is-hydrated": "0.1.0",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-avatar/node_modules/@radix-ui/react-context": {
"version": "1.1.3",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-avatar/node_modules/@radix-ui/react-primitive": {
"version": "2.1.4",
"license": "MIT",
"dependencies": {
"@radix-ui/react-slot": "1.2.4"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-collection": {
"version": "1.1.7",
"license": "MIT",
@@ -1566,35 +1501,6 @@
}
}
},
"node_modules/@radix-ui/react-scroll-area": {
"version": "1.2.10",
"license": "MIT",
"dependencies": {
"@radix-ui/number": "1.1.1",
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-direction": "1.1.1",
"@radix-ui/react-presence": "1.1.5",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-use-callback-ref": "1.1.1",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-separator": {
"version": "1.1.8",
"license": "MIT",
@@ -1763,22 +1669,6 @@
}
}
},
"node_modules/@radix-ui/react-use-is-hydrated": {
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"use-sync-external-store": "^1.5.0"
},
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-use-layout-effect": {
"version": "1.1.1",
"license": "MIT",
@@ -1946,9 +1836,6 @@
"arm"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1963,9 +1850,6 @@
"arm"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1980,9 +1864,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1997,9 +1878,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2014,9 +1892,6 @@
"loong64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2031,9 +1906,6 @@
"loong64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2048,9 +1920,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2065,9 +1934,6 @@
"ppc64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2082,9 +1948,6 @@
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2099,9 +1962,6 @@
"riscv64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2116,9 +1976,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2432,11 +2289,13 @@
"license": "MIT"
},
"node_modules/@types/node": {
"version": "22.19.17",
"version": "24.13.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.2.tgz",
"integrity": "sha512-fRa09kZTgu8o71KFcDjUFuc7F+dEbZYZmkI0mg5YBTRs0yMKjYHsq/c0urDKeDb+D5qVgXOdFcuu+DZPKOITwA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
"undici-types": "~7.18.0"
}
},
"node_modules/@types/prop-types": {
@@ -6751,7 +6610,9 @@
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"dev": true,
"license": "MIT"
},
+3 -2
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { useThemeValue } from "@/hooks/useTheme";
import { hasAnsi, parseAnsiSegments, stripAnsi } from "@/lib/ansi";
import { copyTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
interface CodeBlockProps {
@@ -192,8 +193,8 @@ export function CodeBlock({
const renderAnsi = shouldRenderAnsi(language, code);
const onCopy = useCallback(() => {
if (!navigator.clipboard) return;
navigator.clipboard.writeText(renderAnsi ? stripAnsi(code) : code).then(() => {
void copyTextToClipboard(renderAnsi ? stripAnsi(code) : code).then((ok) => {
if (!ok) return;
setCopied(true);
setTimeout(() => setCopied(false), 1_500);
});
@@ -172,6 +172,7 @@ interface ThreadComposerProps {
workspaceError?: string | null;
onWorkspaceScopeChange?: (scope: WorkspaceScopePayload) => void;
pendingQueueKey?: string | null;
transcriptionProvider?: string | null;
}
const COMMAND_ICONS: Record<string, LucideIcon> = {
@@ -782,6 +783,7 @@ export function ThreadComposer({
workspaceError = null,
onWorkspaceScopeChange,
pendingQueueKey = null,
transcriptionProvider = null,
}: ThreadComposerProps) {
const { t } = useTranslation();
const [value, setValue] = useState("");
@@ -1193,6 +1195,7 @@ export function ThreadComposer({
onError: setVoiceError,
onTranscript: appendTranscription,
onTranscribeAudio,
wantsWav: transcriptionProvider === "xiaomi_mimo",
});
useEffect(() => {
@@ -494,6 +494,7 @@ export function ThreadShell({
return client.onSessionUpdate((updatedChatId, scope) => {
if (updatedChatId !== chatId) return;
if (scope === "metadata") return;
viewportRef.current?.cancelAutoScroll();
pendingCanonicalHydrateRef.current.add(chatId);
refreshHistory();
});
@@ -736,6 +737,7 @@ export function ThreadShell({
workspaceError={workspaceError}
onWorkspaceScopeChange={onWorkspaceScopeChange}
pendingQueueKey={chatId}
transcriptionProvider={settingsSnapshot?.transcription?.provider}
/>
) : (
<ThreadComposer
@@ -765,6 +767,7 @@ export function ThreadShell({
workspaceScopeDisabled={workspaceScopeDisabled}
workspaceError={workspaceError}
onWorkspaceScopeChange={onWorkspaceScopeChange}
transcriptionProvider={settingsSnapshot?.transcription?.provider}
/>
)}
</>
@@ -26,6 +26,7 @@ import type { CliAppInfo, McpPresetInfo, UIMessage } from "@/lib/types";
export interface ThreadViewportHandle {
jumpToUserPrompt: (promptId: string) => void;
cancelAutoScroll: () => void;
}
interface ThreadViewportProps {
@@ -290,7 +291,14 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
setVisibleMessageCount((count) => Math.max(count, messages.length - index));
}, [messages]);
useImperativeHandle(ref, () => ({ jumpToUserPrompt }), [jumpToUserPrompt]);
useImperativeHandle(
ref,
() => ({
jumpToUserPrompt,
cancelAutoScroll: cancelScheduledBottomScroll,
}),
[cancelScheduledBottomScroll, jumpToUserPrompt],
);
const measureComposerDock = useCallback(() => {
const el = composerDockRef.current;
+91 -1
View File
@@ -42,6 +42,8 @@ interface VoiceRecorderOptions {
onError: (key: VoiceRecorderErrorKey) => void;
onTranscript: (text: string) => void;
onTranscribeAudio?: (dataUrl: string, options?: { durationMs?: number }) => Promise<string>;
/** When true, convert recorded audio to WAV before sending (needed for providers that don't support WebM). */
wantsWav?: boolean;
}
export function useVoiceRecorder({
@@ -50,6 +52,7 @@ export function useVoiceRecorder({
onError,
onTranscript,
onTranscribeAudio,
wantsWav = false,
}: VoiceRecorderOptions) {
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const chunksRef = useRef<BlobPart[]>([]);
@@ -223,7 +226,9 @@ export function useVoiceRecorder({
return;
}
setState("transcribing");
void blobToDataUrl(new Blob(chunks, { type: mimeType }))
const blob = new Blob(chunks, { type: mimeType });
const audioPromise = wantsWav ? convertBlobToWav(blob) : blobToDataUrl(blob);
void audioPromise
.then((dataUrl) => onTranscribeAudio(dataUrl, { durationMs }))
.then(onTranscript)
.catch((error) => onError(transcriptionErrorKey(error)))
@@ -260,6 +265,7 @@ export function useVoiceRecorder({
startWaveform,
state,
stopRecording,
wantsWav,
]);
const startRecordingWithDeferredStop = useCallback(() => {
@@ -414,6 +420,90 @@ function blobToDataUrl(blob: Blob): Promise<string> {
});
}
/**
* Convert any browser-recorded audio blob (typically webm/opus) to WAV
* using the Web Audio API. This avoids sending unsupported formats
* (e.g. webm) to ASR providers that only accept wav/mp3/mpeg.
*/
async function convertBlobToWav(blob: Blob): Promise<string> {
const AudioCtx = audioContextConstructor();
if (!AudioCtx) return blobToDataUrl(blob);
const arrayBuffer = await blob.arrayBuffer();
const ctx = new AudioCtx();
try {
const audioBuffer = await ctx.decodeAudioData(arrayBuffer);
const wavBlob = audioBufferToWav(audioBuffer);
return blobToDataUrl(wavBlob);
} finally {
void ctx.close();
}
}
/**
* Encode an AudioBuffer as a 16-bit PCM WAV Blob.
*/
function audioBufferToWav(buffer: AudioBuffer): Blob {
const numChannels = buffer.numberOfChannels;
const sampleRate = buffer.sampleRate;
const format = 1; // PCM
const bitsPerSample = 16;
// Interleave channels
const channels: Float32Array[] = [];
for (let ch = 0; ch < numChannels; ch++) {
channels.push(buffer.getChannelData(ch));
}
const length = channels[0].length;
const interleaved = new Int16Array(length * numChannels);
for (let i = 0; i < length; i++) {
for (let ch = 0; ch < numChannels; ch++) {
const sample = Math.max(-1, Math.min(1, channels[ch][i]));
interleaved[i * numChannels + ch] = sample < 0
? sample * 0x8000
: sample * 0x7FFF;
}
}
const byteRate = sampleRate * numChannels * (bitsPerSample / 8);
const blockAlign = numChannels * (bitsPerSample / 8);
const dataSize = interleaved.byteLength;
const headerSize = 44;
const totalSize = headerSize + dataSize;
const buffer2 = new ArrayBuffer(totalSize);
const view = new DataView(buffer2);
// RIFF header
writeString(view, 0, "RIFF");
view.setUint32(4, totalSize - 8, true);
writeString(view, 8, "WAVE");
// fmt sub-chunk
writeString(view, 12, "fmt ");
view.setUint32(16, 16, true); // sub-chunk size
view.setUint16(20, format, true);
view.setUint16(22, numChannels, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, byteRate, true);
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitsPerSample, true);
// data sub-chunk
writeString(view, 36, "data");
view.setUint32(40, dataSize, true);
new Int16Array(buffer2, headerSize).set(interleaved);
return new Blob([buffer2], { type: "audio/wav" });
}
function writeString(view: DataView, offset: number, str: string): void {
for (let i = 0; i < str.length; i++) {
view.setUint8(offset + i, str.charCodeAt(i));
}
}
function transcriptionErrorKey(error: unknown): VoiceRecorderErrorKey {
const detail = error instanceof Error ? error.message : "";
if (detail === "not_configured") return "notConfigured";
+30 -1
View File
@@ -1,4 +1,4 @@
import { act, render, screen } from "@testing-library/react";
import { act, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
@@ -146,6 +146,35 @@ describe("CodeBlock", () => {
}
});
it("copies with the textarea fallback when Clipboard API is unavailable", async () => {
const user = userEvent.setup();
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: undefined,
});
const execCommand = vi.fn().mockReturnValue(true);
Object.defineProperty(document, "execCommand", {
configurable: true,
value: execCommand,
});
try {
render(
<ThemeProvider theme="dark">
<CodeBlock language="ts" code="const value = 1;" highlight={false} />
</ThemeProvider>,
);
await user.click(screen.getByRole("button", { name: /copy/i }));
await waitFor(() => expect(execCommand).toHaveBeenCalledWith("copy"));
expect(screen.getByText("Copied")).toBeInTheDocument();
} finally {
Reflect.deleteProperty(navigator, "clipboard");
Reflect.deleteProperty(document, "execCommand");
}
});
it("reads theme from context without creating per-block observers", async () => {
const originalMutationObserver = globalThis.MutationObserver;
const observer = vi.fn();
+66 -1
View File
@@ -226,7 +226,20 @@ function mockVoiceRecorder(blob = new Blob(["voice"], { type: "audio/webm" })) {
return { getUserMedia, stopTrack };
}
function mockVoiceAudioInput(sample = 128, state: AudioContextState = "running") {
function mockVoiceAudioInput(
sample = 128,
state: AudioContextState = "running",
decodedChannels?: Float32Array[],
) {
const decodeAudioDataMock = vi.fn(async () => {
if (!decodedChannels) throw new Error("decodeAudioData not mocked");
return {
numberOfChannels: decodedChannels.length,
sampleRate: 16_000,
getChannelData: (channel: number) => decodedChannels[channel],
} as AudioBuffer;
});
class FakeAudioContext {
state = state;
@@ -244,6 +257,7 @@ function mockVoiceAudioInput(sample = 128, state: AudioContextState = "running")
}
close = vi.fn(async () => undefined);
decodeAudioData = decodeAudioDataMock;
resume = vi.fn(async () => undefined);
}
@@ -254,6 +268,7 @@ function mockVoiceAudioInput(sample = 128, state: AudioContextState = "running")
vi.spyOn(window, "cancelAnimationFrame").mockImplementation((id) =>
window.clearTimeout(id as unknown as number)
);
return { decodeAudioData: decodeAudioDataMock };
}
async function waitForVoiceCapture(): Promise<void> {
@@ -262,6 +277,15 @@ async function waitForVoiceCapture(): Promise<void> {
});
}
function bytesFromDataUrl(dataUrl: string): Uint8Array {
const [, base64 = ""] = dataUrl.split(",");
return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
}
function ascii(bytes: Uint8Array, offset: number, length: number): string {
return String.fromCharCode(...bytes.slice(offset, offset + length));
}
describe("ThreadComposer", () => {
it("renders a readonly hero model composer when provided", () => {
render(
@@ -337,6 +361,47 @@ describe("ThreadComposer", () => {
expect(onSend).not.toHaveBeenCalled();
});
it("converts voice recordings to wav for Xiaomi MiMo transcription", async () => {
mockVoiceRecorder(new Blob([new Uint8Array([1, 2, 3, 4])], { type: "audio/webm" }));
const { decodeAudioData } = mockVoiceAudioInput(
180,
"running",
[new Float32Array([0, 0.5, -0.5])],
);
const onTranscribeAudio = vi.fn(async () => "mimo voice");
render(
<ThreadComposer
onSend={vi.fn()}
onTranscribeAudio={onTranscribeAudio}
placeholder="Type your message..."
transcriptionProvider="xiaomi_mimo"
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument();
await waitForVoiceCapture();
fireEvent.click(await screen.findByRole("button", { name: "Stop recording" }));
await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledTimes(1));
const [dataUrl, options] = onTranscribeAudio.mock.calls[0];
expect(dataUrl).toMatch(/^data:audio\/wav;base64,/);
expect(options).toEqual(expect.objectContaining({ durationMs: expect.any(Number) }));
expect(decodeAudioData).toHaveBeenCalledTimes(1);
const bytes = bytesFromDataUrl(dataUrl);
const view = new DataView(bytes.buffer);
expect(ascii(bytes, 0, 4)).toBe("RIFF");
expect(ascii(bytes, 8, 4)).toBe("WAVE");
expect(ascii(bytes, 12, 4)).toBe("fmt ");
expect(view.getUint16(20, true)).toBe(1);
expect(view.getUint16(22, true)).toBe(1);
expect(view.getUint32(24, true)).toBe(16_000);
expect(view.getUint16(34, true)).toBe(16);
expect(ascii(bytes, 36, 4)).toBe("data");
await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("mimo voice"));
});
it("does not start duplicate voice recordings while microphone access is pending", async () => {
const { getUserMedia, stopTrack } = mockVoiceRecorder();
let resolveStream: ((stream: MediaStream) => void) | undefined;