chore: merge master into dev/4.11.x

This commit is contained in:
Junyan Qin
2026-08-14 16:04:52 +08:00
121 changed files with 9173 additions and 5846 deletions
-59
View File
@@ -1,59 +0,0 @@
name: Build and deploy production
on:
push:
branches: [deploy/prod]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: langbot-production
cancel-in-progress: false
env:
CORE_IMAGE: ${{ secrets.DOCKER_USERNAME }}/langbot
CLOUD_IMAGE: ${{ secrets.DOCKER_USERNAME }}/langbot-cloud-core
SPACE_REF: 178b1634c104e635c706e1fb4ca37cb3de073cf9
jobs:
build-and-deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build exact Core image
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: |
${{ env.CORE_IMAGE }}:prod-${{ github.sha }}
${{ env.CORE_IMAGE }}:deploy-prod
cache-from: type=gha,scope=core-prod
cache-to: type=gha,mode=max,scope=core-prod
- name: Checkout production Cloud adapter
uses: actions/checkout@v4
with:
repository: langbot-app/langbot-space
ref: ${{ env.SPACE_REF }}
token: ${{ secrets.CLA_PAT }}
path: .space
- name: Build exact Cloud Core image
uses: docker/build-push-action@v6
with:
context: .space
file: .space/Dockerfile.cloud
push: true
build-args: LANGBOT_CORE_IMAGE=${{ env.CORE_IMAGE }}:prod-${{ github.sha }}
tags: |
${{ env.CLOUD_IMAGE }}:prod-${{ github.sha }}
${{ env.CLOUD_IMAGE }}:deploy-prod
cache-from: type=gha,scope=cloud-core-prod
cache-to: type=gha,mode=max,scope=cloud-core-prod
+1 -1
View File
@@ -1,4 +1,4 @@
FROM node:22-alpine AS node
FROM --platform=$BUILDPLATFORM node:22-alpine AS node
WORKDIR /app
+1
View File
@@ -83,6 +83,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### One-Click Cloud Deploy
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/en-US/templates/ZKTBDH)
+1
View File
@@ -83,6 +83,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### 一键云部署
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/zh-CN/templates/ZKTBDH)
+1
View File
@@ -82,6 +82,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### Despliegue en la Nube con un Clic
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/en-US/templates/ZKTBDH)
+1
View File
@@ -82,6 +82,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### Déploiement Cloud en un Clic
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/en-US/templates/ZKTBDH)
+1
View File
@@ -82,6 +82,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### ワンクリッククラウドデプロイ
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/en-US/templates/ZKTBDH)
+1
View File
@@ -82,6 +82,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### 원클릭 클라우드 배포
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/en-US/templates/ZKTBDH)
+1
View File
@@ -82,6 +82,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### Облачное развертывание одним кликом
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/en-US/templates/ZKTBDH)
+1
View File
@@ -84,6 +84,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### 一鍵雲端部署
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/zh-CN/templates/ZKTBDH)
+1
View File
@@ -82,6 +82,7 @@ cd LangBot/docker
docker compose --profile all up -d
```
### Triển khai đám mây một cú nhấp
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/en-US/templates/ZKTBDH)
-97
View File
@@ -1,97 +0,0 @@
#!/usr/bin/env bash
set -Eeuo pipefail
cd /opt/langbot-cloud-prod
TAG=${1:?usage: deploy.sh prod-<40-char-sha>}
[[ "$TAG" =~ ^prod-[0-9a-f]{40}$ ]] || { echo 'invalid immutable image tag' >&2; exit 2; }
[[ -s .env ]] || { echo '/opt/langbot-cloud-prod/.env is missing' >&2; exit 3; }
rendered_compose=$(docker compose config)
grep -Fq 'LANGBOT_SPACE_CONTROL_PLANE_URL: https://space.langbot.app' <<<"$rendered_compose" || {
echo 'Cloud control-plane URL must be https://space.langbot.app' >&2
exit 4
}
grep -Fq 'SPACE__URL: https://space.langbot.app' <<<"$rendered_compose" || {
echo 'Cloud user-facing Space URL must be https://space.langbot.app' >&2
exit 5
}
grep -Eq 'LANGBOT_TELEMETRY_INGEST_TOKEN: .+' <<<"$rendered_compose" || {
echo 'Cloud telemetry ingest token must be configured' >&2
exit 6
}
update_env() {
local key=$1 value=$2
python3 - "$key" "$value" <<'PY'
from pathlib import Path
import os
import sys
path = Path('.env')
key, value = sys.argv[1:]
lines = path.read_text().splitlines()
updated = False
for index, line in enumerate(lines):
if line.startswith(f'{key}='):
lines[index] = f'{key}={value}'
updated = True
break
if not updated:
lines.append(f'{key}={value}')
temporary = Path('.env.tmp')
temporary.write_text('\n'.join(lines) + '\n')
os.chmod(temporary, 0o600)
temporary.replace(path)
PY
}
update_env LANGBOT_IMAGE_TAG "$TAG"
set -a
. ./.env
set +a
: "${CLOUD_V2_CONTROL_PLANE_TOKEN:?CLOUD_V2_CONTROL_PLANE_TOKEN is required}"
for attempt in 1 2 3 4 5; do
if docker compose pull postgres redis migrate plugin-runtime core; then
break
fi
if [ "$attempt" -eq 5 ]; then
echo "docker compose pull failed after $attempt attempts" >&2
exit 1
fi
delay=$((attempt * 10))
echo "docker compose pull failed (attempt $attempt/5); retrying in ${delay}s" >&2
sleep "$delay"
done
docker compose up -d postgres redis
for _ in $(seq 1 60); do
if docker compose exec -T postgres pg_isready -U langbot_operator -d langbot >/dev/null 2>&1; then break; fi
sleep 2
done
docker compose exec -T postgres pg_isready -U langbot_operator -d langbot >/dev/null
docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U langbot_operator -d langbot \
-v runtime_password="$POSTGRES_RUNTIME_PASSWORD" <<'SQL'
SELECT format('CREATE ROLE langbot_runtime LOGIN PASSWORD %L', :'runtime_password')
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'langbot_runtime')\gexec
ALTER ROLE langbot_runtime PASSWORD :'runtime_password';
GRANT CONNECT ON DATABASE langbot TO langbot_runtime;
REVOKE CREATE ON SCHEMA public FROM PUBLIC, langbot_runtime;
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM langbot_runtime;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM langbot_runtime;
ALTER DEFAULT PRIVILEGES FOR ROLE langbot_operator IN SCHEMA public REVOKE ALL ON TABLES FROM langbot_runtime;
ALTER DEFAULT PRIVILEGES FOR ROLE langbot_operator IN SCHEMA public REVOKE ALL ON SEQUENCES FROM langbot_runtime;
GRANT USAGE ON SCHEMA public TO langbot_runtime;
SQL
docker compose --profile tools run --rm migrate
docker compose up -d --remove-orphans plugin-runtime core
for _ in $(seq 1 90); do
if docker compose exec -T core python -c 'import urllib.request; urllib.request.urlopen("http://127.0.0.1:5300/healthz", timeout=3)' >/dev/null 2>&1; then
docker compose ps
exit 0
fi
sleep 2
done
docker compose logs --tail=200 core plugin-runtime >&2
exit 1
-162
View File
@@ -1,162 +0,0 @@
services:
postgres:
image: pgvector/pgvector:pg17
container_name: langbot-cloud-postgres
restart: unless-stopped
environment:
POSTGRES_DB: langbot
POSTGRES_USER: langbot_operator
POSTGRES_PASSWORD: ${POSTGRES_OPERATOR_PASSWORD}
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: [CMD-SHELL, "pg_isready -U langbot_operator -d langbot"]
interval: 5s
timeout: 5s
retries: 30
networks: [internal]
redis:
image: redis:7.4-alpine
container_name: langbot-cloud-redis
restart: unless-stopped
command: [redis-server, --appendonly, "yes", --requirepass, "${REDIS_PASSWORD}"]
volumes:
- redis-data:/data
healthcheck:
test: [CMD-SHELL, "redis-cli -a \"$${REDIS_PASSWORD}\" ping | grep PONG"]
interval: 5s
timeout: 5s
retries: 20
environment:
REDIS_PASSWORD: ${REDIS_PASSWORD}
networks: [internal]
migrate:
image: rockchin/langbot-cloud-core:${LANGBOT_IMAGE_TAG}
profiles: [tools]
command: [uv, run, langbot, migrate, --cloud]
environment: &core-env
TZ: Asia/Shanghai
SYSTEM__INSTANCE_ID: ${CLOUD_V2_INSTANCE_UUID}
SYSTEM__EDITION: cloud
SYSTEM__RECOVERY_KEY: ${SYSTEM_RECOVERY_KEY}
SYSTEM__JWT__SECRET: ${JWT_SECRET}
SYSTEM__LIMITATION__MAX_BOTS: "2"
SYSTEM__LIMITATION__MAX_PIPELINES: "3"
SYSTEM__LIMITATION__MAX_EXTENSIONS: "3"
SYSTEM__LIMITATION__MAX_KNOWLEDGE_BASES: "2"
API__WEBHOOK_PREFIX: https://cloud.langbot.app
API__WEBUI_URL: https://cloud.langbot.app
WORKSPACE__INVITATIONS__PUBLIC_WEB_URL: https://cloud.langbot.app
DATABASE__USE: postgresql
DATABASE__POSTGRESQL__URL: postgresql+asyncpg://langbot_runtime:${POSTGRES_RUNTIME_PASSWORD}@postgres:5432/langbot
DATABASE__CLOUD_MIGRATION__OPERATOR_DSN_ENV: LANGBOT_CLOUD_MIGRATION_DSN
LANGBOT_CLOUD_MIGRATION_DSN: postgresql://langbot_operator:${POSTGRES_OPERATOR_PASSWORD}@postgres:5432/langbot
VDB__USE: pgvector
VDB__PGVECTOR__USE_BUSINESS_DATABASE: "true"
VDB__PGVECTOR__ALLOWED_DIMENSIONS: "384,512,768,1024,1536"
PLUGIN__ENABLE: "true"
PLUGIN__RUNTIME_WS_URL: ws://plugin-runtime:5400/control/ws
PLUGIN__DISPLAY_PLUGIN_DEBUG_URL: wss://cloud.langbot.app/plugin/debug/ws
PLUGIN__WORKER__MAX_CPUS: "0.25"
PLUGIN__WORKER__MAX_MEMORY_MB: "256"
PLUGIN__WORKER__MAX_PIDS: "128"
PLUGIN__WORKER__MAX_WORKERS: "16"
PLUGIN__WORKER__MAX_TOTAL_CPUS: "4.0"
PLUGIN__WORKER__MAX_TOTAL_MEMORY_MB: "4096"
PLUGIN__WORKER__REQUIRE_HARD_LIMITS: "true"
LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN: ${PLUGIN_RUNTIME_CONTROL_TOKEN}
# Cloud v2 currently grants no managed Box capability. Keep the shared
# runtime deployed but disable Core integration until a hard-quota-capable
# backend can satisfy the fail-closed Cloud readiness contract.
BOX__ENABLED: "false"
BOX__BACKEND: nsjail
BOX__RUNTIME__ENDPOINT: ws://box:5410
BOX__ADMISSION__REQUIRED: "true"
BOX__ADMISSION__LOGICAL_SESSION_ID: global
BOX__ADMISSION__REQUIRED_BACKEND: nsjail
BOX__ADMISSION__MAX_SESSIONS: "1"
BOX__ADMISSION__MAX_MANAGED_PROCESSES: "0"
BOX__ADMISSION__CPUS: "0.25"
BOX__ADMISSION__MEMORY_MB: "256"
BOX__ADMISSION__WORKSPACE_QUOTA_MB: "256"
BOX__LOCAL__HOST_ROOT: /app/data/box
BOX__LOCAL__DEFAULT_WORKSPACE: /app/data/box
BOX__LOCAL__ALLOWED_MOUNT_ROOTS: /app/data/box
LANGBOT_BOX_CONTROL_TOKEN: ${BOX_CONTROL_TOKEN}
MCP__STDIO__ENABLED: "false"
LANGBOT_SPACE_CONTROL_PLANE_URL: https://space.langbot.app
LANGBOT_SPACE_CONTROL_PLANE_TOKEN: ${CLOUD_V2_CONTROL_PLANE_TOKEN}
LANGBOT_TELEMETRY_INGEST_TOKEN: ${CLOUD_V2_CONTROL_PLANE_TOKEN}
LANGBOT_SPACE_CONTROL_PLANE_PUBLIC_KEY: ${CLOUD_V2_MANIFEST_PUBLIC_KEY}
LANGBOT_SPACE_CONTROL_PLANE_KEY_ID: ${CLOUD_V2_MANIFEST_KEY_ID}
SPACE__URL: https://space.langbot.app
depends_on:
postgres: {condition: service_healthy}
networks: [internal]
plugin-runtime:
image: rockchin/langbot:${LANGBOT_IMAGE_TAG}
container_name: langbot-cloud-plugin-runtime
restart: unless-stopped
command: [uv, run, python, -m, langbot_plugin.cli.__init__, rt]
environment:
LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN: ${PLUGIN_RUNTIME_CONTROL_TOKEN}
volumes:
- plugin-data:/app/data
- /sys/fs/cgroup:/sys/fs/cgroup:rw
cgroup: host
privileged: true
expose: ["5400"]
networks: [internal]
box:
image: rockchin/langbot:${LANGBOT_IMAGE_TAG}
container_name: langbot-cloud-box
restart: unless-stopped
command: [uv, run, lbp, box, --host, 0.0.0.0, --ws-control-port, "5410"]
environment:
LANGBOT_BOX_CONTROL_TOKEN: ${BOX_CONTROL_TOKEN}
LANGBOT_BOX_ROOT: /app/data/box
volumes:
- box-data:/app/data/box
- /sys/fs/cgroup:/sys/fs/cgroup:rw
cgroup: host
privileged: true
expose: ["5410"]
networks: [internal]
core:
image: rockchin/langbot-cloud-core:${LANGBOT_IMAGE_TAG}
container_name: langbot-cloud-core
restart: unless-stopped
environment: *core-env
volumes:
- core-data:/app/data
- box-data:/app/data/box
depends_on:
postgres: {condition: service_healthy}
redis: {condition: service_healthy}
plugin-runtime: {condition: service_started}
box: {condition: service_started}
expose: ["5300"]
healthcheck:
test: [CMD-SHELL, "python -c 'import urllib.request; urllib.request.urlopen(\"http://127.0.0.1:5300/healthz\", timeout=3)'" ]
interval: 10s
timeout: 5s
retries: 30
start_period: 30s
networks: [internal, shared-network]
networks:
internal:
shared-network:
external: true
volumes:
postgres-data:
redis-data:
plugin-data:
box-data:
core-data:
+10 -11
View File
@@ -14,8 +14,8 @@ services:
restart: on-failure
environment:
- TZ=Asia/Shanghai
# Shared with the langbot service and sent only as a WebSocket handshake
# header. Generate with: openssl rand -hex 32
# Optional. Leave unset on both OSS services, or set the same value on
# both to protect the control WebSocket. Generate with: openssl rand -hex 32
- LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN=${LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN:-}
# Process-wide admission for every asyncio.to_thread() call.
- LANGBOT_BLOCKING_EXECUTOR_MAX_WORKERS=${LANGBOT_BLOCKING_EXECUTOR_MAX_WORKERS:-8}
@@ -47,11 +47,10 @@ services:
restart: on-failure
environment:
- TZ=Asia/Shanghai
# Shared control-plane secret used to authenticate both the RPC socket
# and managed-process relay. Generate once (for example with
# ``openssl rand -hex 32``) and export it before enabling this profile.
# An empty value is accepted by Compose so Box can remain optional, but
# the Box runtime itself fails closed when the profile is started.
# Optional shared control-plane secret used to authenticate both the RPC
# socket and managed-process relay. Leave unset on both OSS services, or
# generate one with ``openssl rand -hex 32`` and set the same value on
# both ends. Strongly recommended when the deployment is Internet-accessible.
- LANGBOT_BOX_CONTROL_TOKEN=${LANGBOT_BOX_CONTROL_TOKEN:-}
# Box has its own process-wide blocking-work budget.
- LANGBOT_BLOCKING_EXECUTOR_MAX_WORKERS=${LANGBOT_BLOCKING_EXECUTOR_MAX_WORKERS:-8}
@@ -77,11 +76,11 @@ services:
restart: on-failure
environment:
- TZ=Asia/Shanghai
# Must match langbot_plugin_runtime. Empty/missing values make the
# external control channel fail closed.
# Optional. Leave unset on both OSS services, or match plugin Runtime.
- LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN=${LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN:-}
# Must match the value supplied to langbot_box. The token is sent only
# in WebSocket handshake headers, never in URLs or action payloads.
# When set, this must match langbot_box. If both ends leave it unset,
# OSS permits the connection without token authentication. The token is
# sent only in WebSocket handshake headers, never in URLs or payloads.
- LANGBOT_BOX_CONTROL_TOKEN=${LANGBOT_BOX_CONTROL_TOKEN:-}
# Core process-wide blocking-work admission. These are native config
# overrides and are persisted with the effective data/config.yaml.
@@ -103,11 +103,11 @@ This log records implementation choices made while delivering the Workspace arch
- Decision: New Core JWTs require `iss=langbot-core`, an audience derived from the immutable instance UUID, and an expiry. Legacy community tokens are accepted only when they have the historical issuer, carry no audience, and the active policy is the OSS singleton policy.
- Reason: A token issued by one instance must not authenticate against another instance that happens to share a secret, and a compatibility decoder must not become an alternate path around the SaaS trust boundary.
### Runtime control transports authenticate before protocol dispatch
### Runtime control transports support opt-in shared-secret authentication
- Decision: External Plugin Runtime and Box WebSocket control channels require independent strong shared secrets in handshake headers. Locally managed child processes receive ephemeral secrets through their environment; secrets are not placed in URLs, process arguments, request payloads, or logs. Box additionally binds the first authenticated control channel to one trusted instance. Plugin Runtime debug and control credentials remain separate.
- Reason: Workspace context inside an RPC payload is not trustworthy until the transport peer itself is authenticated. Separating control and debug credentials also limits accidental privilege reuse.
- Deployment consequence: Docker Compose and Kubernetes wire one shared secret to each host/runtime pair. An empty external-runtime secret fails startup instead of silently exposing an unauthenticated socket.
- Decision: OSS external Plugin Runtime and Box WebSocket control channels preserve tokenless standalone compatibility when the corresponding control token is unset. When a Runtime configures a token, it validates the independent shared secret in the handshake before protocol dispatch. Locally managed child processes still receive ephemeral secrets through their environment; secrets are not placed in URLs, process arguments, request payloads, or logs. Box additionally pins the first control channel to one declared instance identity. Plugin Runtime debug and control credentials remain separate.
- Reason: Local OSS development must remain backward compatible, while exposed or shared Runtime endpoints can opt into transport authentication. Separating control and debug credentials also limits accidental privilege reuse.
- Deployment consequence: Docker Compose and Kubernetes should wire one strong shared secret to each host/runtime pair. Both sides must use the same value for protection to be effective; a Runtime configured with a token rejects clients that omit it or send a different value.
### Dashboard WebSocket sessions are tenant runtime objects
@@ -0,0 +1,476 @@
# 模型思考控制设计方案
> 日期:2026-07-31
> 状态:Phase 1 已审核并实现
> 范围:LangBot 主仓库的模型配置、LiteLLM 请求层、Local Agent、Web 管理面板、监控与测试
## 1. 结论
建议为 LangBot 增加一套与厂商参数解耦的“思考策略”模型,并明确区分三个概念:
1. **思考能力**:模型是否支持思考,以及支持开关、档位还是 token 预算。
2. **思考策略**:一次请求选择厂商默认、关闭、开启或指定思考档位。
3. **思考展示**:是否把模型返回的思考内容展示给最终用户。
现有 `remove-think` 只属于第 3 类。它会过滤输出,但不会阻止模型思考,也不会降低思考 token、费用或延迟。新能力不应复用或改写这个字段。
推荐实现原则:
- 默认值为 `provider_default`,不向上游增加任何新参数,现有模型行为完全不变。
- 用户显式选择的策略必须被准确执行;无法准确执行时返回明确错误,不静默降级。
- LangBot 内部只保存统一策略,Provider 请求层负责翻译成各厂商参数。
- `extra_args` 保留为高级逃生口,但不能成为主 UI 的思考配置方式。
- 模型页只管理并展示能力;可写策略归属于 Local Agent 流水线,同一模型可在不同业务中使用不同思考量。
- 原始 reasoning 数据与展示文本分开保存,保证多轮对话、工具调用和签名字段不丢失。
## 2. 调研结论
### 2.1 可验证资料
本次结论基于以下可验证来源:
- OpenAI 官方 Reasoning Guide`reasoning.effort` 的可选值由模型决定,可包括 `none``minimal``low``medium``high``xhigh``max`;低档位偏向低延迟和低 token,高档位偏向质量。
- https://developers.openai.com/api/docs/guides/reasoning#reasoning-effort
- LangBot 锁定的 LiteLLM `1.88.1` 实现。`uv.lock` 已锁定该版本,本地缓存中的适配代码可以确认 LangBot 实际依赖所支持的翻译行为。
- LangBot 当前实现:模型级 `extra_args` 会在 `LiteLLMRequester._build_completion_args()` 中直接合并到 `acompletion()` 参数。
Anthropic、Google 和 LiteLLM 的官方文档域名在本次环境中被浏览器策略禁止访问,因此下表中这些厂商的结论以 LiteLLM `1.88.1` 实际适配代码为准。实施前应再用对应厂商官方文档做一次参数范围核验,尤其是模型代际和允许值。
### 2.2 厂商差异矩阵
| Provider / 生态 | 可控制能力 | LiteLLM 1.88.1 统一入口 | 关键限制 | 建议支持级别 |
| --- | --- | --- | --- | --- |
| OpenAI | 思考档位,部分模型支持 `none` | `reasoning_effort` | 每个模型支持的档位不同,不能把 `none` 当成通用能力 | 首批完整支持 |
| Anthropic | 旧模型使用 extended thinking + token budget;新模型可用 adaptive thinking + effort | `reasoning_effort``thinking` | `none` 表示不发送 thinking;新旧模型的映射不同 | 首批完整支持 |
| Gemini | 2.x 主要映射为 `thinkingBudget`3.x 主要映射为 `thinkingLevel` | `reasoning_effort``thinking` | Gemini 3 的 `none` 可能只能降到最低档,不能保证真正关闭 | 首批支持,但严格限制关闭语义 |
| DeepSeek | 开启/关闭;当前适配不支持预算档位 | `thinking={type: enabled}`;非 `none` effort 会映射成开启 | 多轮思考模式要求回传 `reasoning_content` | 首批开关支持 |
| xAI | 思考档位 | `reasoning_effort` | 仅 reasoning-capable 模型接受 | 首批完整支持 |
| Ollama | `think` 布尔值;部分模型接受 low/medium/high | `reasoning_effort` | 非 gpt-oss 模型的档位可能退化为布尔开关 | 首批支持,按模型能力裁剪 UI |
| OpenRouter | 聚合多厂商的 reasoning 参数 | `reasoning_effort``thinking` | 实际能力由路由后的模型决定 | 首批支持,能力未知时要求测试 |
| Volcengine / Doubao | `thinking.type` 支持 enabled/disabled/auto | LiteLLM `volcengine` 适配器支持 `thinking` | LangBot 当前 manifest 使用 `openai`,不会进入该适配器 | 第二批,先修正路由并回归 |
| Bailian / Qwen | 厂商兼容接口有独立思考开关/预算 | LiteLLM `dashscope` 适配器目前未提供统一 reasoning 映射 | LangBot 当前 manifest 使用 `openai`,只能通过高级参数透传 | 第二批,实施前核对官方字段 |
| 其他 OpenAI-compatible 网关 | 取决于网关 | 尝试标准 `reasoning_effort` | 不能仅凭模型名推断完整能力 | 保守支持,默认不自动开启 |
### 2.3 对 LangBot 的直接含义
不能把这个功能实现成单一 `enable_thinking: bool`,原因如下:
- 有的模型只有开关,有的模型只有档位,有的模型允许精确 token 预算。
- 有的模型本身始终推理,只能降低思考量,无法真正关闭。
- 同一个通用档位在不同厂商会映射成不同的实际预算。
- 聚合网关和自定义 OpenAI-compatible 服务无法可靠地通过模型名识别能力。
- “不展示思考内容”不等于“关闭思考”。
## 3. 当前项目现状
### 3.1 已有能力
- `LLMModel.extra_args` 是 JSON 字段,Web 端已有通用高级参数编辑器。
- `LiteLLMRequester` 会按“模型级 `extra_args`,再调用级 `extra_args`”的顺序合并参数。
- LiteLLM 已统一处理多个 Provider 的 `reasoning_effort``thinking` 和返回的 `reasoning_content`
- `LocalAgentRunner` 的非流式、流式、工具调用和 fallback 路径都经过 `RuntimeProvider.invoke_llm*()`
- `remove-think` 已能控制 `<think>` 或独立 reasoning 内容是否进入展示文本。
- Gemini 工具调用所需的 `provider_specific_fields` / thought signature 已有保留逻辑和单元测试。
### 3.2 现有缺口
- 管理员只能手写 `extra_args`,没有统一语义、能力提示和校验。
- `remove-think` 名称容易被误解为关闭模型思考。
- 模型扫描只识别 `vision``func_call`,没有 reasoning 能力。
- 当前返回处理会把 `reasoning_content` 拼进 `<think>` 文本后删除原字段,可能损失多轮思考所需的结构化数据。
- DeepSeek 思考模式需要在后续轮次回传 `reasoning_content`,当前链路不能保证完整保留。
- Pipeline 只能选择模型,不能针对业务覆盖模型的思考策略。
- 监控只记录总输入/输出 token,没有单独展示 reasoning token。
- 部分 Provider manifest 仍声明为通用 `openai`,导致 LiteLLM 的厂商专用翻译器不会生效。
### 3.3 预计改动地图
| 层 | 主要文件 | 责任 |
| --- | --- | --- |
| 持久化 | `src/langbot/pkg/entity/persistence/model.py``src/langbot/pkg/persistence/alembic/versions/` | 新增 `reasoning_config` JSON 列和 Alembic 迁移 |
| 模型服务 | `src/langbot/pkg/api/http/service/model.py` | CRUD 校验、冲突检测、测试模型时使用统一策略 |
| HTTP 控制器 | `src/langbot/pkg/api/http/controller/groups/provider/models.py` | 继续复用现有模型路由,不新增平行 API |
| 模型管理 | `src/langbot/pkg/provider/modelmgr/modelmgr.py` | 临时模型、数据库模型与扫描结果加载新字段 |
| 请求抽象 | `src/langbot/pkg/provider/modelmgr/requester.py` | 定义能力查询和 reasoning 参数构建接口 |
| LiteLLM 适配 | `src/langbot/pkg/provider/modelmgr/requesters/litellmchat.py` | 能力识别、策略翻译、参数合并、reasoning 返回保留 |
| Provider manifest | `src/langbot/pkg/provider/modelmgr/requesters/*.yaml` | 必要时修正 Provider 路由;相关变更放到独立阶段 |
| Agent 调用 | `src/langbot/pkg/provider/runners/localagent.py` | 所有非流式、流式、工具调用、fallback 路径传递统一策略 |
| Pipeline 元数据 | `src/langbot/templates/metadata/pipeline/ai.yaml` | 第二阶段加入 Pipeline 级覆盖 |
| 输出配置 | `src/langbot/templates/metadata/pipeline/output.yaml` | 保留键名,澄清 `remove-think` 只控制展示 |
| Web 类型/API | `web/src/app/infra/entities/api/index.ts``web/src/app/infra/http/BackendClient.ts` | 增加配置与能力响应类型 |
| 模型 UI | `web/src/app/home/components/models-dialog/` | 能力标记、策略控件、校验、模型测试 |
| i18n | `web/src/i18n/locales/` | 至少补齐英文、简体中文及项目已有覆盖语言 |
| 测试 | `tests/unit_tests/provider/``web/tests/` | 翻译、服务、流式 round-trip、前端状态测试 |
Phase 1 不修改 `langbot-plugin-sdk` 的公共实体或运行时协议。现有 `provider_message.Message.provider_specific_fields` 已可承载 Provider 原始 reasoning 数据;只有后续要把 reasoning 升级为跨插件公开实体时,才需要跨仓库 SDK 变更。
## 4. 领域模型
### 4.1 统一策略
新增 `ReasoningConfig`,保存于 LLM 模型,Pipeline 可提供同结构覆盖。产品层只暴露一个离散档位:
```json
{
"level": "provider_default"
}
```
字段定义:
| 字段 | 类型 | 含义 |
| --- | --- | --- |
| `level` | `provider_default \| disabled \| enabled \| minimal \| low \| medium \| high \| xhigh \| max` | 同时表达开关和思考强度 |
校验规则:
- `provider_default`:不发送任何 reasoning 参数,保持厂商和模型默认行为。
- `disabled`:明确关闭;仅当模型可真正关闭时允许保存/运行。
- `enabled`:明确开启,但由 Provider 决定具体强度,适用于只有开关的模型。
- `minimal``max`:明确开启,并指定强度;仅允许选择模型实际支持的档位。
- 厂商的 `auto` 统一映射为 `provider_default`,不再增加一个重复状态。
- 精确 token 预算不进入主数据结构。少数需要预算的场景继续通过高级参数配置,并由模型测试接口校验。
### 4.2 能力描述
沿用现有 `LLMModel.abilities`,新增 `reasoning` 能力标记。同时由后端在 API 返回中计算只读的 `reasoning_capabilities`
```json
{
"supported": true,
"controls": ["toggle", "effort"],
"efforts": ["none", "low", "medium", "high"],
"can_disable": true,
"source": "litellm"
}
```
设计约束:
- `abilities` 仍是用户可编辑的粗粒度能力,符合现有 `vision``func_call` 模式。
- `reasoning_capabilities` 不持久化,优先从 LiteLLM 模型元数据计算,避免模型升级后数据库残留过期能力。
- 无法识别的自定义模型返回 `supported: null``source: unknown`,不猜测。
- 用户可手动添加 `reasoning` ability,但未知能力模型必须先通过“测试模型”验证显式策略。
- UI 只展示后端声明可用的控件;未知模型保留 Provider Default 和高级参数入口。
### 4.3 持久化
`llm_models` 表新增 JSON 列:
```text
reasoning_config JSON NOT NULL DEFAULT {"level":"provider_default"}
```
使用 Alembic 新迁移,不修改冻结的 legacy migration。
该列作为已实现版本的兼容字段保留;新的模型页不再提供写入口,Local Agent 请求以流水线中按模型 UUID 保存的策略为准。
不建议把内部策略塞进 `extra_args`,原因是当前 `extra_args` 会原样发送给 LiteLLM;使用保留键会让内部元数据泄漏到上游,并使高级参数与产品配置难以区分。
## 5. 配置优先级与请求流程
### 5.1 优先级
```text
Pipeline 当前候选模型策略
↓ 缺少配置时固定为 provider_default
Provider / 模型默认行为
```
请求参数合并顺序:
```text
基础参数
-> 模型 extra_args
-> 调用级 extra_args
-> 统一 reasoning 策略翻译结果(最后应用)
```
统一策略最后应用,可以确保流水线行为不受模型页历史设置影响。为了避免用户困惑,保存和测试时要检测 `extra_args` 中的冲突字段;当 `level != provider_default` 时,发现以下字段应直接报错:
- `reasoning_effort`
- `thinking`
- `reasoning`
- `extra_body` 内已知的 `thinking``enable_thinking``thinking_budget` 等字段
`level == provider_default` 时继续允许这些高级参数,保证旧配置兼容。
### 5.2 翻译层
`pkg/provider/modelmgr/` 内新增独立的 reasoning 规范化模块,职责是:
1. 读取当前流水线候选模型的请求级策略。
2. 查询 `ProviderAPIRequester.get_reasoning_capabilities(model)`
3. 严格校验策略是否可以准确执行。
4. 生成 LiteLLM 参数,不直接发 HTTP。
5. 返回可观测的“最终生效策略”供日志和测试使用。
建议接口:
```python
class ProviderAPIRequester:
def get_reasoning_capabilities(self, model: RuntimeLLMModel) -> ReasoningCapabilities: ...
def build_reasoning_args(
self,
model: RuntimeLLMModel,
config: ReasoningConfig,
) -> dict[str, Any]: ...
```
LiteLLMRequester 默认优先生成统一参数:
- 强度档位:`reasoning_effort=<level>`
- 仅开启:`thinking={"type":"enabled"}` 或 Provider 等价参数
- 关闭:优先 `reasoning_effort="none"`
- 高级参数中的精确预算:`thinking={"type":"enabled","budget_tokens":N}`
Provider 特例只放在 requester 翻译层,不进入 Pipeline 或平台适配器。
### 5.3 Provider 特例
- **Gemini 3**:如果 LiteLLM 能力表不能确认真正关闭,`disabled` 必须报“不支持关闭,可选择 Provider Default 或最低档”,不能把 `none` 静默映射成 low/minimal。
- **DeepSeek**:所有非 `none` 档位最终都只是开启。能力 API 只返回 `toggle`,UI 不显示档位;多轮必须保存并回传 `reasoning_content`
- **Ollama**:仅对明确支持等级的模型展示 effort;其他模型只展示开关。
- **OpenRouter**:以路由后的模型能力为准。模型未知时允许 Provider Default,显式策略必须通过测试接口。
- **Volcengine**:使用 `thinking.type=enabled/disabled/auto`。应先让该 requester 进入 LiteLLM `volcengine` 适配器,或增加等价的明确翻译,不能依赖模型名。
- **Bailian/Qwen**:作为第二批 Provider 专用翻译。实施前核对官方字段、模型范围、预算上下限和流式返回结构,不凭经验写接口。
## 6. 返回数据与思考展示
### 6.1 保留原始 reasoning
当前 `LiteLLMRequester` 会读取 `reasoning_content`,将其拼接成 `<think>` 文本,再删除原字段。建议改为:
```text
上游 reasoning_content
├─ 原样保存在 Message.provider_specific_fields.reasoning_content
└─ 根据 remove-think 决定是否渲染为 <think>...</think>
```
流式路径需要在 accumulator 中分别累计 `content``reasoning_content`,最终消息必须携带结构化 reasoning。不能只依赖已经渲染的 `<think>` 文本反向解析。
这样可以同时满足:
- `remove-think=true` 时用户看不到思考内容,但多轮协议仍能回传必要数据。
- `remove-think=false` 时保持当前用户体验。
- DeepSeek 多轮 thinking 不丢上下文。
- Gemini thought signature、Anthropic thinking block 等 Provider 字段可以继续按结构化方式 round-trip。
### 6.2 现有字段处理
保留数据库和 Pipeline 配置键 `remove-think`,避免破坏兼容。Web 文案改为更准确的:
- 中文:`向用户展示思考过程`
- 英文:`Show reasoning process`
UI 使用正向开关,保存时转换回 `remove-think = !showReasoning`。文案必须强调它只影响展示,不影响模型是否思考、token 或费用。
## 7. Web 管理面板
### 7.1 模型编辑
模型页只承担能力管理和只读展示:
1. `Reasoning` ability 复选框与 Vision、Function Calling 并列,供无法自动识别的自定义模型手动声明能力。
2. 模型卡片使用简短图标或 badge 标识 reasoning 能力。
3. 模型页不提供可写思考挡位,避免模型默认值与流水线策略形成两个控制源。
### 7.2 Local Agent 流水线策略
在 Local Agent 的主模型和每一个 fallback 模型下分别显示紧凑离散滑杆:
1. `Provider 默认` 始终为首个选项;选择它时不向上游增加任何思考参数。
2. 完整档位顺序为:`Provider 默认 / 关闭 / 开启 / 最低 / 低 / 中 / 高 / 极高 / 最大`
3. 前端只渲染后端为该模型返回的可用档位;仅开关模型显示 `Provider 默认 / 关闭 / 开启`
4. 模型不能真正关闭时不提供 `关闭`;能力未知时只显示不可调的 `Provider 默认`
5. 主模型和 fallback 分别保存策略,切换候选模型时不会把一个模型的挡位错误应用到另一个模型。
6. Dify、Coze、Langflow、n8n 等外部 Runner 不显示该控件,因为 LangBot 不直接发起其内部模型请求。
流水线配置保持旧格式兼容,并在模型选择对象中增加按 UUID 保存的映射:
```json
{
"model": {
"primary": "primary-model-uuid",
"fallbacks": ["fallback-model-uuid"],
"reasoning": {
"primary-model-uuid": "high"
}
}
}
```
`provider_default` 不写入映射;缺少 `reasoning` 的旧流水线天然等价于全部使用 Provider 默认。
滑杆交互要求:轨道使用现有主色和中性灰,不使用渐变;当前档位同时显示文字;支持键盘方向键和正确的 ARIA value text;窄屏下不溢出。
### 7.3 i18n
新增文案至少覆盖 `en_US``zh_Hans``ja_JP` 在模型面板现有同类字段已覆盖时同步补齐。不要把厂商参数名直接作为用户文案。
## 8. API、MCP 与 Skill
### 8.1 HTTP API
模型 CRUD 增加:
- 请求字段:`reasoning_config`
- 响应字段:`reasoning_config`
- 只读字段:`reasoning_capabilities`
模型测试接口必须使用与真实请求完全相同的规范化和翻译逻辑,并在失败时返回可操作错误,例如:
```text
Model gemini-3-... cannot disable reasoning.
Supported controls: effort=[low, medium, high].
```
可选增加只读调试信息,仅在测试接口返回:
```json
{
"effective_reasoning": {
"level": "low",
"translated_keys": ["reasoning_effort"]
}
}
```
不得返回 API key、完整请求正文或原始思考内容。
### 8.2 MCP 与技能
当前 MCP 仅列出模型 Provider,没有完整模型 CRUD 工具。如果本次不新增 agent-accessible HTTP 操作,则无需强行新增 MCP 工具。
如果后续让 Agent 修改模型思考策略,则必须同一提交更新:
- `src/langbot/pkg/api/mcp/server.py`
- 对应的 `skills/` 文档
- 参数 schema 和安全说明
## 9. 监控与可观测性
控制思考量后,管理员需要判断质量、延迟和成本是否值得。建议第二阶段增加:
- `reasoning_tokens`:从 `completion_tokens_details.reasoning_tokens` 或 Provider 等价字段提取。
- `effective_reasoning_level`:记录规范化后的生效档位,不记录原始思考内容。
- 模型监控页展示输入 token、可见输出 token、reasoning token、总延迟。
- Provider 不返回细分 token 时显示未知,不推算。
安全要求:日志、监控、debug API 默认都不得记录 reasoning 原文。思考内容可能包含敏感信息或系统提示,不应因为新增配置而扩大持久化范围。
## 10. 兼容与迁移
### 10.1 数据迁移
- 所有现有 LLM 记录迁移为 `{"level":"provider_default"}`
- 不自动解析或迁移现有 `extra_args` 中的 reasoning 参数,避免误判嵌套结构和 Provider 语义。
- UI 检测到旧 `extra_args` reasoning 字段时显示“由高级参数控制”,统一策略保持 Provider Default。
- 用户主动改成统一策略时,要求先移除冲突高级参数。
### 10.2 运行时兼容
- `provider_default` 不产生任何新增请求参数。
- 不改变现有 `remove-think` 的存储键和默认值。
- 不改变已有 Provider 的 `litellm_provider`,除非该 Provider 在专项回归后单独切换。
- `drop_params` 不能用于掩盖显式 reasoning 配置错误;显式策略被丢弃应视为失败。
- 自托管和 toB 环境中的自定义兼容接口保持可用,未知能力不阻止 Provider Default 请求。
## 11. 实施拆分
### Phase 1:统一基础设施与主流 Provider
- Alembic 增加 `llm_models.reasoning_config`
- Backend 模型实体、CRUD、测试接口支持统一配置。
- LiteLLMRequester 增加能力查询、严格校验和参数翻译。
- 支持 OpenAI、Anthropic、Gemini、DeepSeek、xAI、Ollama、OpenRouter 的已验证 LiteLLM 路径。
- 修复结构化 reasoning 的非流式/流式保留。
- 模型面板增加 reasoning ability 与只读能力标识。
- Local Agent 主模型和每个 fallback 增加独立的请求级策略。
### Phase 2:国内 Provider
- 专项核对并支持 Volcengine/Doubao、Bailian/Qwen。
- 对相关 requester 的 `litellm_provider` 变更做独立回归,避免把 reasoning 功能和通用请求行为回归混在一起。
- 补齐扫描结果中的 reasoning capability。
### Phase 3:监控与评估
- 持久化 reasoning token 和生效策略。
- 监控页增加 reasoning 成本/延迟指标。
- 建立不同 effort 的离线质量、首 token 延迟、总耗时和 token 对比基线。
## 12. 测试方案
### 12.1 单元测试
- `ReasoningConfig` 所有合法/非法组合。
- `provider_default` 不产生任何新增参数。
- 显式配置覆盖模型/调用 `extra_args` 的顺序。
- reasoning 配置与高级参数冲突时拒绝。
- OpenAI 档位原样映射。
- Anthropic 档位映射,以及高级参数预算兼容。
- Gemini 2 budget、Gemini 3 level,以及不支持真正关闭时拒绝。
- DeepSeek 只显示/接受 toggle,非 `none` effort 不伪装成不同档位。
- Ollama 布尔与分级模型差异。
- Volcengine enabled/disabled/auto 翻译。
- 未知 Provider 只允许 Provider Default,或在显式测试后使用标准参数。
- 非流式 `reasoning_content` 保存到 `provider_specific_fields`
- 流式 reasoning 分片累计后仍能 round-trip。
- Gemini thought signature 和工具调用现有测试不能回归。
### 12.2 服务与持久化测试
- 新建、读取、更新模型的 `reasoning_config`
- Alembic 从当前 head 升级后默认值正确。
- 模型测试接口与真实 Local Agent 使用同一翻译函数。
- 旧模型、旧 `extra_args``remove-think` 行为不变。
### 12.3 前端测试
- 能力不同的模型显示正确控件。
- 离散滑杆只能停在后端返回的可用档位。
- 当前档位文字、键盘操作和 ARIA value text 正确。
- 仅开关模型、不可关闭模型、完整档位模型分别显示正确刻度。
- fallback 能力不兼容时阻止保存并给出明确提示。
- 中英文文案完整,移动端 Popover 不溢出。
### 12.4 Provider 冒烟测试
至少选取以下真实或可控 mock
- 一个支持 `none` 的 OpenAI reasoning 模型。
- 一个不支持 `none` 的 reasoning 模型。
- 一个 Anthropic adaptive thinking 模型。
- 一个 Gemini 2.x 与一个 Gemini 3.x 模型。
- 一个 DeepSeek hybrid thinking 模型,执行两轮含工具调用对话。
- 一个 Ollama 本地 reasoning 模型。
- 一个 OpenAI-compatible 自定义网关,验证 Provider Default 完全不变。
每个模型比较 Provider Default、最低档、中档、高档或关闭,记录成功率、首 token 延迟、总耗时、总 token 和 reasoning token(若可用)。
## 13. 风险与控制
| 风险 | 影响 | 控制措施 |
| --- | --- | --- |
| 将“最低思考”误当成“关闭” | 用户以为节省了成本,实际仍在推理 | `can_disable` 严格校验,不静默降级 |
| 模型能力表过期 | 新模型无法配置或旧模型报错 | 能力未知时保守;允许测试;升级 LiteLLM 时回归 |
| 高 effort 导致延迟/费用陡增 | 用户体验和预算风险 | 默认 Provider DefaultUI 提示;后续监控 reasoning token |
| `extra_args` 与统一配置冲突 | 实际生效值不可预测 | 保存/测试时拒绝冲突;统一策略最后应用 |
| reasoning 原文进入日志 | 敏感信息泄露 | 不记录原文,只记录策略和 token |
| 多轮 reasoning 丢失 | 工具调用或后续轮次失败/降质 | 结构化保存并 round-trip;流式专项测试 |
| 修改 Provider 路由造成通用回归 | 非 reasoning 请求也受影响 | 国内 Provider 路由放第二阶段,独立提交和回归 |
## 14. 需要审核确认的决策
1. **是否同意三层分离**:能力、策略、展示互不替代,保留 `remove-think` 仅控制展示。
2. **是否同意严格语义**:显式关闭无法准确执行时直接报错,不自动降为最低思考。
3. **是否同意请求级配置**:流水线按模型 UUID 保存挡位,不把产品配置塞进 `extra_args`
4. **是否同意 Runner 边界**:仅 Local Agent 展示控制项,外部 Runner 由其外部系统管理模型策略。
5. **是否同意保守默认**:所有现有模型迁移为 Provider Default,不自动开启、关闭或迁移旧高级参数。
6. **是否把结构化 reasoning 保留纳入第一阶段**:这是 DeepSeek 多轮和工具调用正确性的必要条件,建议必须纳入。
## 15. 推荐审核结果
建议按以上 6 项全部通过,并将 Phase 1 作为一个完整功能单元实施。不要只增加前端开关或只在 `extra_args` 中写 `reasoning_effort`;那样虽然改动小,但会继续混淆展示与推理、无法处理 Provider 差异,也无法保证多轮对话正确性。
+2 -2
View File
@@ -23,7 +23,7 @@ dependencies = [
"pynacl>=1.5.0", # Required for Discord voice support
"gewechat-client>=0.1.5",
"lark-oapi>=1.5.5",
"mcp>=1.25.0",
"mcp>=1.25.0,<2.0.0",
"nakuru-project-idk>=0.0.2.1",
"ollama>=0.4.8",
"openai>1.0.0",
@@ -70,7 +70,7 @@ dependencies = [
"chromadb>=1.0.0,<2.0.0",
"qdrant-client (>=1.15.1,<2.0.0)",
"pyseekdb==1.1.0.post3",
"langbot-plugin==0.5.0a2",
"langbot-plugin==0.5.3",
"asyncpg>=0.30.0",
"line-bot-sdk>=3.19.0",
"matrix-nio>=0.25.2",
+12 -10
View File
@@ -27,17 +27,19 @@ The `all` / `box` profile starts three services:
- `langbot_box` — Box sandbox runtime (`:5410`). Uses the host Docker socket to
spawn sandbox containers, so the **Box root host path and in-container path
must be identical** (`BOX__LOCAL__HOST_ROOT=${LANGBOT_BOX_ROOT:-${PWD}/data/box}`).
Its RPC and managed-process relay require a shared
`LANGBOT_BOX_CONTROL_TOKEN` (at least 32 non-whitespace characters) in both
the LangBot and Box containers. Generate it once with `openssl rand -hex 32`;
never put it in `box.runtime.endpoint` or commit it to config.
OSS allows its RPC and managed-process relay to run without a token when both
sides leave `LANGBOT_BOX_CONTROL_TOKEN` unset. For an exposed endpoint, set
the same value of at least 32 non-whitespace characters in both the LangBot
and Box containers. Generate it once with `openssl rand -hex 32`; never put
it in `box.runtime.endpoint` or commit it to config.
Every Compose deployment also needs one
`LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN` shared by `langbot` and
`langbot_plugin_runtime`. Generate it with `openssl rand -hex 32` and export it
before `docker compose up`; the external Plugin Runtime fails closed when the
token is empty or weak. Kubernetes uses the `langbot-plugin-runtime-control`
Secret shown in `docker/kubernetes.yaml`.
A Compose deployment may optionally set
`LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN` on both `langbot` and
`langbot_plugin_runtime` when port 5400 needs shared-secret protection. OSS
defaults to leaving it unset on both sides. If enabled, generate one value with
`openssl rand -hex 32`; configuring only one side causes the control connection
to fail. Kubernetes may use the `langbot-plugin-runtime-control` Secret shown in
`docker/kubernetes.yaml`.
With Box off, the dashboard/skills list stays visible (read-only) but sandbox
tools, skill add/edit, and stdio MCP are disabled. Set `box.enabled: false`
+10 -3
View File
@@ -6,7 +6,8 @@ description: Browse and search the LangBot Space marketplaces (plugins, MCP serv
# LangBot Space MCP Operations
LangBot Space (space.langbot.app) exposes an **MCP server** so user-facing AI
agents can browse and search the marketplaces (plugins, MCP servers, skills).
agents can browse and search the marketplaces (plugins, MCP servers, skills) and
rank live models for automated setup.
## Endpoint
@@ -46,10 +47,12 @@ Authorization: Bearer lbpat_...uests without a valid PAT get `401 Unauthorized`.
| `list_plugins` / `search_plugins` / `get_plugin` | Plugin marketplace |
| `list_mcp_servers` / `search_mcp_servers` / `get_mcp_server` | MCP-server marketplace |
| `list_skills` / `search_skills` / `get_skill` | Skill marketplace |
| `select_models` | Live best-first model list for setup wizards; optional `category` filter |
`list_*` and `search_*` are paged (`page`, `page_size`). `get_*` takes
`author` + `name`. The tool surface mirrors the REST endpoints under
`/api/v1/marketplace/*` and is read/browse only.
`/api/v1/marketplace/*`; `select_models` mirrors `/api/v1/models/selection`.
All tools are read-only.
## How to use
@@ -58,12 +61,16 @@ Authorization: Bearer lbpat_...uests without a valid PAT get `401 Unauthorized`.
3. Use `search_plugins` / `search_mcp_servers` / `search_skills` to find items,
then `get_*` for details (e.g. to obtain author/name for installation in
LangBot itself).
4. For automatic local-agent setup, call `select_models` (optionally with
`category`) and choose the first compatible item. Ordering is latest probe
state (available, unprobed, unavailable), then Space recommendation. Each
item includes `availability.up`, `last_probed_at`, latency, and HTTP status.
## Implementation & maintenance (for Space developers)
- Server: `internal/controller/mcp/server.go` (official Go MCP SDK
`github.com/modelcontextprotocol/go-sdk`). Tools call the service layer
(`PluginService`, `MCPService`, `SkillService`) directly.
(`PluginService`, `MCPService`, `SkillService`, `ModelStatusService`) directly.
- Mount: `internal/controller/api.go` at `/mcp` and `/mcp/*any`.
- Auth: PAT via `AccountService.ValidatePersonalAccessToken`.
- Docs: `docs/MCP_SERVER.md`.
@@ -15,7 +15,6 @@ import posixpath
import sqlalchemy
from .....core import taskmgr
from .....core.task_boundary import run_in_workspace_uow
from .....entity.persistence import plugin as persistence_plugin
from ...authz import Permission
from ...context import ExecutionContext, RequestContext
@@ -311,11 +310,13 @@ class PluginsRouterGroup(group.RouterGroup):
):
"""Revalidate a captured task context immediately before Runtime I/O."""
await run_in_workspace_uow(
self.ap,
execution_context.workspace_uuid,
lambda: self.ap.plugin_connector.require_workspace_context(execution_context),
)
persistence_mgr = getattr(self.ap, 'persistence_mgr', None)
tenant_scope = getattr(persistence_mgr, 'tenant_scope', None)
if callable(tenant_scope):
async with tenant_scope(execution_context.workspace_uuid):
await self.ap.plugin_connector.require_workspace_context(execution_context)
return await operation()
await self.ap.plugin_connector.require_workspace_context(execution_context)
return await operation()
async def _require_authenticated_plugin_runtime_context(
@@ -392,17 +393,27 @@ class PluginsRouterGroup(group.RouterGroup):
)
async def _(request_context: RequestContext) -> str:
"""Get plugin debug information including debug URL and key"""
await self._require_authenticated_plugin_runtime_context(request_context)
debug_info = await self.ap.plugin_connector.get_debug_info()
execution_context = await self._require_authenticated_plugin_runtime_context(request_context)
debug_info = await self.ap.plugin_connector.get_debug_info(execution_context)
# Get debug URL from config
plugin_config = self.ap.instance_config.data.get('plugin', {})
debug_url = plugin_config.get('display_plugin_debug_url', 'http://localhost:5401')
debug_url = plugin_config.get(
'display_plugin_debug_url',
'ws://localhost:5401/plugin/debug/ws',
)
parsed_debug_url = urlparse(debug_url)
if parsed_debug_url.scheme in {'http', 'https'}:
debug_url = parsed_debug_url._replace(
scheme='wss' if parsed_debug_url.scheme == 'https' else 'ws',
path=parsed_debug_url.path or '/plugin/debug/ws',
).geturl()
return self.success(
data={
'debug_url': debug_url,
'plugin_debug_key': debug_info.get('plugin_debug_key', ''),
'expires_at': debug_info.get('expires_at', ''),
}
)
@@ -1,6 +1,7 @@
import quart
import argon2
import asyncio
import datetime
import uuid
from urllib.parse import parse_qs, urlsplit
@@ -13,13 +14,6 @@ from ...service.user import ControlPlaneDirectoryRequiredError, PublicRegistrati
@group.group_class('user', '/api/v1/user')
class UserRouterGroup(group.RouterGroup):
@staticmethod
def _origin(value: str) -> tuple[str, str, int | None] | None:
parsed = urlsplit(value)
if parsed.scheme not in {'http', 'https'} or not parsed.hostname:
return None
return parsed.scheme, parsed.hostname.casefold(), parsed.port
def _validate_space_redirect_uri(self, redirect_uri: str, *, bind: bool) -> str:
parsed = urlsplit(redirect_uri)
if (
@@ -37,17 +31,8 @@ class UserRouterGroup(group.RouterGroup):
if query != {'mode': ['bind']}:
raise ValueError('Invalid Space binding redirect_uri')
elif query:
raise ValueError('Invalid Space login redirect_uri')
raise ValueError('Invalid LangBot Account login redirect_uri')
redirect_origin = self._origin(redirect_uri)
api_config = self.ap.instance_config.data.get('api', {})
trusted_origins = {
self._origin(str(api_config.get(config_key, '') or '').strip())
for config_key in ('webui_url', 'webhook_prefix')
}
trusted_origins.discard(None)
if redirect_origin not in trusted_origins:
raise ValueError('Untrusted redirect_uri origin')
return redirect_uri
async def initialize(self) -> None:
@@ -218,7 +203,22 @@ class UserRouterGroup(group.RouterGroup):
try:
consumed_state = await self.ap.user_service.consume_space_oauth_state_details(state, 'login')
# Exchange code for tokens
token_data = await self.ap.space_service.exchange_oauth_code(code)
launch_workspace_uuid = consumed_state.launch_workspace_uuid
workspace_uuids = [launch_workspace_uuid] if launch_workspace_uuid else []
workspace_created_ats: dict[str, int] = {}
if not workspace_uuids and getattr(getattr(self.ap, 'deployment', None), 'mode', 'oss') != 'cloud':
binding = await self.ap.workspace_service.get_execution_binding()
workspace_uuids = [binding.workspace_uuid]
workspace_created_at = binding.workspace_created_at
if workspace_created_at is not None:
if workspace_created_at.tzinfo is None:
workspace_created_at = workspace_created_at.replace(tzinfo=datetime.UTC)
workspace_created_ats[binding.workspace_uuid] = int(workspace_created_at.timestamp())
token_data = await self.ap.space_service.exchange_oauth_code(
code,
workspace_uuids,
workspace_created_ats,
)
access_token = token_data.get('access_token')
refresh_token = token_data.get('refresh_token')
expires_in = token_data.get('expires_in', 0)
@@ -231,7 +231,6 @@ class UserRouterGroup(group.RouterGroup):
access_token, refresh_token, expires_in
)
launch_workspace_uuid = consumed_state.launch_workspace_uuid
if launch_workspace_uuid:
try:
access = await self.ap.workspace_collaboration_service.resolve_account_workspace(
@@ -401,7 +400,7 @@ class UserRouterGroup(group.RouterGroup):
'Bind the LangBot Account with the same email as this local Account',
)
except ValueError:
return self.http_status(400, -1, 'Space account binding failed')
return self.http_status(400, -1, 'LangBot Account binding failed')
except Exception:
raise
+71 -16
View File
@@ -10,6 +10,7 @@ from ....core import app
from ....entity.persistence import model as persistence_model
from ....entity.persistence import pipeline as persistence_pipeline
from ....provider.modelmgr import requester as model_requester
from ....provider.modelmgr import reasoning as model_reasoning
from ....workspace.errors import WorkspaceNotFoundError
from .secrets import mask_secret_value, redact_secrets, restore_secret_placeholders
from .tenant import TenantContext, require_workspace_uuid, scope_statement
@@ -55,6 +56,53 @@ def _redact_model_secrets(model_data: dict) -> dict:
return redacted
def _normalize_llm_reasoning(model_data: dict) -> None:
model_data['reasoning_config'] = model_reasoning.validate_reasoning_config(
model_data.get('reasoning_config'),
model_data.get('abilities'),
model_data.get('extra_args'),
)
def _validate_llm_reasoning_capability(
model_entity: persistence_model.LLMModel,
runtime_provider: model_requester.RuntimeProvider,
) -> None:
config = model_reasoning.normalize_reasoning_config(model_entity.reasoning_config)
if config['level'] == 'provider_default':
return
runtime_model = model_requester.RuntimeLLMModel(
execution_context=runtime_provider.execution_context,
model_entity=model_entity,
provider=runtime_provider,
)
capabilities = runtime_provider.requester.get_reasoning_capabilities(runtime_model)
model_reasoning.validate_reasoning_capabilities(config, capabilities, model_entity.name)
def _reasoning_capabilities(ap: app.Application, model: persistence_model.LLMModel) -> dict:
model_mgr = getattr(ap, 'model_mgr', None)
runtime_models = getattr(model_mgr, 'llm_model_dict', {}) if model_mgr is not None else {}
for runtime_model in runtime_models.values():
if (
runtime_model.model_entity.uuid == model.uuid
and runtime_model.model_entity.workspace_uuid == model.workspace_uuid
):
return runtime_model.provider.requester.get_reasoning_capabilities(runtime_model)
return model_reasoning.default_reasoning_capabilities(
supported='reasoning' in (model.abilities or []),
source='manual' if 'reasoning' in (model.abilities or []) else 'unknown',
)
def _serialize_llm_model(ap: app.Application, model: persistence_model.LLMModel) -> dict:
model_dict = ap.persistence_mgr.serialize_model(persistence_model.LLMModel, model)
model_dict['reasoning_config'] = model_reasoning.normalize_reasoning_config(model_dict.get('reasoning_config'))
model_dict['reasoning_capabilities'] = _reasoning_capabilities(ap, model)
return model_dict
async def _validate_provider_supports(
ap: app.Application,
context: TenantContext,
@@ -165,7 +213,7 @@ class LLMModelsService:
models_list = []
for model in models:
model_dict = self.ap.persistence_mgr.serialize_model(persistence_model.LLMModel, model)
model_dict = _serialize_llm_model(self.ap, model)
provider = providers.get(model.provider_uuid)
if provider:
provider_dict = self.ap.persistence_mgr.serialize_model(persistence_model.ModelProvider, provider)
@@ -196,7 +244,7 @@ class LLMModelsService:
)
)
models = result.all()
serialized = [self.ap.persistence_mgr.serialize_model(persistence_model.LLMModel, m) for m in models]
serialized = [_serialize_llm_model(self.ap, model) for model in models]
return serialized if include_secret else [_redact_model_secrets(model) for model in serialized]
async def create_llm_model(
@@ -233,13 +281,17 @@ class LLMModelsService:
await _require_workspace_provider(self.ap, context, model_data['provider_uuid'])
await _assert_cloud_managed_provider_mutable(self.ap, context, model_data['provider_uuid'])
await _validate_provider_supports(self.ap, context, model_data['provider_uuid'], 'llm')
_normalize_llm_reasoning(model_data)
runtime_provider = await _require_runtime_provider(self.ap, context, model_data['provider_uuid'])
model_entity = persistence_model.LLMModel(**model_data)
_validate_llm_reasoning_capability(model_entity, runtime_provider)
await self.ap.persistence_mgr.execute_async(sqlalchemy.insert(persistence_model.LLMModel).values(**model_data))
runtime_provider = await _require_runtime_provider(self.ap, context, model_data['provider_uuid'])
runtime_llm_model = await self.ap.model_mgr.load_llm_model_with_provider(
context,
persistence_model.LLMModel(**model_data),
model_entity,
runtime_provider,
)
await self.ap.model_mgr.cache_llm_model(context, runtime_llm_model)
@@ -287,7 +339,7 @@ class LLMModelsService:
if model is None:
return None
model_dict = self.ap.persistence_mgr.serialize_model(persistence_model.LLMModel, model)
model_dict = _serialize_llm_model(self.ap, model)
# Get provider
provider_result = await self.ap.persistence_mgr.execute_async(
@@ -349,6 +401,18 @@ class LLMModelsService:
await _assert_cloud_managed_provider_mutable(self.ap, context, provider_uuid)
await _validate_provider_supports(self.ap, context, provider_uuid, 'llm')
merged_model_data = {
key: value
for key, value in {**existing_model, **model_data, 'provider_uuid': provider_uuid}.items()
if key not in {'provider', 'created_at', 'updated_at', 'reasoning_capabilities'}
}
_normalize_llm_reasoning(merged_model_data)
model_data['reasoning_config'] = merged_model_data['reasoning_config']
runtime_provider = await _require_runtime_provider(self.ap, context, provider_uuid)
model_entity = persistence_model.LLMModel(**_runtime_model_data(model_uuid, merged_model_data))
_validate_llm_reasoning_capability(model_entity, runtime_provider)
result = await self.ap.persistence_mgr.execute_async(
scope_statement(
sqlalchemy.update(persistence_model.LLMModel)
@@ -362,19 +426,9 @@ class LLMModelsService:
raise WorkspaceNotFoundError('Model not found')
await self.ap.model_mgr.remove_llm_model(context, model_uuid)
runtime_provider = await _require_runtime_provider(self.ap, context, provider_uuid)
runtime_llm_model = await self.ap.model_mgr.load_llm_model_with_provider(
context,
persistence_model.LLMModel(
**_runtime_model_data(
model_uuid,
{
key: value
for key, value in {**existing_model, **model_data, 'provider_uuid': provider_uuid}.items()
if key not in {'provider', 'created_at', 'updated_at'}
},
)
),
model_entity,
runtime_provider,
)
await self.ap.model_mgr.cache_llm_model(context, runtime_llm_model)
@@ -407,6 +461,7 @@ class LLMModelsService:
raise WorkspaceNotFoundError('Model not found')
runtime_llm_model = await self.ap.model_mgr.get_model_by_uuid(context, model_uuid)
else:
_normalize_llm_reasoning(model_data)
runtime_llm_model = await self.ap.model_mgr.init_temporary_runtime_llm_model(context, model_data)
extra_args = model_data.get('extra_args', {})
+18 -2
View File
@@ -59,6 +59,10 @@ class SpaceService:
result_list = result.all()
return result_list[0] if result_list else None
async def get_valid_access_token(self, user_email: str) -> str | None:
"""Return a current Space bearer, refreshing and persisting it when needed."""
return await self._ensure_valid_token(user_email)
async def _ensure_valid_token(self, user_email: str) -> str | None:
"""Ensure access token is valid, refresh if expired. Returns valid access_token or None."""
user_obj = await self._get_user_by_email(user_email)
@@ -117,7 +121,12 @@ class SpaceService:
params['state'] = state
return f'{authorize_url}?{urlencode(params)}'
async def exchange_oauth_code(self, code: str) -> typing.Dict:
async def exchange_oauth_code(
self,
code: str,
workspace_uuids: list[str] | None = None,
workspace_created_ats: dict[str, int] | None = None,
) -> typing.Dict:
"""Exchange OAuth authorization code for tokens"""
from langbot.pkg.utils import constants
@@ -127,7 +136,14 @@ class SpaceService:
session = httpclient.get_session()
async with session.post(
f'{space_url}/api/v1/accounts/oauth/token',
json={'code': code, 'instance_id': constants.instance_id},
json={
'code': code,
'instance_id': constants.instance_id,
# Sending an explicit empty list tells new Space servers not to
# synthesize a legacy instance-derived Workspace binding.
'workspace_uuids': workspace_uuids if workspace_uuids is not None else [],
'workspace_created_ats': workspace_created_ats or {},
},
) as response:
if response.status != 200:
error = await httpclient.read_text_limited(response)
+25 -6
View File
@@ -114,7 +114,7 @@ class UserService:
if purpose == 'login' and account_uuid is not None:
raise ValueError('Login state cannot be bound to an Account')
if purpose != 'login' and launch_workspace_uuid is not None:
raise ValueError('Launch Workspace state is only valid for Space login')
raise ValueError('Launch Workspace state is only valid for LangBot Account login')
if ttl_seconds <= 0:
raise ValueError('OAuth state lifetime must be positive')
@@ -327,7 +327,7 @@ class UserService:
normalized_email = normalize_email(user_email)
if self._uses_control_plane_directory():
raise ControlPlaneDirectoryRequiredError(
'Cloud invitation registration must use a Space account to preserve control-plane identity'
'Cloud invitation registration must use a LangBot Account to preserve control-plane identity'
)
invitation, _ = await self.ap.workspace_collaboration_service.inspect_invitation(invitation_token)
if invitation.normalized_email != normalized_email:
@@ -394,7 +394,7 @@ class UserService:
# Check if this user has a local password set
if not user_obj.password:
raise ValueError('请使用 Space登录')
raise ValueError('请使用 LangBot登录')
await self._verify_password(user_obj.password, password)
@@ -779,8 +779,27 @@ class UserService:
local_account = await self.get_user_by_email(user_email)
if local_account is None:
raise ValueError('User not found')
# Exchange code for tokens
token_data = await self.ap.space_service.exchange_oauth_code(code)
# Exchange code for tokens and bind both installation and the active
# OSS Workspace as independent identities.
workspace_service = getattr(self.ap, 'workspace_service', None)
if workspace_service is not None:
binding = await workspace_service.get_execution_binding()
created_at = binding.workspace_created_at
created_ts = (
int(created_at.replace(tzinfo=datetime.timezone.utc).timestamp())
if created_at.tzinfo is None
else int(created_at.timestamp())
)
token_data = await self.ap.space_service.exchange_oauth_code(
code,
[binding.workspace_uuid],
{binding.workspace_uuid: created_ts},
)
else:
# Compatibility for early/bootstrap call sites that have not wired
# WorkspaceService yet; old Space servers still derive the legacy
# Workspace identity from instance_id when the field is omitted.
token_data = await self.ap.space_service.exchange_oauth_code(code)
access_token = token_data.get('access_token')
refresh_token = token_data.get('refresh_token')
expires_in = token_data.get('expires_in', 0)
@@ -806,7 +825,7 @@ class UserService:
# Check if this Space account is already bound to another user
existing_space_user = await self.get_user_by_space_account_uuid(space_account_uuid)
if existing_space_user and existing_space_user.normalized_email != normalize_email(user_email):
raise ValueError('This Space account is already bound to another user')
raise ValueError('This LangBot Account is already bound to another user')
# Update local account to Space account
normalized_email = normalize_email(user_email)
+12 -6
View File
@@ -369,6 +369,12 @@ class BoxRuntimeConnector(ManagedRuntimeConnector):
def _ensure_control_token(self, *, allow_generate: bool) -> str:
if not self._control_token and allow_generate:
self._control_token = secrets.token_urlsafe(48)
if not self._control_token:
if getattr(getattr(self.ap, 'deployment', None), 'mode', 'oss') == 'cloud':
raise BoxRuntimeUnavailableError(
f'{BOX_CONTROL_TOKEN_ENV} must be configured with a strong shared secret for a Cloud Box runtime'
)
return ''
try:
self._control_token = validate_control_token(self._control_token)
except ValueError as exc:
@@ -378,19 +384,19 @@ class BoxRuntimeConnector(ManagedRuntimeConnector):
return self._control_token
def get_control_headers(self) -> dict[str, str]:
"""Headers for the instance-authenticated RPC control handshake."""
"""Return instance-scoped RPC headers and the optional shared secret."""
self._ensure_control_token(allow_generate=False)
return {
BOX_CONTROL_TOKEN_HEADER: self._control_token,
BOX_INSTANCE_HEADER: self._trusted_instance_uuid,
}
headers = {BOX_INSTANCE_HEADER: self._trusted_instance_uuid}
if self._control_token:
headers[BOX_CONTROL_TOKEN_HEADER] = self._control_token
return headers
def get_relay_headers(
self,
action_context: ActionContext,
) -> dict[str, str]:
"""Return authenticated, placement-scoped relay handshake headers."""
"""Return instance- and placement-scoped relay handshake headers."""
context = ActionContext.model_validate(action_context).without_installation()
if context.instance_uuid != self._trusted_instance_uuid:
+1 -1
View File
@@ -18,7 +18,7 @@ from .model_catalog import CloudModelCatalogProvider
CLOUD_BOOTSTRAP_ENTRY_POINT = 'langbot.cloud_bootstrap'
REQUIRED_TENANT_ISOLATION_VERSION = 2
SUPPORTED_PGVECTOR_DIMENSIONS = frozenset({384, 512, 768, 1024, 1536})
SUPPORTED_PGVECTOR_DIMENSIONS = frozenset({384, 512, 768, 1024, 1536, 3072})
class CloudBootstrapError(RuntimeError):
+17 -5
View File
@@ -15,6 +15,7 @@ from ..entity.persistence.cloud_directory import DirectoryProjectionInbox, Direc
from ..entity.persistence.user import AccountSource, AccountStatus, User
from ..entity.persistence.workspace import (
MembershipRole,
MembershipSource,
MembershipStatus,
Workspace,
WorkspaceExecutionSource,
@@ -358,6 +359,7 @@ class DirectoryProjectionService:
await self._reconcile_entitlement_snapshot_set(snapshot)
self._publish_runtime_execution_projection(snapshot.workspaces)
self._request_model_catalog_sync()
self._record_batch_cardinality(
active_workspaces=active_workspace_count,
workspaces=workspace_count,
@@ -466,6 +468,7 @@ class DirectoryProjectionService:
returned.values(),
affected_workspace_uuids=requested,
)
self._request_model_catalog_sync()
self._record_batch_cardinality(
active_workspaces=active_workspace_count,
workspaces=workspace_count,
@@ -475,6 +478,14 @@ class DirectoryProjectionService:
self._record_success()
self._consumer_cursor = batch.cursor
def _request_model_catalog_sync(self) -> None:
"""Wake model provisioning after a committed directory change."""
service = getattr(self.ap, 'cloud_model_catalog_service', None)
request_sync = getattr(service, 'request_sync', None)
if callable(request_sync):
request_sync()
def _publish_runtime_execution_projection(
self,
workspaces: Iterable[DirectoryWorkspace],
@@ -876,15 +887,15 @@ class DirectoryProjectionService:
account_uuid=member.account_uuid,
role=role,
status=status,
source=MembershipSource.CLOUD_PROJECTION.value,
joined_at=joined_at,
projection_revision=member.projection_revision,
)
)
continue
if membership.projection_revision == 0:
# Revision zero is Core-owned collaboration state. Directory
# projection seeds memberships, but must not overwrite later
# invitation, role, or removal decisions made by Core.
if membership.source != MembershipSource.CLOUD_PROJECTION.value:
# Core-owned collaboration state is never adopted based on
# account provenance, revision, or matching account identity.
continue
if membership.uuid != member.membership_uuid:
raise DirectoryProjectionUnavailableError('Directory membership UUID changed for one account')
@@ -896,11 +907,12 @@ class DirectoryProjectionService:
raise DirectoryProjectionUnavailableError('Directory membership revision has conflicting contents')
membership.role = role
membership.status = status
membership.source = MembershipSource.CLOUD_PROJECTION.value
membership.joined_at = joined_at
membership.projection_revision = member.projection_revision
for account_uuid, membership in existing.items():
if account_uuid not in included_accounts and membership.projection_revision != 0:
if account_uuid not in included_accounts and membership.source == MembershipSource.CLOUD_PROJECTION.value:
membership.status = MembershipStatus.REMOVED.value
membership.projection_revision = max(
int(membership.projection_revision),
+11 -1
View File
@@ -151,6 +151,7 @@ class CloudModelCatalogSyncService:
# following database reconciliation is a no-op.
self._runtime_reload_pending = False
self._workspace_credits: dict[str, int | None] = {}
self._sync_requested = asyncio.Event()
def get_workspace_credits(self, workspace_uuid: str) -> int | None:
"""Return the latest signed owner-credit projection for a Workspace."""
@@ -159,9 +160,18 @@ class CloudModelCatalogSyncService:
async def initialize(self) -> None:
await self.sync_once(reload_runtime=False)
def request_sync(self) -> None:
"""Wake the catalog loop after a directory Workspace change."""
self._sync_requested.set()
async def run(self) -> None:
while True:
await asyncio.sleep(self.sync_interval_seconds)
try:
await asyncio.wait_for(self._sync_requested.wait(), timeout=self.sync_interval_seconds)
except TimeoutError:
pass
self._sync_requested.clear()
try:
await self.sync_once(reload_runtime=True)
except asyncio.CancelledError:
+4
View File
@@ -263,6 +263,10 @@ class Application:
{},
)
),
'plugin_runtime_connected': bool(
self.plugin_connector is not None
and getattr(self.plugin_connector, '_runtime_available', lambda: False)()
),
}
mcp_loader = getattr(self.tool_mgr, 'mcp_tool_loader', None)
runtime_stats.update(
+2 -1
View File
@@ -41,6 +41,7 @@ _RUNTIME_POLICY_DEFAULTS = {
}
},
'plugin': {
'connect_timeout_seconds': 180.0,
'worker': {
'max_cpus': 1.0,
'max_memory_mb': 512,
@@ -56,7 +57,7 @@ _RUNTIME_POLICY_DEFAULTS = {
'restart_failure_window_seconds': 30.0,
'restart_circuit_open_seconds': 60.0,
'require_hard_limits': False,
}
},
},
'mcp': {'stdio': {'enabled': True}},
'monitoring': {
+1 -1
View File
@@ -17,4 +17,4 @@ class SpaceAccountBindingRequiredError(AccountEmailMismatchError):
code = 'space_account_binding_required'
def __str__(self) -> str:
return 'This local Account must bind Space from Account settings before Space login'
return 'This local account must bind a LangBot Account from Account settings before LangBot Account login'
@@ -48,6 +48,12 @@ class LLMModel(Base):
provider_uuid = sqlalchemy.Column(sqlalchemy.String(255), nullable=False)
abilities = sqlalchemy.Column(sqlalchemy.JSON, nullable=False, default=[])
context_length = sqlalchemy.Column(sqlalchemy.Integer, nullable=True)
reasoning_config = sqlalchemy.Column(
sqlalchemy.JSON,
nullable=False,
default=lambda: {'level': 'provider_default'},
server_default=sqlalchemy.text('\'{"level":"provider_default"}\''),
)
extra_args = sqlalchemy.Column(sqlalchemy.JSON, nullable=False, default={})
prefered_ranking = sqlalchemy.Column(sqlalchemy.Integer, nullable=False, default=0)
created_at = sqlalchemy.Column(sqlalchemy.DateTime, nullable=False, server_default=sqlalchemy.func.now())
@@ -40,6 +40,11 @@ class MembershipStatus(enum.StrEnum):
REMOVED = 'removed'
class MembershipSource(enum.StrEnum):
LOCAL = 'local'
CLOUD_PROJECTION = 'cloud_projection'
class InvitationStatus(enum.StrEnum):
PENDING = 'pending'
ACCEPTED = 'accepted'
@@ -151,6 +156,11 @@ class WorkspaceMembership(Base):
nullable=True,
)
joined_at = sqlalchemy.Column(sqlalchemy.DateTime, nullable=True)
source = sqlalchemy.Column(
sqlalchemy.String(32),
nullable=False,
server_default=MembershipSource.LOCAL.value,
)
projection_revision = sqlalchemy.Column(sqlalchemy.BigInteger, nullable=False, server_default='0')
created_at = sqlalchemy.Column(sqlalchemy.DateTime, nullable=False, server_default=sqlalchemy.func.now())
updated_at = sqlalchemy.Column(
@@ -178,6 +188,10 @@ class WorkspaceMembership(Base):
"status IN ('active', 'disabled', 'removed')",
name='ck_workspace_memberships_status',
),
sqlalchemy.CheckConstraint(
"source IN ('local', 'cloud_projection')",
name='ck_workspace_memberships_source',
),
)
@@ -0,0 +1,57 @@
"""add llm reasoning config
Revision ID: 0018_llm_reasoning_config
Revises: 0017_oss_workspace_identity
Create Date: 2026-07-27
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = '0018_llm_reasoning_config'
down_revision = '0017_oss_workspace_identity'
branch_labels = None
depends_on = None
_LLM_MODELS = sa.table(
'llm_models',
sa.column('reasoning_config', sa.JSON()),
)
def upgrade() -> None:
conn = op.get_bind()
inspector = sa.inspect(conn)
if 'llm_models' not in inspector.get_table_names():
return
columns = {column['name'] for column in inspector.get_columns('llm_models')}
if 'reasoning_config' in columns:
return
op.add_column(
'llm_models',
sa.Column(
'reasoning_config',
sa.JSON(),
nullable=True,
server_default=sa.text('\'{"level":"provider_default"}\''),
),
)
conn.execute(_LLM_MODELS.update().values(reasoning_config={'level': 'provider_default'}))
with op.batch_alter_table('llm_models') as batch_op:
batch_op.alter_column('reasoning_config', existing_type=sa.JSON(), nullable=False)
def downgrade() -> None:
conn = op.get_bind()
inspector = sa.inspect(conn)
if 'llm_models' not in inspector.get_table_names():
return
columns = {column['name'] for column in inspector.get_columns('llm_models')}
if 'reasoning_config' in columns:
with op.batch_alter_table('llm_models') as batch_op:
batch_op.drop_column('reasoning_config')
@@ -0,0 +1,43 @@
"""enable 3072-dimensional pgvector embeddings
Revision ID: 001a_pgvector_dimension_3072
Revises: 0019_single_workspace_owner
Create Date: 2026-08-05
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = '001a_pgvector_dimension_3072'
down_revision = '0019_single_workspace_owner'
branch_labels = None
depends_on = None
_TABLE = 'langbot_vectors'
_CHECK = 'ck_langbot_vectors_embedding_dimension_enabled'
_INDEX = 'ix_langbot_vectors_hnsw_cosine_3072'
def upgrade() -> None:
conn = op.get_bind()
if conn.dialect.name != 'postgresql' or _TABLE not in sa.inspect(conn).get_table_names():
return
op.drop_constraint(_CHECK, _TABLE, type_='check')
op.create_check_constraint(_CHECK, _TABLE, 'embedding_dimension IN (384, 512, 768, 1024, 1536, 3072)')
op.execute(
sa.text(
f'CREATE INDEX {_INDEX} ON {_TABLE} USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops) WHERE embedding_dimension = 3072'
)
)
def downgrade() -> None:
conn = op.get_bind()
if conn.dialect.name != 'postgresql' or _TABLE not in sa.inspect(conn).get_table_names():
return
count = conn.scalar(sa.text(f'SELECT COUNT(*) FROM {_TABLE} WHERE embedding_dimension = 3072'))
if count:
raise RuntimeError('Cannot disable 3072-dimensional pgvector while matching embeddings exist')
op.drop_index(_INDEX, table_name=_TABLE)
op.drop_constraint(_CHECK, _TABLE, type_='check')
op.create_check_constraint(_CHECK, _TABLE, 'embedding_dimension IN (384, 512, 768, 1024, 1536)')
@@ -0,0 +1,49 @@
"""add explicit Workspace membership source
Revision ID: 0020_membership_source
Revises: 001a_pgvector_dimension_3072
Create Date: 2026-08-06
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = '0020_membership_source'
down_revision = '001a_pgvector_dimension_3072'
branch_labels = None
depends_on = None
_CONSTRAINT_NAME = 'ck_workspace_memberships_source'
def upgrade() -> None:
conn = op.get_bind()
inspector = sa.inspect(conn)
if 'workspace_memberships' not in inspector.get_table_names():
return
if 'source' in {column['name'] for column in inspector.get_columns('workspace_memberships')}:
return
# No durable historical field distinguishes Directory-created revision-zero
# rows from Core invitations. Protect every existing row; production can
# reclassify separately after UUIDs have been verified against Space.
with op.batch_alter_table('workspace_memberships') as batch_op:
batch_op.add_column(sa.Column('source', sa.String(length=32), nullable=False, server_default='local'))
batch_op.create_check_constraint(
_CONSTRAINT_NAME,
"source IN ('local', 'cloud_projection')",
)
def downgrade() -> None:
conn = op.get_bind()
inspector = sa.inspect(conn)
if 'workspace_memberships' not in inspector.get_table_names():
return
if 'source' not in {column['name'] for column in inspector.get_columns('workspace_memberships')}:
return
with op.batch_alter_table('workspace_memberships') as batch_op:
batch_op.drop_constraint(_CONSTRAINT_NAME, type_='check')
batch_op.drop_column('source')
@@ -0,0 +1,21 @@
"""merge reasoning config with the main migration branch
Revision ID: 0021_merge_reasoning_config
Revises: 0020_membership_source, 0018_llm_reasoning_config
Create Date: 2026-08-09
"""
from __future__ import annotations
revision = '0021_merge_reasoning_config'
down_revision = ('0020_membership_source', '0018_llm_reasoning_config')
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -0,0 +1,21 @@
"""merge AgentRunner and model reasoning migration heads
Revision ID: 0022_merge_agent_reasoning_heads
Revises: 0020_merge_agent_cloud_heads, 0021_merge_reasoning_config
Create Date: 2026-08-14
"""
from __future__ import annotations
revision = '0022_merge_agent_reasoning_heads'
down_revision = ('0020_merge_agent_cloud_heads', '0021_merge_reasoning_config')
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
+6 -4
View File
@@ -98,7 +98,7 @@ _WORKSPACE_ALEMBIC_REVISION = '0009_workspace_tenancy'
_RESOURCE_SCOPE_ALEMBIC_REVISION = '0010_scope_resources'
_OSS_WORKSPACE_METADATA_KEY = 'oss_workspace_uuid'
_RELEASE_MIGRATION_ADVISORY_LOCK_ID = 0x4C414E47424F5432
_PGVECTOR_ALLOWED_DIMENSIONS = (384, 512, 768, 1024, 1536)
_PGVECTOR_ALLOWED_DIMENSIONS = (384, 512, 768, 1024, 1536, 3072)
_RUNTIME_SCHEMA = 'public'
_ALEMBIC_RUNTIME_TABLE = 'alembic_version'
_RUNTIME_TABLE_PRIVILEGES = frozenset({'SELECT', 'INSERT', 'UPDATE', 'DELETE'})
@@ -1311,14 +1311,16 @@ class PersistenceManager:
index = by_index.get(index_name)
index_definition = normalized(None if index is None else index['definition'])
predicate = normalized(None if index is None else index['predicate'])
vector_type = 'halfvec' if dimension > 2000 else 'vector'
operator_class = f'{vector_type}_cosine_ops'
if (
index is None
or index['access_method'] != 'hnsw'
or index['is_valid'] is not True
or index['is_ready'] is not True
or f'vector({dimension})' not in index_definition
or f'(embedding)::vector({dimension})' not in index_definition
or 'vector_cosine_ops' not in index_definition
or f'{vector_type}({dimension})' not in index_definition
or f'(embedding)::{vector_type}({dimension})' not in index_definition
or operator_class not in index_definition
or predicate.strip('() ') != f'embedding_dimension = {dimension}'
):
raise RuntimeError(f'PostgreSQL pgvector ANN index {index_name!r} is invalid')
+3 -3
View File
@@ -13,7 +13,7 @@ import typing
import sqlalchemy
import sqlalchemy.ext.asyncio as sqlalchemy_asyncio
import sqlalchemy.orm as sqlalchemy_orm
from pgvector.sqlalchemy import Vector
from pgvector.sqlalchemy import HALFVEC, Vector
from sqlalchemy.dialects.postgresql.dml import OnConflictDoNothing as PostgreSQLOnConflictDoNothing
from sqlalchemy.dialects.postgresql.dml import OnConflictDoUpdate as PostgreSQLOnConflictDoUpdate
from sqlalchemy.dialects.sqlite.dml import OnConflictDoNothing as SQLiteOnConflictDoNothing
@@ -282,7 +282,7 @@ def _validate_scoped_sql_type(
return
seen.add(identity)
if type(sql_type) is Vector:
if type(sql_type) in {Vector, HALFVEC}:
return
if not type(sql_type).__module__.startswith('sqlalchemy.'):
raise ScopedSessionTransactionError('TenantUnitOfWork does not allow custom SQL types in public statements')
@@ -463,7 +463,7 @@ def _validate_scoped_statement_call(args: tuple[typing.Any, ...], kwargs: dict[s
if isinstance(element, sqlalchemy.sql.elements.BindParameter) and element.literal_execute:
raise ScopedSessionTransactionError('TenantUnitOfWork does not allow literal-execute SQL parameters')
if isinstance(element, sqlalchemy.sql.elements.Cast) and type(element.type) is not Vector:
if isinstance(element, sqlalchemy.sql.elements.Cast) and type(element.type) not in {Vector, HALFVEC}:
raise ScopedSessionTransactionError(
'TenantUnitOfWork only allows the trusted pgvector cast used by tenant vector search'
)
+4 -12
View File
@@ -58,12 +58,8 @@ class Controller:
query.session = await self.ap.sess_mgr.get_session(query)
query.pipeline_config = pipeline.pipeline_entity.config
query.variables['_pipeline_bound_plugins'] = pipeline.bound_plugins
query.variables['_pipeline_bound_mcp_servers'] = (
pipeline.bound_mcp_servers
)
return await self.ap.agent_run_orchestrator.try_claim_steering_from_query(
query
)
query.variables['_pipeline_bound_mcp_servers'] = pipeline.bound_mcp_servers
return await self.ap.agent_run_orchestrator.try_claim_steering_from_query(query)
except Exception as exc:
self.ap.logger.warning(
f'Failed to claim query {query.query_id} as steering input: {exc}',
@@ -157,9 +153,7 @@ class Controller:
# that can cause memory overflow in high-traffic scenarios
if session._semaphore.locked():
if await self._try_claim_steering_before_session_slot(
query
):
if await self._try_claim_steering_before_session_slot(query):
claimed_steering_query = query
break
continue
@@ -175,9 +169,7 @@ class Controller:
break
if claimed_steering_query is not None:
self.ap.query_pool.remove_query_locked(
claimed_steering_query
)
self.ap.query_pool.remove_query_locked(claimed_steering_query)
self.ap.query_pool.condition.notify_all()
continue
if selected_query is None: # 没找到 说明:没有请求 或者 所有query对应的session都已达到并发上限
+5 -15
View File
@@ -70,24 +70,18 @@ class PreProcessor(stage.PipelineStage):
if primary_uuid in config_schema.NONE_SENTINELS:
return None
try:
return await self.ap.model_mgr.get_model_by_uuid(
get_query_execution_context(query), primary_uuid
)
return await self.ap.model_mgr.get_model_by_uuid(get_query_execution_context(query), primary_uuid)
except ValueError:
self.ap.logger.warning(f'LLM model {primary_uuid} not found or not configured')
return None
async def _resolve_fallback_models(
self, query: pipeline_query.Query, fallback_uuids: list[str]
) -> list[str]:
async def _resolve_fallback_models(self, query: pipeline_query.Query, fallback_uuids: list[str]) -> list[str]:
valid_fallbacks = []
for fallback_uuid in fallback_uuids:
if fallback_uuid in config_schema.NONE_SENTINELS:
continue
try:
await self.ap.model_mgr.get_model_by_uuid(
get_query_execution_context(query), fallback_uuid
)
await self.ap.model_mgr.get_model_by_uuid(get_query_execution_context(query), fallback_uuid)
valid_fallbacks.append(fallback_uuid)
except ValueError:
self.ap.logger.warning(f'Fallback model {fallback_uuid} not found, skipping')
@@ -225,9 +219,7 @@ class PreProcessor(stage.PipelineStage):
if uses_host_models:
primary_uuid, fallback_uuids = config_schema.extract_model_selection(descriptor, runner_config)
llm_model = await self._resolve_llm_model(query, primary_uuid)
valid_fallbacks = await self._resolve_fallback_models(
query, fallback_uuids
)
valid_fallbacks = await self._resolve_fallback_models(query, fallback_uuids)
if valid_fallbacks:
query.variables['_fallback_model_uuids'] = valid_fallbacks
@@ -426,9 +418,7 @@ class PreProcessor(stage.PipelineStage):
query.pipeline_uuid,
include_secret=True,
)
extensions_prefs = normalize_extension_preferences(
(pipeline_data or {}).get('extensions_preferences')
)
extensions_prefs = normalize_extension_preferences((pipeline_data or {}).get('extensions_preferences'))
enable_all_skills = extensions_prefs['enable_all_skills']
if enable_all_skills:
@@ -5,6 +5,7 @@ import contextvars
import logging
import time
import typing
from dataclasses import dataclass
from datetime import datetime
import pydantic
@@ -25,6 +26,15 @@ _current_pipeline_uuid: contextvars.ContextVar[str | None] = contextvars.Context
)
@dataclass(frozen=True)
class WebSocketReplyContext:
"""Trusted routing context retained when the originating socket reconnects."""
scope: WebSocketScope
pipeline_uuid: str
session_id: str | None
class WebSocketMessage(pydantic.BaseModel):
"""WebSocket消息格式"""
@@ -265,10 +275,14 @@ class WebSocketAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter)
embed_target = self._parse_embed_target(sender_id)
if embed_target is not None:
return embed_target
reply_context = getattr(message_source, '_websocket_reply_context', None)
if isinstance(reply_context, WebSocketReplyContext):
if reply_context.scope != self._scope():
raise ValueError('WebSocket reply context does not match this adapter scope')
return reply_context.pipeline_uuid, reply_context.session_id
pipeline_uuid = getattr(message_source, '_langbot_pipeline_uuid', None)
if isinstance(pipeline_uuid, str) and pipeline_uuid:
return pipeline_uuid, None
raise ValueError('WebSocket reply target is not bound to this adapter scope')
async def send_message(
@@ -439,9 +453,9 @@ class WebSocketAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter)
# 更新历史记录中的对应消息
message_list[existing_index] = message_data
# Keep the index for the lifetime of the history entry. Some runners
# emit a final delta followed by message.completed/run.completed. They
# all share one Host response id and must update one UI message.
# Keep the index for the lifetime of the history entry. AgentRunner can
# emit a final delta followed by message.completed/run.completed; all
# events with the same Host response id must update one UI message.
await ws_connection_manager.broadcast_to_pipeline(
pipeline_uuid,
@@ -537,8 +551,7 @@ class WebSocketAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter)
Image / Voice / File components uploaded from the web client carry a
storage key in ``path``. Resolve it to a base64 data URI so downstream
stages (multimodal LLM input and the Box sandbox inbox) have a usable
payload. Keep the storage key for browser history; the configured
storage-retention cleanup removes expired uploads.
payload, then drop the now-consumed storage object.
Args:
message_chain_obj: 消息链对象列表
@@ -593,6 +606,12 @@ class WebSocketAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter)
mime_type = mimetypes.guess_type(comp_path)[0] or 'application/octet-stream'
component['base64'] = f'data:{mime_type};base64,{base64_str}'
await storage_mgr.delete_scoped_object_key(
execution_context,
comp_path,
expected_owner_type='upload_image',
)
component['path'] = ''
except Exception as e:
await self.logger.error(f'Failed to load {comp_type} file {comp_path}: {e}')
raise
@@ -683,10 +702,19 @@ class WebSocketAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter)
sender=sender, message_chain=message_chain, time=datetime.now().timestamp()
)
object.__setattr__(event, '_langbot_pipeline_uuid', pipeline_uuid)
# 异步触发事件处理
# Use owner_bot's listeners if available, otherwise fall back to proxy bot
object.__setattr__(
event,
'_websocket_reply_context',
WebSocketReplyContext(
scope=connection.scope,
pipeline_uuid=pipeline_uuid,
session_id=connection.session_id,
),
)
object.__setattr__(event, '_langbot_pipeline_uuid', pipeline_uuid)
listeners = (
owner_bot.adapter.listeners
if (owner_bot and hasattr(owner_bot.adapter, 'listeners') and owner_bot.adapter.listeners)
+43 -19
View File
@@ -6,6 +6,7 @@ import contextlib
import contextvars
import hashlib
import json
import math
import time
import uuid
from typing import Any
@@ -76,7 +77,7 @@ _GITHUB_ASSET_HOSTS = frozenset(
}
)
_HTTP_REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})
_CONNECT_TIMEOUT_SEC = 30.0
_DEFAULT_CONNECT_TIMEOUT_SECONDS = 180.0
_HEARTBEAT_INTERVAL_SEC = 20.0
_HEARTBEAT_FAILURE_THRESHOLD = 3
_RECONNECT_MAX_DELAY_SEC = 60.0
@@ -206,6 +207,17 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
return f'{constants.instance_id}:plugin-runtime'
@staticmethod
def _runtime_connect_timeout(plugin_config: dict[str, Any]) -> float:
value = plugin_config.get('connect_timeout_seconds', _DEFAULT_CONNECT_TIMEOUT_SECONDS)
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
raise ValueError('plugin.connect_timeout_seconds must be a positive number')
return float(value)
@staticmethod
def _runtime_connect_timeout_error(timeout_seconds: float) -> str:
return f'Plugin runtime did not become ready within {timeout_seconds:g} seconds'
def _runtime_handler(self) -> handler.RuntimeConnectionHandler:
runtime_handler = getattr(self, 'handler', None)
if runtime_handler is None:
@@ -251,6 +263,13 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
def _control_headers(self, *, allow_generate: bool) -> dict[str, str]:
if not self._control_token and allow_generate:
self._control_token = secrets.token_urlsafe(48)
if not self._control_token:
if self.runtime_profile == 'shared':
raise PluginRuntimeNotConnectedError(
f'{PLUGIN_RUNTIME_CONTROL_TOKEN_ENV} must be configured with a strong shared secret '
'for a Cloud Plugin Runtime'
)
return {}
try:
self._control_token = validate_runtime_secret(
self._control_token,
@@ -699,10 +718,13 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
"""
runtime_handler = self._runtime_handler()
started_at = time.monotonic()
async with self._state_lock:
all_states: dict[str, PluginInstallationDesiredState] = {}
workspace_installations: dict[str, set[str]] = {}
workspace_count = 0
for context in contexts:
workspace_count += 1
execution_context = await self._validate_execution_context(context)
states = await self._load_workspace_desired_states(execution_context)
installation_ids = {state.binding.installation_uuid for state in states}
@@ -722,6 +744,13 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
runtime_handler.unregister_installation_binding(previous.binding)
self._known_desired_states = all_states
self._workspace_installations = workspace_installations
self.ap.logger.info(
'Shared plugin runtime reconcile completed: workspaces=%d desired_installations=%d '
'elapsed_seconds=%.3f',
workspace_count,
len(all_states),
time.monotonic() - started_at,
)
return result
async def _validate_execution_context(self, context: TenantContext) -> ExecutionContext:
@@ -817,6 +846,8 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
runtime_id=self._runtime_id,
)
self.worker_policy = self._load_worker_policy()
plugin_config = self.ap.instance_config.data.get('plugin', {})
connect_timeout_seconds = self._runtime_connect_timeout(plugin_config)
async with self._lifecycle_lock:
if self._closing:
@@ -958,10 +989,12 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
self._transport_task = asyncio.create_task(task_coro)
try:
await asyncio.wait_for(self._connected.wait(), timeout=_CONNECT_TIMEOUT_SEC)
await asyncio.wait_for(self._connected.wait(), timeout=connect_timeout_seconds)
except asyncio.TimeoutError as exc:
await self._stop_transport()
raise PluginRuntimeNotConnectedError('Plugin runtime did not become ready within 30 seconds') from exc
raise PluginRuntimeNotConnectedError(
self._runtime_connect_timeout_error(connect_timeout_seconds)
) from exc
if connect_errors:
await self._stop_transport()
raise PluginRuntimeNotConnectedError(f'Plugin runtime connection failed: {connect_errors[-1]}')
@@ -1989,11 +2022,11 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
with runtime_handler.installation_scope(binding):
return await runtime_handler.handle_page_api(plugin_author, plugin_name, page_id, endpoint, method, body)
async def get_debug_info(self) -> dict[str, Any]:
async def get_debug_info(self, execution_context: ExecutionContext) -> dict[str, Any]:
"""Get debug information including debug key and WS URL"""
if not self.is_enable_plugin or not self._runtime_available():
return {}
return await self._runtime_handler().get_debug_info()
return await self._runtime_handler().get_debug_info(execution_context)
async def emit_event(
self,
@@ -2164,15 +2197,9 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
return []
runtime_handler = self._runtime_handler()
runners: list[dict[str, Any]] = []
for binding in await self._operation_bindings(
include_plugins=bound_plugins
):
for binding in await self._operation_bindings(include_plugins=bound_plugins):
with runtime_handler.installation_scope(binding):
runners.extend(
await runtime_handler.list_agent_runners(
include_plugins=bound_plugins
)
)
runners.extend(await runtime_handler.list_agent_runners(include_plugins=bound_plugins))
return runners
async def run_agent(
@@ -2205,12 +2232,9 @@ class PluginRuntimeConnector(ManagedRuntimeConnector):
}
return
workspace_id = (
(context.get('conversation') or {}).get('workspace_id')
or (context.get('runtime') or {}).get('metadata', {}).get(
'workspace_id'
)
)
workspace_id = (context.get('conversation') or {}).get('workspace_id') or (context.get('runtime') or {}).get(
'metadata', {}
).get('workspace_id')
if not isinstance(workspace_id, str) or not workspace_id.strip():
raise ValueError('AgentRunner execution requires a Workspace')
execution_context = await self._current_execution_context()
+24 -33
View File
@@ -81,6 +81,7 @@ def _is_host_reserved_query_var(key: str) -> bool:
"""Return whether a Query variable controls Host authorization or runtime state."""
return key in _HOST_RESERVED_QUERY_VAR_KEYS or key.startswith(_HOST_RESERVED_QUERY_VAR_PREFIXES)
_DEFAULT_BINARY_STORAGE_VALUE_BYTES = 10 * 1024 * 1024
_HARD_MAX_BINARY_STORAGE_VALUE_BYTES = 64 * 1024 * 1024
@@ -322,9 +323,7 @@ def _get_cached_query(
try:
if isinstance(query_id, str):
return ap.query_pool.cached_queries.get((workspace_uuid, query_id))
query_uuid = ap.query_pool.legacy_query_index.get(
(workspace_uuid, query_id)
)
query_uuid = ap.query_pool.legacy_query_index.get((workspace_uuid, query_id))
if query_uuid is None:
return None
return ap.query_pool.cached_queries.get((workspace_uuid, query_uuid))
@@ -669,20 +668,14 @@ class RuntimeConnectionHandler(handler.Handler):
trusted_plugin_identity = None
if not _runtime_scoped:
action_context, identity = await self._require_plugin_action_context()
trusted_plugin_identity = (
f'{identity.plugin_author}/{identity.plugin_name}'
)
trusted_plugin_identity = f'{identity.plugin_author}/{identity.plugin_name}'
await self._require_active_action_context(action_context)
safe_data = {
key: value
for key, value in data.items()
if key not in _UNTRUSTED_SCOPE_FIELDS
}
safe_data = {key: value for key, value in data.items() if key not in _UNTRUSTED_SCOPE_FIELDS}
claimed_identity = safe_data.get('caller_plugin_identity')
if (
trusted_plugin_identity is not None
and claimed_identity not in {None, trusted_plugin_identity}
):
if trusted_plugin_identity is not None and claimed_identity not in {
None,
trusted_plugin_identity,
}:
yield handler.ActionResponse.error(
message='Caller plugin identity does not match the installation binding'
)
@@ -706,16 +699,11 @@ class RuntimeConnectionHandler(handler.Handler):
trusted_plugin_identity = None
if not _runtime_scoped:
action_context, identity = await self._require_plugin_action_context()
trusted_plugin_identity = (
f'{identity.plugin_author}/{identity.plugin_name}'
)
trusted_plugin_identity = f'{identity.plugin_author}/{identity.plugin_name}'
await self._require_active_action_context(action_context)
safe_data = {key: value for key, value in data.items() if key not in _UNTRUSTED_SCOPE_FIELDS}
claimed_identity = safe_data.get('caller_plugin_identity')
if (
trusted_plugin_identity is not None
and claimed_identity not in {None, trusted_plugin_identity}
):
if trusted_plugin_identity is not None and claimed_identity not in {None, trusted_plugin_identity}:
return handler.ActionResponse.error(
message='Caller plugin identity does not match the installation binding'
)
@@ -874,9 +862,7 @@ class RuntimeConnectionHandler(handler.Handler):
):
super().__init__(connection, disconnect_callback)
self.ap = ap
self._outbound_installation_context: contextvars.ContextVar[
InstallationBinding | None | object
] = (
self._outbound_installation_context: contextvars.ContextVar[InstallationBinding | None | object] = (
contextvars.ContextVar(
f'{self.__class__.__name__}_{id(self)}_outbound_installation',
default=_OUTBOUND_INSTALLATION_CONTEXT_UNSET,
@@ -2497,7 +2483,7 @@ class RuntimeConnectionHandler(handler.Handler):
return await self.call_action(
LangBotToRuntimeAction.RECONCILE_PLUGIN_INSTALLATIONS,
request.model_dump(),
timeout=120,
timeout=300,
)
async def apply_plugin_installation(
@@ -2938,14 +2924,19 @@ class RuntimeConnectionHandler(handler.Handler):
)
return result
async def get_debug_info(self) -> dict[str, Any]:
async def get_debug_info(self, execution_context: ExecutionContext) -> dict[str, Any]:
"""Get debug information including debug key and WS URL"""
with self.installation_scope(None):
result = await self.call_action(
LangBotToRuntimeAction.GET_DEBUG_INFO,
{},
timeout=10,
)
action_context = ActionContext(
instance_uuid=execution_context.instance_uuid,
workspace_uuid=execution_context.workspace_uuid,
placement_generation=execution_context.placement_generation,
)
result = await self.call_action(
LangBotToRuntimeAction.GET_DEBUG_INFO,
{},
timeout=10,
action_context=action_context,
)
return result
# ================= RAG Capability Callers (LangBot -> Runtime) =================
@@ -649,6 +649,7 @@ class ModelManager:
provider_uuid=runtime_provider.provider_entity.uuid,
abilities=model_info.get('abilities', []),
context_length=model_info.get('context_length'),
reasoning_config=model_info.get('reasoning_config', {'level': 'provider_default'}),
extra_args=model_info.get('extra_args', {}),
)
return self._build_llm_model(execution_context, model_entity, runtime_provider)
@@ -717,7 +718,10 @@ class ModelManager:
provider_entity = self._coerce_provider(provider_info, context)
requester_manifest = self.get_available_requester_manifest_by_name(provider_entity.requester)
litellm_provider = self._get_litellm_provider_from_manifest(requester_manifest)
config = {'base_url': provider_entity.base_url}
config = {
'base_url': provider_entity.base_url,
'requester_name': provider_entity.requester,
}
if litellm_provider:
from .requesters import litellmchat
@@ -0,0 +1,125 @@
from __future__ import annotations
import typing
ReasoningLevel = typing.Literal[
'provider_default',
'disabled',
'enabled',
'minimal',
'low',
'medium',
'high',
'xhigh',
'max',
]
REASONING_LEVELS: tuple[str, ...] = (
'provider_default',
'disabled',
'enabled',
'minimal',
'low',
'medium',
'high',
'xhigh',
'max',
)
DEFAULT_REASONING_CONFIG: dict[str, str] = {'level': 'provider_default'}
_CONFLICTING_TOP_LEVEL_ARGS = {
'reasoning_effort',
'thinking',
'enable_thinking',
'thinking_budget',
'reasoning',
}
_CONFLICTING_EXTRA_BODY_ARGS = {
'reasoning_effort',
'thinking',
'enable_thinking',
'thinking_budget',
'reasoning',
}
def normalize_reasoning_config(value: typing.Any) -> dict[str, str]:
"""Return the canonical model reasoning configuration."""
if value is None:
return dict(DEFAULT_REASONING_CONFIG)
if not isinstance(value, dict):
raise ValueError('reasoning_config must be an object')
unknown_fields = set(value) - {'level'}
if unknown_fields:
raise ValueError(f'Unsupported reasoning_config fields: {", ".join(sorted(unknown_fields))}')
level = value.get('level', 'provider_default')
if level not in REASONING_LEVELS:
raise ValueError(f'Unsupported reasoning level: {level}')
return {'level': typing.cast(str, level)}
def validate_reasoning_config(
value: typing.Any,
abilities: typing.Iterable[str] | None,
extra_args: typing.Any,
) -> dict[str, str]:
"""Validate a model-facing reasoning config and conflicting raw arguments."""
config = normalize_reasoning_config(value)
if config['level'] == 'provider_default':
return config
if 'reasoning' not in set(abilities or []):
raise ValueError('The reasoning ability must be enabled before selecting a reasoning level')
conflicts = find_reasoning_arg_conflicts(extra_args)
if conflicts:
raise ValueError('reasoning_config conflicts with advanced parameters: ' + ', '.join(conflicts))
return config
def find_reasoning_arg_conflicts(extra_args: typing.Any) -> list[str]:
if not isinstance(extra_args, dict):
return []
conflicts = [key for key in sorted(_CONFLICTING_TOP_LEVEL_ARGS) if key in extra_args]
extra_body = extra_args.get('extra_body')
if isinstance(extra_body, dict):
conflicts.extend(f'extra_body.{key}' for key in sorted(_CONFLICTING_EXTRA_BODY_ARGS) if key in extra_body)
return conflicts
def validate_reasoning_capabilities(
config: typing.Any,
capabilities: typing.Mapping[str, typing.Any],
model_name: str,
) -> None:
"""Ensure an explicit reasoning level can be honored by the requester."""
level = normalize_reasoning_config(config)['level']
if level == 'provider_default':
return
available_levels = capabilities.get('levels')
if not isinstance(available_levels, list):
available_levels = []
legacy_levels = capabilities.get('legacy_levels')
if not isinstance(legacy_levels, list):
legacy_levels = []
if capabilities.get('supported') is not True or (level not in available_levels and level not in legacy_levels):
available_text = ', '.join(str(item) for item in available_levels) or 'provider_default'
raise ValueError(
f'Reasoning level "{level}" is not supported by model {model_name}. Available levels: {available_text}'
)
def default_reasoning_capabilities(
supported: bool = False,
source: str = 'unknown',
) -> dict[str, typing.Any]:
return {
'supported': supported,
'levels': ['provider_default'],
'source': source,
}
@@ -10,6 +10,7 @@ from ...entity.persistence import model as persistence_model
from ...workspace.errors import WorkspaceInvariantError
import langbot_plugin.api.entities.builtin.resource.tool as resource_tool
from . import token
from . import reasoning
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
import langbot_plugin.api.entities.builtin.provider.message as provider_message
@@ -377,11 +378,15 @@ class RuntimeLLMModel:
provider: RuntimeProvider
"""提供商实例"""
reasoning_config_override: dict[str, str] | None
"""Request-scoped reasoning policy supplied by the active pipeline."""
def __init__(
self,
execution_context: ExecutionContext,
model_entity: persistence_model.LLMModel,
provider: RuntimeProvider,
reasoning_config_override: dict[str, str] | None = None,
):
_ensure_same_execution_scope(provider.execution_context, execution_context, resource='LLM model')
if model_entity.workspace_uuid != execution_context.workspace_uuid:
@@ -391,6 +396,7 @@ class RuntimeLLMModel:
self.execution_context = execution_context
self.model_entity = model_entity
self.provider = provider
self.reasoning_config_override = reasoning_config_override
class RuntimeEmbeddingModel:
@@ -482,6 +488,13 @@ class ProviderAPIRequester(metaclass=abc.ABCMeta):
"""
raise NotImplementedError('This provider does not support model scanning')
def get_reasoning_capabilities(self, model: RuntimeLLMModel) -> dict[str, typing.Any]:
"""Return normalized reasoning controls supported by a model."""
return reasoning.default_reasoning_capabilities(
supported='reasoning' in (model.model_entity.abilities or []),
source='manual' if 'reasoning' in (model.model_entity.abilities or []) else 'unknown',
)
@abc.abstractmethod
async def invoke_llm(
self,
@@ -7,7 +7,7 @@ import typing
import litellm
from litellm import acompletion, aembedding, arerank
from .. import errors, requester
from .. import errors, reasoning, requester
from ....utils import httpclient
import langbot_plugin.api.entities.builtin.resource.tool as resource_tool
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
@@ -164,6 +164,39 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
_EMBEDDING_MODEL_HINTS = ('embedding', 'embed', 'bge-', 'e5-', 'm3e', 'gte-', 'text-embedding')
_RERANK_MODEL_HINTS = ('rerank', 're-rank', 're_rank')
_QWEN_DEDICATED_THINKING_MODELS = frozenset(
{
'qwen3.7-max-preview',
'qwen3.7-max-2026-05-17',
}
)
_QWEN_REASONING_BUDGETS = {
'low': 1024,
'medium': 4096,
'high': 8192,
}
_INFERRED_EFFORT_PROVIDERS = frozenset(
{
'anthropic',
'gemini',
'groq',
'mistral',
'openai',
'openrouter',
'together_ai',
'xai',
}
)
_REQUESTER_REASONING_FAMILIES = {
'openai-chat-completions': 'openai',
'anthropic-messages': 'anthropic',
'deepseek-chat-completions': 'deepseek',
'moonshot-chat-completions': 'kimi',
'moonshot-cn-chat-completions': 'kimi',
'bailian-chat-completions': 'qwen',
'doubao-chat-completions': 'doubao',
'mimo-chat-completions': 'mimo',
}
default_config: dict[str, typing.Any] = {
'base_url': '',
@@ -172,6 +205,7 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
'drop_params': False,
'num_retries': 0,
'api_version': '',
'requester_name': '',
}
async def initialize(self):
@@ -201,7 +235,10 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
return False
provider = self._get_custom_llm_provider()
candidates: list[tuple[str, str | None]] = [(model_name, provider)]
candidates: list[tuple[str, str | None]] = [
(candidate, None) for candidate in self._metadata_model_candidates(model_name)
]
candidates.append((model_name, provider))
litellm_model_name = self._build_litellm_model_name(model_name)
if litellm_model_name != model_name:
candidates.append((litellm_model_name, None))
@@ -268,6 +305,14 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
deduped_candidates.append(candidate)
return deduped_candidates
@staticmethod
def _metadata_model_candidates(model_name: str) -> list[str]:
"""Return known equivalent model IDs used only for LiteLLM metadata lookup."""
normalized_model_name = (model_name or '').lower()
if normalized_model_name.startswith('mimo-v2.5'):
return [f'openrouter/xiaomi/{normalized_model_name}']
return []
def _known_context_length_fallback(self, model_name: str) -> int | None:
normalized_model_name = (model_name or '').lower()
if normalized_model_name.startswith('deepseek-v4-'):
@@ -287,7 +332,8 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
if not callable(helper):
return self._known_context_length_fallback(model_name)
candidates = [model_name]
candidates = self._metadata_model_candidates(model_name)
candidates.append(model_name)
litellm_model_name = self._build_litellm_model_name(model_name)
if litellm_model_name != model_name:
candidates.append(litellm_model_name)
@@ -314,6 +360,297 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
def _supports_vision(self, model_name: str) -> bool:
return self._safe_litellm_bool_helper('supports_vision', model_name)
def _supports_reasoning(self, model_name: str) -> bool:
return self._safe_litellm_bool_helper('supports_reasoning', model_name)
def _requester_name(self, model: requester.RuntimeLLMModel | None = None) -> str:
if model is not None:
provider_entity = getattr(getattr(model, 'provider', None), 'provider_entity', None)
name = getattr(provider_entity, 'requester', None)
if isinstance(name, str) and name:
return name.lower()
return str(self.requester_cfg.get('requester_name') or '').lower()
@staticmethod
def _infer_reasoning_family_from_model_name(model_name: str) -> str:
normalized_name = (model_name or '').lower()
basename = normalized_name.rsplit('/', 1)[-1]
if basename.startswith(('gpt-', 'chatgpt-', 'o1', 'o3', 'o4')):
return 'openai'
if basename.startswith('claude-'):
return 'anthropic'
if basename.startswith('deepseek-'):
return 'deepseek'
if basename.startswith(('kimi-', 'moonshot-')):
return 'kimi'
if basename.startswith(('qwen-', 'qwen3', 'qwq')):
return 'qwen'
if basename.startswith(('doubao-', 'seed-')):
return 'doubao'
if basename.startswith('mimo-'):
return 'mimo'
return ''
def _reasoning_family(
self,
model_name: str,
model: requester.RuntimeLLMModel | None = None,
) -> str:
requester_name = self._requester_name(model)
if requester_name in {'new-api-chat-completions', 'volcark-chat-completions'}:
inferred_family = self._infer_reasoning_family_from_model_name(model_name)
if inferred_family:
return inferred_family
return 'volcengine' if requester_name == 'volcark-chat-completions' else ''
# Bailian's compatible endpoint also hosts Kimi models. Keep those
# models on Kimi's ``thinking`` protocol instead of Qwen's
# ``enable_thinking`` protocol.
if requester_name == 'bailian-chat-completions':
inferred_family = self._infer_reasoning_family_from_model_name(model_name)
if inferred_family == 'kimi':
return inferred_family
requester_family = self._REQUESTER_REASONING_FAMILIES.get(requester_name)
if requester_family:
return requester_family
inferred_family = self._infer_reasoning_family_from_model_name(model_name)
provider = (self._get_custom_llm_provider() or '').lower()
if provider == 'openai':
return inferred_family or ('openai' if requester_name in {'', 'openai'} else '')
if provider:
return provider
return inferred_family
@staticmethod
def _is_anthropic_adaptive_model(model_name: str) -> bool:
basename = model_name.lower().rsplit('/', 1)[-1]
if 'mythos-preview' in basename:
return True
parts = basename.split('-')
if len(parts) < 3 or parts[0] != 'claude':
return False
model_families = {'opus', 'sonnet', 'fable', 'mythos'}
if parts[1] in model_families:
if parts[2] == '5':
return True
return len(parts) >= 4 and parts[2] == '4' and parts[3] in {'6', '7', '8'}
return parts[1] == '5' and parts[2] in model_families
@staticmethod
def _is_anthropic_always_thinking_model(model_name: str) -> bool:
normalized_name = model_name.lower()
return any(marker in normalized_name for marker in ('fable-5', 'mythos-5', 'mythos-preview'))
@staticmethod
def _is_dedicated_qwen_thinking_model(model_name: str) -> bool:
normalized_name = model_name.lower().rsplit('/', 1)[-1]
return (
normalized_name in LiteLLMRequester._QWEN_DEDICATED_THINKING_MODELS
or normalized_name.startswith('qwq')
or '-thinking' in normalized_name
)
@staticmethod
def _supports_qwen_thinking_budget(model_name: str) -> bool:
"""Return whether the documented Qwen3 family supports thinking_budget."""
normalized_name = model_name.lower().rsplit('/', 1)[-1]
return normalized_name.startswith('qwen3')
def _known_reasoning_levels(self, model_name: str, family: str) -> list[str] | None:
normalized_name = model_name.lower().rsplit('/', 1)[-1]
if family == 'deepseek' and normalized_name.startswith('deepseek-'):
if normalized_name.startswith('deepseek-v4-'):
return ['provider_default', 'disabled', 'low', 'high', 'xhigh', 'max']
if 'reasoner' in normalized_name or '-r1' in normalized_name:
return ['provider_default']
return ['provider_default', 'disabled', 'enabled']
if family == 'kimi':
if normalized_name.startswith('kimi-k3'):
return ['provider_default', 'low', 'high', 'max']
if normalized_name.startswith('kimi-k2.7-code'):
return ['provider_default']
if normalized_name.startswith(('kimi-k2.5', 'kimi-k2.6')):
return ['provider_default', 'disabled', 'enabled']
if 'thinking' in normalized_name:
return ['provider_default']
if family == 'qwen' and normalized_name.startswith(('qwen-', 'qwen3', 'qwq')):
if self._is_dedicated_qwen_thinking_model(normalized_name):
if self._supports_qwen_thinking_budget(normalized_name):
return ['provider_default', 'low', 'medium', 'high']
return ['provider_default']
if self._supports_qwen_thinking_budget(normalized_name):
return ['provider_default', 'disabled', 'low', 'medium', 'high']
return ['provider_default', 'disabled', 'enabled']
if family == 'doubao' and normalized_name.startswith(('doubao-', 'seed-')):
return ['provider_default', 'disabled', 'low', 'medium', 'high']
if family == 'mimo' and normalized_name.startswith(('mimo-v2.5',)):
return ['provider_default', 'disabled', 'enabled']
if family == 'anthropic' and normalized_name.startswith('claude-'):
levels = ['provider_default']
adaptive = self._is_anthropic_adaptive_model(normalized_name)
if adaptive and not self._is_anthropic_always_thinking_model(normalized_name):
levels.append('disabled')
levels.extend(['low', 'medium', 'high'])
if adaptive:
levels.extend(['xhigh', 'max'])
return levels
if family == 'openai' and normalized_name.startswith(('gpt-5', 'o1', 'o3', 'o4')):
return ['provider_default', 'low', 'medium', 'high']
return None
def _openai_reasoning_levels(self, model_name: str) -> list[str]:
model_info = self._safe_model_info(model_name)
levels = ['provider_default']
if model_info.get('supports_none_reasoning_effort') is True:
levels.append('disabled')
if model_info.get('supports_minimal_reasoning_effort') is True:
levels.append('minimal')
for level in ('low', 'medium', 'high'):
if model_info.get(f'supports_{level}_reasoning_effort') is not False:
levels.append(level)
for level in ('xhigh', 'max'):
if model_info.get(f'supports_{level}_reasoning_effort') is True:
levels.append(level)
return levels
def _safe_model_info(self, model_name: str) -> dict[str, typing.Any]:
helper = getattr(litellm, 'get_model_info', None)
if not callable(helper):
return {}
candidates = [
*self._metadata_model_candidates(model_name),
model_name,
self._build_litellm_model_name(model_name),
]
for candidate in candidates:
try:
info = helper(candidate)
except Exception:
continue
if isinstance(info, dict):
return info
model_dump = getattr(info, 'model_dump', None)
if callable(model_dump):
try:
dumped = model_dump()
if isinstance(dumped, dict):
return dumped
except Exception:
continue
return {}
def get_reasoning_capabilities(self, model: requester.RuntimeLLMModel) -> dict[str, typing.Any]:
model_name = model.model_entity.name
abilities = model.model_entity.abilities or []
detected = self._supports_reasoning(model_name)
declared = 'reasoning' in abilities
family = self._reasoning_family(model_name, model)
known_levels = self._known_reasoning_levels(model_name, family)
supported = detected or declared or known_levels is not None
if not supported:
return reasoning.default_reasoning_capabilities()
normalized_name = model_name.lower()
if family == 'openai':
levels = self._openai_reasoning_levels(model_name)
elif known_levels is not None:
levels = known_levels
elif family == 'anthropic':
levels = ['provider_default', 'low', 'medium', 'high']
elif family in {'deepseek', 'qwen', 'mimo', 'volcengine'}:
levels = ['provider_default', 'disabled', 'enabled']
elif family == 'doubao':
levels = ['provider_default', 'disabled', 'low', 'medium', 'high']
elif family == 'ollama':
levels = ['provider_default']
levels.append('disabled')
if normalized_name.startswith('gpt-oss') or '/gpt-oss' in normalized_name:
levels.extend(['low', 'medium', 'high'])
else:
levels.append('enabled')
elif family in self._INFERRED_EFFORT_PROVIDERS:
levels = ['provider_default', 'low', 'medium', 'high']
else:
levels = ['provider_default']
capabilities = {
'supported': True,
'levels': list(dict.fromkeys(levels)),
'source': 'litellm' if detected else ('provider' if known_levels is not None else 'manual'),
}
if family == 'qwen' and 'disabled' in capabilities['levels'] and 'enabled' not in capabilities['levels']:
capabilities['legacy_levels'] = ['enabled']
return capabilities
def _build_reasoning_args(self, model: requester.RuntimeLLMModel) -> dict[str, typing.Any]:
level = self._reasoning_level(model)
if level == 'provider_default':
return {}
config = {'level': level}
capabilities = self.get_reasoning_capabilities(model)
try:
reasoning.validate_reasoning_capabilities(config, capabilities, model.model_entity.name)
except ValueError as exc:
raise errors.RequesterError(str(exc)) from exc
family = self._reasoning_family(model.model_entity.name, model)
if level == 'disabled':
if family in {'deepseek', 'kimi', 'mimo', 'doubao'}:
return {'extra_body': {'thinking': {'type': 'disabled'}}}
if family == 'qwen':
return {'extra_body': {'enable_thinking': False}}
if family == 'volcengine':
return {'extra_body': {'thinking': {'type': 'disabled'}}}
if family == 'anthropic':
return {'thinking': {'type': 'disabled'}}
return {'reasoning_effort': 'none'}
if level == 'enabled':
if family in {'deepseek', 'kimi', 'mimo', 'volcengine'}:
return {'extra_body': {'thinking': {'type': 'enabled'}}}
if family == 'qwen':
return {'extra_body': {'enable_thinking': True}}
return {'reasoning_effort': 'low'}
if family == 'qwen' and level in self._QWEN_REASONING_BUDGETS:
return {
'extra_body': {
'enable_thinking': True,
'thinking_budget': self._QWEN_REASONING_BUDGETS[level],
}
}
if family == 'deepseek':
return {
'extra_body': {
'thinking': {'type': 'enabled'},
'reasoning_effort': level,
}
}
return {'reasoning_effort': level}
@staticmethod
def _reasoning_config_value(model: requester.RuntimeLLMModel) -> typing.Any:
raw_config = getattr(model, 'reasoning_config_override', None)
if raw_config is None:
raw_config = getattr(model.model_entity, 'reasoning_config', None)
if not isinstance(raw_config, dict):
return None
return raw_config
def _reasoning_level(self, model: requester.RuntimeLLMModel) -> str:
return reasoning.normalize_reasoning_config(self._reasoning_config_value(model))['level']
def _infer_model_type(self, model_id: str) -> str:
normalized_id = (model_id or '').lower()
if any(kw in normalized_id for kw in self._RERANK_MODEL_HINTS):
@@ -344,6 +681,13 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
)
if supports_provider_reported_vision or self._supports_vision(model_id):
abilities.append('vision')
supports_provider_reported_reasoning = bool(
model_payload and model_payload.get('supports_reasoning') is True
)
family = self._reasoning_family(model_id)
supports_known_reasoning = self._known_reasoning_levels(model_id, family) is not None
if supports_provider_reported_reasoning or supports_known_reasoning or self._supports_reasoning(model_id):
abilities.append('reasoning')
scanned_model['abilities'] = abilities
context_length = self._context_length_from_scan_payload(model_payload)
@@ -354,13 +698,51 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
return scanned_model
def _convert_messages(self, messages: typing.List[provider_message.Message]) -> list[dict]:
def _convert_messages(
self,
messages: typing.List[provider_message.Message],
reasoning_family: str = '',
include_reasoning_context: bool = True,
) -> list[dict]:
"""Convert LangBot messages to LiteLLM/OpenAI format."""
req_messages = []
for m in messages:
msg_dict = m.dict(exclude_none=True)
content = msg_dict.get('content')
if msg_dict.get('role') == 'assistant' and reasoning_family:
provider_fields = msg_dict.get('provider_specific_fields')
if isinstance(provider_fields, dict):
cleaned_provider_fields = dict(provider_fields)
reasoning_content = cleaned_provider_fields.pop('reasoning_content', None)
thinking_blocks = cleaned_provider_fields.pop('thinking_blocks', None)
# ``content`` is also used for the user-facing rendering.
# Do not replay that rendered <think> wrapper alongside the
# structured provider reasoning on the next request.
if reasoning_content or thinking_blocks:
content = msg_dict.get('content')
if isinstance(content, str):
msg_dict['content'] = self._strip_think(content)
if include_reasoning_context:
if reasoning_family == 'anthropic' and thinking_blocks:
msg_dict['thinking_blocks'] = thinking_blocks
elif reasoning_family in {
'deepseek',
'kimi',
'qwen',
'doubao',
'mimo',
'volcengine',
} and isinstance(reasoning_content, str):
msg_dict['reasoning_content'] = reasoning_content
if cleaned_provider_fields:
msg_dict['provider_specific_fields'] = cleaned_provider_fields
else:
msg_dict.pop('provider_specific_fields', None)
if isinstance(content, list):
converted_parts = []
for part in content:
@@ -421,6 +803,52 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
return content or ''
@staticmethod
def _thinking_blocks_text(thinking_blocks: typing.Any) -> str:
if not isinstance(thinking_blocks, list):
return ''
parts = []
for block in thinking_blocks:
if isinstance(block, dict):
text = block.get('thinking')
else:
text = getattr(block, 'thinking', None)
if isinstance(text, str) and text:
parts.append(text)
return ''.join(parts)
@classmethod
def _merge_thinking_blocks(
cls,
current: list[dict[str, typing.Any]],
incoming: typing.Any,
) -> list[dict[str, typing.Any]]:
"""Merge Anthropic thinking block fragments emitted by a stream."""
if not isinstance(incoming, list):
return current
merged = [dict(block) for block in current]
for raw_block in incoming:
block = cls._as_dict(raw_block)
if not block:
continue
block_type = block.get('type')
if block_type == 'redacted_thinking':
merged.append(block)
continue
text = block.get('thinking') if isinstance(block.get('thinking'), str) else ''
signature = block.get('signature')
if merged and merged[-1].get('type') == 'thinking' and not merged[-1].get('signature'):
merged[-1]['thinking'] = f'{merged[-1].get("thinking", "")}{text}'
if signature:
merged[-1]['signature'] = signature
elif merged and signature and merged[-1].get('signature') == signature:
if text and text != merged[-1].get('thinking', ''):
merged[-1]['thinking'] = f'{merged[-1].get("thinking", "")}{text}'
else:
merged.append(block)
return merged
@staticmethod
def _normalize_usage(usage: typing.Any) -> dict:
"""Normalize a LiteLLM/OpenAI usage object into a plain token dict.
@@ -651,7 +1079,13 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
stream: bool = False,
) -> dict:
"""Build common completion arguments for invoke_llm and invoke_llm_stream."""
req_messages = self._convert_messages(messages)
reasoning_family = self._reasoning_family(model.model_entity.name, model)
reasoning_level = self._reasoning_level(model)
req_messages = self._convert_messages(
messages,
reasoning_family=reasoning_family,
include_reasoning_context=reasoning_level != 'disabled',
)
model_name = self._build_litellm_model_name(model.model_entity.name)
api_key = model.provider.token_mgr.get_token()
@@ -670,6 +1104,29 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
args.update(model.model_entity.extra_args)
args.update(extra_args)
reasoning_args = self._build_reasoning_args(model)
if reasoning_args:
conflicts = reasoning.find_reasoning_arg_conflicts(model.model_entity.extra_args)
conflicts.extend(reasoning.find_reasoning_arg_conflicts(extra_args))
if conflicts:
raise errors.RequesterError(
'reasoning_config conflicts with advanced parameters: ' + ', '.join(dict.fromkeys(conflicts))
)
reasoning_extra_body = reasoning_args.get('extra_body')
if isinstance(reasoning_extra_body, dict):
existing_extra_body = args.get('extra_body') or {}
if not isinstance(existing_extra_body, dict):
raise errors.RequesterError('extra_body must be an object')
args.update({key: value for key, value in reasoning_args.items() if key != 'extra_body'})
args['extra_body'] = {**existing_extra_body, **reasoning_extra_body}
else:
args.update(reasoning_args)
if 'reasoning_effort' in reasoning_args and self._get_custom_llm_provider() == 'openai':
allowed_openai_params = args.get('allowed_openai_params') or []
if not isinstance(allowed_openai_params, (list, tuple, set)):
raise errors.RequesterError('allowed_openai_params must be an array')
args['allowed_openai_params'] = list(dict.fromkeys([*allowed_openai_params, 'reasoning_effort']))
if funcs:
tools = await self.ap.tool_mgr.generate_tools_for_openai(funcs)
if tools:
@@ -730,10 +1187,21 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
content = message_data.get('content', '')
reasoning_content = message_data.get('reasoning_content', None)
message_data['content'] = self._process_thinking_content(content, reasoning_content, remove_think)
thinking_blocks = message_data.get('thinking_blocks')
if reasoning_content or thinking_blocks:
provider_fields = dict(message_data.get('provider_specific_fields') or {})
if reasoning_content:
provider_fields['reasoning_content'] = reasoning_content
if thinking_blocks:
provider_fields['thinking_blocks'] = thinking_blocks
message_data['provider_specific_fields'] = provider_fields
display_reasoning = reasoning_content or self._thinking_blocks_text(thinking_blocks) or None
message_data['content'] = self._process_thinking_content(content, display_reasoning, remove_think)
if 'reasoning_content' in message_data:
del message_data['reasoning_content']
if 'thinking_blocks' in message_data:
del message_data['thinking_blocks']
message = provider_message.Message(**message_data)
usage_info = self._extract_usage(response)
@@ -759,6 +1227,9 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
role = 'assistant'
tool_call_state: dict[int, dict[str, typing.Any]] = {}
think_state = _ThinkStripState() if remove_think else None
reasoning_started = False
reasoning_closed = False
thinking_blocks_state: list[dict[str, typing.Any]] = []
try:
response = await acompletion(**args)
@@ -789,28 +1260,63 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
if 'role' in delta and delta['role']:
role = delta['role']
delta_content = delta.get('content', '')
reasoning_content = delta.get('reasoning_content', '')
delta_content = delta.get('content') or ''
reasoning_content = delta.get('reasoning_content') or ''
provider_fields = dict(delta.get('provider_specific_fields') or {})
raw_thinking_blocks = delta.get('thinking_blocks')
if raw_thinking_blocks:
thinking_blocks_state = self._merge_thinking_blocks(thinking_blocks_state, raw_thinking_blocks)
provider_fields['thinking_blocks'] = thinking_blocks_state
thinking_blocks_text = self._thinking_blocks_text(raw_thinking_blocks)
display_reasoning_content = reasoning_content or thinking_blocks_text
# Handle reasoning_content based on remove_think flag
if reasoning_content:
provider_fields['reasoning_content'] = reasoning_content
if remove_think:
# Skip reasoning content when remove_think is True
chunk_idx += 1
continue
delta_content = delta_content or None
else:
# Use reasoning_content as the displayed content
delta_content = reasoning_content
# Stream explicit markers so downstream adapters and
# the debug page see the same format as non-streaming
# responses.
if not reasoning_started:
delta_content = '<think>\n'
reasoning_started = True
else:
delta_content = ''
delta_content += display_reasoning_content
if delta.get('content'):
delta_content += f'\n</think>\n{delta.get("content")}'
reasoning_closed = True
elif display_reasoning_content:
if remove_think:
delta_content = delta_content or None
else:
if not reasoning_started:
delta_content = '<think>\n'
reasoning_started = True
else:
delta_content = ''
delta_content += display_reasoning_content
if delta.get('content'):
delta_content += f'\n</think>\n{delta.get("content")}'
reasoning_closed = True
elif delta_content and not remove_think and reasoning_started and not reasoning_closed:
delta_content = f'\n</think>\n{delta_content}'
reasoning_closed = True
if finish_reason and not remove_think and reasoning_started and not reasoning_closed:
delta_content = f'{delta_content}\n</think>\n'
reasoning_closed = True
if think_state is not None and delta_content:
delta_content = think_state.feed(delta_content)
if not delta_content:
chunk_idx += 1
continue
tool_calls = self._normalize_stream_tool_calls(delta.get('tool_calls'), tool_call_state)
if chunk_idx == 0 and not delta_content and not tool_calls:
if not delta_content and not tool_calls and not provider_fields and not finish_reason:
chunk_idx += 1
continue
@@ -822,13 +1328,20 @@ class LiteLLMRequester(requester.ProviderAPIRequester):
}
# Preserve provider_specific_fields from delta (e.g., Gemini thought_signatures)
if delta.get('provider_specific_fields'):
chunk_data['provider_specific_fields'] = delta['provider_specific_fields']
if provider_fields:
chunk_data['provider_specific_fields'] = provider_fields
chunk_data = {k: v for k, v in chunk_data.items() if v is not None}
yield provider_message.MessageChunk(**chunk_data)
chunk_idx += 1
if reasoning_started and not reasoning_closed:
yield provider_message.MessageChunk(
role=role,
content='\n</think>\n',
is_final=True,
)
if think_state is not None:
pending_content = think_state.flush()
if pending_content:
+18
View File
@@ -120,6 +120,7 @@ async def build_heartbeat_payload(
ap: core_app.Application,
*,
workspace_uuid: str,
workspace_create_ts: int = 0,
workspace_resource: WorkspaceResourceSnapshot | None = None,
) -> dict:
"""Collect one anonymous Workspace profile snapshot."""
@@ -212,7 +213,9 @@ async def build_heartbeat_payload(
'event_type': 'instance_heartbeat',
'query_id': '',
'version': constants.semantic_version,
'instance_id': constants.instance_id,
'workspace_uuid': workspace_uuid,
'workspace_create_ts': workspace_create_ts,
'instance_create_ts': constants.instance_create_ts,
'edition': constants.edition,
'features': features,
@@ -220,10 +223,24 @@ async def build_heartbeat_payload(
}
def _workspace_created_timestamp(created_at: datetime | None) -> int:
if created_at is None:
return 0
if created_at.tzinfo is None:
# SQLAlchemy may return persisted UTC values without tzinfo. Never
# reinterpret them in the host's local timezone.
created_at = created_at.replace(tzinfo=timezone.utc)
return int(created_at.timestamp())
async def build_heartbeat_payloads(ap: core_app.Application) -> list[dict]:
"""Build one heartbeat per active Workspace."""
bindings = await ap.workspace_service.list_active_execution_bindings()
workspace_uuids = sorted({binding.workspace_uuid for binding in bindings})
workspace_create_ts = {
binding.workspace_uuid: _workspace_created_timestamp(getattr(binding, 'workspace_created_at', None))
for binding in bindings
}
resources = {
resource['workspace_uuid']: resource for resource in await _cloud_workspace_resource_counts(ap, bindings)
}
@@ -231,6 +248,7 @@ async def build_heartbeat_payloads(ap: core_app.Application) -> list[dict]:
await build_heartbeat_payload(
ap,
workspace_uuid=workspace_uuid,
workspace_create_ts=workspace_create_ts.get(workspace_uuid, 0),
workspace_resource=resources.get(workspace_uuid),
)
for workspace_uuid in workspace_uuids
+8 -2
View File
@@ -4,13 +4,19 @@ import typing
class WorkspaceExecutionContext(typing.Protocol):
@property
def instance_uuid(self) -> str: ...
@property
def workspace_uuid(self) -> str: ...
def workspace_identity(execution_context: WorkspaceExecutionContext) -> dict[str, str]:
"""Build the canonical telemetry identity for one Workspace execution."""
"""Build both first-class telemetry identities for one execution."""
instance_id = execution_context.instance_uuid.strip()
workspace_uuid = execution_context.workspace_uuid.strip()
if not instance_id:
raise ValueError('Telemetry execution instance ID is empty')
if not workspace_uuid:
raise ValueError('Telemetry execution Workspace UUID is empty')
return {'workspace_uuid': workspace_uuid}
return {'instance_id': instance_id, 'workspace_uuid': workspace_uuid}
+24 -5
View File
@@ -136,12 +136,31 @@ class TelemetryManager:
try:
# Use asyncio.wait_for to ensure we always bound the total time
telemetry_token = os.getenv('LANGBOT_TELEMETRY_INGEST_TOKEN', '').strip()
headers: dict[str, str] = {}
if telemetry_token:
request = client.post(
url,
json=sanitized,
headers={'X-LangBot-Telemetry-Token': telemetry_token},
)
headers['X-LangBot-Telemetry-Token'] = telemetry_token
else:
workspace_uuid = str(sanitized.get('workspace_uuid', '')).strip()
user_service = getattr(self.ap, 'user_service', None)
if workspace_uuid and user_service is not None:
try:
owner = await user_service.get_workspace_owner(workspace_uuid)
owner_email = str(getattr(owner, 'user', '') or '').strip()
space_service = getattr(self.ap, 'space_service', None)
access_token = (
await space_service.get_valid_access_token(owner_email)
if owner_email and space_service is not None
else None
)
access_token = str(access_token or '').strip()
if access_token:
headers['Authorization'] = f'Bearer {access_token}'
except Exception:
self.ap.logger.debug(
'Could not resolve authenticated telemetry reporter', exc_info=True
)
if headers:
request = client.post(url, json=sanitized, headers=headers)
else:
request = client.post(url, json=sanitized)
resp = await asyncio.wait_for(request, timeout=10 + 1)
+1 -1
View File
@@ -67,7 +67,7 @@ class VectorDBManager:
use_business_database = pgvector_config.get('use_business_database', False)
allowed_dimensions = pgvector_config.get(
'allowed_dimensions',
[384, 512, 768, 1024, 1536],
[384, 512, 768, 1024, 1536, 3072],
)
common_options = {
'use_business_database': use_business_database,
+8 -3
View File
@@ -6,7 +6,7 @@ from collections.abc import AsyncIterator
from typing import Any
import sqlalchemy
from pgvector.sqlalchemy import Vector
from pgvector.sqlalchemy import HALFVEC, Vector
from sqlalchemy.dialects.postgresql import insert as postgresql_insert
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import declarative_base
@@ -18,7 +18,7 @@ from langbot.pkg.vector.vdb import VectorDatabase
Base = declarative_base()
DEFAULT_ALLOWED_DIMENSIONS = (384, 512, 768, 1024, 1536)
DEFAULT_ALLOWED_DIMENSIONS = (384, 512, 768, 1024, 1536, 3072)
# pgvector schema only stores these metadata fields.
_PG_SUPPORTED_FIELDS = {'text', 'file_id', 'chunk_uuid'}
@@ -321,7 +321,12 @@ class PgVectorDatabase(VectorDatabase):
if len(query_embedding) != scope.embedding_dimension:
raise ValueError(f'Query embedding must have the selected dimension {scope.embedding_dimension}')
typed_embedding = sqlalchemy.cast(PgVectorEntry.embedding, Vector(scope.embedding_dimension))
typed_embedding = sqlalchemy.cast(
PgVectorEntry.embedding,
HALFVEC(scope.embedding_dimension)
if scope.embedding_dimension > 2000
else Vector(scope.embedding_dimension),
)
distance = typed_embedding.cosine_distance(query_embedding)
statement = (
sqlalchemy.select(
@@ -17,6 +17,7 @@ from ..entity.persistence.user import AccountStatus, User
from ..entity.persistence.workspace import (
InvitationStatus,
MembershipRole,
MembershipSource,
MembershipStatus,
Workspace,
WorkspaceInvitation,
@@ -483,6 +484,7 @@ class WorkspaceCollaborationService:
account_uuid=account_uuid,
role=invitation.role,
status=MembershipStatus.ACTIVE.value,
source=MembershipSource.LOCAL.value,
invited_by_account_uuid=invitation.created_by_account_uuid,
joined_at=now,
projection_revision=0,
@@ -491,6 +493,7 @@ class WorkspaceCollaborationService:
elif membership.status != MembershipStatus.ACTIVE.value:
membership.role = invitation.role
membership.status = MembershipStatus.ACTIVE.value
membership.source = MembershipSource.LOCAL.value
membership.invited_by_account_uuid = invitation.created_by_account_uuid
membership.joined_at = now
+2
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import datetime
from dataclasses import dataclass
@@ -12,3 +13,4 @@ class WorkspaceExecutionBinding:
placement_generation: int
write_fenced: bool
state: str
workspace_created_at: datetime.datetime | None = None
+4
View File
@@ -11,6 +11,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from ..entity.persistence.workspace import (
MembershipRole,
MembershipSource,
MembershipStatus,
Workspace,
WorkspaceExecutionSource,
@@ -283,6 +284,7 @@ class WorkspaceService:
placement_generation=execution_state.active_generation,
write_fenced=execution_state.write_fenced,
state=execution_state.state,
workspace_created_at=workspace.created_at,
)
binding = await self._run(operation, session=session)
@@ -450,6 +452,7 @@ class WorkspaceService:
account_uuid=account_uuid,
role=MembershipRole.OWNER.value,
status=MembershipStatus.ACTIVE.value,
source=MembershipSource.LOCAL.value,
joined_at=joined_at,
projection_revision=0,
)
@@ -457,6 +460,7 @@ class WorkspaceService:
else:
membership.role = MembershipRole.OWNER.value
membership.status = MembershipStatus.ACTIVE.value
membership.source = MembershipSource.LOCAL.value
membership.joined_at = membership.joined_at or joined_at
if workspace.created_by_account_uuid is None:
+6 -3
View File
@@ -201,7 +201,7 @@ vdb:
# keep this false when deliberately using an external pgvector DB.
use_business_database: false
# Release migrations create one partial ANN index per enabled value.
allowed_dimensions: [384, 512, 768, 1024, 1536]
allowed_dimensions: [384, 512, 768, 1024, 1536, 3072]
host: '127.0.0.1'
port: 5433
database: 'langbot'
@@ -245,6 +245,8 @@ storage:
max_concurrency: 16
plugin:
enable: true
# Maximum time for the Runtime transport, handshake, and desired-state replay.
connect_timeout_seconds: 180.0
runtime_ws_url: 'ws://langbot_plugin_runtime:5400/control/ws'
enable_marketplace: true
display_plugin_debug_url: 'ws://localhost:5401/plugin/debug/ws'
@@ -339,8 +341,9 @@ box:
enabled: true
backend: 'local' # 'local' (Docker/nsjail), 'docker', 'nsjail', or 'e2b'. Can be written via BOX__BACKEND.
runtime:
# External WebSocket runtimes also require LANGBOT_BOX_CONTROL_TOKEN in
# both LangBot and Box. Keep the shared secret out of this config file.
# LANGBOT_BOX_CONTROL_TOKEN is optional for OSS external WebSocket
# runtimes. To protect an exposed endpoint, set the same strong secret
# in both LangBot and Box. Keep it out of this config file.
endpoint: '' # External Box Runtime base URL, e.g. 'ws://127.0.0.1:5410'. Leave empty for local auto-managed runtime.
limits:
max_sessions: 64
+20 -3
View File
@@ -106,7 +106,12 @@ async def plugin_security_api(plugin_module):
application.plugin_connector.require_workspace_context = AsyncMock()
application.plugin_connector.list_plugins = AsyncMock(return_value=[raw_plugin])
application.plugin_connector.get_plugin_info = AsyncMock(return_value=raw_plugin)
application.plugin_connector.get_debug_info = AsyncMock(return_value={'plugin_debug_key': 'runtime-debug-secret'})
application.plugin_connector.get_debug_info = AsyncMock(
return_value={
'plugin_debug_key': 'runtime-debug-secret',
'expires_at': '2026-08-04T12:00:00Z',
}
)
application.plugin_connector.get_plugin_logs = AsyncMock(return_value=['private runtime line'])
application.plugin_connector.set_plugin_config = AsyncMock()
@@ -230,10 +235,22 @@ async def test_debug_key_requires_resource_manage_permission(plugin_security_api
assert operator_denied.status_code == 403
assert allowed.status_code == 200
assert (await allowed.get_json())['data'] == {
'debug_url': 'http://localhost:5401',
'debug_url': 'ws://localhost:5401/plugin/debug/ws',
'plugin_debug_key': 'runtime-debug-secret',
'expires_at': '2026-08-04T12:00:00Z',
}
application.plugin_connector.get_debug_info.assert_awaited_once_with()
application.plugin_connector.get_debug_info.assert_awaited_once()
@pytest.mark.asyncio
async def test_debug_info_uses_websocket_endpoint_for_legacy_config(plugin_security_api):
application, client, _ = plugin_security_api
application.instance_config.data['plugin'].pop('display_plugin_debug_url')
response = await client.get('/api/v1/plugins/debug-info', headers=_headers('manager-token'))
assert response.status_code == 200
assert (await response.get_json())['data']['debug_url'] == 'ws://localhost:5401/plugin/debug/ws'
@pytest.mark.asyncio
+55 -26
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
from urllib.parse import parse_qs, urlsplit
@@ -14,6 +15,7 @@ from langbot.pkg.api.http.controller.groups.user import UserRouterGroup
pytestmark = pytest.mark.integration
WORKSPACE_UUID = '11111111-1111-4111-8111-111111111111'
WORKSPACE_CREATED_AT = datetime.datetime(2026, 1, 2, 3, 4, 5, tzinfo=datetime.UTC)
@pytest.fixture
@@ -58,6 +60,12 @@ async def space_oauth_api():
return_value={'account_uuid': 'account-a', 'workspace_uuid': WORKSPACE_UUID}
)
application.workspace_collaboration_service.resolve_account_workspace = AsyncMock(return_value=access)
application.workspace_service.get_execution_binding = AsyncMock(
return_value=SimpleNamespace(
workspace_uuid=WORKSPACE_UUID,
workspace_created_at=WORKSPACE_CREATED_AT,
)
)
application.space_service.get_oauth_authorize_url = Mock(
side_effect=lambda redirect_uri, state: f'https://space.example/authorize?state={state}'
)
@@ -157,34 +165,51 @@ async def test_bind_state_is_account_bound_and_requires_authentication(space_oau
@pytest.mark.asyncio
async def test_redirect_origin_and_callback_path_are_restricted(space_oauth_api):
async def test_redirect_allows_any_http_or_https_origin(space_oauth_api):
_, client = space_oauth_api
wrong_origin = await client.get(
'/api/v1/user/space/authorize-url',
query_string={'redirect_uri': 'https://evil.example/auth/space/callback'},
headers={'Origin': 'http://localhost'},
)
wrong_path = await client.get(
'/api/v1/user/space/authorize-url',
query_string={'redirect_uri': 'http://localhost/arbitrary'},
headers={'Origin': 'http://localhost'},
)
forged_origin = await client.get(
'/api/v1/user/space/authorize-url',
query_string={'redirect_uri': 'https://evil.example/auth/space/callback'},
headers={'Origin': 'https://evil.example'},
)
forged_host = await client.get(
'/api/v1/user/space/authorize-url',
query_string={'redirect_uri': 'https://evil.example/auth/space/callback'},
headers={'Host': 'evil.example'},
)
responses = [
await client.get(
'/api/v1/user/space/authorize-url',
query_string={'redirect_uri': redirect_uri},
headers={'Origin': 'https://irrelevant.example'},
)
for redirect_uri in (
'https://langbot.example/auth/space/callback',
'https://gateway.example:8443/auth/space/callback',
'https://192.0.2.10/auth/space/callback',
'http://localhost:5300/auth/space/callback',
'http://127.0.0.1:5300/auth/space/callback',
'http://[::1]:5300/auth/space/callback',
'http://langbot.example/auth/space/callback',
'http://192.0.2.10:5300/auth/space/callback',
)
]
assert (await wrong_origin.get_json())['code'] == 1
assert (await wrong_path.get_json())['code'] == 1
assert (await forged_origin.get_json())['code'] == 1
assert (await forged_host.get_json())['code'] == 1
assert all(response.status_code == 200 for response in responses)
payloads = [await response.get_json() for response in responses]
assert all(payload['code'] == 0 for payload in payloads)
@pytest.mark.asyncio
async def test_redirect_rejects_invalid_callback_shape(space_oauth_api):
_, client = space_oauth_api
responses = [
await client.get(
'/api/v1/user/space/authorize-url',
query_string={'redirect_uri': redirect_uri},
)
for redirect_uri in (
'https://langbot.example/arbitrary',
'https://langbot.example/auth/space/callback?next=https://evil.example',
'https://user@langbot.example/auth/space/callback',
'https://langbot.example/auth/space/callback#fragment',
)
]
payloads = [await response.get_json() for response in responses]
assert all(payload['code'] == 1 for payload in payloads)
@pytest.mark.asyncio
@@ -234,7 +259,11 @@ async def test_login_callback_requires_and_consumes_server_state(space_oauth_api
assert response.status_code == 200
assert (await response.get_json())['data']['token'] == 'space-login-token'
application.user_service.consume_space_oauth_state_details.assert_awaited_once_with('opaque-login-state', 'login')
application.space_service.exchange_oauth_code.assert_awaited_once_with('oauth-code')
application.space_service.exchange_oauth_code.assert_awaited_once_with(
'oauth-code',
[WORKSPACE_UUID],
{WORKSPACE_UUID: int(WORKSPACE_CREATED_AT.timestamp())},
)
@pytest.mark.asyncio
@@ -0,0 +1,70 @@
from __future__ import annotations
import pytest
import sqlalchemy as sa
from sqlalchemy.ext.asyncio import create_async_engine
from langbot.pkg.persistence.alembic_runner import run_alembic_stamp, run_alembic_upgrade
@pytest.mark.asyncio
async def test_membership_source_migration_backfills_existing_rows_as_local_and_enforces_constraint(tmp_path):
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "membership-source.db"}')
try:
async with engine.begin() as connection:
await connection.execute(
sa.text(
"""
CREATE TABLE workspace_memberships (
uuid VARCHAR(36) PRIMARY KEY,
workspace_uuid VARCHAR(36) NOT NULL,
account_uuid VARCHAR(36) NOT NULL,
role VARCHAR(32) NOT NULL,
status VARCHAR(32) NOT NULL,
projection_revision BIGINT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await connection.execute(
sa.text(
"""
INSERT INTO workspace_memberships
(uuid, workspace_uuid, account_uuid, role, status, projection_revision)
VALUES
('00000000-0000-4000-8000-000000000001', 'workspace', 'local-account',
'viewer', 'active', 0),
('00000000-0000-4000-8000-000000000002', 'workspace', 'cloud-account',
'viewer', 'active', 0)
"""
)
)
await run_alembic_stamp(engine, '0019_single_workspace_owner')
await run_alembic_upgrade(engine, 'head')
async with engine.connect() as connection:
rows = (
await connection.execute(sa.text('SELECT uuid, source FROM workspace_memberships ORDER BY uuid'))
).all()
columns = await connection.run_sync(
lambda sync_connection: {
column['name']: column
for column in sa.inspect(sync_connection).get_columns('workspace_memberships')
}
)
assert rows == [
('00000000-0000-4000-8000-000000000001', 'local'),
('00000000-0000-4000-8000-000000000002', 'local'),
]
assert columns['source']['nullable'] is False
with pytest.raises(sa.exc.IntegrityError):
async with engine.begin() as connection:
await connection.execute(
sa.text("UPDATE workspace_memberships SET source = 'guessed-from-user-source'")
)
finally:
await engine.dispose()
@@ -9,8 +9,11 @@ Run: uv run pytest tests/integration/persistence/test_migrations.py -q
from __future__ import annotations
import json
import pytest
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
from langbot.pkg.entity.persistence.base import Base
@@ -105,7 +108,7 @@ class TestSQLiteMigrationUpgrade:
await run_alembic_upgrade(sqlite_engine, 'head')
assert await get_alembic_current(sqlite_engine) == _get_script_head()
assert _get_script_head() == '0020_merge_agent_cloud_heads'
assert _get_script_head() == '0022_merge_agent_reasoning_heads'
@pytest.mark.asyncio
async def test_upgrade_from_development_workspace_head_to_merged_head(self, sqlite_engine):
@@ -117,7 +120,18 @@ class TestSQLiteMigrationUpgrade:
await run_alembic_upgrade(sqlite_engine, 'head')
assert await get_alembic_current(sqlite_engine) == _get_script_head()
assert _get_script_head() == '0020_merge_agent_cloud_heads'
assert _get_script_head() == '0022_merge_agent_reasoning_heads'
@pytest.mark.asyncio
async def test_upgrade_from_reasoning_config_head_to_merged_head(self, sqlite_engine):
"""A database that already ran the feature migration must remain upgradable."""
async with sqlite_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
await run_alembic_stamp(sqlite_engine, '0018_llm_reasoning_config')
await run_alembic_upgrade(sqlite_engine, 'head')
assert await get_alembic_current(sqlite_engine) == '0022_merge_agent_reasoning_heads'
@pytest.mark.asyncio
async def test_upgrade_from_baseline_to_head(self, sqlite_engine):
@@ -214,6 +228,66 @@ class TestSQLiteMigrationUpgrade:
await run_alembic_upgrade(sqlite_engine, 'head')
assert await get_alembic_current(sqlite_engine) == _get_script_head()
@pytest.mark.asyncio
async def test_reasoning_config_migrates_existing_models(self, sqlite_engine):
"""Upgrade from 0017 backfills reasoning config and keeps a database default."""
async with sqlite_engine.begin() as conn:
await conn.execute(
text(
"""
CREATE TABLE llm_models (
uuid VARCHAR(255) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
provider_uuid VARCHAR(255) NOT NULL,
abilities JSON NOT NULL,
context_length INTEGER,
extra_args JSON NOT NULL,
prefered_ranking INTEGER NOT NULL DEFAULT 0
)
"""
)
)
await conn.execute(
text(
"""
INSERT INTO llm_models (
uuid, name, provider_uuid, abilities, extra_args, prefered_ranking
) VALUES (
'existing-model', 'Existing Model', 'provider', '[]', '{}', 0
)
"""
)
)
await run_alembic_stamp(sqlite_engine, '0017_oss_workspace_identity')
await run_alembic_upgrade(sqlite_engine, 'head')
async with sqlite_engine.begin() as conn:
columns = await conn.run_sync(lambda sync_conn: sqlalchemy.inspect(sync_conn).get_columns('llm_models'))
reasoning_column = next(column for column in columns if column['name'] == 'reasoning_config')
assert reasoning_column['nullable'] is False
existing_value = (
await conn.execute(text("SELECT reasoning_config FROM llm_models WHERE uuid = 'existing-model'"))
).scalar_one()
assert json.loads(existing_value) == {'level': 'provider_default'}
await conn.execute(
text(
"""
INSERT INTO llm_models (
uuid, name, provider_uuid, abilities, extra_args, prefered_ranking
) VALUES (
'new-model', 'New Model', 'provider', '[]', '{}', 0
)
"""
)
)
new_value = (
await conn.execute(text("SELECT reasoning_config FROM llm_models WHERE uuid = 'new-model'"))
).scalar_one()
assert json.loads(new_value) == {'level': 'provider_default'}
class TestSQLiteMigrationFreshDatabase:
"""Tests for fresh database workflow."""
@@ -85,6 +85,32 @@ async def clean_database(postgres_engine: AsyncEngine):
await clean()
async def test_upgrade_adds_3072_dimension_index_and_constraint(
postgres_engine: AsyncEngine,
clean_database,
) -> None:
async with postgres_engine.begin() as conn:
await conn.execute(text('CREATE EXTENSION IF NOT EXISTS vector'))
await conn.run_sync(Base.metadata.create_all)
await run_alembic_stamp(postgres_engine, '0010_scope_resources')
await run_alembic_upgrade(postgres_engine, 'head')
async with postgres_engine.connect() as conn:
constraint = await conn.scalar(
text(
'SELECT pg_get_constraintdef(oid) FROM pg_constraint '
"WHERE conrelid = 'langbot_vectors'::regclass "
"AND conname = 'ck_langbot_vectors_embedding_dimension_enabled'"
)
)
assert '3072' in constraint
index_definition = await conn.scalar(
text("SELECT indexdef FROM pg_indexes WHERE indexname = 'ix_langbot_vectors_hnsw_cosine_3072'")
)
assert 'halfvec(3072)' in index_definition
assert 'halfvec_cosine_ops' in index_definition
async def test_legacy_upgrade_temporarily_suspends_and_restores_source_rls_for_unprivileged_owner(
postgres_url: str,
postgres_engine: AsyncEngine,
@@ -92,7 +92,7 @@ def _application(postgres_url: str, *, runtime_role: str = 'langbot_runtime_not_
'use': 'pgvector',
'pgvector': {
'use_business_database': True,
'allowed_dimensions': [384, 512, 768, 1024, 1536],
'allowed_dimensions': [384, 512, 768, 1024, 1536, 3072],
},
},
}
@@ -17,12 +17,14 @@ import pytest
from unittest.mock import AsyncMock, Mock
from types import SimpleNamespace
from langbot.pkg.api.http.context import ExecutionContext
from langbot.pkg.api.http.service.model import (
LLMModelsService,
EmbeddingModelsService,
RerankModelsService,
_parse_provider_api_keys,
_runtime_model_data,
_serialize_llm_model,
_validate_provider_supports,
)
from langbot.pkg.api.http.service import model as model_service_module
@@ -64,15 +66,19 @@ def _create_mock_llm_model(
abilities: list = None,
context_length: int | None = None,
extra_args: dict = None,
reasoning_config: dict = None,
) -> Mock:
"""Helper to create mock LLMModel entity."""
model = Mock(spec=LLMModel)
model.workspace_uuid = WORKSPACE_UUID
model.uuid = model_uuid
model.name = name
model.provider_uuid = provider_uuid
model.abilities = abilities or []
model.context_length = context_length
model.extra_args = extra_args or {}
model.reasoning_config = reasoning_config or {'level': 'provider_default'}
model.prefered_ranking = 0
return model
@@ -156,6 +162,26 @@ def _create_runtime_model_mgr() -> SimpleNamespace:
return manager
def _create_reasoning_runtime_provider(capabilities: dict) -> SimpleNamespace:
execution_context = ExecutionContext(
instance_uuid='instance-test',
workspace_uuid=WORKSPACE_UUID,
placement_generation=1,
)
return SimpleNamespace(
execution_context=execution_context,
provider_entity=ModelProvider(
workspace_uuid=WORKSPACE_UUID,
uuid='provider-uuid',
name='Reasoning Provider',
requester='openai',
base_url='https://api.openai.com',
api_keys=[],
),
requester=SimpleNamespace(get_reasoning_capabilities=Mock(return_value=capabilities)),
)
class TestParseProviderApiKeys:
"""Tests for _parse_provider_api_keys helper function."""
@@ -209,6 +235,42 @@ class TestRuntimeModelData:
assert result['extra_args'] == {'temp': 0.7}
class TestSerializeLLMModel:
def test_includes_runtime_reasoning_capabilities(self):
model = _create_mock_llm_model(
abilities=['reasoning'],
reasoning_config={'level': 'high'},
)
capabilities = {
'supported': True,
'levels': ['provider_default', 'low', 'high'],
'source': 'litellm',
}
runtime_model = SimpleNamespace(
model_entity=model,
provider=SimpleNamespace(
requester=SimpleNamespace(get_reasoning_capabilities=Mock(return_value=capabilities))
),
)
ap = SimpleNamespace(
persistence_mgr=SimpleNamespace(
serialize_model=Mock(
return_value={
'uuid': model.uuid,
'name': model.name,
'reasoning_config': {'level': 'high'},
}
)
),
model_mgr=SimpleNamespace(llm_model_dict={('workspace', model.uuid): runtime_model}),
)
serialized = _serialize_llm_model(ap, model)
assert serialized['reasoning_config'] == {'level': 'high'}
assert serialized['reasoning_capabilities'] == capabilities
class TestLLMModelsServiceGetLLMModels:
"""Tests for LLMModelsService.get_llm_models method."""
@@ -580,6 +642,66 @@ class TestLLMModelsServiceCreateLLMModel:
ap.provider_service.find_or_create_provider.assert_called_once()
assert result_uuid is not None
async def test_create_llm_model_validates_explicit_reasoning_level(self):
ap = SimpleNamespace()
ap.persistence_mgr = SimpleNamespace(execute_async=AsyncMock(return_value=_create_mock_result([])))
runtime_provider = _create_reasoning_runtime_provider(
{
'supported': True,
'levels': ['provider_default', 'low', 'high'],
'source': 'litellm',
}
)
ap.model_mgr = _create_runtime_model_mgr()
ap.model_mgr.provider_dict = {'provider-uuid': runtime_provider}
service = LLMModelsService(ap)
await service.create_llm_model(
WORKSPACE_UUID,
{
'uuid': 'reasoning-model',
'name': 'Reasoning Model',
'provider_uuid': 'provider-uuid',
'abilities': ['reasoning'],
'reasoning_config': {'level': 'high'},
'extra_args': {},
},
preserve_uuid=True,
auto_set_to_default_pipeline=False,
)
runtime_entity = ap.model_mgr.load_llm_model_with_provider.await_args.args[1]
assert runtime_entity.reasoning_config == {'level': 'high'}
async def test_create_llm_model_rejects_unsupported_reasoning_before_insert(self):
ap = SimpleNamespace()
ap.persistence_mgr = SimpleNamespace(execute_async=AsyncMock())
runtime_provider = _create_reasoning_runtime_provider(
{
'supported': True,
'levels': ['provider_default'],
'source': 'manual',
}
)
ap.model_mgr = _create_runtime_model_mgr()
ap.model_mgr.provider_dict = {'provider-uuid': runtime_provider}
service = LLMModelsService(ap)
with pytest.raises(ValueError, match='Available levels: provider_default'):
await service.create_llm_model(
WORKSPACE_UUID,
{
'name': 'Unknown Reasoning Model',
'provider_uuid': 'provider-uuid',
'abilities': ['reasoning'],
'reasoning_config': {'level': 'high'},
'extra_args': {},
},
auto_set_to_default_pipeline=False,
)
ap.persistence_mgr.execute_async.assert_not_awaited()
class TestLLMModelsServiceUpdateLLMModel:
"""Tests for LLMModelsService.update_llm_model method."""
@@ -595,7 +717,10 @@ class TestLLMModelsServiceUpdateLLMModel:
ap.model_mgr.remove_llm_model = AsyncMock()
ap.model_mgr.load_llm_model_with_provider = AsyncMock(return_value=Mock())
ap.persistence_mgr.execute_async = AsyncMock()
existing_model = _create_mock_llm_model()
ap.persistence_mgr.execute_async = AsyncMock(
side_effect=[_create_mock_result(first_item=existing_model), _create_mock_result()]
)
service = LLMModelsService(ap)
service.get_llm_model = AsyncMock(return_value=_existing_llm_data())
@@ -623,7 +748,8 @@ class TestLLMModelsServiceUpdateLLMModel:
ap.model_mgr.provider_dict = {} # Empty
ap.model_mgr.remove_llm_model = AsyncMock()
ap.persistence_mgr.execute_async = AsyncMock()
existing_model = _create_mock_llm_model()
ap.persistence_mgr.execute_async = AsyncMock(return_value=_create_mock_result(first_item=existing_model))
service = LLMModelsService(ap)
service.get_llm_model = AsyncMock(return_value=_existing_llm_data('nonexistent-provider'))
@@ -25,6 +25,7 @@ import time
from langbot.pkg.api.http.service.space import SpaceService
from langbot.pkg.entity.persistence.user import User
from langbot.pkg.utils import constants
pytestmark = pytest.mark.asyncio
@@ -573,10 +574,20 @@ class TestSpaceServiceExchangeOAuthCode:
mock_session_obj.post.return_value.__aexit__ = AsyncMock(return_value=None)
# Execute
result = await service.exchange_oauth_code('auth_code')
result = await service.exchange_oauth_code(
'auth_code',
['workspace-1'],
{'workspace-1': 1_700_000_000},
)
# Verify
assert result['access_token'] == 'new_access_token'
assert mock_session_obj.post.call_args.kwargs['json'] == {
'code': 'auth_code',
'instance_id': constants.instance_id,
'workspace_uuids': ['workspace-1'],
'workspace_created_ats': {'workspace-1': 1_700_000_000},
}
async def test_exchange_oauth_code_api_error(self):
"""Raises ValueError on API error."""
@@ -377,7 +377,7 @@ class TestUserServiceAuthenticate:
service = UserService(ap)
# Execute & Verify
with pytest.raises(ValueError, match='请使用 Space登录'):
with pytest.raises(ValueError, match='请使用 LangBot登录'):
await service.authenticate('space@example.com', 'password')
@@ -726,7 +726,7 @@ class TestUserServiceCreateOrUpdateSpaceUser:
)
service = UserService(ap)
with pytest.raises(ControlPlaneDirectoryRequiredError, match='Space account'):
with pytest.raises(ControlPlaneDirectoryRequiredError, match='LangBot Account'):
await service.register_invited_account('invite-token', 'member@example.com', 'password')
async def test_create_or_update_new_space_user_first_init(self):
@@ -124,24 +124,37 @@ async def test_background_plugin_operation_refences_captured_generation(plugin_r
@pytest.mark.asyncio
async def test_background_plugin_operation_revalidates_inside_short_tenant_uow(plugin_router_cls):
async def test_background_plugin_operation_revalidates_and_runs_inside_tenant_uow(plugin_router_cls):
scopes = []
active_scope = None
transaction_active = False
@asynccontextmanager
async def tenant_uow(workspace_uuid):
async def tenant_scope(workspace_uuid):
nonlocal active_scope
scopes.append(workspace_uuid)
yield
active_scope = workspace_uuid
try:
yield
finally:
active_scope = None
connector = SimpleNamespace(
require_workspace_context=AsyncMock(side_effect=lambda context: context),
)
operation = AsyncMock(return_value='done')
async def operation():
assert active_scope == CONTEXT.workspace_uuid
assert transaction_active is False
return 'done'
router = object.__new__(plugin_router_cls)
router.ap = SimpleNamespace(
plugin_connector=connector,
persistence_mgr=SimpleNamespace(
mode=SimpleNamespace(value='cloud_runtime'),
tenant_uow=tenant_uow,
tenant_scope=tenant_scope,
),
)
@@ -150,4 +163,3 @@ async def test_background_plugin_operation_revalidates_inside_short_tenant_uow(p
assert result == 'done'
assert scopes == [CONTEXT.workspace_uuid]
connector.require_workspace_context.assert_awaited_once_with(CONTEXT)
operation.assert_awaited_once()
+20 -2
View File
@@ -24,7 +24,7 @@ from langbot.pkg.box.connector import BoxRuntimeConnector
_CONTROL_TOKEN = 'box-control-token-that-is-longer-than-32-bytes'
def make_app(logger: Mock, runtime_endpoint: str = ''):
def make_app(logger: Mock, runtime_endpoint: str = '', *, cloud: bool = False):
return SimpleNamespace(
logger=logger,
workspace_service=SimpleNamespace(instance_uuid='instance-a'),
@@ -42,6 +42,7 @@ def make_app(logger: Mock, runtime_endpoint: str = ''):
}
}
),
deployment=SimpleNamespace(mode='cloud' if cloud else 'oss'),
)
@@ -306,10 +307,27 @@ def test_box_runtime_connector_rejects_relay_context_from_other_instance(
)
def test_external_box_runtime_fails_closed_without_control_token(monkeypatch: pytest.MonkeyPatch):
def test_external_box_runtime_control_headers_are_tokenless_when_secret_is_unset(
monkeypatch: pytest.MonkeyPatch,
):
monkeypatch.delenv(BOX_CONTROL_TOKEN_ENV, raising=False)
connector = BoxRuntimeConnector(make_app(Mock(), runtime_endpoint='http://box-runtime:5410'))
assert connector.get_control_headers() == {BOX_INSTANCE_HEADER: 'instance-a'}
def test_cloud_box_runtime_rejects_missing_control_secret(monkeypatch: pytest.MonkeyPatch):
monkeypatch.delenv(BOX_CONTROL_TOKEN_ENV, raising=False)
connector = BoxRuntimeConnector(make_app(Mock(), runtime_endpoint='http://box-runtime:5410', cloud=True))
with pytest.raises(BoxRuntimeUnavailableError, match=BOX_CONTROL_TOKEN_ENV):
connector.get_control_headers()
def test_external_box_runtime_rejects_invalid_configured_control_token(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv(BOX_CONTROL_TOKEN_ENV, 'too-short')
connector = BoxRuntimeConnector(make_app(Mock(), runtime_endpoint='http://box-runtime:5410'))
with pytest.raises(BoxRuntimeUnavailableError, match=BOX_CONTROL_TOKEN_ENV):
connector.get_control_headers()
+1 -2
View File
@@ -108,7 +108,7 @@ def _cloud_config() -> dict:
'use': 'pgvector',
'pgvector': {
'use_business_database': True,
'allowed_dimensions': [384, 768, 1536],
'allowed_dimensions': [384, 768, 1536, 3072],
},
},
'mcp': {'stdio': {'enabled': False}},
@@ -216,7 +216,6 @@ async def test_cloud_directory_capacity_contract_is_fail_closed(directory_config
[
({'use_business_database': False, 'allowed_dimensions': [1536]}, 'use_business_database=true'),
({'use_business_database': True, 'allowed_dimensions': []}, 'allowed_dimensions'),
({'use_business_database': True, 'allowed_dimensions': [3072]}, 'allowed_dimensions'),
({'use_business_database': True, 'allowed_dimensions': [True]}, 'allowed_dimensions'),
],
)
@@ -181,6 +181,39 @@ def _delta(
)
async def test_directory_delta_requests_model_catalog_sync_after_commit(projection_context):
application, _session_factory = projection_context
request_sync = Mock()
application.cloud_model_catalog_service = SimpleNamespace(request_sync=request_sync)
event = DirectoryEvent(
cursor=2,
uuid='20000000-0000-4000-8000-000000000002',
aggregate_uuid=WORKSPACE_UUID,
event_type='directory.changed',
revision=2,
payload={'workspace_uuid': WORKSPACE_UUID, 'directory_revision': 2},
created_at=datetime.datetime(2026, 7, 24, 12, 30, tzinfo=datetime.UTC),
)
batch = DirectoryEventBatch(
instance_uuid=INSTANCE_UUID,
after_cursor=1,
cursor=2,
high_water_cursor=2,
events=[event],
)
service = DirectoryProjectionService(
application,
_Provider([_snapshot(1)], [batch], [_delta(workspaces=[_workspace(revision=2)])]),
INSTANCE_UUID,
)
await service.initialize()
request_sync.reset_mock()
await service.sync_once()
request_sync.assert_called_once_with()
async def test_initial_snapshot_projects_core_owned_rows(projection_context):
application, session_factory = projection_context
reconcile_execution_projection = Mock()
@@ -1023,7 +1056,7 @@ async def test_snapshot_for_another_instance_is_rejected(projection_context):
await service.initialize()
async def test_core_owned_membership_survives_directory_updates_and_omission(projection_context):
async def test_directory_revision_zero_membership_is_adopted(projection_context):
application, session_factory = projection_context
service = DirectoryProjectionService(application, _Provider([_snapshot(1)]), INSTANCE_UUID)
await service.initialize()
@@ -1034,29 +1067,125 @@ async def test_core_owned_membership_survives_directory_updates_and_omission(pro
membership.role = 'viewer'
membership.status = 'active'
membership.projection_revision = 0
session.add(
WorkspaceMembership(
uuid=SECOND_MEMBERSHIP_UUID,
workspace_uuid=WORKSPACE_UUID,
account_uuid='20000000-0000-0000-0000-000000000099',
role='viewer',
status='active',
joined_at=membership.joined_at,
projection_revision=0,
)
)
projected_member = _member(revision=2).model_copy(update={'role': 'owner', 'membership_status': 'removed'})
projected_workspace = _workspace(revision=2).model_copy(update={'members': (projected_member,)})
await service.apply_snapshot(_snapshot(2, workspaces=[projected_workspace]))
async with session_factory() as session:
memberships = {
membership.uuid: membership
for membership in (await session.scalars(sqlalchemy.select(WorkspaceMembership))).all()
}
assert memberships[MEMBERSHIP_UUID].role == 'viewer'
assert memberships[MEMBERSHIP_UUID].status == 'active'
assert memberships[MEMBERSHIP_UUID].projection_revision == 0
assert memberships[SECOND_MEMBERSHIP_UUID].status == 'active'
assert memberships[SECOND_MEMBERSHIP_UUID].projection_revision == 0
membership = await session.scalar(sqlalchemy.select(WorkspaceMembership))
assert membership.source == 'cloud_projection'
assert membership.role == 'owner'
assert membership.status == 'removed'
assert membership.projection_revision == 2
async def test_directory_revision_zero_membership_omitted_from_snapshot_is_removed(projection_context):
application, session_factory = projection_context
service = DirectoryProjectionService(application, _Provider([_snapshot(1)]), INSTANCE_UUID)
await service.initialize()
historical_account_uuid = '20000000-0000-0000-0000-000000000099'
async with session_factory() as session:
async with session.begin():
membership = await session.scalar(sqlalchemy.select(WorkspaceMembership))
session.add(
User(
uuid=historical_account_uuid,
user='Historical Space Member',
normalized_email='historical@example.com',
password='',
status='active',
source='cloud_projection',
projection_revision=1,
account_type='space',
space_account_uuid=historical_account_uuid,
)
)
session.add(
WorkspaceMembership(
uuid=SECOND_MEMBERSHIP_UUID,
workspace_uuid=WORKSPACE_UUID,
account_uuid=historical_account_uuid,
role='viewer',
status='active',
source='cloud_projection',
joined_at=membership.joined_at,
projection_revision=0,
)
)
await service.apply_snapshot(_snapshot(2))
async with session_factory() as session:
historical = await session.get(WorkspaceMembership, SECOND_MEMBERSHIP_UUID)
assert historical.status == 'removed'
assert historical.projection_revision == 2
async def test_cloud_account_core_invitation_membership_survives_directory_omission(projection_context):
application, session_factory = projection_context
service = DirectoryProjectionService(application, _Provider([_snapshot(1)]), INSTANCE_UUID)
await service.initialize()
invited_account_uuid = '20000000-0000-0000-0000-000000000098'
async with session_factory() as session:
async with session.begin():
projected_membership = await session.scalar(sqlalchemy.select(WorkspaceMembership))
session.add(
User(
uuid=invited_account_uuid,
user='Invited Cloud Account',
normalized_email='invited-cloud@example.com',
password='',
status='active',
source='cloud_projection',
projection_revision=1,
account_type='space',
space_account_uuid=invited_account_uuid,
)
)
session.add(
WorkspaceMembership(
uuid=SECOND_MEMBERSHIP_UUID,
workspace_uuid=WORKSPACE_UUID,
account_uuid=invited_account_uuid,
role='viewer',
status='active',
source='local',
joined_at=projected_membership.joined_at,
projection_revision=0,
)
)
await service.apply_snapshot(_snapshot(2))
async with session_factory() as session:
membership = await session.get(WorkspaceMembership, SECOND_MEMBERSHIP_UUID)
assert membership.source == 'local'
assert membership.status == 'active'
assert membership.projection_revision == 0
async def test_directory_does_not_adopt_local_membership_with_different_uuid_for_same_cloud_account(projection_context):
application, session_factory = projection_context
service = DirectoryProjectionService(application, _Provider([_snapshot(1)]), INSTANCE_UUID)
await service.initialize()
async with session_factory() as session:
async with session.begin():
membership = await session.scalar(sqlalchemy.select(WorkspaceMembership))
membership.uuid = SECOND_MEMBERSHIP_UUID
membership.source = 'local'
membership.projection_revision = 0
projected_member = _member(revision=2).model_copy(update={'role': 'owner', 'membership_status': 'removed'})
projected_workspace = _workspace(revision=2).model_copy(update={'members': (projected_member,)})
await service.apply_snapshot(_snapshot(2, workspaces=[projected_workspace]))
async with session_factory() as session:
membership = await session.get(WorkspaceMembership, SECOND_MEMBERSHIP_UUID)
assert membership.source == 'local'
assert membership.role == 'developer'
assert membership.status == 'active'
assert membership.projection_revision == 0
@@ -273,6 +273,94 @@ async def test_snapshot_must_cover_every_active_workspace() -> None:
await service.sync_once()
async def test_periodic_sync_discovers_workspace_created_after_startup_cache_release(tmp_path) -> None:
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "model-catalog-new-workspace.db"}')
manager = PersistenceManager(object(), mode=PersistenceMode.CLOUD_RUNTIME)
manager.db = SimpleNamespace(get_engine=lambda: engine)
startup_bindings = [
SimpleNamespace(instance_uuid=INSTANCE_UUID, workspace_uuid=WORKSPACE_A, placement_generation=1)
]
live_bindings = [
*startup_bindings,
SimpleNamespace(instance_uuid=INSTANCE_UUID, workspace_uuid=WORKSPACE_B, placement_generation=1),
]
class _WorkspaceService:
startup_released = False
async def list_active_execution_bindings(self):
return list(live_bindings if self.startup_released else startup_bindings)
def release_startup_execution_bindings(self):
self.startup_released = True
workspace_service = _WorkspaceService()
app = SimpleNamespace(
persistence_mgr=manager,
workspace_service=workspace_service,
model_mgr=SimpleNamespace(load_models_from_db=_AsyncCounter()),
logger=logging.getLogger(__name__),
)
service = CloudModelCatalogSyncService(app, _CatalogProvider(_snapshot()), INSTANCE_UUID)
try:
async with engine.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
await connection.execute(
sqlalchemy.insert(Workspace),
[
{
'uuid': WORKSPACE_A,
'instance_uuid': INSTANCE_UUID,
'name': 'A',
'slug': 'a',
'source': 'cloud_projection',
},
{
'uuid': WORKSPACE_B,
'instance_uuid': INSTANCE_UUID,
'name': 'B',
'slug': 'b',
'source': 'cloud_projection',
},
],
)
await service.initialize()
workspace_service.release_startup_execution_bindings()
await service.sync_once()
async with engine.connect() as connection:
provider_b = await connection.scalar(
sqlalchemy.select(ModelProvider).where(ModelProvider.uuid == system_provider_uuid(WORKSPACE_B))
)
assert provider_b is not None
finally:
await engine.dispose()
async def test_catalog_run_wakes_immediately_when_directory_changes() -> None:
sync_started = asyncio.Event()
class _WakeService(CloudModelCatalogSyncService):
async def sync_once(self, *, reload_runtime: bool = True):
del reload_runtime
sync_started.set()
return {'workspaces': 0, 'created': 0, 'updated': 0, 'deleted': 0}
app = SimpleNamespace(logger=logging.getLogger(__name__))
service = _WakeService(app, _CatalogProvider(_snapshot()), INSTANCE_UUID, sync_interval_seconds=3600)
task = asyncio.create_task(service.run())
try:
await asyncio.sleep(0)
service.request_sync()
await asyncio.wait_for(sync_started.wait(), timeout=0.2)
finally:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
async def _async_value(value):
return value
+5 -1
View File
@@ -87,7 +87,10 @@ async def test_runtime_resource_stats_are_aggregate_and_constant_time() -> None:
app.platform_mgr = SimpleNamespace(_bots_by_key={})
app.pipeline_mgr = SimpleNamespace(_pipelines_by_key={})
app.rag_mgr = SimpleNamespace(knowledge_bases={})
app.plugin_connector = SimpleNamespace(_known_desired_states={'installation': object()})
app.plugin_connector = SimpleNamespace(
_known_desired_states={'installation': object()},
_runtime_available=lambda: True,
)
app.persistence_mgr = SimpleNamespace(
get_resource_stats=lambda: {
'configured_capacity': 20,
@@ -140,3 +143,4 @@ async def test_runtime_resource_stats_are_aggregate_and_constant_time() -> None:
}
assert stats['models']['providers'] == 1
assert stats['runtimes']['plugin_installations'] == 1
assert stats['runtimes']['plugin_runtime_connected'] is True
+12 -1
View File
@@ -319,6 +319,7 @@ class TestApplyEnvOverridesToConfig:
load_config = get_load_config_module()
cfg = {
'plugin': {
'connect_timeout_seconds': 30.0,
'worker': {
'max_cpus': 1.0,
'max_memory_mb': 512,
@@ -329,11 +330,12 @@ class TestApplyEnvOverridesToConfig:
'restart_failure_threshold': 8,
'restart_failure_window_seconds': 30.0,
'restart_circuit_open_seconds': 60.0,
}
},
},
'mcp': {'stdio': {'enabled': True}},
}
env = {
'PLUGIN__CONNECT_TIMEOUT_SECONDS': '180',
'PLUGIN__WORKER__MAX_CPUS': '2.5',
'PLUGIN__WORKER__MAX_MEMORY_MB': '1024',
'PLUGIN__WORKER__MAX_PIDS': '64',
@@ -349,6 +351,7 @@ class TestApplyEnvOverridesToConfig:
with patch.dict(os.environ, env, clear=True):
result = load_config._apply_env_overrides_to_config(cfg)
assert result['plugin']['connect_timeout_seconds'] == 180.0
assert result['plugin']['worker'] == {
'max_cpus': 2.5,
'max_memory_mb': 1024,
@@ -393,6 +396,14 @@ class TestApplyEnvOverridesToConfig:
assert isinstance(result['plugin']['worker']['max_memory_mb'], int)
assert result['mcp']['stdio']['enabled'] is False
def test_runtime_policy_defaults_add_typed_plugin_connect_timeout(self):
load_config = get_load_config_module()
completed = load_config._complete_runtime_policy_defaults({'plugin': {'enable': True}})
assert completed['plugin']['connect_timeout_seconds'] == 180.0
assert isinstance(completed['plugin']['connect_timeout_seconds'], float)
def test_webhook_prefix_override(self):
"""Test overriding webhook_prefix via environment variable."""
load_config = get_load_config_module()
@@ -7,7 +7,7 @@ from types import SimpleNamespace
import pytest
import sqlalchemy as sa
from pgvector.sqlalchemy import Vector
from pgvector.sqlalchemy import HALFVEC, Vector
from sqlalchemy.dialects.postgresql import insert as postgresql_insert
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.ext.asyncio import create_async_engine
@@ -967,6 +967,7 @@ async def test_scoped_session_rejects_raw_or_unapproved_sql(
),
sa.select(sa.column('embedding').op('<=>')(sa.literal([0.1]))),
sa.select(sa.cast(sa.column('embedding'), Vector(384))),
sa.select(sa.cast(sa.column('embedding'), HALFVEC(3072))),
sa.insert(sa.table('rows', sa.column('id'))).values(id=1),
_multi_value_statement(value=1),
_on_conflict_statement(update_value=sa.func.coalesce(sa.literal(1), sa.literal(0))),
@@ -29,6 +29,57 @@ def _prepare_scheduler(mock_app):
return query_pool, session
@pytest.mark.asyncio
async def test_consumer_schedules_query_after_running_transition(
mock_app,
sample_query,
):
query_pool = MagicMock()
query_pool.queries = [sample_query]
query_pool.__aenter__ = AsyncMock(return_value=query_pool)
query_pool.__aexit__ = AsyncMock(return_value=None)
query_pool.remove_query = AsyncMock(return_value=True)
wait_for_query = asyncio.Event()
query_pool.condition = SimpleNamespace(
wait=AsyncMock(side_effect=wait_for_query.wait),
notify_all=Mock(),
)
query_pool.mark_query_running_locked = Mock(side_effect=query_pool.queries.remove)
mock_app.query_pool = query_pool
session = SimpleNamespace(_semaphore=asyncio.Semaphore(1))
mock_app.sess_mgr.get_session = AsyncMock(return_value=session)
runtime_pipeline = SimpleNamespace(run=AsyncMock())
mock_app.pipeline_mgr = SimpleNamespace(get_pipeline_by_uuid=AsyncMock(return_value=runtime_pipeline))
task_created = asyncio.Event()
process_tasks = []
def create_process_task(coro, **_kwargs):
process_tasks.append(asyncio.create_task(coro))
task_created.set()
mock_app.task_mgr.create_task = Mock(side_effect=create_process_task)
controller = Controller(mock_app)
initial_slots = controller.semaphore._value
consumer_task = asyncio.create_task(controller.consumer())
try:
await asyncio.wait_for(task_created.wait(), timeout=2)
finally:
consumer_task.cancel()
with pytest.raises(asyncio.CancelledError):
await consumer_task
await asyncio.gather(*process_tasks)
query_pool.mark_query_running_locked.assert_called_once_with(sample_query)
runtime_pipeline.run.assert_awaited_once_with(sample_query)
query_pool.remove_query.assert_awaited_once_with(sample_query)
assert query_pool.queries == []
assert session._semaphore._value == 1
assert controller.semaphore._value == initial_slots
@pytest.mark.asyncio
async def test_controller_drops_stale_query_before_pipeline_lookup(
mock_app,
@@ -2,8 +2,8 @@
The web debug client uploads Image / Voice / File components carrying a storage
key in ``path``. This helper resolves each to a base64 data URI (so multimodal
LLM input and the Box sandbox inbox have usable bytes) while retaining the key
for browser history. Covers mimetype selection per type and fail-closed error
LLM input and the Box sandbox inbox have usable bytes), then deletes the
consumed upload. Covers mimetype selection per type and fail-closed error
handling.
"""
@@ -52,7 +52,7 @@ def _make_adapter(load_return=b'hello', load_side_effect=None):
@pytest.mark.asyncio
async def test_image_jpeg_mimetype_and_retained_storage_key():
async def test_image_jpeg_mimetype_and_consumed_storage_key():
adapter, storage_mgr, _ = _make_adapter(load_return=b'\xff\xd8\xff')
path = f'{_UPLOAD_PREFIX}photo.jpg'
chain = [{'type': 'Image', 'path': path}]
@@ -61,8 +61,12 @@ async def test_image_jpeg_mimetype_and_retained_storage_key():
expected_b64 = base64.b64encode(b'\xff\xd8\xff').decode('utf-8')
assert chain[0]['base64'] == f'data:image/jpeg;base64,{expected_b64}'
assert chain[0]['path'] == path
storage_mgr.delete_scoped_object_key.assert_not_awaited()
assert chain[0]['path'] == ''
storage_mgr.delete_scoped_object_key.assert_awaited_once_with(
_CONTEXT,
path,
expected_owner_type='upload_image',
)
def test_history_retains_storage_key_without_large_base64_payload():
@@ -7,8 +7,8 @@ from unittest.mock import AsyncMock, Mock
import pytest
import langbot_plugin.api.entities.builtin.platform.events as platform_events
import langbot_plugin.api.entities.builtin.platform.entities as platform_entities
import langbot_plugin.api.entities.builtin.platform.events as platform_events
import langbot_plugin.api.entities.builtin.platform.message as platform_message
import langbot_plugin.api.entities.builtin.provider.message as provider_message
from langbot.pkg.platform.sources import websocket_adapter as websocket_adapter_module
@@ -347,9 +347,9 @@ async def test_stable_session_launcher_resolves_to_active_connection(monkeypatch
@pytest.mark.asyncio
async def test_dashboard_reply_uses_event_pipeline_after_connection_closes(monkeypatch):
async def test_dashboard_reply_survives_connection_replacement(monkeypatch):
manager = WebSocketConnectionManager()
connection = await manager.add_connection(
original = await manager.add_connection(
websocket=Mock(),
scope=SCOPE_A,
pipeline_uuid='pipeline-1',
@@ -357,22 +357,36 @@ async def test_dashboard_reply_uses_event_pipeline_after_connection_closes(monke
)
monkeypatch.setattr(websocket_adapter_module, 'ws_connection_manager', manager)
app = Mock()
app.platform_mgr.websocket_proxy_bot.bot_entity = Mock(spec=[])
adapter = WebSocketAdapter.model_construct(ap=app, logger=AsyncMock())
message_source = platform_events.FriendMessage(
sender=platform_entities.Friend(
id=f'websocket_{connection.connection_id}',
nickname='User',
remark='User',
),
message_chain=platform_message.MessageChain([platform_message.Plain(text='hello')]),
time=1,
)
object.__setattr__(message_source, '_langbot_pipeline_uuid', 'pipeline-1')
await manager.remove_connection(connection.connection_id)
adapter = WebSocketAdapter.model_construct(ap=Mock(), logger=_adapter_logger())
adapter.websocket_person_session = WebSocketSession(id='person')
adapter.websocket_group_session = WebSocketSession(id='group')
received = []
assert await adapter._get_message_context(message_source) == ('pipeline-1', None)
async def listener(event, _callback_adapter):
received.append(event)
adapter.listeners = {platform_events.FriendMessage: listener}
await adapter.handle_websocket_message(
original,
{'message': [{'type': 'Plain', 'text': 'hello'}], 'stream': False},
)
await asyncio.sleep(0)
await manager.remove_connection(original.connection_id)
replacement = await manager.add_connection(
websocket=Mock(),
scope=SCOPE_A,
pipeline_uuid='pipeline-1',
session_type='person',
)
await adapter.reply_message(
received[0],
platform_message.MessageChain([platform_message.Plain(text='done')]),
)
response = await replacement.send_queue.get()
assert response['type'] == 'response'
assert response['data']['content'] == 'done'
@pytest.mark.asyncio
@@ -468,7 +482,7 @@ async def test_attachment_key_must_belong_to_connection_upload_scope():
await adapter._process_image_components(connection, message_chain)
assert message_chain[0]['base64'].startswith('data:image/png;base64,')
assert message_chain[0]['path'] == 'v1/current/upload_image/key.png'
assert message_chain[0]['path'] == ''
storage_mgr.scoped_prefix.assert_called_once_with(
connection.execution_context,
owner_type='upload_image',
@@ -482,7 +496,11 @@ async def test_attachment_key_must_belong_to_connection_upload_scope():
'v1/current/upload_image/key.png',
expected_owner_type='upload_image',
)
storage_mgr.delete_scoped_object_key.assert_not_awaited()
storage_mgr.delete_scoped_object_key.assert_awaited_once_with(
connection.execution_context,
'v1/current/upload_image/key.png',
expected_owner_type='upload_image',
)
with pytest.raises(ValueError, match='does not belong'):
await adapter._process_image_components(
@@ -93,14 +93,10 @@ class TestRunAgent:
@pytest.mark.asyncio
async def test_revalidates_trusted_execution_context(self):
connector = create_mock_connector()
connector._current_execution_context = AsyncMock(
return_value=TEST_EXECUTION_CONTEXT
)
connector._current_execution_context = AsyncMock(return_value=TEST_EXECUTION_CONTEXT)
class RuntimeHandler:
installation_scope = Mock(
side_effect=lambda _binding: nullcontext()
)
installation_scope = Mock(side_effect=lambda _binding: nullcontext())
async def run_agent(self, *_args):
yield {'type': 'run.completed'}
@@ -113,16 +109,12 @@ class TestRunAgent:
)
assert results == [{'type': 'run.completed'}]
connector.require_workspace_context.assert_awaited_once_with(
TEST_EXECUTION_CONTEXT
)
connector.require_workspace_context.assert_awaited_once_with(TEST_EXECUTION_CONTEXT)
@pytest.mark.asyncio
async def test_rejects_payload_workspace_mismatch(self):
connector = create_mock_connector()
connector._current_execution_context = AsyncMock(
return_value=TEST_EXECUTION_CONTEXT
)
connector._current_execution_context = AsyncMock(return_value=TEST_EXECUTION_CONTEXT)
configure_handler(connector, AsyncMock())
with pytest.raises(WorkspaceNotFoundError, match='Plugin resource not found'):
@@ -670,8 +662,13 @@ class TestDisabledPluginEarlyReturns:
mock_app.instance_config.data = {'plugin': {'enable': False}}
connector = connector_module.PluginRuntimeConnector(mock_app, mock_disconnect)
execution_context = connector_module.ExecutionContext(
instance_uuid='instance-a',
workspace_uuid='workspace-a',
placement_generation=1,
)
result = await connector.get_debug_info()
result = await connector.get_debug_info(execution_context)
assert result == {}
+53 -2
View File
@@ -15,7 +15,7 @@ from langbot_plugin.runtime.security import (
)
def make_connector() -> PluginRuntimeConnector:
def make_connector(*, cloud: bool = False) -> PluginRuntimeConnector:
app = SimpleNamespace(
logger=Mock(),
instance_config=SimpleNamespace(
@@ -34,6 +34,7 @@ def make_connector() -> PluginRuntimeConnector:
'space': {'url': ''},
}
),
deployment=SimpleNamespace(mode='cloud' if cloud else 'oss'),
)
return PluginRuntimeConnector(app, AsyncMock())
@@ -142,6 +143,49 @@ async def test_stdio_runtime_connection_does_not_capture_unconsumed_stderr(
await connector.aclose()
@pytest.mark.asyncio
async def test_invalid_connect_timeout_is_rejected_before_transport_startup(
monkeypatch: pytest.MonkeyPatch,
):
connector = make_connector()
connector.ap.instance_config.data['plugin']['connect_timeout_seconds'] = 0
stdio_controller = Mock()
websocket_controller = Mock()
create_task = Mock()
get_platform = Mock(return_value='linux')
use_websocket = Mock(return_value=False)
connector._start_runtime_subprocess = AsyncMock()
monkeypatch.setattr(connector_module.constants, 'instance_id', 'instance-a')
monkeypatch.setattr(connector_module.asyncio, 'create_task', create_task)
monkeypatch.setattr(connector_module.platform, 'get_platform', get_platform)
monkeypatch.setattr(
connector_module.platform,
'use_websocket_to_connect_plugin_runtime',
use_websocket,
)
monkeypatch.setattr(
connector_module.stdio_client_controller,
'StdioClientController',
stdio_controller,
)
monkeypatch.setattr(
connector_module.ws_client_controller,
'WebSocketClientController',
websocket_controller,
)
with pytest.raises(ValueError, match='plugin.connect_timeout_seconds'):
await connector.initialize()
get_platform.assert_not_called()
use_websocket.assert_not_called()
stdio_controller.assert_not_called()
websocket_controller.assert_not_called()
connector._start_runtime_subprocess.assert_not_awaited()
create_task.assert_not_called()
assert connector._transport_task is None
@pytest.mark.asyncio
async def test_runtime_disconnect_notifies_once_and_clears_handler(
monkeypatch: pytest.MonkeyPatch,
@@ -292,10 +336,17 @@ def test_closed_deployment_selects_instance_scoped_shared_profile():
assert connector.runtime_profile == 'shared'
def test_external_runtime_control_headers_require_strong_secret(monkeypatch):
def test_external_runtime_control_headers_are_empty_when_secret_is_unset(monkeypatch):
monkeypatch.delenv(PLUGIN_RUNTIME_CONTROL_TOKEN_ENV, raising=False)
connector = make_connector()
assert connector._control_headers(allow_generate=False) == {}
def test_cloud_runtime_rejects_missing_control_secret(monkeypatch):
monkeypatch.delenv(PLUGIN_RUNTIME_CONTROL_TOKEN_ENV, raising=False)
connector = make_connector(cloud=True)
with pytest.raises(PluginRuntimeNotConnectedError, match=PLUGIN_RUNTIME_CONTROL_TOKEN_ENV):
connector._control_headers(allow_generate=False)
@@ -153,6 +153,31 @@ async def test_empty_projected_workspaces_do_not_retain_installation_sets():
connector.handler.reconcile_plugin_installations.assert_awaited_once_with(())
@pytest.mark.asyncio
async def test_shared_reconcile_logs_workspace_installation_counts_and_elapsed_time():
binding_a = execution_binding('workspace-a')
binding_b = execution_binding('workspace-b')
setting_a = plugin_setting('01', 'a' * 64)
setting_b = plugin_setting('02', 'b' * 64)
connector = shared_connector(
[[binding_a, binding_b]],
{'workspace-a': [setting_a], 'workspace-b': [setting_b]},
)
connector.handler = runtime_handler()
await connector._prepare_connected_runtime()
matching_calls = [
call
for call in connector.ap.logger.info.call_args_list
if call.args
and call.args[0]
== 'Shared plugin runtime reconcile completed: workspaces=%d desired_installations=%d elapsed_seconds=%.3f'
]
assert len(matching_calls) == 1
assert matching_calls[0].args[1:3] == (2, 2)
assert matching_calls[0].args[3] >= 0
@pytest.mark.asyncio
async def test_fresh_shared_runtime_cache_replays_persisted_local_package():
package = b'local-lbpkg-bytes'
@@ -6,9 +6,10 @@ Tests cover:
from __future__ import annotations
import pytest
from importlib import import_module
import pytest
def get_connector_module():
"""Lazy import to avoid circular import issues."""
@@ -60,3 +61,28 @@ def test_runtime_id_is_stable_across_core_restarts(monkeypatch):
monkeypatch.setattr(connector.constants, 'instance_id', 'instance-a')
assert connector.PluginRuntimeConnector._build_runtime_id() == 'instance-a:plugin-runtime'
def test_runtime_connect_timeout_defaults_to_three_minutes():
connector = get_connector_module()
assert connector.PluginRuntimeConnector._runtime_connect_timeout({}) == 180.0
def test_runtime_connect_timeout_reads_typed_plugin_config():
connector = get_connector_module()
assert connector.PluginRuntimeConnector._runtime_connect_timeout({'connect_timeout_seconds': 45.5}) == 45.5
@pytest.mark.parametrize('value', [True, False, None, 0, -1, float('nan'), float('inf'), '180', object()])
def test_runtime_connect_timeout_rejects_invalid_values(value):
connector = get_connector_module()
with pytest.raises(ValueError, match='plugin.connect_timeout_seconds'):
connector.PluginRuntimeConnector._runtime_connect_timeout({'connect_timeout_seconds': value})
def test_runtime_connect_timeout_error_displays_actual_seconds():
connector = get_connector_module()
assert connector.PluginRuntimeConnector._runtime_connect_timeout_error(45.5) == (
'Plugin runtime did not become ready within 45.5 seconds'
)
+16 -2
View File
@@ -9,8 +9,8 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, Mock
import pytest
from langbot_plugin.entities.io.actions.enums import PluginToRuntimeAction
from langbot_plugin.entities.io.context import ActionContext, InstallationBinding
from langbot_plugin.entities.io.actions.enums import LangBotToRuntimeAction, PluginToRuntimeAction
from langbot_plugin.entities.io.context import ActionContext, InstallationBinding, PluginInstallationDesiredState
def make_handler(app):
@@ -67,6 +67,20 @@ def make_handler(app):
return runtime_handler
@pytest.mark.asyncio
async def test_reconcile_plugin_installations_allows_cloud_cold_start_to_finish():
app = SimpleNamespace()
runtime_handler = make_handler(app)
runtime_handler.call_action = AsyncMock(return_value={})
binding = next(iter(runtime_handler._installation_bindings.values()))[0]
desired = PluginInstallationDesiredState(binding=binding, enabled=True)
await runtime_handler.reconcile_plugin_installations((desired,))
assert runtime_handler.call_action.await_args.args[0] == LangBotToRuntimeAction.RECONCILE_PLUGIN_INSTALLATIONS
assert runtime_handler.call_action.await_args.kwargs['timeout'] == 300
class TestHandlerQueryVariables:
"""Tests for handler query variable logic."""
@@ -396,9 +396,7 @@ async def test_legacy_oss_knowledge_file_reply_uses_complete_installation_bindin
get_file_stream=AsyncMock(return_value=b'knowledge-file'),
)
runtime_handler.send_file = AsyncMock(return_value='knowledge-file-key')
legacy_context = workspace_context().for_installation(
installation_context.installation_uuid
)
legacy_context = workspace_context().for_installation(installation_context.installation_uuid)
response = await invoke_with_context(
runtime_handler,
@@ -505,3 +503,23 @@ async def test_host_to_runtime_action_carries_trusted_connector_context():
'runtime_id': 'runtime-a',
}
assert request.get('context') is None
@pytest.mark.asyncio
async def test_get_debug_info_converts_execution_context_to_sdk_action_context():
runtime_handler, _app, _installation_context = make_handler()
runtime_handler.call_action = AsyncMock(return_value={'plugin_debug_key': 'debug-key'})
execution_context = ExecutionContext(
instance_uuid='instance-a',
workspace_uuid='workspace-a',
placement_generation=7,
)
result = await runtime_handler.get_debug_info(execution_context)
assert result == {'plugin_debug_key': 'debug-key'}
assert runtime_handler.call_action.await_args.kwargs['action_context'] == ActionContext(
instance_uuid='instance-a',
workspace_uuid='workspace-a',
placement_generation=7,
)
@@ -1305,6 +1305,7 @@ class TestScanModels:
)
requester._supports_function_calling = Mock(side_effect=lambda model_id: model_id == 'gpt-4o')
requester._supports_vision = Mock(side_effect=lambda model_id: model_id == 'gpt-4o')
requester._supports_reasoning = Mock(side_effect=lambda model_id: model_id == 'o3')
requester._safe_context_length = Mock(side_effect=lambda model_id: 128000 if model_id == 'gpt-4o' else None)
mock_response = Mock()
@@ -1312,6 +1313,7 @@ class TestScanModels:
return_value={
'data': [
{'id': 'gpt-4o'},
{'id': 'o3'},
{'id': 'text-embedding-3-small'},
{'id': 'bge-reranker-v2'},
]
@@ -1328,6 +1330,7 @@ class TestScanModels:
by_id = {model['id']: model for model in result['models']}
assert by_id['gpt-4o']['abilities'] == ['func_call', 'vision']
assert by_id['gpt-4o']['context_length'] == 128000
assert by_id['o3']['abilities'] == ['reasoning']
assert by_id['text-embedding-3-small']['type'] == 'embedding'
assert by_id['bge-reranker-v2']['type'] == 'rerank'
@@ -1375,8 +1378,8 @@ class TestScanModels:
)
with patch.object(litellmchat.litellm, 'get_model_info') as mock_get_model_info:
mock_get_model_info.side_effect = (
lambda model: {'max_input_tokens': 131072} if model == 'moonshot/moonshot-v1-128k' else {}
mock_get_model_info.side_effect = lambda model: (
{'max_input_tokens': 131072} if model == 'moonshot/moonshot-v1-128k' else {}
)
assert requester._safe_context_length('moonshot-v1-128k') == 131072
@@ -1405,8 +1408,8 @@ class TestScanModels:
)
with patch.object(litellmchat.litellm, 'supports_function_calling') as mock_supports_function_calling:
mock_supports_function_calling.side_effect = (
lambda model, custom_llm_provider=None: model == 'moonshot/kimi-k2.6' and custom_llm_provider is None
mock_supports_function_calling.side_effect = lambda model, custom_llm_provider=None: (
model == 'moonshot/kimi-k2.6' and custom_llm_provider is None
)
assert requester._supports_function_calling('kimi-k2.6') is True
@@ -0,0 +1,884 @@
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
import langbot_plugin.api.entities.builtin.provider.message as provider_message
from langbot.pkg.api.http.context import ExecutionContext
from langbot.pkg.entity.persistence import model as persistence_model
from langbot.pkg.provider.modelmgr import errors, reasoning, requester
from langbot.pkg.provider.modelmgr.requesters import litellmchat
from langbot.pkg.provider.modelmgr.requesters.litellmchat import LiteLLMRequester
def _runtime_model(
request: LiteLLMRequester,
level: str = 'provider_default',
name: str = 'reasoning-model',
abilities: list[str] | None = None,
requester_name: str | None = None,
) -> requester.RuntimeLLMModel:
execution_context = ExecutionContext(
instance_uuid='instance-test',
workspace_uuid='workspace-test',
placement_generation=1,
)
entity = persistence_model.LLMModel(
workspace_uuid='workspace-test',
uuid='reasoning-model',
name=name,
provider_uuid='provider-test',
abilities=abilities if abilities is not None else ['reasoning'],
reasoning_config={'level': level},
extra_args={},
)
provider = SimpleNamespace(
execution_context=execution_context,
provider_entity=persistence_model.ModelProvider(
workspace_uuid='workspace-test',
uuid='provider-test',
name='provider',
requester=requester_name or request.requester_cfg.get('requester_name') or 'custom-requester',
base_url='https://example.com',
api_keys=[],
),
requester=request,
token_mgr=SimpleNamespace(),
)
return requester.RuntimeLLMModel(execution_context, entity, provider)
def _requester(provider: str = '', requester_name: str = '') -> LiteLLMRequester:
return LiteLLMRequester(
SimpleNamespace(),
{
'custom_llm_provider': provider,
'requester_name': requester_name,
},
)
def test_reasoning_config_normalization_and_conflicts():
assert reasoning.normalize_reasoning_config(None) == {'level': 'provider_default'}
assert reasoning.normalize_reasoning_config({}) == {'level': 'provider_default'}
assert reasoning.validate_reasoning_config(
{'level': 'high'},
['reasoning'],
{},
) == {'level': 'high'}
with pytest.raises(ValueError, match='Unsupported reasoning level'):
reasoning.normalize_reasoning_config({'level': 'turbo'})
with pytest.raises(ValueError, match='reasoning ability'):
reasoning.validate_reasoning_config({'level': 'low'}, [], {})
with pytest.raises(ValueError, match='extra_body.thinking_budget'):
reasoning.validate_reasoning_config(
{'level': 'low'},
['reasoning'],
{'extra_body': {'thinking_budget': 1024}},
)
assert reasoning.find_reasoning_arg_conflicts(
{
'enable_thinking': True,
'extra_body': {'reasoning_effort': 'high'},
}
) == ['enable_thinking', 'extra_body.reasoning_effort']
def test_manual_reasoning_model_without_known_protocol_stays_conservative(monkeypatch):
request = _requester()
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(_runtime_model(request))
assert capabilities == {
'supported': True,
'levels': ['provider_default'],
'source': 'manual',
}
def test_openai_protocol_does_not_mark_unknown_models_as_reasoning(monkeypatch):
request = _requester('openai', 'openai-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(
_runtime_model(request, name='future-reasoning-model', abilities=[])
)
assert capabilities == {
'supported': False,
'levels': ['provider_default'],
'source': 'unknown',
}
def test_unknown_unmarked_model_without_provider_stays_safe(monkeypatch):
request = _requester()
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(_runtime_model(request, name='unknown-model', abilities=[]))
assert capabilities == {
'supported': False,
'levels': ['provider_default'],
'source': 'unknown',
}
def test_mimo_exposes_off_on_without_fake_effort_levels(monkeypatch):
request = _requester('openai', 'mimo-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(_runtime_model(request, name='mimo-v2.5', abilities=[]))
assert capabilities == {
'supported': True,
'levels': ['provider_default', 'disabled', 'enabled'],
'source': 'provider',
}
def test_openai_reasoning_levels_follow_litellm_metadata(monkeypatch):
request = _requester('openai', 'openai-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: True)
monkeypatch.setattr(
request,
'_safe_model_info',
lambda _: {
'supports_none_reasoning_effort': True,
'supports_minimal_reasoning_effort': False,
'supports_low_reasoning_effort': True,
'supports_xhigh_reasoning_effort': True,
},
)
capabilities = request.get_reasoning_capabilities(_runtime_model(request, name='gpt-5'))
assert capabilities['source'] == 'litellm'
assert capabilities['levels'] == [
'provider_default',
'disabled',
'low',
'medium',
'high',
'xhigh',
]
def test_anthropic_adaptive_and_always_on_profiles(monkeypatch):
request = _requester('anthropic', 'anthropic-messages')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
adaptive = request.get_reasoning_capabilities(_runtime_model(request, name='claude-sonnet-4-6', abilities=[]))
assert adaptive['levels'] == [
'provider_default',
'disabled',
'low',
'medium',
'high',
'xhigh',
'max',
]
always_on = request.get_reasoning_capabilities(_runtime_model(request, name='claude-fable-5', abilities=[]))
assert 'disabled' not in always_on['levels']
legacy = request.get_reasoning_capabilities(_runtime_model(request, name='claude-3-5-sonnet', abilities=[]))
assert legacy['levels'] == ['provider_default', 'low', 'medium', 'high']
def test_deepseek_profiles_match_model_generation(monkeypatch):
request = _requester('deepseek', 'deepseek-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
assert request.get_reasoning_capabilities(_runtime_model(request, name='deepseek-v4-flash', abilities=[]))[
'levels'
] == ['provider_default', 'disabled', 'low', 'high', 'xhigh', 'max']
assert request.get_reasoning_capabilities(_runtime_model(request, name='deepseek-chat', abilities=[]))[
'levels'
] == ['provider_default', 'disabled', 'enabled']
assert request.get_reasoning_capabilities(_runtime_model(request, name='deepseek-r1', abilities=[]))['levels'] == [
'provider_default'
]
@pytest.mark.parametrize(
('model_name', 'expected_levels'),
[
('kimi-k3', ['provider_default', 'low', 'high', 'max']),
('kimi-k2.7-code', ['provider_default']),
('kimi-k2.6', ['provider_default', 'disabled', 'enabled']),
('kimi-k2.5', ['provider_default', 'disabled', 'enabled']),
],
)
def test_kimi_profiles(model_name, expected_levels, monkeypatch):
request = _requester('openai', 'moonshot-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(_runtime_model(request, name=model_name, abilities=[]))
assert capabilities['levels'] == expected_levels
def test_qwen_mixed_and_dedicated_thinking_profiles(monkeypatch):
request = _requester('openai', 'bailian-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
mixed = request.get_reasoning_capabilities(_runtime_model(request, name='qwen-plus', abilities=[]))
dedicated = request.get_reasoning_capabilities(
_runtime_model(request, name='qwen3-235b-a22b-thinking-2507', abilities=[])
)
assert mixed['levels'] == ['provider_default', 'disabled', 'enabled']
assert dedicated['levels'] == ['provider_default', 'low', 'medium', 'high']
def test_qwen3_exposes_budget_based_reasoning_levels(monkeypatch):
request = _requester('openai', 'bailian-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
mixed = request.get_reasoning_capabilities(_runtime_model(request, name='qwen3.8-max', abilities=[]))
dedicated = request.get_reasoning_capabilities(_runtime_model(request, name='qwen3.7-max-preview', abilities=[]))
assert mixed['levels'] == ['provider_default', 'disabled', 'low', 'medium', 'high']
assert mixed['legacy_levels'] == ['enabled']
assert dedicated['levels'] == ['provider_default', 'low', 'medium', 'high']
def test_qwen3_legacy_enabled_config_remains_supported(monkeypatch):
request = _requester('openai', 'bailian-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
assert request._build_reasoning_args(_runtime_model(request, 'enabled', name='qwen3.8-max')) == {
'extra_body': {'enable_thinking': True}
}
@pytest.mark.parametrize(
('level', 'budget'),
[('low', 1024), ('medium', 4096), ('high', 8192)],
)
def test_qwen3_reasoning_levels_translate_to_thinking_budget(level, budget, monkeypatch):
request = _requester('openai', 'bailian-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
assert request._build_reasoning_args(_runtime_model(request, level, name='qwen3.8-max')) == {
'extra_body': {
'enable_thinking': True,
'thinking_budget': budget,
}
}
@pytest.mark.parametrize('model_name', ['qwen3.7-max-preview', 'qwen3.7-max-2026-05-17'])
def test_qwen_dedicated_thinking_release_models_are_not_toggleable(model_name, monkeypatch):
request = _requester('openai', 'bailian-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(_runtime_model(request, name=model_name, abilities=[]))
assert capabilities['levels'] == ['provider_default', 'low', 'medium', 'high']
@pytest.mark.parametrize(
('model_name', 'expected_levels'),
[
('kimi-k2.6', ['provider_default', 'disabled', 'enabled']),
('kimi-k2.5', ['provider_default', 'disabled', 'enabled']),
('kimi-k2.7-code', ['provider_default']),
('kimi-k2-thinking', ['provider_default']),
],
)
def test_bailian_kimi_profiles_use_kimi_model_rules(model_name, expected_levels, monkeypatch):
request = _requester('openai', 'bailian-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(_runtime_model(request, name=model_name, abilities=[]))
assert capabilities['levels'] == expected_levels
def test_bailian_kimi_uses_thinking_protocol_instead_of_qwen_protocol(monkeypatch):
request = _requester('openai', 'bailian-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
assert request._build_reasoning_args(_runtime_model(request, 'disabled', name='kimi-k2.6')) == {
'extra_body': {'thinking': {'type': 'disabled'}}
}
def test_doubao_exposes_documented_effort_range(monkeypatch):
request = _requester('openai', 'doubao-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(
_runtime_model(request, name='doubao-seed-2-1-pro-260628', abilities=[])
)
assert capabilities['levels'] == ['provider_default', 'disabled', 'low', 'medium', 'high']
@pytest.mark.parametrize(
('model_name', 'expected_levels'),
[
('gpt-5', ['provider_default', 'low', 'medium', 'high']),
(
'claude-sonnet-4-6',
['provider_default', 'disabled', 'low', 'medium', 'high', 'xhigh', 'max'],
),
('deepseek-v4-flash', ['provider_default', 'disabled', 'low', 'high', 'xhigh', 'max']),
('kimi-k2.6', ['provider_default', 'disabled', 'enabled']),
('qwen-plus', ['provider_default', 'disabled', 'enabled']),
('doubao-seed-2-1-pro-260628', ['provider_default', 'disabled', 'low', 'medium', 'high']),
('mimo-v2.5', ['provider_default', 'disabled', 'enabled']),
],
)
def test_new_api_infers_upstream_protocol_from_model_name(model_name, expected_levels, monkeypatch):
request = _requester('openai', 'new-api-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
monkeypatch.setattr(request, '_safe_model_info', lambda _: {})
capabilities = request.get_reasoning_capabilities(_runtime_model(request, name=model_name, abilities=[]))
assert capabilities['levels'] == expected_levels
@pytest.mark.parametrize(
('provider', 'requester_name', 'model_name'),
[
('openai', 'openai-chat-completions', 'gpt-5'),
('anthropic', 'anthropic-messages', 'claude-sonnet-4-6'),
('deepseek', 'deepseek-chat-completions', 'deepseek-v4-flash'),
('openai', 'mimo-chat-completions', 'mimo-v2.5'),
('openai', 'moonshot-chat-completions', 'kimi-k2.6'),
('openai', 'bailian-chat-completions', 'qwen-plus'),
('openai', 'doubao-chat-completions', 'doubao-seed-2-1-pro-260628'),
('openai', 'new-api-chat-completions', 'deepseek-v4-flash'),
],
)
def test_scanned_known_models_gain_reasoning_ability(provider, requester_name, model_name, monkeypatch):
request = _requester(provider, requester_name)
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
monkeypatch.setattr(request, '_supports_function_calling', lambda _: False)
monkeypatch.setattr(request, '_supports_vision', lambda _: False)
monkeypatch.setattr(request, '_safe_context_length', lambda _: None)
scanned = request._enrich_scanned_model(model_name)
assert scanned['abilities'] == ['reasoning']
def test_new_api_unknown_alias_stays_conservative(monkeypatch):
request = _requester('openai', 'new-api-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
capabilities = request.get_reasoning_capabilities(
_runtime_model(request, name='company-internal-alias', abilities=[])
)
assert capabilities == {
'supported': False,
'levels': ['provider_default'],
'source': 'unknown',
}
def test_reasoning_argument_translation(monkeypatch):
openai_request = _requester('openai', 'openai-chat-completions')
monkeypatch.setattr(openai_request, '_supports_reasoning', lambda _: True)
monkeypatch.setattr(openai_request, '_safe_model_info', lambda _: {'supports_none_reasoning_effort': True})
assert openai_request._build_reasoning_args(_runtime_model(openai_request, 'disabled', name='gpt-5')) == {
'reasoning_effort': 'none'
}
anthropic_request = _requester('anthropic', 'anthropic-messages')
assert anthropic_request._build_reasoning_args(
_runtime_model(anthropic_request, 'disabled', name='claude-sonnet-4-6')
) == {'thinking': {'type': 'disabled'}}
deepseek_request = _requester('deepseek', 'deepseek-chat-completions')
assert deepseek_request._build_reasoning_args(
_runtime_model(deepseek_request, 'high', name='deepseek-v4-flash')
) == {
'extra_body': {
'thinking': {'type': 'enabled'},
'reasoning_effort': 'high',
}
}
kimi_request = _requester('openai', 'moonshot-chat-completions')
assert kimi_request._build_reasoning_args(_runtime_model(kimi_request, 'enabled', name='kimi-k2.6')) == {
'extra_body': {'thinking': {'type': 'enabled'}}
}
assert kimi_request._build_reasoning_args(_runtime_model(kimi_request, 'high', name='kimi-k3')) == {
'reasoning_effort': 'high'
}
qwen_request = _requester('openai', 'bailian-chat-completions')
assert qwen_request._build_reasoning_args(_runtime_model(qwen_request, 'disabled', name='qwen-plus')) == {
'extra_body': {'enable_thinking': False}
}
doubao_request = _requester('openai', 'doubao-chat-completions')
assert doubao_request._build_reasoning_args(
_runtime_model(doubao_request, 'high', name='doubao-seed-2-1-pro-260628')
) == {'reasoning_effort': 'high'}
mimo_request = _requester('openai', 'mimo-chat-completions')
assert mimo_request._build_reasoning_args(_runtime_model(mimo_request, 'disabled', name='mimo-v2.5')) == {
'extra_body': {'thinking': {'type': 'disabled'}}
}
def test_pipeline_reasoning_override_takes_precedence(monkeypatch):
request = _requester('openai', 'openai-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: True)
monkeypatch.setattr(request, '_safe_model_info', lambda _: {})
model = _runtime_model(request, 'high', name='gpt-5')
model.reasoning_config_override = {'level': 'provider_default'}
assert request._build_reasoning_args(model) == {}
model.reasoning_config_override = {'level': 'low'}
assert request._build_reasoning_args(model) == {'reasoning_effort': 'low'}
def test_always_on_reasoning_models_do_not_offer_disabled(monkeypatch):
deepseek_request = _requester('deepseek', 'deepseek-chat-completions')
monkeypatch.setattr(deepseek_request, '_supports_reasoning', lambda _: True)
monkeypatch.setattr(deepseek_request, '_safe_model_info', lambda _: {})
deepseek_capabilities = deepseek_request.get_reasoning_capabilities(
_runtime_model(deepseek_request, name='deepseek-r1')
)
assert deepseek_capabilities['levels'] == ['provider_default']
gemini_request = _requester('gemini')
monkeypatch.setattr(gemini_request, '_supports_reasoning', lambda _: True)
monkeypatch.setattr(
gemini_request,
'_safe_model_info',
lambda _: {'supports_none_reasoning_effort': True},
)
gemini_capabilities = gemini_request.get_reasoning_capabilities(_runtime_model(gemini_request, name='gemini-3-pro'))
assert 'disabled' not in gemini_capabilities['levels']
with pytest.raises(errors.RequesterError, match='not supported'):
gemini_request._build_reasoning_args(_runtime_model(gemini_request, 'disabled', name='gemini-3-pro'))
def test_non_target_provider_capabilities_remain_supported(monkeypatch):
ollama_request = _requester('ollama', 'ollama')
monkeypatch.setattr(ollama_request, '_supports_reasoning', lambda _: False)
monkeypatch.setattr(ollama_request, '_safe_model_info', lambda _: {})
toggle_capabilities = ollama_request.get_reasoning_capabilities(_runtime_model(ollama_request, name='qwen3'))
assert toggle_capabilities['levels'] == [
'provider_default',
'disabled',
'enabled',
]
assert ollama_request._build_reasoning_args(_runtime_model(ollama_request, 'enabled', name='qwen3')) == {
'reasoning_effort': 'low'
}
effort_capabilities = ollama_request.get_reasoning_capabilities(_runtime_model(ollama_request, name='gpt-oss:20b'))
assert effort_capabilities['levels'] == [
'provider_default',
'disabled',
'low',
'medium',
'high',
]
assert ollama_request._build_reasoning_args(_runtime_model(ollama_request, 'high', name='gpt-oss:20b')) == {
'reasoning_effort': 'high'
}
volcengine_request = _requester('volcengine', 'volcark-chat-completions')
monkeypatch.setattr(volcengine_request, '_supports_reasoning', lambda _: False)
monkeypatch.setattr(volcengine_request, '_safe_model_info', lambda _: {})
assert volcengine_request._build_reasoning_args(
_runtime_model(volcengine_request, 'disabled', name='doubao-seed')
) == {'extra_body': {'thinking': {'type': 'disabled'}}}
def test_explicit_unsupported_level_raises(monkeypatch):
request = _requester()
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
monkeypatch.setattr(request, '_safe_model_info', lambda _: {})
with pytest.raises(errors.RequesterError, match='Available levels: provider_default'):
request._build_reasoning_args(_runtime_model(request, 'high', abilities=[]))
def test_provider_inference_rejects_levels_outside_conservative_profile(monkeypatch):
request = _requester('openai', 'openai-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
monkeypatch.setattr(request, '_safe_model_info', lambda _: {})
with pytest.raises(errors.RequesterError, match='Available levels: provider_default, low, medium, high'):
request._build_reasoning_args(_runtime_model(request, 'xhigh', name='gpt-5', abilities=[]))
@pytest.mark.asyncio
async def test_completion_args_reject_reasoning_extra_arg_conflicts(monkeypatch):
request = _requester('openai', 'openai-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: True)
monkeypatch.setattr(request, '_safe_model_info', lambda _: {})
model = _runtime_model(request, 'high', name='gpt-5')
model.model_entity.extra_args = {'reasoning_effort': 'low'}
model.provider.token_mgr.get_token = lambda: 'test-token'
with pytest.raises(errors.RequesterError, match='conflicts with advanced parameters'):
await request._build_completion_args(model, [])
@pytest.mark.asyncio
async def test_openai_compatible_reasoning_effort_is_explicitly_allowed(monkeypatch):
request = _requester('openai', 'moonshot-chat-completions')
model = _runtime_model(request, 'high', name='kimi-k3')
model.model_entity.extra_args = {'allowed_openai_params': ['custom_extension']}
model.provider.token_mgr.get_token = lambda: 'test-token'
args = await request._build_completion_args(model, [])
assert args['reasoning_effort'] == 'high'
assert args['allowed_openai_params'] == ['custom_extension', 'reasoning_effort']
@pytest.mark.asyncio
async def test_provider_default_does_not_allow_or_send_reasoning_effort():
request = _requester('openai', 'new-api-chat-completions')
model = _runtime_model(request, 'provider_default', name='deepseek-v4-flash')
model.provider.token_mgr.get_token = lambda: 'test-token'
args = await request._build_completion_args(model, [])
assert 'reasoning_effort' not in args
assert 'allowed_openai_params' not in args
@pytest.mark.asyncio
async def test_deepseek_disabled_thinking_is_merged_into_extra_body(monkeypatch):
request = _requester('deepseek', 'deepseek-chat-completions')
monkeypatch.setattr(request, '_supports_reasoning', lambda _: False)
model = _runtime_model(request, 'disabled', name='deepseek-chat')
model.model_entity.extra_args = {'extra_body': {'custom_extension': True}}
model.provider.token_mgr.get_token = lambda: 'test-token'
args = await request._build_completion_args(model, [])
assert args['extra_body'] == {
'custom_extension': True,
'thinking': {'type': 'disabled'},
}
@pytest.mark.asyncio
async def test_openai_compatible_reasoning_history_is_promoted_for_tool_continuity():
request = _requester('openai', 'mimo-chat-completions')
model = _runtime_model(request, 'enabled', name='mimo-v2.5')
model.provider.token_mgr.get_token = lambda: 'test-token'
history = [
provider_message.Message(
role='assistant',
content='<think>\nprior reasoning\n</think>\nanswer',
provider_specific_fields={'reasoning_content': 'prior reasoning'},
)
]
args = await request._build_completion_args(model, history)
assert args['messages'][0]['reasoning_content'] == 'prior reasoning'
assert args['messages'][0]['content'] == 'answer'
assert 'provider_specific_fields' not in args['messages'][0]
@pytest.mark.asyncio
async def test_disabling_reasoning_removes_previous_reasoning_context():
request = _requester('openai', 'mimo-chat-completions')
model = _runtime_model(request, 'disabled', name='mimo-v2.5')
model.provider.token_mgr.get_token = lambda: 'test-token'
history = [
provider_message.Message(
role='assistant',
content='answer',
provider_specific_fields={'reasoning_content': 'prior reasoning'},
)
]
args = await request._build_completion_args(model, history)
assert 'reasoning_content' not in args['messages'][0]
assert 'provider_specific_fields' not in args['messages'][0]
@pytest.mark.asyncio
async def test_anthropic_history_promotes_thinking_blocks_instead_of_reasoning_content():
request = _requester('anthropic', 'anthropic-messages')
model = _runtime_model(request, 'high', name='claude-sonnet-4-6')
model.provider.token_mgr.get_token = lambda: 'test-token'
thinking_blocks = [{'type': 'thinking', 'thinking': 'prior reasoning', 'signature': 'sig'}]
history = [
provider_message.Message(
role='assistant',
content='',
provider_specific_fields={
'reasoning_content': 'prior reasoning',
'thinking_blocks': thinking_blocks,
},
)
]
args = await request._build_completion_args(model, history)
assert args['messages'][0]['thinking_blocks'] == thinking_blocks
assert 'reasoning_content' not in args['messages'][0]
assert 'provider_specific_fields' not in args['messages'][0]
@pytest.mark.asyncio
async def test_non_stream_anthropic_thinking_blocks_are_preserved(monkeypatch):
request = _requester('anthropic', 'anthropic-messages')
request._build_completion_args = AsyncMock(return_value={})
thinking_blocks = [{'type': 'thinking', 'thinking': 'private reasoning', 'signature': 'sig'}]
response = SimpleNamespace(
choices=[
SimpleNamespace(
message=_Dumpable(
{
'role': 'assistant',
'content': 'answer',
'thinking_blocks': thinking_blocks,
}
)
)
],
usage=None,
)
monkeypatch.setattr(litellmchat, 'acompletion', AsyncMock(return_value=response))
message, _ = await request.invoke_llm(None, _runtime_model(request, 'high', name='claude-sonnet-4-6'), [])
assert message.content == '<think>\nprivate reasoning\n</think>\nanswer'
assert message.provider_specific_fields == {'thinking_blocks': thinking_blocks}
class _Dumpable:
def __init__(self, data: dict):
self.data = data
def model_dump(self) -> dict:
return dict(self.data)
@pytest.mark.asyncio
async def test_non_stream_reasoning_content_is_preserved(monkeypatch):
request = _requester('deepseek')
request._build_completion_args = AsyncMock(return_value={})
response = SimpleNamespace(
choices=[
SimpleNamespace(
message=_Dumpable(
{
'role': 'assistant',
'content': 'answer',
'reasoning_content': 'private reasoning',
}
)
)
],
usage=None,
)
monkeypatch.setattr(litellmchat, 'acompletion', AsyncMock(return_value=response))
message, _ = await request.invoke_llm(None, _runtime_model(request), [], remove_think=True)
assert message.content == 'answer'
assert message.provider_specific_fields == {'reasoning_content': 'private reasoning'}
@pytest.mark.asyncio
async def test_stream_reasoning_round_trip_with_hidden_display(monkeypatch):
request = _requester('deepseek')
request._build_completion_args = AsyncMock(return_value={})
async def chunks():
yield SimpleNamespace(
choices=[
SimpleNamespace(
delta=_Dumpable({'role': 'assistant', 'reasoning_content': 'private '}),
finish_reason=None,
)
],
usage=None,
)
yield SimpleNamespace(
choices=[
SimpleNamespace(
delta=_Dumpable({'content': 'answer'}),
finish_reason='stop',
)
],
usage=None,
)
monkeypatch.setattr(litellmchat, 'acompletion', AsyncMock(return_value=chunks()))
emitted = [
chunk
async for chunk in request.invoke_llm_stream(
None,
_runtime_model(request),
[],
remove_think=True,
)
]
assert ''.join(chunk.content or '' for chunk in emitted) == 'answer'
assert (
''.join(
chunk.provider_specific_fields.get('reasoning_content', '')
for chunk in emitted
if chunk.provider_specific_fields
)
== 'private '
)
@pytest.mark.asyncio
async def test_stream_reasoning_content_is_wrapped_for_display(monkeypatch):
request = _requester('deepseek')
request._build_completion_args = AsyncMock(return_value={})
async def chunks():
yield SimpleNamespace(
choices=[
SimpleNamespace(
delta=_Dumpable({'role': 'assistant', 'reasoning_content': 'private '}),
finish_reason=None,
)
],
usage=None,
)
yield SimpleNamespace(
choices=[
SimpleNamespace(
delta=_Dumpable({'content': 'answer'}),
finish_reason='stop',
)
],
usage=None,
)
monkeypatch.setattr(litellmchat, 'acompletion', AsyncMock(return_value=chunks()))
emitted = [
chunk
async for chunk in request.invoke_llm_stream(
None,
_runtime_model(request),
[],
remove_think=False,
)
]
assert ''.join(chunk.content or '' for chunk in emitted) == '<think>\nprivate \n</think>\nanswer'
assert (
''.join(
chunk.provider_specific_fields.get('reasoning_content', '')
for chunk in emitted
if chunk.provider_specific_fields
)
== 'private '
)
@pytest.mark.asyncio
async def test_stream_anthropic_thinking_blocks_are_preserved(monkeypatch):
request = _requester('anthropic', 'anthropic-messages')
request._build_completion_args = AsyncMock(return_value={})
thinking_blocks = [{'type': 'thinking', 'thinking': 'private ', 'signature': 'sig'}]
async def chunks():
yield SimpleNamespace(
choices=[
SimpleNamespace(
delta=_Dumpable({'role': 'assistant', 'thinking_blocks': thinking_blocks}),
finish_reason=None,
)
],
usage=None,
)
yield SimpleNamespace(
choices=[
SimpleNamespace(
delta=_Dumpable({'content': 'answer'}),
finish_reason='stop',
)
],
usage=None,
)
monkeypatch.setattr(litellmchat, 'acompletion', AsyncMock(return_value=chunks()))
emitted = [
chunk
async for chunk in request.invoke_llm_stream(
None,
_runtime_model(request, 'high', name='claude-sonnet-4-6'),
[],
remove_think=False,
)
]
assert ''.join(chunk.content or '' for chunk in emitted) == '<think>\nprivate \n</think>\nanswer'
assert (
next(
chunk.provider_specific_fields['thinking_blocks']
for chunk in emitted
if chunk.provider_specific_fields and 'thinking_blocks' in chunk.provider_specific_fields
)
== thinking_blocks
)
@pytest.mark.asyncio
async def test_hidden_thinking_does_not_drop_same_delta_tool_call(monkeypatch):
request = _requester('openai', 'openai-chat-completions')
request._build_completion_args = AsyncMock(return_value={})
async def chunks():
yield SimpleNamespace(
choices=[
SimpleNamespace(
delta=_Dumpable(
{
'content': '<think>hidden</think>',
'tool_calls': [
{
'index': 0,
'id': 'call_1',
'type': 'function',
'function': {'name': 'lookup', 'arguments': '{}'},
}
],
}
),
finish_reason='tool_calls',
)
],
usage=None,
)
monkeypatch.setattr(litellmchat, 'acompletion', AsyncMock(return_value=chunks()))
collected = [
chunk
async for chunk in request.invoke_llm_stream(
None,
_runtime_model(request, 'provider_default'),
[],
remove_think=True,
)
]
assert len(collected) == 1
assert collected[0].tool_calls[0].id == 'call_1'
@@ -510,6 +510,7 @@ def test_runtime_llm_model_initialization(runtime_llm_model, fake_persistence_da
assert model.model_entity.abilities == model_entity.abilities
assert model.model_entity.extra_args == model_entity.extra_args
assert model.provider is not None
assert model.reasoning_config_override is None
def test_runtime_llm_model_provider_ref(runtime_llm_model):
+21 -5
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
from datetime import datetime, timezone
from types import SimpleNamespace
import pytest
@@ -14,6 +15,12 @@ def get_heartbeat_module():
return import_module('langbot.pkg.telemetry.heartbeat')
def test_workspace_created_timestamp_treats_naive_database_values_as_utc():
heartbeat = get_heartbeat_module()
created_at = datetime(2026, 8, 4, 0, 0, 0)
assert heartbeat._workspace_created_timestamp(created_at) == 1785801600
def make_app():
ap = Mock()
ap.instance_config = Mock()
@@ -57,15 +64,17 @@ def make_app():
class TestBuildHeartbeatPayload:
@pytest.mark.asyncio
async def test_payload_shape(self):
async def test_payload_shape(self, monkeypatch):
heartbeat = get_heartbeat_module()
monkeypatch.setattr(heartbeat.constants, 'instance_id', 'instance-test')
ap = make_app()
payload = await heartbeat.build_heartbeat_payload(ap, workspace_uuid='workspace-a')
assert payload['event_type'] == 'instance_heartbeat'
assert payload['query_id'] == ''
assert payload['workspace_uuid'] == 'workspace-a'
assert 'instance_id' not in payload
assert payload['instance_id']
assert payload['workspace_create_ts'] == 0
assert 'instance_create_ts' in payload
assert 'timestamp' in payload
f = payload['features']
@@ -100,8 +109,9 @@ class TestBuildHeartbeatPayload:
assert payload['features']['pipeline_count'] == -1
@pytest.mark.asyncio
async def test_cloud_counts_loaded_registries_without_tenant_sql(self):
async def test_cloud_counts_loaded_registries_without_tenant_sql(self, monkeypatch):
heartbeat = get_heartbeat_module()
monkeypatch.setattr(heartbeat.constants, 'instance_id', 'instance-test')
ap = make_app()
ap.persistence_mgr.mode = SimpleNamespace(value='cloud_runtime')
ap.persistence_mgr.execute_async = AsyncMock(
@@ -140,7 +150,11 @@ class TestBuildHeartbeatPayload:
ap.workspace_service.list_active_execution_bindings = AsyncMock(
return_value=[
SimpleNamespace(workspace_uuid='workspace-a', placement_generation=7),
SimpleNamespace(workspace_uuid='workspace-b', placement_generation=9),
SimpleNamespace(
workspace_uuid='workspace-b',
placement_generation=9,
workspace_created_at=datetime(2026, 8, 4, tzinfo=timezone.utc),
),
],
)
ap.platform_mgr._bots_by_key[('instance-a', 'workspace-b', 'bot-b')] = SimpleNamespace(
@@ -150,7 +164,9 @@ class TestBuildHeartbeatPayload:
payloads = await heartbeat.build_heartbeat_payloads(ap)
assert [payload['workspace_uuid'] for payload in payloads] == ['workspace-a', 'workspace-b']
assert all('instance_id' not in payload for payload in payloads)
assert all(payload['instance_id'] for payload in payloads)
assert payloads[0]['workspace_create_ts'] == 0
assert payloads[1]['workspace_create_ts'] == 1785801600
by_workspace = {payload['workspace_uuid']: payload['features'] for payload in payloads}
assert by_workspace['workspace-a']['pipeline_count'] == 2
assert by_workspace['workspace-a']['mcp_server_count'] == 3
@@ -596,6 +596,36 @@ class TestTelemetryManagedRuntimeAuthentication:
assert captured['headers'] == {'X-LangBot-Telemetry-Token': 'managed-runtime-secret'}
class TestAuthenticatedWorkspaceReporter:
@pytest.mark.asyncio
async def test_workspace_owner_access_token_is_sent_as_bearer(self):
telemetry = get_telemetry_module()
mock_app = Mock()
mock_app.logger = Mock()
mock_app.user_service = Mock()
mock_app.user_service.get_workspace_owner = AsyncMock(
return_value=Mock(user='owner@example.com', space_access_token='expired-token')
)
mock_app.space_service = Mock()
mock_app.space_service.get_valid_access_token = AsyncMock(return_value='refreshed-workspace-owner-token')
manager = telemetry.TelemetryManager(mock_app)
manager.telemetry_config = {'url': 'https://example.com'}
response = Mock(status_code=200, text='')
response.json = Mock(return_value={'code': 0})
mock_client = Mock()
mock_client.post = Mock(return_value=response)
with patch.object(httpx, 'AsyncClient', return_value=mock_client):
await manager.send({'query_id': 'q-1', 'workspace_uuid': 'workspace-1'})
mock_app.user_service.get_workspace_owner.assert_awaited_once_with('workspace-1')
mock_app.space_service.get_valid_access_token.assert_awaited_once_with('owner@example.com')
assert mock_client.post.call_args.kwargs['headers'] == {
'Authorization': 'Bearer refreshed-workspace-owner-token'
}
class TestStartSendTask:
"""Tests for start_send_task() method."""
@@ -7,25 +7,28 @@ from types import SimpleNamespace
def test_standard_oss_instance_id_aligns_to_embedded_uuid():
from langbot.pkg.workspace.identity import workspace_uuid_from_instance_id
instance_uuid = "a711d9e4-0953-443f-a0e9-7dd50193a79f"
instance_uuid = 'a711d9e4-0953-443f-a0e9-7dd50193a79f'
assert workspace_uuid_from_instance_id(instance_uuid) == instance_uuid
assert workspace_uuid_from_instance_id(f"instance_{instance_uuid}") == instance_uuid
assert workspace_uuid_from_instance_id(f'instance_{instance_uuid}') == instance_uuid
def test_custom_legacy_instance_id_maps_to_stable_valid_uuid():
from langbot.pkg.workspace.identity import workspace_uuid_from_instance_id
first = workspace_uuid_from_instance_id("instance_migration_test")
second = workspace_uuid_from_instance_id("instance_migration_test")
first = workspace_uuid_from_instance_id('instance_migration_test')
second = workspace_uuid_from_instance_id('instance_migration_test')
assert first == second
assert str(uuid.UUID(first)) == first
def test_query_telemetry_identity_uses_execution_workspace_only():
def test_query_telemetry_identity_reports_instance_and_workspace():
from langbot.pkg.telemetry.identity import workspace_identity
identity = workspace_identity(SimpleNamespace(workspace_uuid="workspace-a", instance_uuid="instance-a"))
identity = workspace_identity(SimpleNamespace(workspace_uuid='workspace-a', instance_uuid='instance-a'))
assert identity == {"workspace_uuid": "workspace-a"}
assert identity == {
'instance_id': 'instance-a',
'workspace_uuid': 'workspace-a',
}
+3 -3
View File
@@ -204,7 +204,7 @@ class TestVectorDBManagerInitialization:
mock_app,
connection_string='postgresql://user:pass@host:5432/langbot',
use_business_database=False,
allowed_dimensions=[384, 512, 768, 1024, 1536],
allowed_dimensions=[384, 512, 768, 1024, 1536, 3072],
)
@pytest.mark.asyncio
@@ -241,7 +241,7 @@ class TestVectorDBManagerInitialization:
user='admin',
password='secret',
use_business_database=False,
allowed_dimensions=[384, 512, 768, 1024, 1536],
allowed_dimensions=[384, 512, 768, 1024, 1536, 3072],
)
@pytest.mark.asyncio
@@ -269,7 +269,7 @@ class TestVectorDBManagerInitialization:
user='postgres',
password='postgres',
use_business_database=False,
allowed_dimensions=[384, 512, 768, 1024, 1536],
allowed_dimensions=[384, 512, 768, 1024, 1536, 3072],
)
@pytest.mark.asyncio
@@ -99,6 +99,7 @@ async def test_invitation_secret_is_hashed_and_acceptance_is_one_time(collaborat
membership = await service.accept_invitation(created.token, account.uuid)
assert membership.workspace_uuid == workspace.uuid
assert membership.role == 'developer'
assert membership.source == 'local'
with pytest.raises(InvitationUsedError):
await service.accept_invitation(created.token, account.uuid)
@@ -153,6 +153,33 @@ async def test_initial_owner_cannot_be_claimed_by_another_account(workspace_test
).all()
assert len(owners) == 1
assert owners[0].account_uuid == first_account_uuid
assert owners[0].source == 'local'
async def test_claim_initial_owner_reclassifies_existing_membership_as_local(workspace_test_context):
service, session_factory = workspace_test_context
async with session_factory() as session:
async with session.begin():
account_uuid = await _insert_account(session, 'reclaimed@example.com')
workspace = await service.ensure_singleton_workspace(session=session)
session.add(
WorkspaceMembership(
uuid='44444444-4444-4444-8444-444444444444',
workspace_uuid=workspace.uuid,
account_uuid=account_uuid,
role='viewer',
status='removed',
source='cloud_projection',
projection_revision=4,
)
)
membership = await service.claim_initial_owner(account_uuid)
assert membership.role == 'owner'
assert membership.status == 'active'
assert membership.source == 'local'
async def test_execution_binding_returns_persisted_generation(workspace_test_context):
Generated
+3859 -4376
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -48,6 +48,7 @@
"@radix-ui/react-scroll-area": "^1.2.9",
"@radix-ui/react-select": "^2.2.4",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slider": "^1.4.7",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-switch": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.11",
+540 -534
View File
File diff suppressed because it is too large Load Diff
@@ -146,6 +146,7 @@ function getValueSchema(spec: DynamicFormValueSpec) {
return z.object({
primary: z.string(),
fallbacks: z.array(z.string()),
reasoning: z.record(z.string()),
});
case DynamicFormItemType.PROMPT_EDITOR:
return z.array(
@@ -497,12 +498,24 @@ export default function DynamicFormComponent({
(v): v is string => typeof v === 'string',
)
: [],
reasoning:
obj.reasoning != null &&
typeof obj.reasoning === 'object' &&
!Array.isArray(obj.reasoning)
? Object.fromEntries(
Object.entries(obj.reasoning).filter(
(entry): entry is [string, string] =>
typeof entry[1] === 'string',
),
)
: {},
};
}
// Legacy string format or any other unexpected type
return {
primary: typeof value === 'string' ? value : '',
fallbacks: [],
reasoning: {},
};
}
if (item.type === 'prompt-editor') {
@@ -25,6 +25,7 @@ import {
EmbeddingModel,
RerankModel,
PluginTool,
ReasoningLevel,
} from '@/app/infra/entities/api';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
@@ -67,6 +68,9 @@ import SettingsDialog, {
} from '@/app/home/components/settings-dialog/SettingsDialog';
import ToolResourceSelectors from '@/app/home/components/dynamic-form/ToolResourceSelectors';
import { LANGBOT_MODELS_PROVIDER_REQUESTER } from '@/app/home/components/models-dialog/types';
import ReasoningLevelPicker, {
REASONING_LEVELS,
} from '@/app/home/components/reasoning/ReasoningLevelPicker';
function hasUsableUuid<T extends { uuid?: string | null }>(
item: T,
@@ -990,7 +994,11 @@ export default function DynamicFormItemComponent({
];
const rawModelValue = field.value;
const modelValue: { primary: string; fallbacks: string[] } =
const modelValue: {
primary: string;
fallbacks: string[];
reasoning: Record<string, ReasoningLevel>;
} =
rawModelValue != null &&
typeof rawModelValue === 'object' &&
!Array.isArray(rawModelValue)
@@ -1009,10 +1017,29 @@ export default function DynamicFormItemComponent({
.fallbacks as unknown[]
).filter((v): v is string => typeof v === 'string')
: [],
reasoning:
(rawModelValue as Record<string, unknown>).reasoning != null &&
typeof (rawModelValue as Record<string, unknown>).reasoning ===
'object' &&
!Array.isArray(
(rawModelValue as Record<string, unknown>).reasoning,
)
? (Object.fromEntries(
Object.entries(
(rawModelValue as Record<string, unknown>)
.reasoning as Record<string, unknown>,
).filter(
(entry): entry is [string, ReasoningLevel] =>
typeof entry[1] === 'string' &&
REASONING_LEVELS.includes(entry[1] as ReasoningLevel),
),
) as Record<string, ReasoningLevel>)
: {},
}
: {
primary: typeof rawModelValue === 'string' ? rawModelValue : '',
fallbacks: [],
reasoning: {},
};
const renderModelSelect = (
@@ -1159,20 +1186,79 @@ export default function DynamicFormItemComponent({
field.onChange({ ...modelValue, ...patch });
};
const updateModelReasoning = (
modelUuid: string,
level: ReasoningLevel,
) => {
if (!modelUuid) return;
const updated = { ...modelValue.reasoning };
if (level === 'provider_default') {
delete updated[modelUuid];
} else {
updated[modelUuid] = level;
}
updateValue({ reasoning: updated });
};
const replaceModel = (
currentUuid: string,
nextUuid: string,
patch: Partial<typeof modelValue>,
) => {
const nextValue = { ...modelValue, ...patch };
const updatedReasoning = { ...modelValue.reasoning };
const currentModelStillSelected =
nextValue.primary === currentUuid ||
nextValue.fallbacks.includes(currentUuid);
if (
currentUuid &&
currentUuid !== nextUuid &&
!currentModelStillSelected
) {
delete updatedReasoning[currentUuid];
}
updateValue({ ...nextValue, reasoning: updatedReasoning });
};
const renderReasoningPicker = (modelUuid: string) => {
if (!modelUuid) return null;
const model = llmModels.find(
(candidate) => candidate.uuid === modelUuid,
);
const currentLevel =
modelValue.reasoning[modelUuid] || 'provider_default';
const availableLevels = model?.reasoning_capabilities?.levels || [
'provider_default',
];
const levels = REASONING_LEVELS.filter(
(level) => availableLevels.includes(level) || level === currentLevel,
);
return (
<ReasoningLevelPicker
value={currentLevel}
levels={levels}
onChange={(level) => updateModelReasoning(modelUuid, level)}
/>
);
};
const addFallbackModel = () => {
updateValue({ fallbacks: [...modelValue.fallbacks, ''] });
};
const updateFallbackModel = (index: number, value: string) => {
const updated = [...modelValue.fallbacks];
const currentUuid = updated[index];
updated[index] = value;
updateValue({ fallbacks: updated });
replaceModel(currentUuid, value, { fallbacks: updated });
};
const removeFallbackModel = (index: number) => {
const updated = [...modelValue.fallbacks];
const removedUuid = updated[index];
updated.splice(index, 1);
updateValue({ fallbacks: updated });
replaceModel(removedUuid, '', { fallbacks: updated });
};
const moveFallbackModel = (index: number, direction: 'up' | 'down') => {
@@ -1197,10 +1283,12 @@ export default function DynamicFormItemComponent({
<div className="min-w-0 flex-1">
{renderModelSelect(
modelValue.primary,
(val) => updateValue({ primary: val }),
(val) =>
replaceModel(modelValue.primary, val, { primary: val }),
t('models.selectModel'),
)}
</div>
{renderReasoningPicker(modelValue.primary)}
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -1234,15 +1322,18 @@ export default function DynamicFormItemComponent({
</p>
{modelValue.fallbacks.map((fbUuid: string, index: number) => (
<div key={index} className="flex min-w-0 items-center gap-2">
<span className="text-xs text-muted-foreground w-4 shrink-0">
<span className="w-4 shrink-0 text-xs text-muted-foreground">
{index + 1}.
</span>
<div className="min-w-0 flex-1">
{renderModelSelect(
fbUuid,
(val) => updateFallbackModel(index, val),
t('models.selectModel'),
)}
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<div className="min-w-0 flex-1">
{renderModelSelect(
fbUuid,
(val) => updateFallbackModel(index, val),
t('models.selectModel'),
)}
</div>
{renderReasoningPicker(fbUuid)}
</div>
<div className="flex gap-1 shrink-0">
<Button
@@ -5,6 +5,56 @@ export type DynamicFormSaveValueSpec = Pick<
'default' | 'name' | 'type'
>;
const reasoningLevels = new Set([
'disabled',
'enabled',
'minimal',
'low',
'medium',
'high',
'xhigh',
'max',
]);
function normalizeModelFallbackValue(value: unknown): {
primary: string;
fallbacks: string[];
reasoning: Record<string, string>;
} {
const raw =
value != null && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
const primary =
typeof raw.primary === 'string'
? raw.primary
: typeof value === 'string'
? value
: '';
const fallbacks = Array.isArray(raw.fallbacks)
? raw.fallbacks.filter(
(fallback): fallback is string => typeof fallback === 'string',
)
: [];
const selectedModels = new Set([primary, ...fallbacks].filter(Boolean));
const rawReasoning =
raw.reasoning != null &&
typeof raw.reasoning === 'object' &&
!Array.isArray(raw.reasoning)
? (raw.reasoning as Record<string, unknown>)
: {};
const reasoning = Object.fromEntries(
Object.entries(rawReasoning).filter(
([modelUuid, level]) =>
selectedModels.has(modelUuid) &&
typeof level === 'string' &&
reasoningLevels.has(level),
),
) as Record<string, string>;
return { primary, fallbacks, reasoning };
}
/**
* Build the value snapshot emitted to parent forms for persistence.
* Only single-line string fields trim surrounding whitespace; multiline text
@@ -16,10 +66,14 @@ export function normalizeDynamicFormValuesForSave(
): Record<string, unknown> {
return specs.reduce<Record<string, unknown>>((values, spec) => {
const value = formValues[spec.name] ?? spec.default;
values[spec.name] =
spec.type === 'string' && typeof value === 'string'
? value.trim()
: value;
if (spec.type === 'model-fallback-selector') {
values[spec.name] = normalizeModelFallbackValue(value);
} else {
values[spec.name] =
spec.type === 'string' && typeof value === 'string'
? value.trim()
: value;
}
return values;
}, {});
}
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react';
import { Plus, Boxes } from 'lucide-react';
import { httpClient, systemInfo } from '@/app/infra/http/HttpClient';
import { ModelProvider } from '@/app/infra/entities/api';
import { ModelProvider, ReasoningConfig } from '@/app/infra/entities/api';
import {
Dialog,
DialogContent,
@@ -15,6 +15,7 @@ import ProviderForm from './component/provider-form/ProviderForm';
import { ProviderCard } from './components';
import {
ExtraArg,
DEFAULT_REASONING_CONFIG,
ModelType,
ScanModelsResult,
SelectedScannedModel,
@@ -285,6 +286,7 @@ export default function ModelsPanel({
name: string,
abilities: string[],
extraArgs: ExtraArg[],
reasoningConfig: ReasoningConfig,
contextLength?: number | null,
) {
if (!name.trim()) {
@@ -300,6 +302,7 @@ export default function ModelsPanel({
name,
provider_uuid: providerUuid,
abilities,
reasoning_config: reasoningConfig,
context_length: parseContextLength(
contextLength,
t('models.contextLengthInvalid'),
@@ -361,6 +364,7 @@ export default function ModelsPanel({
name: item.model.name,
provider_uuid: providerUuid,
abilities: item.abilities,
reasoning_config: DEFAULT_REASONING_CONFIG,
context_length: item.model.context_length ?? null,
extra_args: {},
} as never);
@@ -398,6 +402,7 @@ export default function ModelsPanel({
name: string,
abilities: string[],
extraArgs: ExtraArg[],
reasoningConfig: ReasoningConfig,
contextLength?: number | null,
) {
if (!name.trim()) {
@@ -413,6 +418,7 @@ export default function ModelsPanel({
name,
provider_uuid: providerUuid,
abilities,
reasoning_config: reasoningConfig,
context_length: parseContextLength(
contextLength,
t('models.contextLengthInvalid'),
@@ -469,6 +475,7 @@ export default function ModelsPanel({
modelType: ModelType,
abilities: string[],
extraArgs: ExtraArg[],
reasoningConfig: ReasoningConfig,
) {
setIsTesting(true);
setTestResult(null);
@@ -491,6 +498,7 @@ export default function ModelsPanel({
provider_uuid: '',
provider: providerData,
abilities,
reasoning_config: reasoningConfig,
extra_args: extraArgsObj,
} as never);
} else if (modelType === 'embedding') {
@@ -554,13 +562,21 @@ export default function ModelsPanel({
onSpaceLogin={handleSpaceLogin}
onOpenAddModel={() => setAddModelPopoverOpen(provider.uuid)}
onCloseAddModel={() => setAddModelPopoverOpen(null)}
onAddModel={(modelType, name, abilities, extraArgs, contextLength) =>
onAddModel={(
modelType,
name,
abilities,
extraArgs,
reasoningConfig,
contextLength,
) =>
handleAddModel(
provider.uuid,
modelType,
name,
abilities,
extraArgs,
reasoningConfig,
contextLength,
)
}
@@ -576,6 +592,7 @@ export default function ModelsPanel({
name,
abilities,
extraArgs,
reasoningConfig,
contextLength,
) =>
handleUpdateModel(
@@ -585,6 +602,7 @@ export default function ModelsPanel({
name,
abilities,
extraArgs,
reasoningConfig,
contextLength,
)
}
@@ -593,8 +611,15 @@ export default function ModelsPanel({
onDeleteModel={(modelId, modelType) =>
handleDeleteModel(provider.uuid, modelId, modelType)
}
onTestModel={(name, modelType, abilities, extraArgs) =>
handleTestModel(provider.uuid, name, modelType, abilities, extraArgs)
onTestModel={(name, modelType, abilities, extraArgs, reasoningConfig) =>
handleTestModel(
provider.uuid,
name,
modelType,
abilities,
extraArgs,
reasoningConfig,
)
}
isSubmitting={isSubmitting}
isTesting={isTesting}

Some files were not shown because too many files have changed in this diff Show More